update
This commit is contained in:
Binary file not shown.
@@ -0,0 +1 @@
|
||||
module.exports={A:{A:{"2":"K D E F A B mC"},B:{"1":"0 9 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 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I","2":"C L M G N","257":"O P"},C:{"1":"0 9 m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC","2":"1 2 3 4 5 6 7 8 nC LC J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B qC rC","578":"5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l"},D:{"1":"0 9 BC CC DC 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 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC","2":"1 2 3 4 5 6 7 8 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB","194":"kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC"},E:{"1":"KC gC hC iC jC 3C","2":"J PB K D E sC SC tC uC vC","33":"F A B C L M G wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C"},F:{"1":"0 zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC 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":"1 2 3 4 5 6 7 8 F B C G N O P QB RB SB TB UB VB WB 4C 5C 6C 7C FC kC 8C GC","194":"XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB"},G:{"1":"KC gC hC iC jC","2":"E SC 9C lC AD BD CD DD","33":"ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD"},H:{"2":"WD"},I:{"1":"I","2":"LC J XD YD ZD aD lC bD cD"},J:{"2":"D A"},K:{"1":"H","2":"A B C FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"2":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 jD kD lD mD IC JC KC nD","2":"J","194":"dD eD fD gD hD TC iD"},Q:{"2":"oD"},R:{"1":"pD"},S:{"2":"qD rD"}},B:7,C:"CSS Backdrop Filter",D:true};
|
||||
@@ -0,0 +1,195 @@
|
||||
import { HistoryState, ParsedHistoryState } from '@tanstack/history';
|
||||
import { AllParams, CatchAllPaths, CurrentPath, FullSearchSchema, FullSearchSchemaInput, ParentPath, RouteByPath, RouteByToPath, RoutePaths, RouteToPath, ToPath } from './routeInfo.cjs';
|
||||
import { AnyRouter, RegisteredRouter, ViewTransitionOptions } from './router.cjs';
|
||||
import { ConstrainLiteral, Expand, MakeDifferenceOptional, NoInfer, NonNullableUpdater, PickRequired, Updater, WithoutEmpty } from './utils.cjs';
|
||||
import { ParsedLocation } from './location.cjs';
|
||||
export type IsRequiredParams<TParams> = Record<never, never> extends TParams ? never : true;
|
||||
export type ParsePathParams<T extends string, TAcc = never> = T & `${string}$${string}` extends never ? TAcc : T extends `${string}$${infer TPossiblyParam}` ? TPossiblyParam extends '' ? TAcc : TPossiblyParam & `${string}/${string}` extends never ? TPossiblyParam | TAcc : TPossiblyParam extends `${infer TParam}/${infer TRest}` ? ParsePathParams<TRest, TParam extends '' ? TAcc : TParam | TAcc> : never : TAcc;
|
||||
export type AddTrailingSlash<T> = T extends `${string}/` ? T : `${T & string}/`;
|
||||
export type RemoveTrailingSlashes<T> = T & `${string}/` extends never ? T : T extends `${infer R}/` ? R : T;
|
||||
export type AddLeadingSlash<T> = T & `/${string}` extends never ? `/${T & string}` : T;
|
||||
export type RemoveLeadingSlashes<T> = T & `/${string}` extends never ? T : T extends `/${infer R}` ? R : T;
|
||||
type JoinPath<TLeft extends string, TRight extends string> = TRight extends '' ? TLeft : TLeft extends '' ? TRight : `${RemoveTrailingSlashes<TLeft>}/${RemoveLeadingSlashes<TRight>}`;
|
||||
type RemoveLastSegment<T extends string, TAcc extends string = ''> = T extends `${infer TSegment}/${infer TRest}` ? TRest & `${string}/${string}` extends never ? TRest extends '' ? TAcc : `${TAcc}${TSegment}` : RemoveLastSegment<TRest, `${TAcc}${TSegment}/`> : TAcc;
|
||||
export type ResolveCurrentPath<TFrom extends string, TTo extends string> = TTo extends '.' ? TFrom : TTo extends './' ? AddTrailingSlash<TFrom> : TTo & `./${string}` extends never ? never : TTo extends `./${infer TRest}` ? AddLeadingSlash<JoinPath<TFrom, TRest>> : never;
|
||||
export type ResolveParentPath<TFrom extends string, TTo extends string> = TTo extends '../' | '..' ? TFrom extends '' | '/' ? never : AddLeadingSlash<RemoveLastSegment<TFrom>> : TTo & `../${string}` extends never ? AddLeadingSlash<JoinPath<TFrom, TTo>> : TFrom extends '' | '/' ? never : TTo extends `../${infer ToRest}` ? ResolveParentPath<RemoveLastSegment<TFrom>, ToRest> : AddLeadingSlash<JoinPath<TFrom, TTo>>;
|
||||
export type ResolveRelativePath<TFrom, TTo = '.'> = string extends TFrom ? TTo : string extends TTo ? TFrom : undefined extends TTo ? TFrom : TTo extends string ? TFrom extends string ? TTo extends `/${string}` ? TTo : TTo extends `..${string}` ? ResolveParentPath<TFrom, TTo> : TTo extends `.${string}` ? ResolveCurrentPath<TFrom, TTo> : AddLeadingSlash<JoinPath<TFrom, TTo>> : never : never;
|
||||
export type FindDescendantToPaths<TRouter extends AnyRouter, TPrefix extends string> = `${TPrefix}/${string}` & RouteToPath<TRouter>;
|
||||
export type InferDescendantToPaths<TRouter extends AnyRouter, TPrefix extends string, TPaths = FindDescendantToPaths<TRouter, TPrefix>> = TPaths extends `${TPrefix}/` ? never : TPaths extends `${TPrefix}/${infer TRest}` ? TRest : never;
|
||||
export type RelativeToPath<TRouter extends AnyRouter, TTo extends string, TResolvedPath extends string> = (TResolvedPath & RouteToPath<TRouter> extends never ? never : ToPath<TRouter, TTo>) | `${RemoveTrailingSlashes<TTo>}/${InferDescendantToPaths<TRouter, RemoveTrailingSlashes<TResolvedPath>>}`;
|
||||
export type RelativeToParentPath<TRouter extends AnyRouter, TFrom extends string, TTo extends string, TResolvedPath extends string = ResolveRelativePath<TFrom, TTo>> = RelativeToPath<TRouter, TTo, TResolvedPath> | (TTo extends `${string}..` | `${string}../` ? TResolvedPath extends '/' | '' ? never : FindDescendantToPaths<TRouter, RemoveTrailingSlashes<TResolvedPath>> extends never ? never : `${RemoveTrailingSlashes<TTo>}/${ParentPath<TRouter>}` : never);
|
||||
export type RelativeToCurrentPath<TRouter extends AnyRouter, TFrom extends string, TTo extends string, TResolvedPath extends string = ResolveRelativePath<TFrom, TTo>> = RelativeToPath<TRouter, TTo, TResolvedPath> | CurrentPath<TRouter>;
|
||||
export type AbsoluteToPath<TRouter extends AnyRouter, TFrom extends string> = (string extends TFrom ? CurrentPath<TRouter> : TFrom extends `/` ? never : CurrentPath<TRouter>) | (string extends TFrom ? ParentPath<TRouter> : TFrom extends `/` ? never : ParentPath<TRouter>) | RouteToPath<TRouter> | (TFrom extends '/' ? never : string extends TFrom ? never : InferDescendantToPaths<TRouter, RemoveTrailingSlashes<TFrom>>);
|
||||
export type RelativeToPathAutoComplete<TRouter extends AnyRouter, TFrom extends string, TTo extends string> = string extends TTo ? string : string extends TFrom ? AbsoluteToPath<TRouter, TFrom> : TTo & `..${string}` extends never ? TTo & `.${string}` extends never ? AbsoluteToPath<TRouter, TFrom> : RelativeToCurrentPath<TRouter, TFrom, TTo> : RelativeToParentPath<TRouter, TFrom, TTo>;
|
||||
export type NavigateOptions<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = '.', TMaskFrom extends string = TFrom, TMaskTo extends string = '.'> = ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & NavigateOptionProps;
|
||||
/**
|
||||
* The NavigateOptions type is used to describe the options that can be used when describing a navigation action in TanStack Router.
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType)
|
||||
*/
|
||||
export interface NavigateOptionProps {
|
||||
/**
|
||||
* If set to `true`, the router will scroll the element with an id matching the hash into view with default `ScrollIntoViewOptions`.
|
||||
* If set to `false`, the router will not scroll the element with an id matching the hash into view.
|
||||
* If set to `ScrollIntoViewOptions`, the router will scroll the element with an id matching the hash into view with the provided options.
|
||||
* @default true
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#hashscrollintoview)
|
||||
* @see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView)
|
||||
*/
|
||||
hashScrollIntoView?: boolean | ScrollIntoViewOptions;
|
||||
/**
|
||||
* `replace` is a boolean that determines whether the navigation should replace the current history entry or push a new one.
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#replace)
|
||||
*/
|
||||
replace?: boolean;
|
||||
/**
|
||||
* Defaults to `true` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.
|
||||
* If `false`, the scroll position will not be reset to 0,0 after the location is committed to history.
|
||||
* @default true
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#resetscroll)
|
||||
*/
|
||||
resetScroll?: boolean;
|
||||
/** @deprecated All navigations now use startTransition under the hood */
|
||||
startTransition?: boolean;
|
||||
/**
|
||||
* If set to `true`, the router will wrap the resulting navigation in a `document.startViewTransition()` call.
|
||||
* If `ViewTransitionOptions`, route navigations will be called using `document.startViewTransition({update, types})`
|
||||
* where `types` will be the strings array passed with `ViewTransitionOptions["types"]`.
|
||||
* If the browser does not support viewTransition types, the navigation will fall back to normal `document.startTransition()`, same as if `true` was passed.
|
||||
*
|
||||
* If the browser does not support this api, this option will be ignored.
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#viewtransition)
|
||||
* @see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition)
|
||||
* @see [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types)
|
||||
*/
|
||||
viewTransition?: boolean | ViewTransitionOptions;
|
||||
/**
|
||||
* If `true`, navigation will ignore any blockers that might prevent it.
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#ignoreblocker)
|
||||
*/
|
||||
ignoreBlocker?: boolean;
|
||||
/**
|
||||
* If `true`, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#reloaddocument)
|
||||
*/
|
||||
reloadDocument?: boolean;
|
||||
/**
|
||||
* This can be used instead of `to` to navigate to a fully built href, e.g. pointing to an external target.
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#href)
|
||||
*/
|
||||
href?: string;
|
||||
}
|
||||
export type ToOptions<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = '.', TMaskFrom extends string = TFrom, TMaskTo extends string = '.'> = ToSubOptions<TRouter, TFrom, TTo> & MaskOptions<TRouter, TMaskFrom, TMaskTo>;
|
||||
export interface MaskOptions<in out TRouter extends AnyRouter, in out TMaskFrom extends string, in out TMaskTo extends string> {
|
||||
_fromLocation?: ParsedLocation;
|
||||
mask?: ToMaskOptions<TRouter, TMaskFrom, TMaskTo>;
|
||||
}
|
||||
export type ToMaskOptions<TRouter extends AnyRouter = RegisteredRouter, TMaskFrom extends string = string, TMaskTo extends string = '.'> = ToSubOptions<TRouter, TMaskFrom, TMaskTo> & {
|
||||
unmaskOnReload?: boolean;
|
||||
};
|
||||
export type ToSubOptions<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = '.'> = ToSubOptionsProps<TRouter, TFrom, TTo> & SearchParamOptions<TRouter, TFrom, TTo> & PathParamOptions<TRouter, TFrom, TTo>;
|
||||
export interface RequiredToOptions<in out TRouter extends AnyRouter, in out TFrom extends string, in out TTo extends string | undefined> {
|
||||
to: ToPathOption<TRouter, TFrom, TTo> & {};
|
||||
}
|
||||
export interface OptionalToOptions<in out TRouter extends AnyRouter, in out TFrom extends string, in out TTo extends string | undefined> {
|
||||
to?: ToPathOption<TRouter, TFrom, TTo> & {};
|
||||
}
|
||||
export type MakeToRequired<TRouter extends AnyRouter, TFrom extends string, TTo extends string | undefined> = string extends TFrom ? string extends TTo ? OptionalToOptions<TRouter, TFrom, TTo> : TTo & CatchAllPaths<TRouter> extends never ? RequiredToOptions<TRouter, TFrom, TTo> : OptionalToOptions<TRouter, TFrom, TTo> : OptionalToOptions<TRouter, TFrom, TTo>;
|
||||
export type ToSubOptionsProps<TRouter extends AnyRouter = RegisteredRouter, TFrom extends RoutePaths<TRouter['routeTree']> | string = string, TTo extends string | undefined = '.'> = MakeToRequired<TRouter, TFrom, TTo> & {
|
||||
hash?: true | Updater<string>;
|
||||
state?: true | NonNullableUpdater<ParsedHistoryState, HistoryState>;
|
||||
from?: FromPathOption<TRouter, TFrom> & {};
|
||||
};
|
||||
export type ParamsReducerFn<in out TRouter extends AnyRouter, in out TParamVariant extends ParamVariant, in out TFrom, in out TTo> = (current: Expand<ResolveFromParams<TRouter, TParamVariant, TFrom>>) => Expand<ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>>;
|
||||
type ParamsReducer<TRouter extends AnyRouter, TParamVariant extends ParamVariant, TFrom, TTo> = Expand<ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>> | (ParamsReducerFn<TRouter, TParamVariant, TFrom, TTo> & {});
|
||||
type ParamVariant = 'PATH' | 'SEARCH';
|
||||
export type ResolveRoute<TRouter extends AnyRouter, TFrom, TTo, TPath = ResolveRelativePath<TFrom, TTo>> = TPath extends string ? TFrom extends TPath ? RouteByPath<TRouter['routeTree'], TPath> : RouteByToPath<TRouter, TPath> : never;
|
||||
type ResolveFromParamType<TParamVariant extends ParamVariant> = TParamVariant extends 'PATH' ? 'allParams' : 'fullSearchSchema';
|
||||
type ResolveFromAllParams<TRouter extends AnyRouter, TParamVariant extends ParamVariant> = TParamVariant extends 'PATH' ? AllParams<TRouter['routeTree']> : FullSearchSchema<TRouter['routeTree']>;
|
||||
type ResolveFromParams<TRouter extends AnyRouter, TParamVariant extends ParamVariant, TFrom> = string extends TFrom ? ResolveFromAllParams<TRouter, TParamVariant> : RouteByPath<TRouter['routeTree'], TFrom>['types'][ResolveFromParamType<TParamVariant>];
|
||||
type ResolveToParamType<TParamVariant extends ParamVariant> = TParamVariant extends 'PATH' ? 'allParams' : 'fullSearchSchemaInput';
|
||||
type ResolveAllToParams<TRouter extends AnyRouter, TParamVariant extends ParamVariant> = TParamVariant extends 'PATH' ? AllParams<TRouter['routeTree']> : FullSearchSchemaInput<TRouter['routeTree']>;
|
||||
export type ResolveToParams<TRouter extends AnyRouter, TParamVariant extends ParamVariant, TFrom, TTo> = ResolveRelativePath<TFrom, TTo> extends infer TPath ? undefined extends TPath ? never : string extends TPath ? ResolveAllToParams<TRouter, TParamVariant> : TPath extends CatchAllPaths<TRouter> ? ResolveAllToParams<TRouter, TParamVariant> : ResolveRoute<TRouter, TFrom, TTo>['types'][ResolveToParamType<TParamVariant>] : never;
|
||||
type ResolveRelativeToParams<TRouter extends AnyRouter, TParamVariant extends ParamVariant, TFrom, TTo, TToParams = ResolveToParams<TRouter, TParamVariant, TFrom, TTo>> = TParamVariant extends 'SEARCH' ? TToParams : string extends TFrom ? TToParams : MakeDifferenceOptional<ResolveFromParams<TRouter, TParamVariant, TFrom>, TToParams>;
|
||||
export interface MakeOptionalSearchParams<in out TRouter extends AnyRouter, in out TFrom, in out TTo> {
|
||||
search?: true | (ParamsReducer<TRouter, 'SEARCH', TFrom, TTo> & {});
|
||||
}
|
||||
export interface MakeOptionalPathParams<in out TRouter extends AnyRouter, in out TFrom, in out TTo> {
|
||||
params?: true | (ParamsReducer<TRouter, 'PATH', TFrom, TTo> & {});
|
||||
}
|
||||
type MakeRequiredParamsReducer<TRouter extends AnyRouter, TParamVariant extends ParamVariant, TFrom, TTo> = (string extends TFrom ? never : ResolveFromParams<TRouter, TParamVariant, TFrom> extends WithoutEmpty<PickRequired<ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>>> ? true : never) | (ParamsReducer<TRouter, TParamVariant, TFrom, TTo> & {});
|
||||
export interface MakeRequiredPathParams<in out TRouter extends AnyRouter, in out TFrom, in out TTo> {
|
||||
params: MakeRequiredParamsReducer<TRouter, 'PATH', TFrom, TTo> & {};
|
||||
}
|
||||
export interface MakeRequiredSearchParams<in out TRouter extends AnyRouter, in out TFrom, in out TTo> {
|
||||
search: MakeRequiredParamsReducer<TRouter, 'SEARCH', TFrom, TTo> & {};
|
||||
}
|
||||
export type IsRequired<TRouter extends AnyRouter, TParamVariant extends ParamVariant, TFrom, TTo> = ResolveRelativePath<TFrom, TTo> extends infer TPath ? undefined extends TPath ? never : TPath extends CatchAllPaths<TRouter> ? never : IsRequiredParams<ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>> : never;
|
||||
export type SearchParamOptions<TRouter extends AnyRouter, TFrom, TTo> = IsRequired<TRouter, 'SEARCH', TFrom, TTo> extends never ? MakeOptionalSearchParams<TRouter, TFrom, TTo> : MakeRequiredSearchParams<TRouter, TFrom, TTo>;
|
||||
export type PathParamOptions<TRouter extends AnyRouter, TFrom, TTo> = IsRequired<TRouter, 'PATH', TFrom, TTo> extends never ? MakeOptionalPathParams<TRouter, TFrom, TTo> : MakeRequiredPathParams<TRouter, TFrom, TTo>;
|
||||
export type ToPathOption<TRouter extends AnyRouter = AnyRouter, TFrom extends string = string, TTo extends string | undefined = string> = ConstrainLiteral<TTo, RelativeToPathAutoComplete<TRouter, NoInfer<TFrom> extends string ? NoInfer<TFrom> : '', NoInfer<TTo> & string>>;
|
||||
export type FromPathOption<TRouter extends AnyRouter, TFrom> = ConstrainLiteral<TFrom, RoutePaths<TRouter['routeTree']>>;
|
||||
/**
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/navigation#active-options)
|
||||
*/
|
||||
export interface ActiveOptions {
|
||||
/**
|
||||
* If true, the link will be active if the current route matches the `to` route path exactly (no children routes)
|
||||
* @default false
|
||||
*/
|
||||
exact?: boolean;
|
||||
/**
|
||||
* If true, the link will only be active if the current URL hash matches the `hash` prop
|
||||
* @default false
|
||||
*/
|
||||
includeHash?: boolean;
|
||||
/**
|
||||
* If true, the link will only be active if the current URL search params inclusively match the `search` prop
|
||||
* @default true
|
||||
*/
|
||||
includeSearch?: boolean;
|
||||
/**
|
||||
* This modifies the `includeSearch` behavior.
|
||||
* If true, properties in `search` that are explicitly `undefined` must NOT be present in the current URL search params for the link to be active.
|
||||
* @default false
|
||||
*/
|
||||
explicitUndefined?: boolean;
|
||||
}
|
||||
export interface LinkOptionsProps {
|
||||
/**
|
||||
* The standard anchor tag target attribute
|
||||
*/
|
||||
target?: HTMLAnchorElement['target'];
|
||||
/**
|
||||
* Configurable options to determine if the link should be considered active or not
|
||||
* @default {exact:true,includeHash:true}
|
||||
*/
|
||||
activeOptions?: ActiveOptions;
|
||||
/**
|
||||
* The preloading strategy for this link
|
||||
* - `false` - No preloading
|
||||
* - `'intent'` - Preload the linked route on hover and cache it for this many milliseconds in hopes that the user will eventually navigate there.
|
||||
* - `'viewport'` - Preload the linked route when it enters the viewport
|
||||
*/
|
||||
preload?: false | 'intent' | 'viewport' | 'render';
|
||||
/**
|
||||
* When a preload strategy is set, this delays the preload by this many milliseconds.
|
||||
* If the user exits the link before this delay, the preload will be cancelled.
|
||||
*/
|
||||
preloadDelay?: number;
|
||||
/**
|
||||
* Control whether the link should be disabled or not
|
||||
* If set to `true`, the link will be rendered without an `href` attribute
|
||||
* @default false
|
||||
*/
|
||||
disabled?: boolean;
|
||||
}
|
||||
export type LinkOptions<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = '.', TMaskFrom extends string = TFrom, TMaskTo extends string = '.'> = NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & LinkOptionsProps;
|
||||
export type LinkCurrentTargetElement = {
|
||||
preloadTimeout?: null | ReturnType<typeof setTimeout>;
|
||||
};
|
||||
export declare const preloadWarning = "Error preloading route! \u261D\uFE0F";
|
||||
export {};
|
||||
Binary file not shown.
@@ -0,0 +1,123 @@
|
||||
"use strict";
|
||||
|
||||
var _utils = require("./utils.js");
|
||||
(0, _utils.default)("ArgumentPlaceholder", {});
|
||||
(0, _utils.default)("BindExpression", {
|
||||
visitor: ["object", "callee"],
|
||||
aliases: ["Expression"],
|
||||
fields: !process.env.BABEL_TYPES_8_BREAKING ? {
|
||||
object: {
|
||||
validate: Object.assign(() => {}, {
|
||||
oneOfNodeTypes: ["Expression"]
|
||||
})
|
||||
},
|
||||
callee: {
|
||||
validate: Object.assign(() => {}, {
|
||||
oneOfNodeTypes: ["Expression"]
|
||||
})
|
||||
}
|
||||
} : {
|
||||
object: {
|
||||
validate: (0, _utils.assertNodeType)("Expression")
|
||||
},
|
||||
callee: {
|
||||
validate: (0, _utils.assertNodeType)("Expression")
|
||||
}
|
||||
}
|
||||
});
|
||||
(0, _utils.default)("Decorator", {
|
||||
visitor: ["expression"],
|
||||
fields: {
|
||||
expression: {
|
||||
validate: (0, _utils.assertNodeType)("Expression")
|
||||
}
|
||||
}
|
||||
});
|
||||
(0, _utils.default)("DoExpression", {
|
||||
visitor: ["body"],
|
||||
builder: ["body", "async"],
|
||||
aliases: ["Expression"],
|
||||
fields: {
|
||||
body: {
|
||||
validate: (0, _utils.assertNodeType)("BlockStatement")
|
||||
},
|
||||
async: {
|
||||
validate: (0, _utils.assertValueType)("boolean"),
|
||||
default: false
|
||||
}
|
||||
}
|
||||
});
|
||||
(0, _utils.default)("ExportDefaultSpecifier", {
|
||||
visitor: ["exported"],
|
||||
aliases: ["ModuleSpecifier"],
|
||||
fields: {
|
||||
exported: {
|
||||
validate: (0, _utils.assertNodeType)("Identifier")
|
||||
}
|
||||
}
|
||||
});
|
||||
(0, _utils.default)("RecordExpression", {
|
||||
visitor: ["properties"],
|
||||
aliases: ["Expression"],
|
||||
fields: {
|
||||
properties: (0, _utils.validateArrayOfType)("ObjectProperty", "SpreadElement")
|
||||
}
|
||||
});
|
||||
(0, _utils.default)("TupleExpression", {
|
||||
fields: {
|
||||
elements: {
|
||||
validate: (0, _utils.arrayOfType)("Expression", "SpreadElement"),
|
||||
default: []
|
||||
}
|
||||
},
|
||||
visitor: ["elements"],
|
||||
aliases: ["Expression"]
|
||||
});
|
||||
{
|
||||
(0, _utils.default)("DecimalLiteral", {
|
||||
builder: ["value"],
|
||||
fields: {
|
||||
value: {
|
||||
validate: (0, _utils.assertValueType)("string")
|
||||
}
|
||||
},
|
||||
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
|
||||
});
|
||||
}
|
||||
(0, _utils.default)("ModuleExpression", {
|
||||
visitor: ["body"],
|
||||
fields: {
|
||||
body: {
|
||||
validate: (0, _utils.assertNodeType)("Program")
|
||||
}
|
||||
},
|
||||
aliases: ["Expression"]
|
||||
});
|
||||
(0, _utils.default)("TopicReference", {
|
||||
aliases: ["Expression"]
|
||||
});
|
||||
(0, _utils.default)("PipelineTopicExpression", {
|
||||
builder: ["expression"],
|
||||
visitor: ["expression"],
|
||||
fields: {
|
||||
expression: {
|
||||
validate: (0, _utils.assertNodeType)("Expression")
|
||||
}
|
||||
},
|
||||
aliases: ["Expression"]
|
||||
});
|
||||
(0, _utils.default)("PipelineBareFunction", {
|
||||
builder: ["callee"],
|
||||
visitor: ["callee"],
|
||||
fields: {
|
||||
callee: {
|
||||
validate: (0, _utils.assertNodeType)("Expression")
|
||||
}
|
||||
},
|
||||
aliases: ["Expression"]
|
||||
});
|
||||
(0, _utils.default)("PipelinePrimaryTopicReference", {
|
||||
aliases: ["Expression"]
|
||||
});
|
||||
|
||||
//# sourceMappingURL=experimental.js.map
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = _skipFirstGeneratorNext;
|
||||
function _skipFirstGeneratorNext(fn) {
|
||||
return function () {
|
||||
var it = fn.apply(this, arguments);
|
||||
it.next();
|
||||
return it;
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=skipFirstGeneratorNext.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"urn-uuid.js","sourceRoot":"","sources":["../../../src/schemes/urn-uuid.ts"],"names":[],"mappings":"AAQA,MAAM,IAAI,GAAG,0DAA0D,CAAC;AACxE,MAAM,UAAU,GAAG,oBAAoB,CAAC;AAExC,UAAU;AACV,MAAM,OAAO,GAA+D;IAC3E,MAAM,EAAG,UAAU;IAEnB,KAAK,EAAG,UAAU,aAA2B,EAAE,OAAkB;QAChE,MAAM,cAAc,GAAG,aAA+B,CAAC;QACvD,cAAc,CAAC,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC;QACzC,cAAc,CAAC,GAAG,GAAG,SAAS,CAAC;QAE/B,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC,cAAc,CAAC,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE;YACpF,cAAc,CAAC,KAAK,GAAG,cAAc,CAAC,KAAK,IAAI,oBAAoB,CAAC;SACpE;QAED,OAAO,cAAc,CAAC;IACvB,CAAC;IAED,SAAS,EAAG,UAAU,cAA6B,EAAE,OAAkB;QACtE,MAAM,aAAa,GAAG,cAA+B,CAAC;QACtD,gBAAgB;QAChB,aAAa,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9D,OAAO,aAAa,CAAC;IACtB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { default as default2 } from "tiny-invariant";
|
||||
import { default as default3 } from "tiny-warning";
|
||||
import { PathParamError, SearchParamError, TSR_DEFERRED_PROMISE, cleanPath, componentTypes, createControlledPromise, decode, deepEqual, defaultParseSearch, defaultSerializeError, defaultStringifySearch, defer, encode, escapeJSON, functionalUpdate, getInitialRouterState, interpolatePath, isMatch, isNotFound, isPlainArray, isPlainObject, isRedirect, joinPaths, lazyFn, matchByPath, matchPathname, notFound, parsePathname, parseSearchWith, pick, redirect, removeBasepath, replaceEqualDeep, resolvePath, retainSearchParams, rootRouteId, shallow, stringifySearchWith, stripSearchParams, trimPath, trimPathLeft, trimPathRight } from "@tanstack/router-core";
|
||||
import { createBrowserHistory, createHashHistory, createHistory, createMemoryHistory } from "@tanstack/history";
|
||||
import { Await, useAwaited } from "./awaited.js";
|
||||
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
|
||||
import { FileRoute, FileRouteLoader, LazyRoute, createFileRoute, createLazyFileRoute, createLazyRoute } from "./fileRoute.js";
|
||||
import { lazyRouteComponent } from "./lazyRouteComponent.js";
|
||||
import { Link, createLink, linkOptions, useLinkProps } from "./link.js";
|
||||
import { MatchRoute, Matches, useChildMatches, useMatchRoute, useMatches, useParentMatches } from "./Matches.js";
|
||||
import { matchContext } from "./matchContext.js";
|
||||
import { Match, Outlet } from "./Match.js";
|
||||
import { useMatch } from "./useMatch.js";
|
||||
import { useLoaderDeps } from "./useLoaderDeps.js";
|
||||
import { useLoaderData } from "./useLoaderData.js";
|
||||
import { NotFoundRoute, RootRoute, Route, RouteApi, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, getRouteApi, rootRouteWithContext } from "./route.js";
|
||||
import { Router, createRouter } from "./router.js";
|
||||
import { RouterContextProvider, RouterProvider } from "./RouterProvider.js";
|
||||
import { ScrollRestoration, useElementScrollRestoration } from "./ScrollRestoration.js";
|
||||
import { Block, useBlocker } from "./useBlocker.js";
|
||||
import { Navigate, useNavigate } from "./useNavigate.js";
|
||||
import { useParams } from "./useParams.js";
|
||||
import { useSearch } from "./useSearch.js";
|
||||
import { getRouterContext } from "./routerContext.js";
|
||||
import { useRouteContext } from "./useRouteContext.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { useRouterState } from "./useRouterState.js";
|
||||
import { useLocation } from "./useLocation.js";
|
||||
import { useCanGoBack } from "./useCanGoBack.js";
|
||||
import { useLayoutEffect, useStableCallback } from "./utils.js";
|
||||
import { CatchNotFound, DefaultGlobalNotFound } from "./not-found.js";
|
||||
import { ScriptOnce } from "./ScriptOnce.js";
|
||||
import { Asset } from "./Asset.js";
|
||||
import { HeadContent } from "./HeadContent.js";
|
||||
import { Scripts } from "./Scripts.js";
|
||||
export {
|
||||
Asset,
|
||||
Await,
|
||||
Block,
|
||||
CatchBoundary,
|
||||
CatchNotFound,
|
||||
DefaultGlobalNotFound,
|
||||
ErrorComponent,
|
||||
FileRoute,
|
||||
FileRouteLoader,
|
||||
HeadContent,
|
||||
LazyRoute,
|
||||
Link,
|
||||
Match,
|
||||
MatchRoute,
|
||||
Matches,
|
||||
Navigate,
|
||||
NotFoundRoute,
|
||||
Outlet,
|
||||
PathParamError,
|
||||
RootRoute,
|
||||
Route,
|
||||
RouteApi,
|
||||
Router,
|
||||
RouterContextProvider,
|
||||
RouterProvider,
|
||||
ScriptOnce,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
SearchParamError,
|
||||
TSR_DEFERRED_PROMISE,
|
||||
cleanPath,
|
||||
componentTypes,
|
||||
createBrowserHistory,
|
||||
createControlledPromise,
|
||||
createFileRoute,
|
||||
createHashHistory,
|
||||
createHistory,
|
||||
createLazyFileRoute,
|
||||
createLazyRoute,
|
||||
createLink,
|
||||
createMemoryHistory,
|
||||
createRootRoute,
|
||||
createRootRouteWithContext,
|
||||
createRoute,
|
||||
createRouteMask,
|
||||
createRouter,
|
||||
decode,
|
||||
deepEqual,
|
||||
defaultParseSearch,
|
||||
defaultSerializeError,
|
||||
defaultStringifySearch,
|
||||
defer,
|
||||
encode,
|
||||
escapeJSON,
|
||||
functionalUpdate,
|
||||
getInitialRouterState,
|
||||
getRouteApi,
|
||||
getRouterContext,
|
||||
interpolatePath,
|
||||
default2 as invariant,
|
||||
isMatch,
|
||||
isNotFound,
|
||||
isPlainArray,
|
||||
isPlainObject,
|
||||
isRedirect,
|
||||
joinPaths,
|
||||
lazyFn,
|
||||
lazyRouteComponent,
|
||||
linkOptions,
|
||||
matchByPath,
|
||||
matchContext,
|
||||
matchPathname,
|
||||
notFound,
|
||||
parsePathname,
|
||||
parseSearchWith,
|
||||
pick,
|
||||
redirect,
|
||||
removeBasepath,
|
||||
replaceEqualDeep,
|
||||
resolvePath,
|
||||
retainSearchParams,
|
||||
rootRouteId,
|
||||
rootRouteWithContext,
|
||||
shallow,
|
||||
stringifySearchWith,
|
||||
stripSearchParams,
|
||||
trimPath,
|
||||
trimPathLeft,
|
||||
trimPathRight,
|
||||
useAwaited,
|
||||
useBlocker,
|
||||
useCanGoBack,
|
||||
useChildMatches,
|
||||
useElementScrollRestoration,
|
||||
useLayoutEffect,
|
||||
useLinkProps,
|
||||
useLoaderData,
|
||||
useLoaderDeps,
|
||||
useLocation,
|
||||
useMatch,
|
||||
useMatchRoute,
|
||||
useMatches,
|
||||
useNavigate,
|
||||
useParams,
|
||||
useParentMatches,
|
||||
useRouteContext,
|
||||
useRouter,
|
||||
useRouterState,
|
||||
useSearch,
|
||||
useStableCallback,
|
||||
default3 as warning
|
||||
};
|
||||
//# sourceMappingURL=index.js.map
|
||||
@@ -0,0 +1,494 @@
|
||||
/**
|
||||
* @fileoverview Rule to enforce return statements in callbacks of array's methods
|
||||
* @author Toru Nagashima
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
|
||||
const TARGET_METHODS =
|
||||
/^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort|toSorted)$/u;
|
||||
|
||||
/**
|
||||
* Checks a given node is a member access which has the specified name's
|
||||
* property.
|
||||
* @param {ASTNode} node A node to check.
|
||||
* @returns {boolean} `true` if the node is a member access which has
|
||||
* the specified name's property. The node may be a `(Chain|Member)Expression` node.
|
||||
*/
|
||||
function isTargetMethod(node) {
|
||||
return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks all segments in a set and returns true if any are reachable.
|
||||
* @param {Set<CodePathSegment>} segments The segments to check.
|
||||
* @returns {boolean} True if any segment is reachable; false otherwise.
|
||||
*/
|
||||
function isAnySegmentReachable(segments) {
|
||||
for (const segment of segments) {
|
||||
if (segment.reachable) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a human-legible description of an array method
|
||||
* @param {string} arrayMethodName A method name to fully qualify
|
||||
* @returns {string} the method name prefixed with `Array.` if it is a class method,
|
||||
* or else `Array.prototype.` if it is an instance method.
|
||||
*/
|
||||
function fullMethodName(arrayMethodName) {
|
||||
if (["from", "of", "isArray"].includes(arrayMethodName)) {
|
||||
return "Array.".concat(arrayMethodName);
|
||||
}
|
||||
return "Array.prototype.".concat(arrayMethodName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether or not a given node is a function expression which is the
|
||||
* callback of an array method, returning the method name.
|
||||
* @param {ASTNode} node A node to check. This is one of
|
||||
* FunctionExpression or ArrowFunctionExpression.
|
||||
* @returns {string} The method name if the node is a callback method,
|
||||
* null otherwise.
|
||||
*/
|
||||
function getArrayMethodName(node) {
|
||||
let currentNode = node;
|
||||
|
||||
while (currentNode) {
|
||||
const parent = currentNode.parent;
|
||||
|
||||
switch (parent.type) {
|
||||
/*
|
||||
* Looks up the destination. e.g.,
|
||||
* foo.every(nativeFoo || function foo() { ... });
|
||||
*/
|
||||
case "LogicalExpression":
|
||||
case "ConditionalExpression":
|
||||
case "ChainExpression":
|
||||
currentNode = parent;
|
||||
break;
|
||||
|
||||
/*
|
||||
* If the upper function is IIFE, checks the destination of the return value.
|
||||
* e.g.
|
||||
* foo.every((function() {
|
||||
* // setup...
|
||||
* return function callback() { ... };
|
||||
* })());
|
||||
*/
|
||||
case "ReturnStatement": {
|
||||
const func = astUtils.getUpperFunction(parent);
|
||||
|
||||
if (func === null || !astUtils.isCallee(func)) {
|
||||
return null;
|
||||
}
|
||||
currentNode = func.parent;
|
||||
break;
|
||||
}
|
||||
|
||||
/*
|
||||
* e.g.
|
||||
* Array.from([], function() {});
|
||||
* list.every(function() {});
|
||||
*/
|
||||
case "CallExpression":
|
||||
if (astUtils.isArrayFromMethod(parent.callee)) {
|
||||
if (
|
||||
parent.arguments.length >= 2 &&
|
||||
parent.arguments[1] === currentNode
|
||||
) {
|
||||
return "from";
|
||||
}
|
||||
}
|
||||
if (isTargetMethod(parent.callee)) {
|
||||
if (
|
||||
parent.arguments.length >= 1 &&
|
||||
parent.arguments[0] === currentNode
|
||||
) {
|
||||
return astUtils.getStaticPropertyName(parent.callee);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
// Otherwise this node is not target.
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* c8 ignore next */
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given node is a void expression.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} - `true` if the node is a void expression
|
||||
*/
|
||||
function isExpressionVoid(node) {
|
||||
return node.type === "UnaryExpression" && node.operator === "void";
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes the linting error by prepending "void " to the given node
|
||||
* @param {Object} sourceCode context given by context.sourceCode
|
||||
* @param {ASTNode} node The node to fix.
|
||||
* @param {Object} fixer The fixer object provided by ESLint.
|
||||
* @returns {Array<Object>} - An array of fix objects to apply to the node.
|
||||
*/
|
||||
function voidPrependFixer(sourceCode, node, fixer) {
|
||||
const requiresParens =
|
||||
// prepending `void ` will fail if the node has a lower precedence than void
|
||||
astUtils.getPrecedence(node) <
|
||||
astUtils.getPrecedence({
|
||||
type: "UnaryExpression",
|
||||
operator: "void",
|
||||
}) &&
|
||||
// check if there are parentheses around the node to avoid redundant parentheses
|
||||
!astUtils.isParenthesised(sourceCode, node);
|
||||
|
||||
// avoid parentheses issues
|
||||
const returnOrArrowToken = sourceCode.getTokenBefore(
|
||||
node,
|
||||
node.parent.type === "ArrowFunctionExpression"
|
||||
? astUtils.isArrowToken
|
||||
: // isReturnToken
|
||||
token => token.type === "Keyword" && token.value === "return",
|
||||
);
|
||||
|
||||
const firstToken = sourceCode.getTokenAfter(returnOrArrowToken);
|
||||
|
||||
const prependSpace =
|
||||
// is return token, as => allows void to be adjacent
|
||||
returnOrArrowToken.value === "return" &&
|
||||
// If two tokens (return and "(") are adjacent
|
||||
returnOrArrowToken.range[1] === firstToken.range[0];
|
||||
|
||||
return [
|
||||
fixer.insertTextBefore(
|
||||
firstToken,
|
||||
`${prependSpace ? " " : ""}void ${requiresParens ? "(" : ""}`,
|
||||
),
|
||||
fixer.insertTextAfter(node, requiresParens ? ")" : ""),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes the linting error by `wrapping {}` around the given node's body.
|
||||
* @param {Object} sourceCode context given by context.sourceCode
|
||||
* @param {ASTNode} node The node to fix.
|
||||
* @param {Object} fixer The fixer object provided by ESLint.
|
||||
* @returns {Array<Object>} - An array of fix objects to apply to the node.
|
||||
*/
|
||||
function curlyWrapFixer(sourceCode, node, fixer) {
|
||||
const arrowToken = sourceCode.getTokenBefore(
|
||||
node.body,
|
||||
astUtils.isArrowToken,
|
||||
);
|
||||
const firstToken = sourceCode.getTokenAfter(arrowToken);
|
||||
const lastToken = sourceCode.getLastToken(node);
|
||||
|
||||
return [
|
||||
fixer.insertTextBefore(firstToken, "{"),
|
||||
fixer.insertTextAfter(lastToken, "}"),
|
||||
];
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../shared/types').Rule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "problem",
|
||||
|
||||
defaultOptions: [
|
||||
{
|
||||
allowImplicit: false,
|
||||
checkForEach: false,
|
||||
allowVoid: false,
|
||||
},
|
||||
],
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Enforce `return` statements in callbacks of array methods",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/array-callback-return",
|
||||
},
|
||||
|
||||
// eslint-disable-next-line eslint-plugin/require-meta-has-suggestions -- false positive
|
||||
hasSuggestions: true,
|
||||
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
allowImplicit: {
|
||||
type: "boolean",
|
||||
},
|
||||
checkForEach: {
|
||||
type: "boolean",
|
||||
},
|
||||
allowVoid: {
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
expectedAtEnd:
|
||||
"{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.",
|
||||
expectedInside:
|
||||
"{{arrayMethodName}}() expects a return value from {{name}}.",
|
||||
expectedReturnValue:
|
||||
"{{arrayMethodName}}() expects a return value from {{name}}.",
|
||||
expectedNoReturnValue:
|
||||
"{{arrayMethodName}}() expects no useless return value from {{name}}.",
|
||||
wrapBraces: "Wrap the expression in `{}`.",
|
||||
prependVoid: "Prepend `void` to the expression.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const [options] = context.options;
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
let funcInfo = {
|
||||
arrayMethodName: null,
|
||||
upper: null,
|
||||
codePath: null,
|
||||
hasReturn: false,
|
||||
shouldCheck: false,
|
||||
node: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks whether or not the last code path segment is reachable.
|
||||
* Then reports this function if the segment is reachable.
|
||||
*
|
||||
* If the last code path segment is reachable, there are paths which are not
|
||||
* returned or thrown.
|
||||
* @param {ASTNode} node A node to check.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkLastSegment(node) {
|
||||
if (!funcInfo.shouldCheck) {
|
||||
return;
|
||||
}
|
||||
|
||||
const messageAndSuggestions = { messageId: "", suggest: [] };
|
||||
|
||||
if (funcInfo.arrayMethodName === "forEach") {
|
||||
if (
|
||||
options.checkForEach &&
|
||||
node.type === "ArrowFunctionExpression" &&
|
||||
node.expression
|
||||
) {
|
||||
if (options.allowVoid) {
|
||||
if (isExpressionVoid(node.body)) {
|
||||
return;
|
||||
}
|
||||
|
||||
messageAndSuggestions.messageId =
|
||||
"expectedNoReturnValue";
|
||||
messageAndSuggestions.suggest = [
|
||||
{
|
||||
messageId: "wrapBraces",
|
||||
fix(fixer) {
|
||||
return curlyWrapFixer(
|
||||
sourceCode,
|
||||
node,
|
||||
fixer,
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
messageId: "prependVoid",
|
||||
fix(fixer) {
|
||||
return voidPrependFixer(
|
||||
sourceCode,
|
||||
node.body,
|
||||
fixer,
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
} else {
|
||||
messageAndSuggestions.messageId =
|
||||
"expectedNoReturnValue";
|
||||
messageAndSuggestions.suggest = [
|
||||
{
|
||||
messageId: "wrapBraces",
|
||||
fix(fixer) {
|
||||
return curlyWrapFixer(
|
||||
sourceCode,
|
||||
node,
|
||||
fixer,
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (
|
||||
node.body.type === "BlockStatement" &&
|
||||
isAnySegmentReachable(funcInfo.currentSegments)
|
||||
) {
|
||||
messageAndSuggestions.messageId = funcInfo.hasReturn
|
||||
? "expectedAtEnd"
|
||||
: "expectedInside";
|
||||
}
|
||||
}
|
||||
|
||||
if (messageAndSuggestions.messageId) {
|
||||
const name = astUtils.getFunctionNameWithKind(node);
|
||||
|
||||
context.report({
|
||||
node,
|
||||
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
|
||||
messageId: messageAndSuggestions.messageId,
|
||||
data: {
|
||||
name,
|
||||
arrayMethodName: fullMethodName(
|
||||
funcInfo.arrayMethodName,
|
||||
),
|
||||
},
|
||||
suggest:
|
||||
messageAndSuggestions.suggest.length !== 0
|
||||
? messageAndSuggestions.suggest
|
||||
: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
// Stacks this function's information.
|
||||
onCodePathStart(codePath, node) {
|
||||
let methodName = null;
|
||||
|
||||
if (TARGET_NODE_TYPE.test(node.type)) {
|
||||
methodName = getArrayMethodName(node);
|
||||
}
|
||||
|
||||
funcInfo = {
|
||||
arrayMethodName: methodName,
|
||||
upper: funcInfo,
|
||||
codePath,
|
||||
hasReturn: false,
|
||||
shouldCheck: methodName && !node.async && !node.generator,
|
||||
node,
|
||||
currentSegments: new Set(),
|
||||
};
|
||||
},
|
||||
|
||||
// Pops this function's information.
|
||||
onCodePathEnd() {
|
||||
funcInfo = funcInfo.upper;
|
||||
},
|
||||
|
||||
onUnreachableCodePathSegmentStart(segment) {
|
||||
funcInfo.currentSegments.add(segment);
|
||||
},
|
||||
|
||||
onUnreachableCodePathSegmentEnd(segment) {
|
||||
funcInfo.currentSegments.delete(segment);
|
||||
},
|
||||
|
||||
onCodePathSegmentStart(segment) {
|
||||
funcInfo.currentSegments.add(segment);
|
||||
},
|
||||
|
||||
onCodePathSegmentEnd(segment) {
|
||||
funcInfo.currentSegments.delete(segment);
|
||||
},
|
||||
|
||||
// Checks the return statement is valid.
|
||||
ReturnStatement(node) {
|
||||
if (!funcInfo.shouldCheck) {
|
||||
return;
|
||||
}
|
||||
|
||||
funcInfo.hasReturn = true;
|
||||
|
||||
const messageAndSuggestions = { messageId: "", suggest: [] };
|
||||
|
||||
if (funcInfo.arrayMethodName === "forEach") {
|
||||
// if checkForEach: true, returning a value at any path inside a forEach is not allowed
|
||||
if (options.checkForEach && node.argument) {
|
||||
if (options.allowVoid) {
|
||||
if (isExpressionVoid(node.argument)) {
|
||||
return;
|
||||
}
|
||||
|
||||
messageAndSuggestions.messageId =
|
||||
"expectedNoReturnValue";
|
||||
messageAndSuggestions.suggest = [
|
||||
{
|
||||
messageId: "prependVoid",
|
||||
fix(fixer) {
|
||||
return voidPrependFixer(
|
||||
sourceCode,
|
||||
node.argument,
|
||||
fixer,
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
} else {
|
||||
messageAndSuggestions.messageId =
|
||||
"expectedNoReturnValue";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// if allowImplicit: false, should also check node.argument
|
||||
if (!options.allowImplicit && !node.argument) {
|
||||
messageAndSuggestions.messageId = "expectedReturnValue";
|
||||
}
|
||||
}
|
||||
|
||||
if (messageAndSuggestions.messageId) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: messageAndSuggestions.messageId,
|
||||
data: {
|
||||
name: astUtils.getFunctionNameWithKind(
|
||||
funcInfo.node,
|
||||
),
|
||||
arrayMethodName: fullMethodName(
|
||||
funcInfo.arrayMethodName,
|
||||
),
|
||||
},
|
||||
suggest:
|
||||
messageAndSuggestions.suggest.length !== 0
|
||||
? messageAndSuggestions.suggest
|
||||
: null,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Reports a given function if the last path is reachable.
|
||||
"FunctionExpression:exit": checkLastSegment,
|
||||
"ArrowFunctionExpression:exit": checkLastSegment,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* @fileoverview enforce the location of single-line statements
|
||||
* @author Teddy Katz
|
||||
* @deprecated in ESLint v8.53.0
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const POSITION_SCHEMA = { enum: ["beside", "below", "any"] };
|
||||
|
||||
/** @type {import('../shared/types').Rule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
deprecated: {
|
||||
message: "Formatting rules are being moved out of ESLint core.",
|
||||
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
|
||||
deprecatedSince: "8.53.0",
|
||||
availableUntil: "10.0.0",
|
||||
replacedBy: [
|
||||
{
|
||||
message:
|
||||
"ESLint Stylistic now maintains deprecated stylistic core rules.",
|
||||
url: "https://eslint.style/guide/migration",
|
||||
plugin: {
|
||||
name: "@stylistic/eslint-plugin-js",
|
||||
url: "https://eslint.style/packages/js",
|
||||
},
|
||||
rule: {
|
||||
name: "nonblock-statement-body-position",
|
||||
url: "https://eslint.style/rules/js/nonblock-statement-body-position",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
type: "layout",
|
||||
|
||||
docs: {
|
||||
description: "Enforce the location of single-line statements",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/nonblock-statement-body-position",
|
||||
},
|
||||
|
||||
fixable: "whitespace",
|
||||
|
||||
schema: [
|
||||
POSITION_SCHEMA,
|
||||
{
|
||||
properties: {
|
||||
overrides: {
|
||||
properties: {
|
||||
if: POSITION_SCHEMA,
|
||||
else: POSITION_SCHEMA,
|
||||
while: POSITION_SCHEMA,
|
||||
do: POSITION_SCHEMA,
|
||||
for: POSITION_SCHEMA,
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
expectNoLinebreak: "Expected no linebreak before this statement.",
|
||||
expectLinebreak: "Expected a linebreak before this statement.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
// Helpers
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Gets the applicable preference for a particular keyword
|
||||
* @param {string} keywordName The name of a keyword, e.g. 'if'
|
||||
* @returns {string} The applicable option for the keyword, e.g. 'beside'
|
||||
*/
|
||||
function getOption(keywordName) {
|
||||
return (
|
||||
(context.options[1] &&
|
||||
context.options[1].overrides &&
|
||||
context.options[1].overrides[keywordName]) ||
|
||||
context.options[0] ||
|
||||
"beside"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the location of a single-line statement
|
||||
* @param {ASTNode} node The single-line statement
|
||||
* @param {string} keywordName The applicable keyword name for the single-line statement
|
||||
* @returns {void}
|
||||
*/
|
||||
function validateStatement(node, keywordName) {
|
||||
const option = getOption(keywordName);
|
||||
|
||||
if (node.type === "BlockStatement" || option === "any") {
|
||||
return;
|
||||
}
|
||||
|
||||
const tokenBefore = sourceCode.getTokenBefore(node);
|
||||
|
||||
if (
|
||||
tokenBefore.loc.end.line === node.loc.start.line &&
|
||||
option === "below"
|
||||
) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "expectLinebreak",
|
||||
fix: fixer => fixer.insertTextBefore(node, "\n"),
|
||||
});
|
||||
} else if (
|
||||
tokenBefore.loc.end.line !== node.loc.start.line &&
|
||||
option === "beside"
|
||||
) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "expectNoLinebreak",
|
||||
fix(fixer) {
|
||||
if (
|
||||
sourceCode
|
||||
.getText()
|
||||
.slice(tokenBefore.range[1], node.range[0])
|
||||
.trim()
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return fixer.replaceTextRange(
|
||||
[tokenBefore.range[1], node.range[0]],
|
||||
" ",
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
// Public
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
IfStatement(node) {
|
||||
validateStatement(node.consequent, "if");
|
||||
|
||||
// Check the `else` node, but don't check 'else if' statements.
|
||||
if (node.alternate && node.alternate.type !== "IfStatement") {
|
||||
validateStatement(node.alternate, "else");
|
||||
}
|
||||
},
|
||||
WhileStatement: node => validateStatement(node.body, "while"),
|
||||
DoWhileStatement: node => validateStatement(node.body, "do"),
|
||||
ForStatement: node => validateStatement(node.body, "for"),
|
||||
ForInStatement: node => validateStatement(node.body, "for"),
|
||||
ForOfStatement: node => validateStatement(node.body, "for"),
|
||||
};
|
||||
},
|
||||
};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* @typedef {import('./types').Jiti} Jiti
|
||||
* @typedef {import('./types').JitiOptions} JitiOptions
|
||||
*/
|
||||
|
||||
const isDeno = "Deno" in globalThis;
|
||||
|
||||
/**
|
||||
* @param {string|URL} [parentURL]
|
||||
* @param {JitiOptions} [jitiOptions]
|
||||
* @returns {Jiti}
|
||||
*/
|
||||
export function createJiti(parentURL, jitiOptions) {
|
||||
parentURL = normalizeParentURL(parentURL);
|
||||
|
||||
/** @type {Jiti} */
|
||||
function jiti() {
|
||||
throw unsupportedError(
|
||||
"`jiti()` is not supported in native mode, use `jiti.import()` instead.",
|
||||
);
|
||||
}
|
||||
|
||||
jiti.resolve = () => {
|
||||
throw unsupportedError("`jiti.resolve()` is not supported in native mode.");
|
||||
};
|
||||
|
||||
jiti.esmResolve = (id, opts) => {
|
||||
try {
|
||||
const importMeta = jitiOptions?.importMeta || import.meta;
|
||||
if (isDeno) {
|
||||
// Deno throws TypeError: Invalid arguments when passing parentURL
|
||||
return importMeta.resolve(id);
|
||||
}
|
||||
const parent = normalizeParentURL(opts?.parentURL || parentURL);
|
||||
return importMeta.resolve(id, parent);
|
||||
} catch (error) {
|
||||
if (opts?.try) {
|
||||
return undefined;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
jiti.import = async function (id, opts) {
|
||||
for (const suffix of ["", "/index"]) {
|
||||
// prettier-ignore
|
||||
for (const ext of ["", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts"]) {
|
||||
try {
|
||||
const resolved = this.esmResolve(id + suffix + ext, opts);
|
||||
if (!resolved) {
|
||||
continue;
|
||||
}
|
||||
let importAttrs = undefined
|
||||
if (resolved.endsWith('.json')) {
|
||||
importAttrs = { with: { type: 'json'}}
|
||||
}
|
||||
return await import(resolved, importAttrs);
|
||||
} catch (error) {
|
||||
if (error.code === 'ERR_MODULE_NOT_FOUND' || error.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
|
||||
continue
|
||||
}
|
||||
if (opts?.try) {
|
||||
return undefined;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!opts?.try) {
|
||||
const parent = normalizeParentURL(opts?.parentURL || parentURL);
|
||||
const error = new Error(
|
||||
`[jiti] [ERR_MODULE_NOT_FOUND] Cannot import '${id}' from '${parent}'.`,
|
||||
);
|
||||
error.code = "ERR_MODULE_NOT_FOUND";
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
jiti.transform = () => {
|
||||
throw unsupportedError(
|
||||
"`jiti.transform()` is not supported in native mode.",
|
||||
);
|
||||
};
|
||||
|
||||
jiti.evalModule = () => {
|
||||
throw unsupportedError(
|
||||
"`jiti.evalModule()` is not supported in native mode.",
|
||||
);
|
||||
};
|
||||
|
||||
jiti.main = undefined;
|
||||
jiti.extensions = Object.create(null);
|
||||
jiti.cache = Object.create(null);
|
||||
|
||||
return jiti;
|
||||
}
|
||||
|
||||
export default createJiti;
|
||||
|
||||
/**
|
||||
* @param {string} message
|
||||
*/
|
||||
function unsupportedError(message) {
|
||||
throw new Error(
|
||||
`[jiti] ${message} (import or require 'jiti' instead of 'jiti/native' for more features).`,
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeParentURL(input) {
|
||||
if (!input) {
|
||||
return "file:///";
|
||||
}
|
||||
if (typeof filename !== "string" || input.startsWith("file://")) {
|
||||
return input;
|
||||
}
|
||||
if (input.endsWith("/")) {
|
||||
input += "_"; // append a dummy filename
|
||||
}
|
||||
return `file://${input}`;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"SafeFragment.cjs","sources":["../../src/SafeFragment.tsx"],"sourcesContent":["import * as React from 'react'\n\nexport function SafeFragment(props: any) {\n return <>{props.children}</>\n}\n"],"names":["jsx","Fragment"],"mappings":";;;AAEO,SAAS,aAAa,OAAY;AAChC,SAAAA,2BAAAA,IAAAC,WAAAA,UAAA,EAAG,gBAAM,SAAS,CAAA;AAC3B;;"}
|
||||
@@ -0,0 +1,822 @@
|
||||
import { P as getDefaultExportFromCjs } from './dep-Pj_jxEzN.js';
|
||||
import require$$0 from 'path';
|
||||
import { l as lib } from './dep-3RmXg9uo.js';
|
||||
|
||||
import { createRequire as __cjs_createRequire } from 'node:module';
|
||||
|
||||
const __require = __cjs_createRequire(import.meta.url);
|
||||
function _mergeNamespaces(n, m) {
|
||||
for (var i = 0; i < m.length; i++) {
|
||||
var e = m[i];
|
||||
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
|
||||
if (k !== 'default' && !(k in n)) {
|
||||
n[k] = e[k];
|
||||
}
|
||||
} }
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
var formatImportPrelude$2 = function formatImportPrelude(layer, media, supports) {
|
||||
const parts = [];
|
||||
|
||||
if (typeof layer !== "undefined") {
|
||||
let layerParams = "layer";
|
||||
if (layer) {
|
||||
layerParams = `layer(${layer})`;
|
||||
}
|
||||
|
||||
parts.push(layerParams);
|
||||
}
|
||||
|
||||
if (typeof supports !== "undefined") {
|
||||
parts.push(`supports(${supports})`);
|
||||
}
|
||||
|
||||
if (typeof media !== "undefined") {
|
||||
parts.push(media);
|
||||
}
|
||||
|
||||
return parts.join(" ")
|
||||
};
|
||||
|
||||
const formatImportPrelude$1 = formatImportPrelude$2;
|
||||
|
||||
// Base64 encode an import with conditions
|
||||
// The order of conditions is important and is interleaved with cascade layer declarations
|
||||
// Each group of conditions and cascade layers needs to be interpreted in order
|
||||
// To achieve this we create a list of base64 encoded imports, where each import contains a stylesheet with another import.
|
||||
// Each import can define a single group of conditions and a single cascade layer.
|
||||
var base64EncodedImport = function base64EncodedConditionalImport(prelude, conditions) {
|
||||
conditions.reverse();
|
||||
const first = conditions.pop();
|
||||
let params = `${prelude} ${formatImportPrelude$1(
|
||||
first.layer,
|
||||
first.media,
|
||||
first.supports,
|
||||
)}`;
|
||||
|
||||
for (const condition of conditions) {
|
||||
params = `'data:text/css;base64,${Buffer.from(`@import ${params}`).toString(
|
||||
"base64",
|
||||
)}' ${formatImportPrelude$1(
|
||||
condition.layer,
|
||||
condition.media,
|
||||
condition.supports,
|
||||
)}`;
|
||||
}
|
||||
|
||||
return params
|
||||
};
|
||||
|
||||
const base64EncodedConditionalImport = base64EncodedImport;
|
||||
|
||||
var applyConditions$1 = function applyConditions(bundle, atRule) {
|
||||
bundle.forEach(stmt => {
|
||||
if (
|
||||
stmt.type === "charset" ||
|
||||
stmt.type === "warning" ||
|
||||
!stmt.conditions?.length
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (stmt.type === "import") {
|
||||
stmt.node.params = base64EncodedConditionalImport(
|
||||
stmt.fullUri,
|
||||
stmt.conditions,
|
||||
);
|
||||
return
|
||||
}
|
||||
|
||||
const { nodes } = stmt;
|
||||
const { parent } = nodes[0];
|
||||
|
||||
const atRules = [];
|
||||
|
||||
// Convert conditions to at-rules
|
||||
for (const condition of stmt.conditions) {
|
||||
if (typeof condition.media !== "undefined") {
|
||||
const mediaNode = atRule({
|
||||
name: "media",
|
||||
params: condition.media,
|
||||
source: parent.source,
|
||||
});
|
||||
|
||||
atRules.push(mediaNode);
|
||||
}
|
||||
|
||||
if (typeof condition.supports !== "undefined") {
|
||||
const supportsNode = atRule({
|
||||
name: "supports",
|
||||
params: `(${condition.supports})`,
|
||||
source: parent.source,
|
||||
});
|
||||
|
||||
atRules.push(supportsNode);
|
||||
}
|
||||
|
||||
if (typeof condition.layer !== "undefined") {
|
||||
const layerNode = atRule({
|
||||
name: "layer",
|
||||
params: condition.layer,
|
||||
source: parent.source,
|
||||
});
|
||||
|
||||
atRules.push(layerNode);
|
||||
}
|
||||
}
|
||||
|
||||
// Add nodes to AST
|
||||
const outerAtRule = atRules.shift();
|
||||
const innerAtRule = atRules.reduce((previous, next) => {
|
||||
previous.append(next);
|
||||
return next
|
||||
}, outerAtRule);
|
||||
|
||||
parent.insertBefore(nodes[0], outerAtRule);
|
||||
|
||||
// remove nodes
|
||||
nodes.forEach(node => {
|
||||
node.parent = undefined;
|
||||
});
|
||||
|
||||
// better output
|
||||
nodes[0].raws.before = nodes[0].raws.before || "\n";
|
||||
|
||||
// wrap new rules with media query and/or layer at rule
|
||||
innerAtRule.append(nodes);
|
||||
|
||||
stmt.type = "nodes";
|
||||
stmt.nodes = [outerAtRule];
|
||||
delete stmt.node;
|
||||
});
|
||||
};
|
||||
|
||||
var applyRaws$1 = function applyRaws(bundle) {
|
||||
bundle.forEach((stmt, index) => {
|
||||
if (index === 0) return
|
||||
|
||||
if (stmt.parent) {
|
||||
const { before } = stmt.parent.node.raws;
|
||||
if (stmt.type === "nodes") stmt.nodes[0].raws.before = before;
|
||||
else stmt.node.raws.before = before;
|
||||
} else if (stmt.type === "nodes") {
|
||||
stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n";
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var applyStyles$1 = function applyStyles(bundle, styles) {
|
||||
styles.nodes = [];
|
||||
|
||||
// Strip additional statements.
|
||||
bundle.forEach(stmt => {
|
||||
if (["charset", "import"].includes(stmt.type)) {
|
||||
stmt.node.parent = undefined;
|
||||
styles.append(stmt.node);
|
||||
} else if (stmt.type === "nodes") {
|
||||
stmt.nodes.forEach(node => {
|
||||
node.parent = undefined;
|
||||
styles.append(node);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const anyDataURLRegexp = /^data:text\/css(?:;(base64|plain))?,/i;
|
||||
const base64DataURLRegexp = /^data:text\/css;base64,/i;
|
||||
const plainDataURLRegexp = /^data:text\/css;plain,/i;
|
||||
|
||||
function isValid(url) {
|
||||
return anyDataURLRegexp.test(url)
|
||||
}
|
||||
|
||||
function contents(url) {
|
||||
if (base64DataURLRegexp.test(url)) {
|
||||
// "data:text/css;base64,".length === 21
|
||||
return Buffer.from(url.slice(21), "base64").toString()
|
||||
}
|
||||
|
||||
if (plainDataURLRegexp.test(url)) {
|
||||
// "data:text/css;plain,".length === 20
|
||||
return decodeURIComponent(url.slice(20))
|
||||
}
|
||||
|
||||
// "data:text/css,".length === 14
|
||||
return decodeURIComponent(url.slice(14))
|
||||
}
|
||||
|
||||
var dataUrl = {
|
||||
isValid,
|
||||
contents,
|
||||
};
|
||||
|
||||
// external tooling
|
||||
const valueParser = lib;
|
||||
|
||||
// extended tooling
|
||||
const { stringify } = valueParser;
|
||||
|
||||
var parseStatements$1 = function parseStatements(result, styles, conditions, from) {
|
||||
const statements = [];
|
||||
let nodes = [];
|
||||
|
||||
styles.each(node => {
|
||||
let stmt;
|
||||
if (node.type === "atrule") {
|
||||
if (node.name === "import")
|
||||
stmt = parseImport(result, node, conditions, from);
|
||||
else if (node.name === "charset")
|
||||
stmt = parseCharset(result, node, conditions, from);
|
||||
}
|
||||
|
||||
if (stmt) {
|
||||
if (nodes.length) {
|
||||
statements.push({
|
||||
type: "nodes",
|
||||
nodes,
|
||||
conditions: [...conditions],
|
||||
from,
|
||||
});
|
||||
nodes = [];
|
||||
}
|
||||
statements.push(stmt);
|
||||
} else nodes.push(node);
|
||||
});
|
||||
|
||||
if (nodes.length) {
|
||||
statements.push({
|
||||
type: "nodes",
|
||||
nodes,
|
||||
conditions: [...conditions],
|
||||
from,
|
||||
});
|
||||
}
|
||||
|
||||
return statements
|
||||
};
|
||||
|
||||
function parseCharset(result, atRule, conditions, from) {
|
||||
if (atRule.prev()) {
|
||||
return result.warn("@charset must precede all other statements", {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
return {
|
||||
type: "charset",
|
||||
node: atRule,
|
||||
conditions: [...conditions],
|
||||
from,
|
||||
}
|
||||
}
|
||||
|
||||
function parseImport(result, atRule, conditions, from) {
|
||||
let prev = atRule.prev();
|
||||
|
||||
// `@import` statements may follow other `@import` statements.
|
||||
if (prev) {
|
||||
do {
|
||||
if (
|
||||
prev.type === "comment" ||
|
||||
(prev.type === "atrule" && prev.name === "import")
|
||||
) {
|
||||
prev = prev.prev();
|
||||
continue
|
||||
}
|
||||
|
||||
break
|
||||
} while (prev)
|
||||
}
|
||||
|
||||
// All `@import` statements may be preceded by `@charset` or `@layer` statements.
|
||||
// But the `@import` statements must be consecutive.
|
||||
if (prev) {
|
||||
do {
|
||||
if (
|
||||
prev.type === "comment" ||
|
||||
(prev.type === "atrule" &&
|
||||
(prev.name === "charset" || (prev.name === "layer" && !prev.nodes)))
|
||||
) {
|
||||
prev = prev.prev();
|
||||
continue
|
||||
}
|
||||
|
||||
return result.warn(
|
||||
"@import must precede all other statements (besides @charset or empty @layer)",
|
||||
{ node: atRule },
|
||||
)
|
||||
} while (prev)
|
||||
}
|
||||
|
||||
if (atRule.nodes) {
|
||||
return result.warn(
|
||||
"It looks like you didn't end your @import statement correctly. " +
|
||||
"Child nodes are attached to it.",
|
||||
{ node: atRule },
|
||||
)
|
||||
}
|
||||
|
||||
const params = valueParser(atRule.params).nodes;
|
||||
const stmt = {
|
||||
type: "import",
|
||||
uri: "",
|
||||
fullUri: "",
|
||||
node: atRule,
|
||||
conditions: [...conditions],
|
||||
from,
|
||||
};
|
||||
|
||||
let layer;
|
||||
let media;
|
||||
let supports;
|
||||
|
||||
for (let i = 0; i < params.length; i++) {
|
||||
const node = params[i];
|
||||
|
||||
if (node.type === "space" || node.type === "comment") continue
|
||||
|
||||
if (node.type === "string") {
|
||||
if (stmt.uri) {
|
||||
return result.warn(`Multiple url's in '${atRule.toString()}'`, {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
|
||||
if (!node.value) {
|
||||
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
|
||||
stmt.uri = node.value;
|
||||
stmt.fullUri = stringify(node);
|
||||
continue
|
||||
}
|
||||
|
||||
if (node.type === "function" && /^url$/i.test(node.value)) {
|
||||
if (stmt.uri) {
|
||||
return result.warn(`Multiple url's in '${atRule.toString()}'`, {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
|
||||
if (!node.nodes?.[0]?.value) {
|
||||
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
|
||||
stmt.uri = node.nodes[0].value;
|
||||
stmt.fullUri = stringify(node);
|
||||
continue
|
||||
}
|
||||
|
||||
if (!stmt.uri) {
|
||||
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
(node.type === "word" || node.type === "function") &&
|
||||
/^layer$/i.test(node.value)
|
||||
) {
|
||||
if (typeof layer !== "undefined") {
|
||||
return result.warn(`Multiple layers in '${atRule.toString()}'`, {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
|
||||
if (typeof supports !== "undefined") {
|
||||
return result.warn(
|
||||
`layers must be defined before support conditions in '${atRule.toString()}'`,
|
||||
{
|
||||
node: atRule,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (node.nodes) {
|
||||
layer = stringify(node.nodes);
|
||||
} else {
|
||||
layer = "";
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if (node.type === "function" && /^supports$/i.test(node.value)) {
|
||||
if (typeof supports !== "undefined") {
|
||||
return result.warn(
|
||||
`Multiple support conditions in '${atRule.toString()}'`,
|
||||
{
|
||||
node: atRule,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
supports = stringify(node.nodes);
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
media = stringify(params.slice(i));
|
||||
break
|
||||
}
|
||||
|
||||
if (!stmt.uri) {
|
||||
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
|
||||
node: atRule,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
typeof media !== "undefined" ||
|
||||
typeof layer !== "undefined" ||
|
||||
typeof supports !== "undefined"
|
||||
) {
|
||||
stmt.conditions.push({
|
||||
layer,
|
||||
media,
|
||||
supports,
|
||||
});
|
||||
}
|
||||
|
||||
return stmt
|
||||
}
|
||||
|
||||
// builtin tooling
|
||||
const path$2 = require$$0;
|
||||
|
||||
// placeholder tooling
|
||||
let sugarss;
|
||||
|
||||
var processContent$1 = function processContent(
|
||||
result,
|
||||
content,
|
||||
filename,
|
||||
options,
|
||||
postcss,
|
||||
) {
|
||||
const { plugins } = options;
|
||||
const ext = path$2.extname(filename);
|
||||
|
||||
const parserList = [];
|
||||
|
||||
// SugarSS support:
|
||||
if (ext === ".sss") {
|
||||
if (!sugarss) {
|
||||
/* c8 ignore next 3 */
|
||||
try {
|
||||
sugarss = __require('sugarss');
|
||||
} catch {} // Ignore
|
||||
}
|
||||
if (sugarss)
|
||||
return runPostcss(postcss, content, filename, plugins, [sugarss])
|
||||
}
|
||||
|
||||
// Syntax support:
|
||||
if (result.opts.syntax?.parse) {
|
||||
parserList.push(result.opts.syntax.parse);
|
||||
}
|
||||
|
||||
// Parser support:
|
||||
if (result.opts.parser) parserList.push(result.opts.parser);
|
||||
// Try the default as a last resort:
|
||||
parserList.push(null);
|
||||
|
||||
return runPostcss(postcss, content, filename, plugins, parserList)
|
||||
};
|
||||
|
||||
function runPostcss(postcss, content, filename, plugins, parsers, index) {
|
||||
if (!index) index = 0;
|
||||
return postcss(plugins)
|
||||
.process(content, {
|
||||
from: filename,
|
||||
parser: parsers[index],
|
||||
})
|
||||
.catch(err => {
|
||||
// If there's an error, try the next parser
|
||||
index++;
|
||||
// If there are no parsers left, throw it
|
||||
if (index === parsers.length) throw err
|
||||
return runPostcss(postcss, content, filename, plugins, parsers, index)
|
||||
})
|
||||
}
|
||||
|
||||
const path$1 = require$$0;
|
||||
|
||||
const dataURL = dataUrl;
|
||||
const parseStatements = parseStatements$1;
|
||||
const processContent = processContent$1;
|
||||
const resolveId$1 = (id) => id;
|
||||
const formatImportPrelude = formatImportPrelude$2;
|
||||
|
||||
async function parseStyles$1(
|
||||
result,
|
||||
styles,
|
||||
options,
|
||||
state,
|
||||
conditions,
|
||||
from,
|
||||
postcss,
|
||||
) {
|
||||
const statements = parseStatements(result, styles, conditions, from);
|
||||
|
||||
for (const stmt of statements) {
|
||||
if (stmt.type !== "import" || !isProcessableURL(stmt.uri)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (options.filter && !options.filter(stmt.uri)) {
|
||||
// rejected by filter
|
||||
continue
|
||||
}
|
||||
|
||||
await resolveImportId(result, stmt, options, state, postcss);
|
||||
}
|
||||
|
||||
let charset;
|
||||
const imports = [];
|
||||
const bundle = [];
|
||||
|
||||
function handleCharset(stmt) {
|
||||
if (!charset) charset = stmt;
|
||||
// charsets aren't case-sensitive, so convert to lower case to compare
|
||||
else if (
|
||||
stmt.node.params.toLowerCase() !== charset.node.params.toLowerCase()
|
||||
) {
|
||||
throw stmt.node.error(
|
||||
`Incompatible @charset statements:
|
||||
${stmt.node.params} specified in ${stmt.node.source.input.file}
|
||||
${charset.node.params} specified in ${charset.node.source.input.file}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// squash statements and their children
|
||||
statements.forEach(stmt => {
|
||||
if (stmt.type === "charset") handleCharset(stmt);
|
||||
else if (stmt.type === "import") {
|
||||
if (stmt.children) {
|
||||
stmt.children.forEach((child, index) => {
|
||||
if (child.type === "import") imports.push(child);
|
||||
else if (child.type === "charset") handleCharset(child);
|
||||
else bundle.push(child);
|
||||
// For better output
|
||||
if (index === 0) child.parent = stmt;
|
||||
});
|
||||
} else imports.push(stmt);
|
||||
} else if (stmt.type === "nodes") {
|
||||
bundle.push(stmt);
|
||||
}
|
||||
});
|
||||
|
||||
return charset ? [charset, ...imports.concat(bundle)] : imports.concat(bundle)
|
||||
}
|
||||
|
||||
async function resolveImportId(result, stmt, options, state, postcss) {
|
||||
if (dataURL.isValid(stmt.uri)) {
|
||||
// eslint-disable-next-line require-atomic-updates
|
||||
stmt.children = await loadImportContent(
|
||||
result,
|
||||
stmt,
|
||||
stmt.uri,
|
||||
options,
|
||||
state,
|
||||
postcss,
|
||||
);
|
||||
|
||||
return
|
||||
} else if (dataURL.isValid(stmt.from.slice(-1))) {
|
||||
// Data urls can't be used as a base url to resolve imports.
|
||||
throw stmt.node.error(
|
||||
`Unable to import '${stmt.uri}' from a stylesheet that is embedded in a data url`,
|
||||
)
|
||||
}
|
||||
|
||||
const atRule = stmt.node;
|
||||
let sourceFile;
|
||||
if (atRule.source?.input?.file) {
|
||||
sourceFile = atRule.source.input.file;
|
||||
}
|
||||
const base = sourceFile
|
||||
? path$1.dirname(atRule.source.input.file)
|
||||
: options.root;
|
||||
|
||||
const paths = [await options.resolve(stmt.uri, base, options, atRule)].flat();
|
||||
|
||||
// Ensure that each path is absolute:
|
||||
const resolved = await Promise.all(
|
||||
paths.map(file => {
|
||||
return !path$1.isAbsolute(file)
|
||||
? resolveId$1(file)
|
||||
: file
|
||||
}),
|
||||
);
|
||||
|
||||
// Add dependency messages:
|
||||
resolved.forEach(file => {
|
||||
result.messages.push({
|
||||
type: "dependency",
|
||||
plugin: "postcss-import",
|
||||
file,
|
||||
parent: sourceFile,
|
||||
});
|
||||
});
|
||||
|
||||
const importedContent = await Promise.all(
|
||||
resolved.map(file => {
|
||||
return loadImportContent(result, stmt, file, options, state, postcss)
|
||||
}),
|
||||
);
|
||||
|
||||
// Merge loaded statements
|
||||
// eslint-disable-next-line require-atomic-updates
|
||||
stmt.children = importedContent.flat().filter(x => !!x);
|
||||
}
|
||||
|
||||
async function loadImportContent(
|
||||
result,
|
||||
stmt,
|
||||
filename,
|
||||
options,
|
||||
state,
|
||||
postcss,
|
||||
) {
|
||||
const atRule = stmt.node;
|
||||
const { conditions, from } = stmt;
|
||||
const stmtDuplicateCheckKey = conditions
|
||||
.map(condition =>
|
||||
formatImportPrelude(condition.layer, condition.media, condition.supports),
|
||||
)
|
||||
.join(":");
|
||||
|
||||
if (options.skipDuplicates) {
|
||||
// skip files already imported at the same scope
|
||||
if (state.importedFiles[filename]?.[stmtDuplicateCheckKey]) {
|
||||
return
|
||||
}
|
||||
|
||||
// save imported files to skip them next time
|
||||
if (!state.importedFiles[filename]) {
|
||||
state.importedFiles[filename] = {};
|
||||
}
|
||||
state.importedFiles[filename][stmtDuplicateCheckKey] = true;
|
||||
}
|
||||
|
||||
if (from.includes(filename)) {
|
||||
return
|
||||
}
|
||||
|
||||
const content = await options.load(filename, options);
|
||||
|
||||
if (content.trim() === "" && options.warnOnEmpty) {
|
||||
result.warn(`${filename} is empty`, { node: atRule });
|
||||
return
|
||||
}
|
||||
|
||||
// skip previous imported files not containing @import rules
|
||||
if (
|
||||
options.skipDuplicates &&
|
||||
state.hashFiles[content]?.[stmtDuplicateCheckKey]
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const importedResult = await processContent(
|
||||
result,
|
||||
content,
|
||||
filename,
|
||||
options,
|
||||
postcss,
|
||||
);
|
||||
|
||||
const styles = importedResult.root;
|
||||
result.messages = result.messages.concat(importedResult.messages);
|
||||
|
||||
if (options.skipDuplicates) {
|
||||
const hasImport = styles.some(child => {
|
||||
return child.type === "atrule" && child.name === "import"
|
||||
});
|
||||
if (!hasImport) {
|
||||
// save hash files to skip them next time
|
||||
if (!state.hashFiles[content]) {
|
||||
state.hashFiles[content] = {};
|
||||
}
|
||||
|
||||
state.hashFiles[content][stmtDuplicateCheckKey] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// recursion: import @import from imported file
|
||||
return parseStyles$1(
|
||||
result,
|
||||
styles,
|
||||
options,
|
||||
state,
|
||||
conditions,
|
||||
[...from, filename],
|
||||
postcss,
|
||||
)
|
||||
}
|
||||
|
||||
function isProcessableURL(uri) {
|
||||
// skip protocol base uri (protocol://url) or protocol-relative
|
||||
if (/^(?:[a-z]+:)?\/\//i.test(uri)) {
|
||||
return false
|
||||
}
|
||||
|
||||
// check for fragment or query
|
||||
try {
|
||||
// needs a base to parse properly
|
||||
const url = new URL(uri, "https://example.com");
|
||||
if (url.search) {
|
||||
return false
|
||||
}
|
||||
} catch {} // Ignore
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var parseStyles_1 = parseStyles$1;
|
||||
|
||||
// builtin tooling
|
||||
const path = require$$0;
|
||||
|
||||
// internal tooling
|
||||
const applyConditions = applyConditions$1;
|
||||
const applyRaws = applyRaws$1;
|
||||
const applyStyles = applyStyles$1;
|
||||
const loadContent = () => "";
|
||||
const parseStyles = parseStyles_1;
|
||||
const resolveId = (id) => id;
|
||||
|
||||
function AtImport(options) {
|
||||
options = {
|
||||
root: process.cwd(),
|
||||
path: [],
|
||||
skipDuplicates: true,
|
||||
resolve: resolveId,
|
||||
load: loadContent,
|
||||
plugins: [],
|
||||
addModulesDirectories: [],
|
||||
warnOnEmpty: true,
|
||||
...options,
|
||||
};
|
||||
|
||||
options.root = path.resolve(options.root);
|
||||
|
||||
// convert string to an array of a single element
|
||||
if (typeof options.path === "string") options.path = [options.path];
|
||||
|
||||
if (!Array.isArray(options.path)) options.path = [];
|
||||
|
||||
options.path = options.path.map(p => path.resolve(options.root, p));
|
||||
|
||||
return {
|
||||
postcssPlugin: "postcss-import",
|
||||
async Once(styles, { result, atRule, postcss }) {
|
||||
const state = {
|
||||
importedFiles: {},
|
||||
hashFiles: {},
|
||||
};
|
||||
|
||||
if (styles.source?.input?.file) {
|
||||
state.importedFiles[styles.source.input.file] = {};
|
||||
}
|
||||
|
||||
if (options.plugins && !Array.isArray(options.plugins)) {
|
||||
throw new Error("plugins option must be an array")
|
||||
}
|
||||
|
||||
const bundle = await parseStyles(
|
||||
result,
|
||||
styles,
|
||||
options,
|
||||
state,
|
||||
[],
|
||||
[],
|
||||
postcss,
|
||||
);
|
||||
|
||||
applyRaws(bundle);
|
||||
applyConditions(bundle, atRule);
|
||||
applyStyles(bundle, styles);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
AtImport.postcss = true;
|
||||
|
||||
var postcssImport = AtImport;
|
||||
|
||||
var index = /*@__PURE__*/getDefaultExportFromCjs(postcssImport);
|
||||
|
||||
var index$1 = /*#__PURE__*/_mergeNamespaces({
|
||||
__proto__: null,
|
||||
default: index
|
||||
}, [postcssImport]);
|
||||
|
||||
export { index$1 as i };
|
||||
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
const RuleTester = require("./rule-tester");
|
||||
|
||||
module.exports = {
|
||||
RuleTester,
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "color-name",
|
||||
"version": "1.1.4",
|
||||
"description": "A list of color names and its values",
|
||||
"main": "index.js",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "node test.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git@github.com:colorjs/color-name.git"
|
||||
},
|
||||
"keywords": [
|
||||
"color-name",
|
||||
"color",
|
||||
"color-keyword",
|
||||
"keyword"
|
||||
],
|
||||
"author": "DY <dfcreative@gmail.com>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/colorjs/color-name/issues"
|
||||
},
|
||||
"homepage": "https://github.com/colorjs/color-name"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { Parser } from "../index.js";
|
||||
|
||||
export declare const parsers: {
|
||||
meriyah: Parser;
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
const fs = require("graceful-fs");
|
||||
const CachedInputFileSystem = require("./CachedInputFileSystem");
|
||||
const ResolverFactory = require("./ResolverFactory");
|
||||
|
||||
/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */
|
||||
/** @typedef {import("./Resolver")} Resolver */
|
||||
/** @typedef {import("./Resolver").FileSystem} FileSystem */
|
||||
/** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */
|
||||
/** @typedef {import("./Resolver").ResolveContext} ResolveContext */
|
||||
/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
|
||||
/** @typedef {import("./ResolverFactory").Plugin} Plugin */
|
||||
/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */
|
||||
/** @typedef {{
|
||||
* (context: object, path: string, request: string, resolveContext: ResolveContext, callback: ResolveCallback): void;
|
||||
* (context: object, path: string, request: string, callback: ResolveCallback): void;
|
||||
* (path: string, request: string, resolveContext: ResolveContext, callback: ResolveCallback): void;
|
||||
* (path: string, request: string, callback: ResolveCallback): void;
|
||||
* }} ResolveFunctionAsync
|
||||
*/
|
||||
/** @typedef {{
|
||||
* (context: object, path: string, request: string): string|false;
|
||||
* (path: string, request: string): string|false;
|
||||
* }} ResolveFunction
|
||||
*/
|
||||
|
||||
const nodeFileSystem = new CachedInputFileSystem(fs, 4000);
|
||||
|
||||
const nodeContext = {
|
||||
environments: ["node+es3+es5+process+native"]
|
||||
};
|
||||
|
||||
const asyncResolver = ResolverFactory.createResolver({
|
||||
conditionNames: ["node"],
|
||||
extensions: [".js", ".json", ".node"],
|
||||
fileSystem: nodeFileSystem
|
||||
});
|
||||
|
||||
/**
|
||||
* @type {ResolveFunctionAsync}
|
||||
*/
|
||||
const resolve =
|
||||
/**
|
||||
* @param {object|string} context
|
||||
* @param {string} path
|
||||
* @param {string|ResolveContext|ResolveCallback} request
|
||||
* @param {ResolveContext|ResolveCallback=} resolveContext
|
||||
* @param {ResolveCallback=} callback
|
||||
*/
|
||||
(context, path, request, resolveContext, callback) => {
|
||||
if (typeof context === "string") {
|
||||
callback = /** @type {ResolveCallback} */ (resolveContext);
|
||||
resolveContext = /** @type {ResolveContext} */ (request);
|
||||
request = path;
|
||||
path = context;
|
||||
context = nodeContext;
|
||||
}
|
||||
if (typeof callback !== "function") {
|
||||
callback = /** @type {ResolveCallback} */ (resolveContext);
|
||||
}
|
||||
asyncResolver.resolve(
|
||||
context,
|
||||
path,
|
||||
/** @type {string} */ (request),
|
||||
/** @type {ResolveContext} */ (resolveContext),
|
||||
/** @type {ResolveCallback} */ (callback)
|
||||
);
|
||||
};
|
||||
|
||||
const syncResolver = ResolverFactory.createResolver({
|
||||
conditionNames: ["node"],
|
||||
extensions: [".js", ".json", ".node"],
|
||||
useSyncFileSystemCalls: true,
|
||||
fileSystem: nodeFileSystem
|
||||
});
|
||||
|
||||
/**
|
||||
* @type {ResolveFunction}
|
||||
*/
|
||||
const resolveSync =
|
||||
/**
|
||||
* @param {object|string} context
|
||||
* @param {string} path
|
||||
* @param {string=} request
|
||||
*/
|
||||
(context, path, request) => {
|
||||
if (typeof context === "string") {
|
||||
request = path;
|
||||
path = context;
|
||||
context = nodeContext;
|
||||
}
|
||||
return syncResolver.resolveSync(
|
||||
context,
|
||||
path,
|
||||
/** @type {string} */ (request)
|
||||
);
|
||||
};
|
||||
|
||||
/** @typedef {Omit<ResolveOptions, "fileSystem"> & Partial<Pick<ResolveOptions, "fileSystem">>} ResolveOptionsOptionalFS */
|
||||
|
||||
/**
|
||||
* @param {ResolveOptionsOptionalFS} options Resolver options
|
||||
* @returns {ResolveFunctionAsync} Resolver function
|
||||
*/
|
||||
function create(options) {
|
||||
const resolver = ResolverFactory.createResolver({
|
||||
fileSystem: nodeFileSystem,
|
||||
...options
|
||||
});
|
||||
/**
|
||||
* @param {object|string} context Custom context
|
||||
* @param {string} path Base path
|
||||
* @param {string|ResolveContext|ResolveCallback} request String to resolve
|
||||
* @param {ResolveContext|ResolveCallback=} resolveContext Resolve context
|
||||
* @param {ResolveCallback=} callback Result callback
|
||||
*/
|
||||
return function (context, path, request, resolveContext, callback) {
|
||||
if (typeof context === "string") {
|
||||
callback = /** @type {ResolveCallback} */ (resolveContext);
|
||||
resolveContext = /** @type {ResolveContext} */ (request);
|
||||
request = path;
|
||||
path = context;
|
||||
context = nodeContext;
|
||||
}
|
||||
if (typeof callback !== "function") {
|
||||
callback = /** @type {ResolveCallback} */ (resolveContext);
|
||||
}
|
||||
resolver.resolve(
|
||||
context,
|
||||
path,
|
||||
/** @type {string} */ (request),
|
||||
/** @type {ResolveContext} */ (resolveContext),
|
||||
callback
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ResolveOptionsOptionalFS} options Resolver options
|
||||
* @returns {ResolveFunction} Resolver function
|
||||
*/
|
||||
function createSync(options) {
|
||||
const resolver = ResolverFactory.createResolver({
|
||||
useSyncFileSystemCalls: true,
|
||||
fileSystem: nodeFileSystem,
|
||||
...options
|
||||
});
|
||||
/**
|
||||
* @param {object|string} context custom context
|
||||
* @param {string} path base path
|
||||
* @param {string=} request request to resolve
|
||||
* @returns {string|false} Resolved path or false
|
||||
*/
|
||||
return function (context, path, request) {
|
||||
if (typeof context === "string") {
|
||||
request = path;
|
||||
path = context;
|
||||
context = nodeContext;
|
||||
}
|
||||
return resolver.resolveSync(context, path, /** @type {string} */ (request));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @template A
|
||||
* @template B
|
||||
* @param {A} obj input a
|
||||
* @param {B} exports input b
|
||||
* @returns {A & B} merged
|
||||
*/
|
||||
const mergeExports = (obj, exports) => {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(exports);
|
||||
Object.defineProperties(obj, descriptors);
|
||||
return /** @type {A & B} */ (Object.freeze(obj));
|
||||
};
|
||||
|
||||
module.exports = mergeExports(resolve, {
|
||||
get sync() {
|
||||
return resolveSync;
|
||||
},
|
||||
create: mergeExports(create, {
|
||||
get sync() {
|
||||
return createSync;
|
||||
}
|
||||
}),
|
||||
ResolverFactory,
|
||||
CachedInputFileSystem,
|
||||
get CloneBasenamePlugin() {
|
||||
return require("./CloneBasenamePlugin");
|
||||
},
|
||||
get LogInfoPlugin() {
|
||||
return require("./LogInfoPlugin");
|
||||
},
|
||||
get forEachBail() {
|
||||
return require("./forEachBail");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,557 @@
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/index.ts
|
||||
var src_exports = {};
|
||||
__export(src_exports, {
|
||||
Path2D: () => Path2D,
|
||||
applyPath2DToCanvasRenderingContext: () => applyPath2DToCanvasRenderingContext,
|
||||
applyRoundRectToCanvasRenderingContext2D: () => applyRoundRectToCanvasRenderingContext2D,
|
||||
applyRoundRectToPath2D: () => applyRoundRectToPath2D,
|
||||
buildPath: () => buildPath,
|
||||
parsePath: () => parsePath,
|
||||
roundRect: () => roundRect
|
||||
});
|
||||
module.exports = __toCommonJS(src_exports);
|
||||
|
||||
// src/parse-path.ts
|
||||
var ARG_LENGTH = {
|
||||
a: 7,
|
||||
c: 6,
|
||||
h: 1,
|
||||
l: 2,
|
||||
m: 2,
|
||||
q: 4,
|
||||
s: 4,
|
||||
t: 2,
|
||||
v: 1,
|
||||
z: 0
|
||||
};
|
||||
var SEGMENT_PATTERN = /([astvzqmhlc])([^astvzqmhlc]*)/gi;
|
||||
var NUMBER = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;
|
||||
function parseValues(args) {
|
||||
const numbers = args.match(NUMBER);
|
||||
return numbers ? numbers.map(Number) : [];
|
||||
}
|
||||
function parsePath(path) {
|
||||
const data = [];
|
||||
const p = String(path).trim();
|
||||
if (p[0] !== "M" && p[0] !== "m") {
|
||||
return data;
|
||||
}
|
||||
p.replace(SEGMENT_PATTERN, (_, command, args) => {
|
||||
const theArgs = parseValues(args);
|
||||
let type = command.toLowerCase();
|
||||
let theCommand = command;
|
||||
if (type === "m" && theArgs.length > 2) {
|
||||
data.push([theCommand, ...theArgs.splice(0, 2)]);
|
||||
type = "l";
|
||||
theCommand = theCommand === "m" ? "l" : "L";
|
||||
}
|
||||
if (theArgs.length < ARG_LENGTH[type]) {
|
||||
return "";
|
||||
}
|
||||
data.push([theCommand, ...theArgs.splice(0, ARG_LENGTH[type])]);
|
||||
while (theArgs.length >= ARG_LENGTH[type] && theArgs.length && ARG_LENGTH[type]) {
|
||||
data.push([theCommand, ...theArgs.splice(0, ARG_LENGTH[type])]);
|
||||
}
|
||||
return "";
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
// src/path2d.ts
|
||||
function rotatePoint(point, angle) {
|
||||
const nx = point.x * Math.cos(angle) - point.y * Math.sin(angle);
|
||||
const ny = point.y * Math.cos(angle) + point.x * Math.sin(angle);
|
||||
point.x = nx;
|
||||
point.y = ny;
|
||||
}
|
||||
function translatePoint(point, dx, dy) {
|
||||
point.x += dx;
|
||||
point.y += dy;
|
||||
}
|
||||
function scalePoint(point, s) {
|
||||
point.x *= s;
|
||||
point.y *= s;
|
||||
}
|
||||
var Path2D = class _Path2D {
|
||||
constructor(path) {
|
||||
this.commands = [];
|
||||
if (path && path instanceof _Path2D) {
|
||||
this.commands.push(...path.commands);
|
||||
} else if (path) {
|
||||
this.commands = parsePath(path);
|
||||
}
|
||||
}
|
||||
addPath(path) {
|
||||
if (path && path instanceof _Path2D) {
|
||||
this.commands.push(...path.commands);
|
||||
}
|
||||
}
|
||||
moveTo(x, y) {
|
||||
this.commands.push(["M", x, y]);
|
||||
}
|
||||
lineTo(x, y) {
|
||||
this.commands.push(["L", x, y]);
|
||||
}
|
||||
arc(x, y, r, start, end, ccw) {
|
||||
this.commands.push(["AC", x, y, r, start, end, !!ccw]);
|
||||
}
|
||||
arcTo(x1, y1, x2, y2, r) {
|
||||
this.commands.push(["AT", x1, y1, x2, y2, r]);
|
||||
}
|
||||
ellipse(x, y, rx, ry, angle, start, end, ccw) {
|
||||
this.commands.push(["E", x, y, rx, ry, angle, start, end, !!ccw]);
|
||||
}
|
||||
closePath() {
|
||||
this.commands.push(["Z"]);
|
||||
}
|
||||
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
|
||||
this.commands.push(["C", cp1x, cp1y, cp2x, cp2y, x, y]);
|
||||
}
|
||||
quadraticCurveTo(cpx, cpy, x, y) {
|
||||
this.commands.push(["Q", cpx, cpy, x, y]);
|
||||
}
|
||||
rect(x, y, width, height) {
|
||||
this.commands.push(["R", x, y, width, height]);
|
||||
}
|
||||
roundRect(x, y, width, height, radii) {
|
||||
if (typeof radii === "undefined") {
|
||||
this.commands.push(["RR", x, y, width, height, 0]);
|
||||
} else {
|
||||
this.commands.push(["RR", x, y, width, height, radii]);
|
||||
}
|
||||
}
|
||||
};
|
||||
function buildPath(ctx, commands) {
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
let endAngle;
|
||||
let startAngle;
|
||||
let largeArcFlag;
|
||||
let sweepFlag;
|
||||
let endPoint;
|
||||
let midPoint;
|
||||
let angle;
|
||||
let lambda;
|
||||
let t1;
|
||||
let t2;
|
||||
let x1;
|
||||
let y1;
|
||||
let r;
|
||||
let rx;
|
||||
let ry;
|
||||
let w;
|
||||
let h;
|
||||
let pathType;
|
||||
let centerPoint;
|
||||
let ccw;
|
||||
let radii;
|
||||
let cpx = null;
|
||||
let cpy = null;
|
||||
let qcpx = null;
|
||||
let qcpy = null;
|
||||
let startPoint = null;
|
||||
let currentPoint = null;
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < commands.length; ++i) {
|
||||
pathType = commands[i][0];
|
||||
if (pathType !== "S" && pathType !== "s" && pathType !== "C" && pathType !== "c") {
|
||||
cpx = null;
|
||||
cpy = null;
|
||||
}
|
||||
if (pathType !== "T" && pathType !== "t" && pathType !== "Q" && pathType !== "q") {
|
||||
qcpx = null;
|
||||
qcpy = null;
|
||||
}
|
||||
let c;
|
||||
switch (pathType) {
|
||||
case "m":
|
||||
case "M":
|
||||
c = commands[i];
|
||||
if (pathType === "m") {
|
||||
x += c[1];
|
||||
y += c[2];
|
||||
} else {
|
||||
x = c[1];
|
||||
y = c[2];
|
||||
}
|
||||
if (pathType === "M" || !startPoint) {
|
||||
startPoint = { x, y };
|
||||
}
|
||||
ctx.moveTo(x, y);
|
||||
break;
|
||||
case "l":
|
||||
c = commands[i];
|
||||
x += c[1];
|
||||
y += c[2];
|
||||
ctx.lineTo(x, y);
|
||||
break;
|
||||
case "L":
|
||||
c = commands[i];
|
||||
x = c[1];
|
||||
y = c[2];
|
||||
ctx.lineTo(x, y);
|
||||
break;
|
||||
case "H":
|
||||
c = commands[i];
|
||||
x = c[1];
|
||||
ctx.lineTo(x, y);
|
||||
break;
|
||||
case "h":
|
||||
c = commands[i];
|
||||
x += c[1];
|
||||
ctx.lineTo(x, y);
|
||||
break;
|
||||
case "V":
|
||||
c = commands[i];
|
||||
y = c[1];
|
||||
ctx.lineTo(x, y);
|
||||
break;
|
||||
case "v":
|
||||
c = commands[i];
|
||||
y += c[1];
|
||||
ctx.lineTo(x, y);
|
||||
break;
|
||||
case "a":
|
||||
case "A":
|
||||
c = commands[i];
|
||||
if (currentPoint === null) {
|
||||
throw new Error("This should never happen");
|
||||
}
|
||||
if (pathType === "a") {
|
||||
x += c[6];
|
||||
y += c[7];
|
||||
} else {
|
||||
x = c[6];
|
||||
y = c[7];
|
||||
}
|
||||
rx = c[1];
|
||||
ry = c[2];
|
||||
angle = c[3] * Math.PI / 180;
|
||||
largeArcFlag = !!c[4];
|
||||
sweepFlag = !!c[5];
|
||||
endPoint = { x, y };
|
||||
midPoint = {
|
||||
x: (currentPoint.x - endPoint.x) / 2,
|
||||
y: (currentPoint.y - endPoint.y) / 2
|
||||
};
|
||||
rotatePoint(midPoint, -angle);
|
||||
lambda = midPoint.x * midPoint.x / (rx * rx) + midPoint.y * midPoint.y / (ry * ry);
|
||||
if (lambda > 1) {
|
||||
lambda = Math.sqrt(lambda);
|
||||
rx *= lambda;
|
||||
ry *= lambda;
|
||||
}
|
||||
centerPoint = {
|
||||
x: rx * midPoint.y / ry,
|
||||
y: -(ry * midPoint.x) / rx
|
||||
};
|
||||
t1 = rx * rx * ry * ry;
|
||||
t2 = rx * rx * midPoint.y * midPoint.y + ry * ry * midPoint.x * midPoint.x;
|
||||
if (sweepFlag !== largeArcFlag) {
|
||||
scalePoint(centerPoint, Math.sqrt((t1 - t2) / t2) || 0);
|
||||
} else {
|
||||
scalePoint(centerPoint, -Math.sqrt((t1 - t2) / t2) || 0);
|
||||
}
|
||||
startAngle = Math.atan2((midPoint.y - centerPoint.y) / ry, (midPoint.x - centerPoint.x) / rx);
|
||||
endAngle = Math.atan2(-(midPoint.y + centerPoint.y) / ry, -(midPoint.x + centerPoint.x) / rx);
|
||||
rotatePoint(centerPoint, angle);
|
||||
translatePoint(centerPoint, (endPoint.x + currentPoint.x) / 2, (endPoint.y + currentPoint.y) / 2);
|
||||
ctx.save();
|
||||
ctx.translate(centerPoint.x, centerPoint.y);
|
||||
ctx.rotate(angle);
|
||||
ctx.scale(rx, ry);
|
||||
ctx.arc(0, 0, 1, startAngle, endAngle, !sweepFlag);
|
||||
ctx.restore();
|
||||
break;
|
||||
case "C":
|
||||
c = commands[i];
|
||||
cpx = c[3];
|
||||
cpy = c[4];
|
||||
x = c[5];
|
||||
y = c[6];
|
||||
ctx.bezierCurveTo(c[1], c[2], cpx, cpy, x, y);
|
||||
break;
|
||||
case "c":
|
||||
c = commands[i];
|
||||
ctx.bezierCurveTo(c[1] + x, c[2] + y, c[3] + x, c[4] + y, c[5] + x, c[6] + y);
|
||||
cpx = c[3] + x;
|
||||
cpy = c[4] + y;
|
||||
x += c[5];
|
||||
y += c[6];
|
||||
break;
|
||||
case "S":
|
||||
c = commands[i];
|
||||
if (cpx === null || cpy === null) {
|
||||
cpx = x;
|
||||
cpy = y;
|
||||
}
|
||||
ctx.bezierCurveTo(2 * x - cpx, 2 * y - cpy, c[1], c[2], c[3], c[4]);
|
||||
cpx = c[1];
|
||||
cpy = c[2];
|
||||
x = c[3];
|
||||
y = c[4];
|
||||
break;
|
||||
case "s":
|
||||
c = commands[i];
|
||||
if (cpx === null || cpy === null) {
|
||||
cpx = x;
|
||||
cpy = y;
|
||||
}
|
||||
ctx.bezierCurveTo(2 * x - cpx, 2 * y - cpy, c[1] + x, c[2] + y, c[3] + x, c[4] + y);
|
||||
cpx = c[1] + x;
|
||||
cpy = c[2] + y;
|
||||
x += c[3];
|
||||
y += c[4];
|
||||
break;
|
||||
case "Q":
|
||||
c = commands[i];
|
||||
qcpx = c[1];
|
||||
qcpy = c[2];
|
||||
x = c[3];
|
||||
y = c[4];
|
||||
ctx.quadraticCurveTo(qcpx, qcpy, x, y);
|
||||
break;
|
||||
case "q":
|
||||
c = commands[i];
|
||||
qcpx = c[1] + x;
|
||||
qcpy = c[2] + y;
|
||||
x += c[3];
|
||||
y += c[4];
|
||||
ctx.quadraticCurveTo(qcpx, qcpy, x, y);
|
||||
break;
|
||||
case "T":
|
||||
c = commands[i];
|
||||
if (qcpx === null || qcpy === null) {
|
||||
qcpx = x;
|
||||
qcpy = y;
|
||||
}
|
||||
qcpx = 2 * x - qcpx;
|
||||
qcpy = 2 * y - qcpy;
|
||||
x = c[1];
|
||||
y = c[2];
|
||||
ctx.quadraticCurveTo(qcpx, qcpy, x, y);
|
||||
break;
|
||||
case "t":
|
||||
c = commands[i];
|
||||
if (qcpx === null || qcpy === null) {
|
||||
qcpx = x;
|
||||
qcpy = y;
|
||||
}
|
||||
qcpx = 2 * x - qcpx;
|
||||
qcpy = 2 * y - qcpy;
|
||||
x += c[1];
|
||||
y += c[2];
|
||||
ctx.quadraticCurveTo(qcpx, qcpy, x, y);
|
||||
break;
|
||||
case "z":
|
||||
case "Z":
|
||||
if (startPoint) {
|
||||
x = startPoint.x;
|
||||
y = startPoint.y;
|
||||
}
|
||||
startPoint = null;
|
||||
ctx.closePath();
|
||||
break;
|
||||
case "AC":
|
||||
c = commands[i];
|
||||
x = c[1];
|
||||
y = c[2];
|
||||
r = c[3];
|
||||
startAngle = c[4];
|
||||
endAngle = c[5];
|
||||
ccw = c[6];
|
||||
ctx.arc(x, y, r, startAngle, endAngle, ccw);
|
||||
break;
|
||||
case "AT":
|
||||
c = commands[i];
|
||||
x1 = c[1];
|
||||
y1 = c[2];
|
||||
x = c[3];
|
||||
y = c[4];
|
||||
r = c[5];
|
||||
ctx.arcTo(x1, y1, x, y, r);
|
||||
break;
|
||||
case "E":
|
||||
c = commands[i];
|
||||
x = c[1];
|
||||
y = c[2];
|
||||
rx = c[3];
|
||||
ry = c[4];
|
||||
angle = c[5];
|
||||
startAngle = c[6];
|
||||
endAngle = c[7];
|
||||
ccw = c[8];
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.rotate(angle);
|
||||
ctx.scale(rx, ry);
|
||||
ctx.arc(0, 0, 1, startAngle, endAngle, ccw);
|
||||
ctx.restore();
|
||||
break;
|
||||
case "R":
|
||||
c = commands[i];
|
||||
x = c[1];
|
||||
y = c[2];
|
||||
w = c[3];
|
||||
h = c[4];
|
||||
startPoint = { x, y };
|
||||
ctx.rect(x, y, w, h);
|
||||
break;
|
||||
case "RR":
|
||||
c = commands[i];
|
||||
x = c[1];
|
||||
y = c[2];
|
||||
w = c[3];
|
||||
h = c[4];
|
||||
radii = c[5];
|
||||
startPoint = { x, y };
|
||||
ctx.roundRect(x, y, w, h, radii);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Invalid path command: ${pathType}`);
|
||||
}
|
||||
if (!currentPoint) {
|
||||
currentPoint = { x, y };
|
||||
} else {
|
||||
currentPoint.x = x;
|
||||
currentPoint.y = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// src/round-rect.ts
|
||||
function roundRect(x, y, width, height, radii = 0) {
|
||||
if (typeof radii === "number") {
|
||||
radii = [radii];
|
||||
}
|
||||
if (Array.isArray(radii)) {
|
||||
if (radii.length === 0 || radii.length > 4) {
|
||||
throw new RangeError(
|
||||
`Failed to execute 'roundRect' on '${this.constructor.name}': ${radii.length} radii provided. Between one and four radii are necessary.`
|
||||
);
|
||||
}
|
||||
radii.forEach((v) => {
|
||||
if (v < 0) {
|
||||
throw new RangeError(
|
||||
`Failed to execute 'roundRect' on '${this.constructor.name}': Radius value ${v} is negative.`
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if (radii.length === 1 && radii[0] === 0) {
|
||||
this.rect(x, y, width, height);
|
||||
return;
|
||||
}
|
||||
const minRadius = Math.min(width, height) / 2;
|
||||
const tl = Math.min(minRadius, radii[0]);
|
||||
let tr = tl;
|
||||
let br = tl;
|
||||
let bl = tl;
|
||||
if (radii.length === 2) {
|
||||
tr = Math.min(minRadius, radii[1]);
|
||||
bl = tr;
|
||||
}
|
||||
if (radii.length === 3) {
|
||||
tr = Math.min(minRadius, radii[1]);
|
||||
bl = tr;
|
||||
br = Math.min(minRadius, radii[2]);
|
||||
}
|
||||
if (radii.length === 4) {
|
||||
tr = Math.min(minRadius, radii[1]);
|
||||
br = Math.min(minRadius, radii[2]);
|
||||
bl = Math.min(minRadius, radii[3]);
|
||||
}
|
||||
this.moveTo(x, y + height - bl);
|
||||
this.arcTo(x, y, x + tl, y, tl);
|
||||
this.arcTo(x + width, y, x + width, y + tr, tr);
|
||||
this.arcTo(x + width, y + height, x + width - br, y + height, br);
|
||||
this.arcTo(x, y + height, x, y + height - bl, bl);
|
||||
this.closePath();
|
||||
}
|
||||
|
||||
// src/apply.ts
|
||||
function applyPath2DToCanvasRenderingContext(CanvasRenderingContext2D) {
|
||||
if (!CanvasRenderingContext2D) return;
|
||||
const cClip = CanvasRenderingContext2D.prototype.clip;
|
||||
const cFill = CanvasRenderingContext2D.prototype.fill;
|
||||
const cStroke = CanvasRenderingContext2D.prototype.stroke;
|
||||
const cIsPointInPath = CanvasRenderingContext2D.prototype.isPointInPath;
|
||||
CanvasRenderingContext2D.prototype.clip = function clip(...args) {
|
||||
if (args[0] instanceof Path2D) {
|
||||
const path = args[0];
|
||||
const fillRule2 = args[1] || "nonzero";
|
||||
buildPath(this, path.commands);
|
||||
return cClip.apply(this, [fillRule2]);
|
||||
}
|
||||
const fillRule = args[0] || "nonzero";
|
||||
return cClip.apply(this, [fillRule]);
|
||||
};
|
||||
CanvasRenderingContext2D.prototype.fill = function fill(...args) {
|
||||
if (args[0] instanceof Path2D) {
|
||||
const path = args[0];
|
||||
const fillRule2 = args[1] || "nonzero";
|
||||
buildPath(this, path.commands);
|
||||
return cFill.apply(this, [fillRule2]);
|
||||
}
|
||||
const fillRule = args[0] || "nonzero";
|
||||
return cFill.apply(this, [fillRule]);
|
||||
};
|
||||
CanvasRenderingContext2D.prototype.stroke = function stroke(path) {
|
||||
if (path) {
|
||||
buildPath(this, path.commands);
|
||||
}
|
||||
cStroke.apply(this);
|
||||
};
|
||||
CanvasRenderingContext2D.prototype.isPointInPath = function isPointInPath(...args) {
|
||||
if (args[0] instanceof Path2D) {
|
||||
const path = args[0];
|
||||
const x = args[1];
|
||||
const y = args[2];
|
||||
const fillRule = args[3] || "nonzero";
|
||||
buildPath(this, path.commands);
|
||||
return cIsPointInPath.apply(this, [x, y, fillRule]);
|
||||
}
|
||||
return cIsPointInPath.apply(this, args);
|
||||
};
|
||||
}
|
||||
function applyRoundRectToCanvasRenderingContext2D(CanvasRenderingContext2D) {
|
||||
if (CanvasRenderingContext2D && !CanvasRenderingContext2D.prototype.roundRect) {
|
||||
CanvasRenderingContext2D.prototype.roundRect = roundRect;
|
||||
}
|
||||
}
|
||||
function applyRoundRectToPath2D(P2D) {
|
||||
if (P2D && !P2D.prototype.roundRect) {
|
||||
P2D.prototype.roundRect = roundRect;
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
Path2D,
|
||||
applyPath2DToCanvasRenderingContext,
|
||||
applyRoundRectToCanvasRenderingContext2D,
|
||||
applyRoundRectToPath2D,
|
||||
buildPath,
|
||||
parsePath,
|
||||
roundRect
|
||||
});
|
||||
Reference in New Issue
Block a user