index.d.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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, Location2 } 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> | VisitorFunction<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: Location2
  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 type VisitorDependency = FileDependency | GlobDependency;
  195. export interface VisitorOptions {
  196. addDependency: (dep: VisitorDependency) => void
  197. }
  198. export type VisitorFunction<C extends CustomAtRules> = (options: VisitorOptions) => Visitor<C>;
  199. export interface CustomAtRules {
  200. [name: string]: CustomAtRuleDefinition
  201. }
  202. export interface CustomAtRuleDefinition {
  203. /**
  204. * Defines the syntax for a custom at-rule prelude. The value should be a
  205. * CSS [syntax string](https://drafts.css-houdini.org/css-properties-values-api/#syntax-strings)
  206. * representing the types of values that are accepted. This property may be omitted or
  207. * set to null to indicate that no prelude is accepted.
  208. */
  209. prelude?: SyntaxString | null,
  210. /**
  211. * Defines the type of body contained within the at-rule block.
  212. * - declaration-list: A CSS declaration list, as in a style rule.
  213. * - rule-list: A list of CSS rules, as supported within a non-nested
  214. * at-rule such as `@media` or `@supports`.
  215. * - style-block: Both a declaration list and rule list, as accepted within
  216. * a nested at-rule within a style rule (e.g. `@media` inside a style rule
  217. * with directly nested declarations).
  218. */
  219. body?: 'declaration-list' | 'rule-list' | 'style-block' | null
  220. }
  221. export interface DependencyOptions {
  222. /** Whether to preserve `@import` rules rather than removing them. */
  223. preserveImports?: boolean
  224. }
  225. export type BundleOptions<C extends CustomAtRules> = Omit<TransformOptions<C>, 'code'>;
  226. export interface BundleAsyncOptions<C extends CustomAtRules> extends BundleOptions<C> {
  227. resolver?: Resolver;
  228. }
  229. /** Custom resolver to use when loading CSS files. */
  230. export interface Resolver {
  231. /** Read the given file and return its contents as a string. */
  232. read?: (file: string) => string | Promise<string>;
  233. /**
  234. * Resolve the given CSS import specifier from the provided originating file to a
  235. * path which gets passed to `read()`.
  236. */
  237. resolve?: (specifier: string, originatingFile: string) => string | Promise<string>;
  238. }
  239. export interface Drafts {
  240. /** Whether to enable @custom-media rules. */
  241. customMedia?: boolean
  242. }
  243. export interface NonStandard {
  244. /** Whether to enable the non-standard >>> and /deep/ selector combinators used by Angular and Vue. */
  245. deepSelectorCombinator?: boolean
  246. }
  247. export interface PseudoClasses {
  248. hover?: string,
  249. active?: string,
  250. focus?: string,
  251. focusVisible?: string,
  252. focusWithin?: string
  253. }
  254. export interface TransformResult {
  255. /** The transformed code. */
  256. code: Uint8Array,
  257. /** The generated source map, if enabled. */
  258. map: Uint8Array | void,
  259. /** CSS module exports, if enabled. */
  260. exports: CSSModuleExports | void,
  261. /** CSS module references, if `dashedIdents` is enabled. */
  262. references: CSSModuleReferences,
  263. /** `@import` and `url()` dependencies, if enabled. */
  264. dependencies: Dependency[] | void,
  265. /** Warnings that occurred during compilation. */
  266. warnings: Warning[]
  267. }
  268. export interface Warning {
  269. message: string,
  270. type: string,
  271. value?: any,
  272. loc: ErrorLocation
  273. }
  274. export interface CSSModulesConfig {
  275. /** The pattern to use when renaming class names and other identifiers. Default is `[hash]_[local]`. */
  276. pattern?: string,
  277. /** Whether to rename dashed identifiers, e.g. custom properties. */
  278. dashedIdents?: boolean,
  279. /** Whether to enable hashing for `@keyframes`. */
  280. animation?: boolean,
  281. /** Whether to enable hashing for CSS grid identifiers. */
  282. grid?: boolean,
  283. /** Whether to enable hashing for `@container` names. */
  284. container?: boolean,
  285. /** Whether to enable hashing for custom identifiers. */
  286. customIdents?: boolean,
  287. /** Whether to require at least one class or id selector in each rule. */
  288. pure?: boolean
  289. }
  290. export type CSSModuleExports = {
  291. /** Maps exported (i.e. original) names to local names. */
  292. [name: string]: CSSModuleExport
  293. };
  294. export interface CSSModuleExport {
  295. /** The local (compiled) name for this export. */
  296. name: string,
  297. /** Whether the export is referenced in this file. */
  298. isReferenced: boolean,
  299. /** Other names that are composed by this export. */
  300. composes: CSSModuleReference[]
  301. }
  302. export type CSSModuleReferences = {
  303. /** Maps placeholder names to references. */
  304. [name: string]: DependencyCSSModuleReference,
  305. };
  306. export type CSSModuleReference = LocalCSSModuleReference | GlobalCSSModuleReference | DependencyCSSModuleReference;
  307. export interface LocalCSSModuleReference {
  308. type: 'local',
  309. /** The local (compiled) name for the reference. */
  310. name: string,
  311. }
  312. export interface GlobalCSSModuleReference {
  313. type: 'global',
  314. /** The referenced global name. */
  315. name: string,
  316. }
  317. export interface DependencyCSSModuleReference {
  318. type: 'dependency',
  319. /** The name to reference within the dependency. */
  320. name: string,
  321. /** The dependency specifier for the referenced file. */
  322. specifier: string
  323. }
  324. export type Dependency = ImportDependency | UrlDependency | FileDependency | GlobDependency;
  325. export interface ImportDependency {
  326. type: 'import',
  327. /** The url of the `@import` dependency. */
  328. url: string,
  329. /** The media query for the `@import` rule. */
  330. media: string | null,
  331. /** The `supports()` query for the `@import` rule. */
  332. supports: string | null,
  333. /** The source location where the `@import` rule was found. */
  334. loc: SourceLocation,
  335. /** The placeholder that the import was replaced with. */
  336. placeholder: string
  337. }
  338. export interface UrlDependency {
  339. type: 'url',
  340. /** The url of the dependency. */
  341. url: string,
  342. /** The source location where the `url()` was found. */
  343. loc: SourceLocation,
  344. /** The placeholder that the url was replaced with. */
  345. placeholder: string
  346. }
  347. export interface FileDependency {
  348. type: 'file',
  349. filePath: string
  350. }
  351. export interface GlobDependency {
  352. type: 'glob',
  353. glob: string
  354. }
  355. export interface SourceLocation {
  356. /** The file path in which the dependency exists. */
  357. filePath: string,
  358. /** The start location of the dependency. */
  359. start: Location,
  360. /** The end location (inclusive) of the dependency. */
  361. end: Location
  362. }
  363. export interface Location {
  364. /** The line number (1-based). */
  365. line: number,
  366. /** The column number (0-based). */
  367. column: number
  368. }
  369. export interface ErrorLocation extends Location {
  370. filename: string
  371. }
  372. /**
  373. * Compiles a CSS file, including optionally minifying and lowering syntax to the given
  374. * targets. A source map may also be generated, but this is not enabled by default.
  375. */
  376. export declare function transform<C extends CustomAtRules>(options: TransformOptions<C>): TransformResult;
  377. export interface TransformAttributeOptions {
  378. /** The filename in which the style attribute appeared. Used for error messages and dependencies. */
  379. filename?: string,
  380. /** The source code to transform. */
  381. code: Uint8Array,
  382. /** Whether to enable minification. */
  383. minify?: boolean,
  384. /** The browser targets for the generated code. */
  385. targets?: Targets,
  386. /**
  387. * Whether to analyze `url()` dependencies.
  388. * When enabled, `url()` dependencies are replaced with hashed placeholders
  389. * that can be replaced with the final urls later (after bundling).
  390. * Dependencies are returned as part of the result.
  391. */
  392. analyzeDependencies?: boolean,
  393. /**
  394. * Whether to ignore invalid rules and declarations rather than erroring.
  395. * When enabled, warnings are returned, and the invalid rule or declaration is
  396. * omitted from the output code.
  397. */
  398. errorRecovery?: boolean,
  399. /**
  400. * An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript.
  401. * Multiple visitors can be composed into one using the `composeVisitors` function.
  402. * For optimal performance, visitors should be as specific as possible about what types of values
  403. * they care about so that JavaScript has to be called as little as possible.
  404. */
  405. visitor?: Visitor<never> | VisitorFunction<never>
  406. }
  407. export interface TransformAttributeResult {
  408. /** The transformed code. */
  409. code: Uint8Array,
  410. /** `@import` and `url()` dependencies, if enabled. */
  411. dependencies: Dependency[] | void,
  412. /** Warnings that occurred during compilation. */
  413. warnings: Warning[]
  414. }
  415. /**
  416. * Compiles a single CSS declaration list, such as an inline style attribute in HTML.
  417. */
  418. export declare function transformStyleAttribute(options: TransformAttributeOptions): TransformAttributeResult;
  419. /**
  420. * Converts a browserslist result into targets that can be passed to lightningcss.
  421. * @param browserslist the result of calling `browserslist`
  422. */
  423. export declare function browserslistToTargets(browserslist: string[]): Targets;
  424. /**
  425. * Bundles a CSS file and its dependencies, inlining @import rules.
  426. */
  427. export declare function bundle<C extends CustomAtRules>(options: BundleOptions<C>): TransformResult;
  428. /**
  429. * Bundles a CSS file and its dependencies asynchronously, inlining @import rules.
  430. */
  431. export declare function bundleAsync<C extends CustomAtRules>(options: BundleAsyncOptions<C>): Promise<TransformResult>;
  432. /**
  433. * Composes multiple visitor objects into a single one.
  434. */
  435. export declare function composeVisitors<C extends CustomAtRules>(visitors: (Visitor<C> | VisitorFunction<C>)[]): Visitor<C> | VisitorFunction<C>;