4
0

index.d.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import type { Angle, CssColor, Rule, CustomProperty, EnvironmentVariable, Function, Image, LengthValue, MediaQuery, Declaration, Ratio, Resolution, Selector, SupportsCondition, Time, Token, TokenOrValue, UnknownAtRule, Url, Variable, StyleRule, DeclarationBlock, ParsedComponent, Multiplier, StyleSheet } from './ast';
  2. import { Targets, Features } from './targets';
  3. export * from './ast';
  4. export { Targets, Features };
  5. export interface TransformOptions<C extends CustomAtRules> {
  6. /** The filename being transformed. Used for error messages and source maps. */
  7. filename: string,
  8. /** The source code to transform. */
  9. code: Uint8Array,
  10. /** Whether to enable minification. */
  11. minify?: boolean,
  12. /** Whether to output a source map. */
  13. sourceMap?: boolean,
  14. /** An input source map to extend. */
  15. inputSourceMap?: string,
  16. /**
  17. * An optional project root path, used as the source root in the output source map.
  18. * Also used to generate relative paths for sources used in CSS module hashes.
  19. */
  20. projectRoot?: string,
  21. /** The browser targets for the generated code. */
  22. targets?: Targets,
  23. /** Features that should always be compiled, even when supported by targets. */
  24. include?: number,
  25. /** Features that should never be compiled, even when unsupported by targets. */
  26. exclude?: number,
  27. /** Whether to enable parsing various draft syntax. */
  28. drafts?: Drafts,
  29. /** Whether to enable various non-standard syntax. */
  30. nonStandard?: NonStandard,
  31. /** Whether to compile this file as a CSS module. */
  32. cssModules?: boolean | CSSModulesConfig,
  33. /**
  34. * Whether to analyze dependencies (e.g. `@import` and `url()`).
  35. * When enabled, `@import` rules are removed, and `url()` dependencies
  36. * are replaced with hashed placeholders that can be replaced with the final
  37. * urls later (after bundling). Dependencies are returned as part of the result.
  38. */
  39. analyzeDependencies?: boolean | DependencyOptions,
  40. /**
  41. * Replaces user action pseudo classes with class names that can be applied from JavaScript.
  42. * This is useful for polyfills, for example.
  43. */
  44. pseudoClasses?: PseudoClasses,
  45. /**
  46. * A list of class names, ids, and custom identifiers (e.g. @keyframes) that are known
  47. * to be unused. These will be removed during minification. Note that these are not
  48. * selectors but individual names (without any . or # prefixes).
  49. */
  50. unusedSymbols?: string[],
  51. /**
  52. * Whether to ignore invalid rules and declarations rather than erroring.
  53. * When enabled, warnings are returned, and the invalid rule or declaration is
  54. * omitted from the output code.
  55. */
  56. errorRecovery?: boolean,
  57. /**
  58. * An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript.
  59. * Multiple visitors can be composed into one using the `composeVisitors` function.
  60. * For optimal performance, visitors should be as specific as possible about what types of values
  61. * they care about so that JavaScript has to be called as little as possible.
  62. */
  63. visitor?: Visitor<C>,
  64. /**
  65. * Defines how to parse custom CSS at-rules. Each at-rule can have a prelude, defined using a CSS
  66. * [syntax string](https://drafts.css-houdini.org/css-properties-values-api/#syntax-strings), and
  67. * a block body. The body can be a declaration list, rule list, or style block as defined in the
  68. * [css spec](https://drafts.csswg.org/css-syntax/#declaration-rule-list).
  69. */
  70. customAtRules?: C
  71. }
  72. // This is a hack to make TS still provide autocomplete for `property` vs. just making it `string`.
  73. type PropertyStart = '-' | '_' | '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';
  74. export type ReturnedDeclaration = Declaration | {
  75. /** The property name. */
  76. property: `${PropertyStart}${string}`,
  77. /** The raw string value for the declaration. */
  78. raw: string
  79. };
  80. export type ReturnedMediaQuery = MediaQuery | {
  81. /** The raw string value for the media query. */
  82. raw: string
  83. };
  84. type FindByType<Union, Name> = Union extends { type: Name } ? Union : never;
  85. export type ReturnedRule = Rule<ReturnedDeclaration, ReturnedMediaQuery>;
  86. type RequiredValue<Rule> = Rule extends { value: object }
  87. ? Rule['value'] extends StyleRule
  88. ? Rule & { value: Required<StyleRule> & { declarations: Required<DeclarationBlock> } }
  89. : Rule & { value: Required<Rule['value']> }
  90. : Rule;
  91. type RuleVisitor<R = RequiredValue<Rule>> = ((rule: R) => ReturnedRule | ReturnedRule[] | void);
  92. type MappedRuleVisitors = {
  93. [Name in Exclude<Rule['type'], 'unknown' | 'custom'>]?: RuleVisitor<RequiredValue<FindByType<Rule, Name>>>;
  94. }
  95. type UnknownVisitors<T> = {
  96. [name: string]: RuleVisitor<T>
  97. }
  98. type CustomVisitors<T extends CustomAtRules> = {
  99. [Name in keyof T]?: RuleVisitor<CustomAtRule<Name, T[Name]>>
  100. };
  101. type AnyCustomAtRule<C extends CustomAtRules> = {
  102. [Key in keyof C]: CustomAtRule<Key, C[Key]>
  103. }[keyof C];
  104. type RuleVisitors<C extends CustomAtRules> = MappedRuleVisitors & {
  105. unknown?: UnknownVisitors<UnknownAtRule> | Omit<RuleVisitor<UnknownAtRule>, keyof CallableFunction>,
  106. custom?: CustomVisitors<C> | Omit<RuleVisitor<AnyCustomAtRule<C>>, keyof CallableFunction>
  107. };
  108. type PreludeTypes = Exclude<ParsedComponent['type'], 'literal' | 'repeated' | 'token'>;
  109. type SyntaxString = `<${PreludeTypes}>` | `<${PreludeTypes}>+` | `<${PreludeTypes}>#` | (string & {});
  110. type ComponentTypes = {
  111. [Key in PreludeTypes as `<${Key}>`]: FindByType<ParsedComponent, Key>
  112. };
  113. type Repetitions = {
  114. [Key in PreludeTypes as `<${Key}>+` | `<${Key}>#`]: {
  115. type: "repeated",
  116. value: {
  117. components: FindByType<ParsedComponent, Key>[],
  118. multiplier: Multiplier
  119. }
  120. }
  121. };
  122. type MappedPrelude = ComponentTypes & Repetitions;
  123. type MappedBody<P extends CustomAtRuleDefinition['body']> = P extends 'style-block' ? 'rule-list' : P;
  124. interface CustomAtRule<N, R extends CustomAtRuleDefinition> {
  125. name: N,
  126. prelude: R['prelude'] extends keyof MappedPrelude ? MappedPrelude[R['prelude']] : ParsedComponent,
  127. body: FindByType<CustomAtRuleBody, MappedBody<R['body']>>,
  128. loc: Location
  129. }
  130. type CustomAtRuleBody = {
  131. type: 'declaration-list',
  132. value: Required<DeclarationBlock>
  133. } | {
  134. type: 'rule-list',
  135. value: RequiredValue<Rule>[]
  136. };
  137. type FindProperty<Union, Name> = Union extends { property: Name } ? Union : never;
  138. type DeclarationVisitor<P = Declaration> = ((property: P) => ReturnedDeclaration | ReturnedDeclaration[] | void);
  139. type MappedDeclarationVisitors = {
  140. [Name in Exclude<Declaration['property'], 'unparsed' | 'custom'>]?: DeclarationVisitor<FindProperty<Declaration, Name> | FindProperty<Declaration, 'unparsed'>>;
  141. }
  142. type CustomPropertyVisitors = {
  143. [name: string]: DeclarationVisitor<CustomProperty>
  144. }
  145. type DeclarationVisitors = MappedDeclarationVisitors & {
  146. custom?: CustomPropertyVisitors | DeclarationVisitor<CustomProperty>
  147. }
  148. interface RawValue {
  149. /** A raw string value which will be parsed like CSS. */
  150. raw: string
  151. }
  152. type TokenReturnValue = TokenOrValue | TokenOrValue[] | RawValue | void;
  153. type TokenVisitor = (token: Token) => TokenReturnValue;
  154. type VisitableTokenTypes = 'ident' | 'at-keyword' | 'hash' | 'id-hash' | 'string' | 'number' | 'percentage' | 'dimension';
  155. type TokenVisitors = {
  156. [Name in VisitableTokenTypes]?: (token: FindByType<Token, Name>) => TokenReturnValue;
  157. }
  158. type FunctionVisitor = (fn: Function) => TokenReturnValue;
  159. type EnvironmentVariableVisitor = (env: EnvironmentVariable) => TokenReturnValue;
  160. type EnvironmentVariableVisitors = {
  161. [name: string]: EnvironmentVariableVisitor
  162. };
  163. export interface Visitor<C extends CustomAtRules> {
  164. StyleSheet?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
  165. StyleSheetExit?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
  166. Rule?: RuleVisitor | RuleVisitors<C>;
  167. RuleExit?: RuleVisitor | RuleVisitors<C>;
  168. Declaration?: DeclarationVisitor | DeclarationVisitors;
  169. DeclarationExit?: DeclarationVisitor | DeclarationVisitors;
  170. Url?(url: Url): Url | void;
  171. Color?(color: CssColor): CssColor | void;
  172. Image?(image: Image): Image | void;
  173. ImageExit?(image: Image): Image | void;
  174. Length?(length: LengthValue): LengthValue | void;
  175. Angle?(angle: Angle): Angle | void;
  176. Ratio?(ratio: Ratio): Ratio | void;
  177. Resolution?(resolution: Resolution): Resolution | void;
  178. Time?(time: Time): Time | void;
  179. CustomIdent?(ident: string): string | void;
  180. DashedIdent?(ident: string): string | void;
  181. MediaQuery?(query: MediaQuery): ReturnedMediaQuery | ReturnedMediaQuery[] | void;
  182. MediaQueryExit?(query: MediaQuery): ReturnedMediaQuery | ReturnedMediaQuery[] | void;
  183. SupportsCondition?(condition: SupportsCondition): SupportsCondition;
  184. SupportsConditionExit?(condition: SupportsCondition): SupportsCondition;
  185. Selector?(selector: Selector): Selector | Selector[] | void;
  186. Token?: TokenVisitor | TokenVisitors;
  187. Function?: FunctionVisitor | { [name: string]: FunctionVisitor };
  188. FunctionExit?: FunctionVisitor | { [name: string]: FunctionVisitor };
  189. Variable?(variable: Variable): TokenReturnValue;
  190. VariableExit?(variable: Variable): TokenReturnValue;
  191. EnvironmentVariable?: EnvironmentVariableVisitor | EnvironmentVariableVisitors;
  192. EnvironmentVariableExit?: EnvironmentVariableVisitor | EnvironmentVariableVisitors;
  193. }
  194. export interface CustomAtRules {
  195. [name: string]: CustomAtRuleDefinition
  196. }
  197. export interface CustomAtRuleDefinition {
  198. /**
  199. * Defines the syntax for a custom at-rule prelude. The value should be a
  200. * CSS [syntax string](https://drafts.css-houdini.org/css-properties-values-api/#syntax-strings)
  201. * representing the types of values that are accepted. This property may be omitted or
  202. * set to null to indicate that no prelude is accepted.
  203. */
  204. prelude?: SyntaxString | null,
  205. /**
  206. * Defines the type of body contained within the at-rule block.
  207. * - declaration-list: A CSS declaration list, as in a style rule.
  208. * - rule-list: A list of CSS rules, as supported within a non-nested
  209. * at-rule such as `@media` or `@supports`.
  210. * - style-block: Both a declaration list and rule list, as accepted within
  211. * a nested at-rule within a style rule (e.g. `@media` inside a style rule
  212. * with directly nested declarations).
  213. */
  214. body?: 'declaration-list' | 'rule-list' | 'style-block' | null
  215. }
  216. export interface DependencyOptions {
  217. /** Whether to preserve `@import` rules rather than removing them. */
  218. preserveImports?: boolean
  219. }
  220. export type BundleOptions<C extends CustomAtRules> = Omit<TransformOptions<C>, 'code'>;
  221. export interface BundleAsyncOptions<C extends CustomAtRules> extends BundleOptions<C> {
  222. resolver?: Resolver;
  223. }
  224. /** Custom resolver to use when loading CSS files. */
  225. export interface Resolver {
  226. /** Read the given file and return its contents as a string. */
  227. read?: (file: string) => string | Promise<string>;
  228. /**
  229. * Resolve the given CSS import specifier from the provided originating file to a
  230. * path which gets passed to `read()`.
  231. */
  232. resolve?: (specifier: string, originatingFile: string) => string | Promise<string>;
  233. }
  234. export interface Drafts {
  235. /** Whether to enable @custom-media rules. */
  236. customMedia?: boolean
  237. }
  238. export interface NonStandard {
  239. /** Whether to enable the non-standard >>> and /deep/ selector combinators used by Angular and Vue. */
  240. deepSelectorCombinator?: boolean
  241. }
  242. export interface PseudoClasses {
  243. hover?: string,
  244. active?: string,
  245. focus?: string,
  246. focusVisible?: string,
  247. focusWithin?: string
  248. }
  249. export interface TransformResult {
  250. /** The transformed code. */
  251. code: Uint8Array,
  252. /** The generated source map, if enabled. */
  253. map: Uint8Array | void,
  254. /** CSS module exports, if enabled. */
  255. exports: CSSModuleExports | void,
  256. /** CSS module references, if `dashedIdents` is enabled. */
  257. references: CSSModuleReferences,
  258. /** `@import` and `url()` dependencies, if enabled. */
  259. dependencies: Dependency[] | void,
  260. /** Warnings that occurred during compilation. */
  261. warnings: Warning[]
  262. }
  263. export interface Warning {
  264. message: string,
  265. type: string,
  266. value?: any,
  267. loc: ErrorLocation
  268. }
  269. export interface CSSModulesConfig {
  270. /** The pattern to use when renaming class names and other identifiers. Default is `[hash]_[local]`. */
  271. pattern?: string,
  272. /** Whether to rename dashed identifiers, e.g. custom properties. */
  273. dashedIdents?: boolean
  274. }
  275. export type CSSModuleExports = {
  276. /** Maps exported (i.e. original) names to local names. */
  277. [name: string]: CSSModuleExport
  278. };
  279. export interface CSSModuleExport {
  280. /** The local (compiled) name for this export. */
  281. name: string,
  282. /** Whether the export is referenced in this file. */
  283. isReferenced: boolean,
  284. /** Other names that are composed by this export. */
  285. composes: CSSModuleReference[]
  286. }
  287. export type CSSModuleReferences = {
  288. /** Maps placeholder names to references. */
  289. [name: string]: DependencyCSSModuleReference,
  290. };
  291. export type CSSModuleReference = LocalCSSModuleReference | GlobalCSSModuleReference | DependencyCSSModuleReference;
  292. export interface LocalCSSModuleReference {
  293. type: 'local',
  294. /** The local (compiled) name for the reference. */
  295. name: string,
  296. }
  297. export interface GlobalCSSModuleReference {
  298. type: 'global',
  299. /** The referenced global name. */
  300. name: string,
  301. }
  302. export interface DependencyCSSModuleReference {
  303. type: 'dependency',
  304. /** The name to reference within the dependency. */
  305. name: string,
  306. /** The dependency specifier for the referenced file. */
  307. specifier: string
  308. }
  309. export type Dependency = ImportDependency | UrlDependency;
  310. export interface ImportDependency {
  311. type: 'import',
  312. /** The url of the `@import` dependency. */
  313. url: string,
  314. /** The media query for the `@import` rule. */
  315. media: string | null,
  316. /** The `supports()` query for the `@import` rule. */
  317. supports: string | null,
  318. /** The source location where the `@import` rule was found. */
  319. loc: SourceLocation,
  320. /** The placeholder that the import was replaced with. */
  321. placeholder: string
  322. }
  323. export interface UrlDependency {
  324. type: 'url',
  325. /** The url of the dependency. */
  326. url: string,
  327. /** The source location where the `url()` was found. */
  328. loc: SourceLocation,
  329. /** The placeholder that the url was replaced with. */
  330. placeholder: string
  331. }
  332. export interface SourceLocation {
  333. /** The file path in which the dependency exists. */
  334. filePath: string,
  335. /** The start location of the dependency. */
  336. start: Location,
  337. /** The end location (inclusive) of the dependency. */
  338. end: Location
  339. }
  340. export interface Location {
  341. /** The line number (1-based). */
  342. line: number,
  343. /** The column number (0-based). */
  344. column: number
  345. }
  346. export interface ErrorLocation extends Location {
  347. filename: string
  348. }
  349. /**
  350. * Compiles a CSS file, including optionally minifying and lowering syntax to the given
  351. * targets. A source map may also be generated, but this is not enabled by default.
  352. */
  353. export declare function transform<C extends CustomAtRules>(options: TransformOptions<C>): TransformResult;
  354. export interface TransformAttributeOptions {
  355. /** The filename in which the style attribute appeared. Used for error messages and dependencies. */
  356. filename?: string,
  357. /** The source code to transform. */
  358. code: Uint8Array,
  359. /** Whether to enable minification. */
  360. minify?: boolean,
  361. /** The browser targets for the generated code. */
  362. targets?: Targets,
  363. /**
  364. * Whether to analyze `url()` dependencies.
  365. * When enabled, `url()` dependencies are replaced with hashed placeholders
  366. * that can be replaced with the final urls later (after bundling).
  367. * Dependencies are returned as part of the result.
  368. */
  369. analyzeDependencies?: boolean,
  370. /**
  371. * Whether to ignore invalid rules and declarations rather than erroring.
  372. * When enabled, warnings are returned, and the invalid rule or declaration is
  373. * omitted from the output code.
  374. */
  375. errorRecovery?: boolean,
  376. /**
  377. * An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript.
  378. * Multiple visitors can be composed into one using the `composeVisitors` function.
  379. * For optimal performance, visitors should be as specific as possible about what types of values
  380. * they care about so that JavaScript has to be called as little as possible.
  381. */
  382. visitor?: Visitor<never>
  383. }
  384. export interface TransformAttributeResult {
  385. /** The transformed code. */
  386. code: Uint8Array,
  387. /** `@import` and `url()` dependencies, if enabled. */
  388. dependencies: Dependency[] | void,
  389. /** Warnings that occurred during compilation. */
  390. warnings: Warning[]
  391. }
  392. /**
  393. * Compiles a single CSS declaration list, such as an inline style attribute in HTML.
  394. */
  395. export declare function transformStyleAttribute(options: TransformAttributeOptions): TransformAttributeResult;
  396. /**
  397. * Converts a browserslist result into targets that can be passed to lightningcss.
  398. * @param browserslist the result of calling `browserslist`
  399. */
  400. export declare function browserslistToTargets(browserslist: string[]): Targets;
  401. /**
  402. * Bundles a CSS file and its dependencies, inlining @import rules.
  403. */
  404. export declare function bundle<C extends CustomAtRules>(options: BundleOptions<C>): TransformResult;
  405. /**
  406. * Bundles a CSS file and its dependencies asynchronously, inlining @import rules.
  407. */
  408. export declare function bundleAsync<C extends CustomAtRules>(options: BundleAsyncOptions<C>): Promise<TransformResult>;
  409. /**
  410. * Composes multiple visitor objects into a single one.
  411. */
  412. export declare function composeVisitors<C extends CustomAtRules>(visitors: Visitor<C>[]): Visitor<C>;