All files / css / compatibility.ts

100.00% Branches 161/161
100.00% Lines 581/581
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
x1
x2
x2
x6
x2
 
x2
x2
x2
 
 
x2
x2
x2
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x8
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
 
x2
x2
 
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x5
x15
x5
 
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x2
x2
x54
x18
x1089
x1089
x4500
x1125
x1125
x2124
x2124
x18
x18
 
x2
x2
 
x2
x2
 
x2
x2
x21
x63
x700
x1541
x841
x841
x841
x1415
x715
x715
x715
x1404
x704
x704
x704
x1418
x718
x718
x718
x700
x21
x21
x21
 
x2
x2
x180
x900
x180
 
x2
x2
x31886
x33504
x33504
x31886
x31886
x159430
x31886
 
x2
x2
x267068
x800859
x1067747
x1067747
x800859
x800874
x800874
x1067747
x800859
x800863
x800863
x800859
x534115
x267068
 
x2
x2
x540
x180
x189
x189
x197
x197
x197
x189
x180
x181
x181
x181
x180
x181
x181
x181
x180
x181
x181
x181
x181
x180
x181
x181
x181
x181
x180
x180
x195
x195
x195
x195
x720
x181
x181
x180
x182
x182
x180
x206
x206
x1440
x180
 
x2
x2
x180
x900
x180
x180
x180
x180
x180
x180
x1011
x337
x180
x181
x181
x181
x180
x1333
x83820
x20955
x272415
x20955
x39657
x39657
x20955
x36535
x36535
x20955
x62922
x20974
x20955
x20955
x20955
x1333
x180
 
x2
x2
x49854
x16618
x30447
x68482
x68482
x69632
x69632
x68482
x68712
x68712
x68482
x30447
x30447
x16618
x17768
x17768
x16618
x16618
 
x2
x2
x26673
x217288
x27161
x26673
x26673
x26673
x26673
x43031
x60769
x60769
x65396
x65396
x60769
x54762
x48229
x26673
x29308
x253840
x31730
x31730
x31730
x31730
x118084
x26673
x26673
x247668
x45594
x45594
x50577
x48192
x48192
x48405
x48405
x117084
x26673
 
x2
x2
x58450
x162235
x220683
x220683
x622716
x162235
x189862
x189862
x189862
x162235
x166862
x166862
x166862
x202945
x162235
x163155
x163155
x162235
x111351
x58450
 
x2
x2
x16325
x16325
x16325
x17300
x17300
x31673
x16325
x18259
x18259
x18259
x16325
x16538
x16538
x16538
x16538
x16538
x16538
x16325
x16413
x16413
x16413
x16413
x16325
x16937
x16937
x17336
x17336
x17336
x17150
x16325
x28826
x28826
x28826
x29039
x16325
 
x2
x2
x21
x63
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x19643
x19643
x78509
x102570
x102570
x102570
x410280
x102570
x78509
x19643
x19643
x19643
x19643
x78572
x19643
x19643
x176787
x19643
x78572
x19643
x84
x21
x21
x21
 
x2
x2
x19
x19
x19
x19
x19
 
x2
x2
x19
x19
x19
x19
x19
x132
x132
x2069
x2315
x2315
x2069
x132
x19
 
x19
x19
x19
x132
x132
x5392
x9184
x9184
x9184
x6860
x6860
x6860
x132
x924
x132
x1600
x8940
x17008
x17008
x25996
x25996
x26675
x26675
x25996
x17008
x8940
x1600
x132
x132
x132
x132
x132
x19
x19
 
x2
x2
x1583
x1583
x1583
x1583
x12664
x11081
x1583
x11081
x1583
x1583
x1583
x9488
x9488
x9488
x9488
x1583
x9488
x9488
x1583
x1583
x1583
x1696
x1696
x1583
x1583
 
x2
x2
x19
x19
x19
x132
x5505
x5505
x9297
x9297
x9297
x5505
x5505
x5505
x5505
x38982
x10465
x84678
x14113
x14113
x14113
x17781
x17781
x17781
x18267
x18267
x17781
x18137
x18137
x17781
x20531
x20531
x17781
x17857
x17857
x17921
x17921
x17857
x17781
x17781
x17781
 
x17781
x42339
x14113
x10465
x6497
x7086
x7086
x5505
x132
x19
x27
x19
x28
x28
x28
x28
x19
x19
 
x2
x2
x6832
x6832
x8862
x6832
x8413
x6832
x6976
x6832
x7409
x6832
x6838
x6832
x6892
x6832
x9264
x6832
x6832
 
x2
x2
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
x146
 
x2
x2
x3
x36
x36
x45
x45
x45
x3
x3
x13
x182
x182
x13
x13
x3
 
x2
x2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 















































































































































































































































































































































































































































































































































































































































































































































































































































// Imports
import { generate, parse, walk } from "css-tree"
import browserslist from "browserslist"
import bcd from "@mdn/browser-compat-data" with { type: "json" }
import * as semver from "@std/semver"
import type { Arg, Arrayable, Nullable, rw } from "@libs/typing"
import { type levellike as loglevel, Logger } from "@libs/logger"
import { brightGreen, brightMagenta, gray, green, italic, red, yellow } from "@std/fmt/colors"
import { Table } from "@cliffy/table"
export type { Arg, Arrayable, loglevel, Nullable }

/** Browsers list */
const browsers = {
  name: [
    ["chrome", "Chrome"],
    ["edge", "Edge"],
    ["safari", "Safari"],
    ["firefox", "Firefox"],
    ["ff", "Firefox"],
    ["opera", "Opera"],
    ["explorer", "Internet Explorer"],
    ["ie", "Internet Explorer"],
    ["chromeandroid", "Android Chrome"],
    ["and_chr", "Android Chrome"],
    ["ios_saf", "iOS Safari"],
    ["samsung", "Samsung Internet"],
    ["operamini", "Opera Mini"],
    ["op_mini", "Opera Mini"],
    ["op_mob", "Opera Mobile"],
    ["ucandroid", "UC Browser"],
    ["and_uc", "UC Browser"],
    ["android", "Android Browser"],
    ["firefoxandroid", "Android Firefox"],
    ["and_ff", "Android Firefox"],
    ["and_qq", "QQ Browser"],
    ["baidu", "Baidu Browser"],
    ["kaios", "KaiOS Browser"],
    ["electron", "Electron"],
    ["node", "Node.js"],
    ["blackberry", "BlackBerry"],
    ["bb", "BlackBerry"],
    ["ie_mob", "Internet Explorer Mobile"],
  ],
  compatibility: {
    chrome: "chrome",
    edge: "edge",
    safari: "safari",
    firefox: "firefox",
    ff: "firefox",
    opera: "opera",
    ie: "ie",
    explorer: "ie",
    chromeandroid: "chrome_android",
    and_chr: "chrome_android",
    ios_saf: "safari_ios",
    samsung: "samsunginternet_android",
    op_mob: "opera_android",
    android: "webview_android",
    firefoxandroid: "firefox_android",
    and_ff: "firefox_android",
  },
} as const

/** Vendors regex */
const vendors = /^(?:@|::|:)?(?<prefix>-(?:webkit|moz|o|ms|__debug)-)/

/**
 * Compatibility data generator.
 *
 * Check the compatibility of CSS stylesheets with browsers using {@link https://github.com/mdn/browser-compat-data | MDN compatibility browser data}.
 *
 * This parses the CSS stylesheet into an AST and checks against the compatibility data.
 * It will try to check general compatibility for a given feature, and attempt more granular checks for specific values.
 *
 * Note that it may not be entirely accurate as it does not actually check the * validity of the CSS, it only try to map back to the compatibility data.
 * Report can be either printed in console or exported as a already styled HTML table.
 *
 * This is a helper around {@link Report} which resolves css urls, instantiate a new report and return the printed result.
 *
 * @example
 * ```ts
 * import { compatibility } from "./compatibility.ts"
 *
 * // Print compatibility report in console
 * await compatibility(new URL("testing/test_bundle.css", import.meta.url), { query:"defaults", output:"console" })
 * ```
 * @example
 * ```ts
 * import { compatibility } from "./compatibility.ts"
 *
 * // Format compatibility report as HTML table
 * // Use `style: false` to remove <style> tag from output and use your own styling instead
 * await compatibility(new URL("testing/test_bundle.css", import.meta.url), { query:"defaults", output:"html", style:true })
 * ```
 *
 * ```
 * Copyright (c) Simon Lecoq <@lowlighter>. (MIT License)
 * https://github.com/lowlighter/libs/blob/main/LICENSE
 * ```
 * @author Simon Lecoq (lowlighter)
 * @license MIT
 * @module
 */
export async function compatibility(input: URL | string, { query = "defaults", loglevel, ...options }: { query?: Arrayable<string>; loglevel?: loglevel } & Arg<Report["print"], 1> = {}): Promise<string> {
  const code = input instanceof URL ? await fetch(input).then((response) => response.text()) : input
  return new Report(query, { loglevel }).for(code).print(options)
}

/**
 * Report.
 *
 * Create a new compatibility report for a given CSS stylesheet content.
 *
 * Select browsers to test using {@link https://github.com/browserslist/browserslist?tab=readme-ov-file#queries | browserslist queries}.
 *
 * @example
 * ```ts
 * import { Report } from "./compatibility.ts"
 *
 * // Check compatibility
 * const report = new Report("> 1%")
 * const result = report.for("div { backdrop-filter: blur(5px); }")
 * result.features.list.includes("css-backdrop-filter")
 * console.log(result.browsers.ie["9"].support.unsupported)
 *
 * // HTML table reports
 * console.log(report.print(result, { output: "html", verbose: false }))
 *
 * // Console table reports
 * report.print(result, { output: "console", verbose: false })
 * ```
 *
 * ```
 * Copyright (c) Simon Lecoq <@lowlighter>. (MIT License)
 * https://github.com/lowlighter/libs/blob/main/LICENSE
 * ```
 *
 * @author Simon Lecoq (lowlighter)
 * @license MIT
 */
export class Report {
  /** Constructor */
  constructor(query: Arrayable<string>, { loglevel = "error" as loglevel } = {}) {
    this.#log = new Logger({ level: loglevel })
    browserslist(query).forEach((line: string) => {
      const [browser, version] = line.split(" ")
      if (!(browser in browsers.compatibility)) {
        this.#log.with({ browser, version }).warn("not supported (no compatibility data in database)")
        return
      }
      this.#browsers[browser] ??= []
      this.#browsers[browser].push(version)
    })
  }

  /** Logger */
  readonly #log: Logger

  /** Browsers list by name and versions */
  readonly #browsers = {} as Record<browser, version[]>

  /** Create a report for given stylesheet */
  for(stylesheet: string): report {
    const data = [] as data
    walk(parse(stylesheet, { positions: true }), (node: ast_node) => {
      switch (node.type) {
        case "Declaration": {
          this.#process(data, "properties", node, node.property, node.value)
          break
        }
        case "PseudoClassSelector": {
          this.#process(data, "selectors", node, node.name)
          break
        }
        case "Atrule": {
          this.#process(data, "at-rules", node, node.name, node.prelude)
          break
        }
        case "Function": {
          this.#process(data, "types", node, node.name)
          break
        }
      }
    })
    return this.#report(data)
  }

  /** Format location from AST */
  #location(location: ast_location) {
    const { source: file, start: { line, column } } = location
    return { file, line, column }
  }

  /** Format version from AST */
  #version(version: string) {
    if (version.includes("-")) {
      version = version.split("-")[1]
    }
    version = version.replace("≤", "<=").replace("≥", ">=")
    const [[{ major, minor, patch }]] = semver.parseRange(version)
    return { major, minor, patch }
  }

  /** Search feature in compatibility data recursively */
  #search(section: string, name: feature, compatibility = bcd.css[section] as bcd_compatibility, _feature = null as Nullable<string>): Nullable<string> {
    for (const feature of Object.keys(compatibility)) {
      if (feature === "__compat") {
        continue
      }
      if (name in compatibility[feature]) {
        return _feature ?? feature
      }
      const _search = this.#search(section, name, compatibility[feature] as bcd_compatibility, feature)
      if (_search) {
        return _search
      }
    }
    return null
  }

  /** Prepreocess */
  #preprocess(log: Logger, section: bcd_section, _node: ast_node, name: string, values: ast_value, realname: Nullable<string>, prefix: Nullable<string>, skipped: boolean) {
    const original = [...arguments]
    if (vendors.test(name)) {
      prefix = name.match(vendors)!.groups!.prefix
      if (!bcd.css[section][name]) {
        realname = name
        name = name.replace(vendors, "")
      }
    }
    if ((section === "properties") && (name.startsWith("--"))) {
      realname = name
      name = "custom-property"
    }
    if ((section === "types") && /^rgba?$/.test(name)) {
      realname = name
      name = "color"
    }
    if ((section === "types") && (name === "var")) {
      realname = `${name}()`
      name = "custom-property"
      section = "properties"
    }
    if ((section === "types") && (name === "minmax")) {
      realname = `${name}()`
      name = "grid-template-columns"
      section = "properties"
    }
    const feature = this.#search(section, name)
    if (feature) {
      log.trace(`found ${name} in [${feature}]`)
      realname = name
      name = feature
    }
    if (["src", "format"].includes(name)) {
      skipped = true
    }
    if (original[1] !== section) {
      log.trace(`changed section from "${original[1]}" to "${section}"`)
    }
    if (realname !== null) {
      log.trace(`changed name from "${original[3]}" to "${name}"`)
    }
    return { section, name, _values: values, realname, prefix, skipped }
  }

  /** Process a single AST node */
  #process(data: data, section: bcd_section, node: ast_node, name: string, _values?: ast_value) {
    const location = this.#location(node.loc)
    const log = this.#log.with({ location: `${location.line}:${location.column}`, section, name })
    let realname = null as Nullable<string>, prefix = null as Nullable<string>, skipped = false
    ;({ section, name, _values, realname, prefix, skipped } = this.#preprocess(log, section, node, name, _values!, realname, prefix, skipped))
    const feature = bcd.css[section][name]?.__compat?.source_file?.replace(/^css\//, "").replace(/\.json$/, "") ?? `${section}/${name}`
    const value = _values ? this.#clean(generate(_values) as string) : realname ?? null
    let logger = log
    if (value !== null) {
      logger = log.with({ value })
    }
    if (skipped) {
      logger.debug("skipped")
      return
    }
    for (const browser in this.#browsers) {
      for (const version of this.#browsers[browser]) {
        logger = logger.with({ browser, version })
        const { level, status } = this.#support(logger, bcd.css[section][name] as bcd_compatibility, browser, version, value ? this.#tags(log, value, _values) : [], prefix)
        data.push({ feature, browser, version, location, value, level, status: { deprecated: status.deprecated, experimental: status.experimental, nonstandard: !status.standard_track } })
        if (!status.deprecated) {
          delete (status as rw).deprecated
        }
        if (!status.experimental) {
          delete (status as rw).experimental
        }
        if (status.standard_track === false) {
          Object.assign(status, { nonstandard: true })
        }
        delete (status as rw).standard_track
        logger.with(status).log(level)
      }
    }
  }

  /** Tags value for additional granular checks */
  #tags(log: Logger, value: value, _values?: ast_value) {
    const tags = [value] as tag[]
    if (_values) {
      walk(_values, (value: ast_value) => {
        switch (true) {
          case value.type === "Percentage":
            tags.push("percentages")
            break
          case (value.type === "Number") && (Number.parseFloat(value.value) < 0):
            tags.push("negative_values")
            break
        }
      })
    }
    if (tags.length > 1) {
      log.debug(`added tags: ${tags.slice(1).join(", ")}`)
    }
    return tags
  }

  /** Resolve support from compatibility data against a single browser version */
  #support(log: Logger, compatibility: bcd_compatibility | void, browser: browser, version: version, tags: tag[], prefix: Nullable<string>): { level: level; status: bcd_status } {
    if (!compatibility) {
      return { level: "unknown", status: { standard_track: true, deprecated: false, experimental: false } }
    }
    const support = compatibility.__compat.support[browsers.compatibility[browser as keyof typeof browsers.compatibility]] ?? compatibility.__compat.support[browser]
    const status = compatibility.__compat.status
    // Granular compatibility checks (if value is provided)
    if (tags?.length) {
      for (const tag of tags) {
        const _compatibility = this.#value_compatibility(log, compatibility, tag)
        if (_compatibility) {
          return this.#support(log, _compatibility, browser, version, [], prefix)
        }
      }
    }
    // Multiple compatibility checks
    if (Array.isArray(support)) {
      for (const _support of support) {
        const _result = this.#support(log, { __compat: { support: { [browser]: _support }, status } } as bcd_compatibility, browser, version, [], prefix)
        if (_result.level !== "unknown") {
          return _result
        }
      }
      return { level: "unknown", status }
    } // Simple compatibility checks
    else if (typeof support === "object") {
      return { level: this.#test(log, support, version, prefix), status }
    } // No compatibility data available
    else if (support === undefined) {
      log.warn(`no compatibility data available (available: ${Object.keys(compatibility.__compat.support)})`)
    } // Unimplemented
    else {
      log.error("unimplemented support type, please open an issue", support)
    }
    return { level: "unknown", status }
  }

  /** Search for granular compatibility based on value (either referenced directly in data or in description between <code/> tags) */
  #value_compatibility(log: Logger, compatibility: bcd_compatibility, tag: tag): bcd_compatibility | false {
    for (const key in compatibility) {
      if (key === "__compat") {
        continue
      }
      const keywords = [key]
      if (compatibility[key].__compat.description) {
        const description = compatibility[key].__compat.description!
        keywords.push(...Array.from(description.matchAll(/^<code>([\s\S]+?)<\/code>$/g)).map((match) => (match as string[])[1]))
      }
      if (keywords.includes(tag)) {
        log.trace(`matched granular rule "${key}"`)
        return compatibility[key] as bcd_compatibility
      }
      const _compatibility = this.#value_compatibility(log, compatibility[key] as bcd_compatibility, tag)
      if (_compatibility) {
        return _compatibility
      }
    }
    return false
  }

  /** Test browser version against a single matcher */
  #test(log: Logger, support: bcd_support, version: version, prefix: Nullable<string>) {
    let level = "unsupported" as level
    const tested = this.#version(version)
    if (!support.version_added) {
      return level
    }
    const added = this.#version(support.version_added)
    if (!semver.greaterOrEqual(tested, added)) {
      log.trace(`unsupported prior version ${support.version_added}`)
      return level
    }
    if (support.version_removed) {
      const removed = this.#version(support.version_removed)
      if (semver.greaterOrEqual(tested, removed)) {
        log.trace(`support removed in version ${support.version_removed}`)
        return level
      }
    }
    if (support.partial_implementation) {
      log.trace(`partially supported since version ${support.version_added}`)
      level = "partial"
      return level
    }
    if (support.prefix) {
      log.trace(`supported with ${support.prefix} since version ${support.version_added}`)
      if (prefix !== support.prefix) {
        log.trace(`"${prefix}" does not match required "${support.prefix}"`)
        return "prefixed"
      }
      level = "supported"
    } else {
      log.trace(`supported since version ${support.version_added}`)
      level = "supported"
    }
    return level
  }

  /** Format data into usable one */
  #report(data: data) {
    const features = {
      list: [...new Set<feature>(data.map(({ feature }) => feature))],
      status: {
        deprecated: {} as feature_map,
        experimental: {} as feature_map,
        nonstandard: {} as feature_map,
      },
      support: {
        unknown: {} as feature_map,
        unsupported: {} as feature_map,
        partial: {} as feature_map,
        prefixed: {} as feature_map,
        supported: {} as feature_map,
      },
    } as report["features"]
    const browsers = {} as report["browsers"]
    for (const { feature, browser, version, location, value, level, ...entry } of data) {
      // Sort by status
      for (const status of Object.keys(features.status) as Array<keyof status>) {
        if (entry.status[status as keyof status]) {
          features.status[status][feature] ??= {}
          features.status[status][feature][browser] ??= {}
          features.status[status][feature][browser][version] ??= []
          features.status[status][feature][browser][version].push({ location, value })
        }
      }
      // Sort by support
      features.support[level][feature] ??= {}
      features.support[level][feature][browser] ??= {}
      features.support[level][feature][browser][version] ??= []
      features.support[level][feature][browser][version].push({ location, value })
      // Sort by browser
      browsers[browser] ??= {}
      browsers[browser][version] ??= { support: { unknown: {}, unsupported: {}, partial: {}, prefixed: {}, supported: {} } }
      browsers[browser][version].support[level][feature] ??= []
      browsers[browser][version].support[level][feature].push({ location, value })
    }
    const report = { features, browsers } as report
    report.print = this.print.bind(this, report)
    return report
  }

  /** Generate table data from reported data */
  #view(data: ReturnType<Report["for"]>, type: "browsers") {
    switch (type) {
      case "browsers":
        return this.#view_browsers(data)
    }
  }

  /** Generate browsers table */
  #view_browsers(_data: ReturnType<Report["for"]>) {
    // Prepare data (compute number of versions, filter browsers with data and sort data by descending version)
    const columns = Math.max(...Object.entries(this.#browsers).filter(([browser]) => browsers.name.some(([id]) => id === browser)).map(([_, versions]) => versions.length))
    const rows = browsers.name.filter(([id]) => id in this.#browsers)
    const data = Object.fromEntries(
      Object.entries(_data.browsers).map(([browser, versions]) => [
        browser,
        Object.entries(versions).sort(([a], [b]) => {
          if (a.includes("-")) {
            a = a.split("-")[1]
          }
          return Number.parseFloat(b) - Number.parseFloat(a)
        }),
      ]),
    )
    // Generate table
    const table = []
    for (const [id, name] of rows) {
      const row = [] as Nullable<table_entry>[]
      for (let i = 0; i < columns; i++) {
        if (!data[id][i]) {
          row.push(null)
          continue
        }
        const [version, { support }] = data[id][i]
        row.push(this.#view_browsers_cell(id, version, name, support))
      }
      // Prepare summary data
      const support = { unknown: {}, partial: {}, unsupported: {}, prefixed: {}, supported: {} } as Record<level, browser_map>
      for (const version of row.filter(Boolean) as table_entry[]) {
        for (const level of Object.keys(version.features) as level[]) {
          for (const feature in version.features[level]) {
            support[level][feature] ??= []
            for (const occurence of version.features[level][feature]) {
              const { location } = occurence
              if (!support[level][feature].some(({ location: { line, column } }) => line === location.line && column === location.column)) {
                support[level][feature].push(occurence)
              }
            }
          }
        }
      }
      const summary = this.#view_browsers_cell(id, "all", name, support)
      summary.users = row.reduce((total, cell) => total + (cell?.users ?? 0), 0)
      row.unshift(summary)
      table.push(row)
    }
    return table
  }

  /** Generate browsers table cell */
  #view_browsers_cell(id: string, version: version, name: string, support: Record<level, browser_map>) {
    const cell = {
      browser: name,
      version,
      count: {
        flat: { unknown: 0, unsupported: 0, partial: 0, prefixed: 0, supported: 0, total: 0 },
        percentage: { unknown: 0, unsupported: 0, partial: 0, prefixed: 0, supported: 0 },
      },
      features: { unknown: {}, unsupported: {}, partial: {}, prefixed: {}, supported: {} },
      users: NaN,
    }
    for (const level of Object.keys(cell.features) as level[]) {
      cell.count.flat[level] = Object.keys(support[level]).length
      cell.count.flat.total += cell.count.flat[level]
      cell.features[level] = support[level]
    }
    for (const level of Object.keys(cell.features) as level[]) {
      cell.count.percentage[level] = 100 * cell.count.flat[level] / cell.count.flat.total
    }
    try {
      cell.users = browserslist.coverage(browserslist(`${id} ${version}`))
    } catch {
      // Ignore
    }
    return cell
  }

  /** Print table */
  print(data: ReturnType<Report["for"]>, { view = "browsers" as const, output = "console" as "console" | "html", verbose = false, style = true } = {}): string {
    const table = this.#view(data, view)
    const body = new Array(table[0]?.length).fill(null).map(() => []) as string[][]
    for (let i = 0; i < table.length; i++) {
      for (let j = 0; j < table[0].length; j++) {
        const cell = table[i][j]
        if (!cell) {
          body[j].push("")
          continue
        }
        let text = j === 0 ? cell.browser : cell.version
        text += `\n${this.#color(`${Math.floor(cell.count.percentage.supported)}%`, -2, output)}`
        text = this.#color(text, cell.count.percentage.supported, output)
        if (verbose) {
          for (const level of ["unsupported", "partial", "prefixed", "unknown"] as Exclude<level, "supported">[]) {
            for (const feature in cell.features[level]) {
              const color = { unknown: NaN, partial: 80, unsupported: 0, prefixed: -1 }[level]
              const [type, name] = feature.split("/")
              const messages = new Set<string>()
              for (const { value } of cell.features[level][feature]) {
                let message = ""
                switch (type) {
                  case "at-rules":
                    message = `@${name}`
                    break
                  case "selectors":
                    message = `:${value ?? name}`
                    break
                  case "properties":
                    message = `${name}: ${value};`
                    break
                  case "types":
                    message = `${name}()`
                    if (value) {
                      message = `[${name}] ${value}()`
                    }
                    break
                }
                messages.add(
                  `\n${this.#color(message, color, output)}`,
                )
              }
              text += [...messages].sort((a, b) => a.localeCompare(b)).join("")
            }
          }
        }
        body[j].push(text)
      }
    }
    switch (output) {
      case "console":
        return new Table().align("center").border(true).body(body).render().toString()
      case "html":
        return `<table class="css-compatibility-table">\n${
          body.map((row, i) => `  <tr>${row.map((cell) => !cell ? `    \n    <td data-empty></td>` : `\n    <t${i ? "d" : "h"}>\n${cell.replaceAll(/^(<span .*)$/gm, "      $1<br>").replaceAll(/\n([^< ].+<\/span>)/g, "$1<br>")}\n    </t${i ? "d" : "h"}>`).join("")}\n  </tr>`)
            .join("\n")
        }\n</table>${style ? `\n${Report.styling}` : ""}`
    }
  }

  /** Apply coloring */
  #color(string: string, value: number, output: "console" | "html") {
    switch (true) {
      case Number.isNaN(value):
        return output === "html" ? `<span data-unknown>${string}</span>` : gray(string)
      case value === -2:
        return output === "html" ? `<span data-version>${string}</span>` : italic(string)
      case value === -1:
        return output === "html" ? `<span data-prefix>${string}</span>` : brightMagenta(string)
      case value >= 100:
        return output === "html" ? `<span data-perfect>${string}</span>` : brightGreen(string)
      case value >= 90:
        return output === "html" ? `<span data-good>${string}</span>` : green(string)
      case value >= 80:
        return output === "html" ? `<span data-ok>${string}</span>` : yellow(string)
      default:
        return output === "html" ? `<span data-bad>${string}</span>` : red(string)
    }
  }

  /** Clean value */
  #clean(string: string) {
    return string
      .trim()
      // Format functions
      .replaceAll(/(url|format|attr|var)\(.*?\)/g, "$1()")
      // Clean colors
      .replaceAll(/#[0-9a-fA-F]{3,8}/g, "")
      .replaceAll(/rgba?\(.*?\)/g, "")
      // Clean numbers and units
      .replaceAll(/-?(?:(?:\d+(\.d*)?|(?:\d*\.\d+)))([cm]m|p[ctx]|Q|in|%|r?em|v[hw]|[r]lh|m?s|turn)?/g, "")
      // Clean strings
      .replaceAll(/"[^"]*?"/g, "")
      // Clean vars
      .replaceAll(/var\(\)/g, "")
      .replaceAll(/\s+/g, " ")
      .replaceAll(/,+/g, "")
      .trim() || "*"
  }

  /** Inject testing properties for test cases (internal, only for testing purposes) */
  protected static testing() {
    Object.assign(bcd.css.properties, {
      ["-debug-empty-array"]: { __compat: { support: { chrome: [] }, status: { standard_track: false, deprecated: false, experimental: true } } },
      ["-debug-unimplemented"]: { __compat: { support: { chrome: false }, status: { standard_track: false, deprecated: false, experimental: true } } },
      ["-debug-prefixed"]: { __compat: { support: { chrome: { version_added: "0", prefix: "-__debug-" } }, status: { standard_track: false, deprecated: false, experimental: true } } },
      ["-debug-prefixed-invalid"]: { __compat: { support: { chrome: { version_added: "0", prefix: "-invalid-" } }, status: { standard_track: false, deprecated: false, experimental: true } } },
      ["-debug-removed"]: { __compat: { support: { chrome: { version_added: "0", version_removed: "0" } }, status: { standard_track: false, deprecated: false, experimental: true } } },
    })
    for (let i = 1; i <= 10; i++) {
      Object.assign(bcd.css.properties, {
        [`-debug-pass-${i}`]: { __compat: { support: { chrome: { version_added: "0" } }, status: { standard_track: false, deprecated: false, experimental: true } } },
        [`-debug-fail-${i}`]: { __compat: { support: { chrome: { version_added: false } }, status: { standard_track: false, deprecated: false, experimental: true } } },
      })
    }
  }

  /** HTML styling for tables */
  protected static styling = `
  <style>
    .css-compatibility-table {
      border-collapse: collapse;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
    }
    .css-compatibility-table th {
      background-color: #d0d7de;
    }
    .css-compatibility-table th, .css-compatibility-table td {
      border: 1px solid black;
      padding: 1em;
      white-space: nowrap;
      vertical-align: top;
      text-align: left;
    }
    .css-compatibility-table :is(td, th) :nth-child(1) {
      display: block;
      text-align: center;
      font-weight: bold;
      font-size: 1.15em;
      border-bottom: 1px solid currentColor;
    }
    .css-compatibility-table [data-empty] {background-color: #000;}
    .css-compatibility-table [data-unknown] {color: #848d97;}
    .css-compatibility-table [data-prefix] {color: #8250df;}
    .css-compatibility-table [data-perfect] {color: #1a7f37;}
    .css-compatibility-table [data-good] {color: #3fb950;}
    .css-compatibility-table [data-ok] {color: #d29922;}
    .css-compatibility-table [data-bad] {color: #f85149;}
  </style>`.split("\n").map((line) => line.trim()).join("").replaceAll(/([:\],]) /g, "$1").replaceAll(/ \{/g, "{") as string
}

/** Browser name */
export type browser = string

/** Browser version */
export type version = string

/** CSS feature name */
export type feature = string

/** CSS value */
export type value = string

/** Feature tag (internal) */
type tag = string

/** Feature status */
type status = { nonstandard: boolean; deprecated: boolean; experimental: boolean }

/** Declaration location */
export type location = { file: unknown; line: number; column: number }

/** Support level */
export type level = "unknown" | "unsupported" | "partial" | "prefixed" | "supported"

/** Browser compat data section */
type bcd_section = "selectors" | "properties" | "types" | "at-rules"

/** Browser compat data feature status */
type bcd_status = { standard_track: boolean; deprecated: boolean; experimental: boolean }

/** Browser compat data support matcher */
type bcd_support = {
  version_added: string | false
  version_removed?: string
  partial_implementation?: boolean
  prefix?: string
  notes?: Arrayable<string>
}

/** Browser compat data compatibility structure (internal) */
type _bcd_compatibility = {
  __compat: {
    description?: string
    support: Record<browser, Arrayable<bcd_support>>
    status: bcd_status
  }
}

/** Browser compat data compatibility structure */
type bcd_compatibility = _bcd_compatibility & { [key: string]: _bcd_compatibility }

/** AST node */
type ast_node = {
  type: string
  name: string
  loc: ast_location
  property: string
  value: ast_value
  prelude: ast_value
}

/** AST location */
type ast_location = { source: string; start: { line: number; column: number; offset: number }; end: { line: number; column: number; offset: number } }

/** AST value */
type ast_value = { type: string; loc: ast_location; name: string; value: string; unit: string }

/** Report data */
type data = Array<{
  feature: feature
  browser: browser
  version: version
  location: location
  value: Nullable<value>
  level: level
  status: status
}>

/** Feature map report */
export type feature_map = Record<feature, Record<browser, Record<version, Array<{ location: location; value: Nullable<value> }>>>>

/** Browser map report */
export type browser_map = Record<feature, Array<{ location: location; value: Nullable<value> }>>

/** Report */
export type report = {
  features: {
    list: feature[]
    status: {
      deprecated: feature_map
      experimental: feature_map
      nonstandard: feature_map
    }
    support: Record<level, feature_map>
  }
  browsers: Record<
    browser,
    Record<version, { support: Record<level, browser_map> }>
  >
  print: (options?: Arg<Report["print"], 1>) => ReturnType<Report["print"]>
}

/** Table entry */
type table_entry = {
  browser: browser
  version: string
  count: {
    flat: Record<level | "total", number>
    percentage: Record<level, number>
  }
  features: Record<level, browser_map>
  users: number
}