├── .editorconfig ├── .eslintrc.json ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── close_stale_issues.yml │ ├── node.js.yml │ ├── npm-publish.yml │ └── release-please.yml ├── .gitignore ├── .husky ├── commit-msg └── pre-push ├── .npmignore ├── .prettierignore ├── .prettierrc.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── _config.yml ├── commitlint.config.js ├── docs ├── html │ ├── comp_table.css │ └── comp_table.html └── img │ ├── comp_table.png │ └── crittr_benchmark.png ├── examples ├── basic.js ├── basic_no_css.js ├── benchmark.js └── local_urls.js ├── index.js ├── jest.config.js ├── lib ├── Constants.js ├── classes │ ├── Ast.class.js │ ├── Crittr.class.js │ ├── CssTransformator.class.js │ └── Rule.class.js ├── evaluation │ ├── extract_critical_with_css.js │ └── extract_critical_without_css.js └── helper │ └── localFileServer.js ├── package-lock.json ├── package.json ├── postcss.config.cjs └── test ├── data ├── favicon.ico ├── test.css └── test.html ├── helpers.js ├── results └── .gitkeep ├── setup.js ├── teardown.js └── tests ├── basic.test.js ├── basic_nocss.test.js ├── mq.test.js ├── mq_nocss.test.js ├── screenshot.test.js └── vendor_prefix.test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 4 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | # max_line_length = 120 11 | # tab_width = 4 12 | # ij_continuation_indent_size = 8 13 | # ij_formatter_off_tag = @formatter:off 14 | # ij_formatter_on_tag = @formatter:on 15 | # ij_formatter_tags_enabled = false 16 | # ij_smart_tabs = false 17 | # ij_visual_guides = none 18 | # ij_wrap_on_typing = false 19 | 20 | [*.css] 21 | # ij_css_align_closing_brace_with_properties = false 22 | # ij_css_blank_lines_around_nested_selector = 1 23 | # ij_css_blank_lines_between_blocks = 1 24 | # ij_css_brace_placement = end_of_line 25 | # ij_css_enforce_quotes_on_format = false 26 | # ij_css_hex_color_long_format = false 27 | # ij_css_hex_color_lower_case = false 28 | # ij_css_hex_color_short_format = false 29 | # ij_css_hex_color_upper_case = false 30 | # ij_css_keep_blank_lines_in_code = 2 31 | # ij_css_keep_indents_on_empty_lines = false 32 | # ij_css_keep_single_line_blocks = false 33 | # ij_css_properties_order = font,font-family,font-size,font-weight,font-style,font-variant,font-size-adjust,font-stretch,line-height,position,z-index,top,right,bottom,left,display,visibility,float,clear,overflow,overflow-x,overflow-y,clip,zoom,align-content,align-items,align-self,flex,flex-flow,flex-basis,flex-direction,flex-grow,flex-shrink,flex-wrap,justify-content,order,box-sizing,width,min-width,max-width,height,min-height,max-height,margin,margin-top,margin-right,margin-bottom,margin-left,padding,padding-top,padding-right,padding-bottom,padding-left,table-layout,empty-cells,caption-side,border-spacing,border-collapse,list-style,list-style-position,list-style-type,list-style-image,content,quotes,counter-reset,counter-increment,resize,cursor,user-select,nav-index,nav-up,nav-right,nav-down,nav-left,transition,transition-delay,transition-timing-function,transition-duration,transition-property,transform,transform-origin,animation,animation-name,animation-duration,animation-play-state,animation-timing-function,animation-delay,animation-iteration-count,animation-direction,text-align,text-align-last,vertical-align,white-space,text-decoration,text-emphasis,text-emphasis-color,text-emphasis-style,text-emphasis-position,text-indent,text-justify,letter-spacing,word-spacing,text-outline,text-transform,text-wrap,text-overflow,text-overflow-ellipsis,text-overflow-mode,word-wrap,word-break,tab-size,hyphens,pointer-events,opacity,color,border,border-width,border-style,border-color,border-top,border-top-width,border-top-style,border-top-color,border-right,border-right-width,border-right-style,border-right-color,border-bottom,border-bottom-width,border-bottom-style,border-bottom-color,border-left,border-left-width,border-left-style,border-left-color,border-radius,border-top-left-radius,border-top-right-radius,border-bottom-right-radius,border-bottom-left-radius,border-image,border-image-source,border-image-slice,border-image-width,border-image-outset,border-image-repeat,outline,outline-width,outline-style,outline-color,outline-offset,background,background-color,background-image,background-repeat,background-attachment,background-position,background-position-x,background-position-y,background-clip,background-origin,background-size,box-decoration-break,box-shadow,text-shadow 34 | # ij_css_space_after_colon = true 35 | # ij_css_space_before_opening_brace = true 36 | # ij_css_use_double_quotes = true 37 | # ij_css_value_alignment = do_not_align 38 | 39 | [*.scss] 40 | # ij_scss_align_closing_brace_with_properties = false 41 | # ij_scss_blank_lines_around_nested_selector = 1 42 | # ij_scss_blank_lines_between_blocks = 1 43 | # ij_scss_brace_placement = 0 44 | # ij_scss_enforce_quotes_on_format = false 45 | # ij_scss_hex_color_long_format = false 46 | # ij_scss_hex_color_lower_case = false 47 | # ij_scss_hex_color_short_format = false 48 | # ij_scss_hex_color_upper_case = false 49 | # ij_scss_keep_blank_lines_in_code = 2 50 | # ij_scss_keep_indents_on_empty_lines = false 51 | # ij_scss_keep_single_line_blocks = false 52 | # ij_scss_properties_order = font,font-family,font-size,font-weight,font-style,font-variant,font-size-adjust,font-stretch,line-height,position,z-index,top,right,bottom,left,display,visibility,float,clear,overflow,overflow-x,overflow-y,clip,zoom,align-content,align-items,align-self,flex,flex-flow,flex-basis,flex-direction,flex-grow,flex-shrink,flex-wrap,justify-content,order,box-sizing,width,min-width,max-width,height,min-height,max-height,margin,margin-top,margin-right,margin-bottom,margin-left,padding,padding-top,padding-right,padding-bottom,padding-left,table-layout,empty-cells,caption-side,border-spacing,border-collapse,list-style,list-style-position,list-style-type,list-style-image,content,quotes,counter-reset,counter-increment,resize,cursor,user-select,nav-index,nav-up,nav-right,nav-down,nav-left,transition,transition-delay,transition-timing-function,transition-duration,transition-property,transform,transform-origin,animation,animation-name,animation-duration,animation-play-state,animation-timing-function,animation-delay,animation-iteration-count,animation-direction,text-align,text-align-last,vertical-align,white-space,text-decoration,text-emphasis,text-emphasis-color,text-emphasis-style,text-emphasis-position,text-indent,text-justify,letter-spacing,word-spacing,text-outline,text-transform,text-wrap,text-overflow,text-overflow-ellipsis,text-overflow-mode,word-wrap,word-break,tab-size,hyphens,pointer-events,opacity,color,border,border-width,border-style,border-color,border-top,border-top-width,border-top-style,border-top-color,border-right,border-right-width,border-right-style,border-right-color,border-bottom,border-bottom-width,border-bottom-style,border-bottom-color,border-left,border-left-width,border-left-style,border-left-color,border-radius,border-top-left-radius,border-top-right-radius,border-bottom-right-radius,border-bottom-left-radius,border-image,border-image-source,border-image-slice,border-image-width,border-image-outset,border-image-repeat,outline,outline-width,outline-style,outline-color,outline-offset,background,background-color,background-image,background-repeat,background-attachment,background-position,background-position-x,background-position-y,background-clip,background-origin,background-size,box-decoration-break,box-shadow,text-shadow 53 | # ij_scss_space_after_colon = true 54 | # ij_scss_space_before_opening_brace = true 55 | # ij_scss_use_double_quotes = true 56 | # ij_scss_value_alignment = 0 57 | 58 | [.editorconfig] 59 | ij_editorconfig_align_group_field_declarations = true 60 | # ij_editorconfig_space_after_colon = false 61 | ij_editorconfig_space_after_comma = true 62 | # ij_editorconfig_space_before_colon = false 63 | # ij_editorconfig_space_before_comma = false 64 | ij_editorconfig_spaces_around_assignment_operators = true 65 | 66 | [{*.ant, *.fxml, *.jhm, *.jnlp, *.jrxml, *.rng, *.tld, *.wsdl, *.xml, *.xsd, *.xsl, *.xslt, *.xul, phpunit.xml.dist}] 67 | # ij_xml_align_attributes = true 68 | # ij_xml_align_text = false 69 | # ij_xml_attribute_wrap = normal 70 | # ij_xml_block_comment_at_first_column = true 71 | # ij_xml_keep_blank_lines = 2 72 | # ij_xml_keep_indents_on_empty_lines = false 73 | # ij_xml_keep_line_breaks = true 74 | # ij_xml_keep_line_breaks_in_text = true 75 | # ij_xml_keep_whitespaces = false 76 | # ij_xml_keep_whitespaces_around_cdata = preserve 77 | # ij_xml_keep_whitespaces_inside_cdata = false 78 | # ij_xml_line_comment_at_first_column = true 79 | # ij_xml_space_after_tag_name = false 80 | # ij_xml_space_around_equals_in_attribute = false 81 | # ij_xml_space_inside_empty_tag = false 82 | # ij_xml_text_wrap = normal 83 | 84 | [{*.ats, *.ts}] 85 | # ij_continuation_indent_size = 4 86 | # ij_typescript_align_imports = false 87 | # ij_typescript_align_multiline_array_initializer_expression = false 88 | # ij_typescript_align_multiline_binary_operation = false 89 | # ij_typescript_align_multiline_chained_methods = false 90 | # ij_typescript_align_multiline_extends_list = false 91 | # ij_typescript_align_multiline_for = true 92 | # ij_typescript_align_multiline_parameters = true 93 | # ij_typescript_align_multiline_parameters_in_calls = false 94 | # ij_typescript_align_multiline_ternary_operation = false 95 | # ij_typescript_align_object_properties = 0 96 | # ij_typescript_align_union_types = false 97 | # ij_typescript_align_var_statements = 0 98 | # ij_typescript_array_initializer_new_line_after_left_brace = false 99 | # ij_typescript_array_initializer_right_brace_on_new_line = false 100 | # ij_typescript_array_initializer_wrap = off 101 | # ij_typescript_assignment_wrap = off 102 | # ij_typescript_binary_operation_sign_on_next_line = false 103 | # ij_typescript_binary_operation_wrap = off 104 | # ij_typescript_blacklist_imports = rxjs/Rx,node_modules/**,**/node_modules/**,@angular/material,@angular/material/typings/** 105 | # ij_typescript_blank_lines_after_imports = 1 106 | # ij_typescript_blank_lines_around_class = 1 107 | # ij_typescript_blank_lines_around_field = 0 108 | # ij_typescript_blank_lines_around_field_in_interface = 0 109 | # ij_typescript_blank_lines_around_function = 1 110 | # ij_typescript_blank_lines_around_method = 1 111 | # ij_typescript_blank_lines_around_method_in_interface = 1 112 | # ij_typescript_block_brace_style = end_of_line 113 | # ij_typescript_call_parameters_new_line_after_left_paren = false 114 | # ij_typescript_call_parameters_right_paren_on_new_line = false 115 | # ij_typescript_call_parameters_wrap = off 116 | # ij_typescript_catch_on_new_line = false 117 | # ij_typescript_chained_call_dot_on_new_line = true 118 | # ij_typescript_class_brace_style = end_of_line 119 | # ij_typescript_comma_on_new_line = false 120 | # ij_typescript_do_while_brace_force = never 121 | # ij_typescript_else_on_new_line = false 122 | # ij_typescript_enforce_trailing_comma = keep 123 | # ij_typescript_extends_keyword_wrap = off 124 | # ij_typescript_extends_list_wrap = off 125 | # ij_typescript_field_prefix = _ 126 | # ij_typescript_file_name_style = relaxed 127 | # ij_typescript_finally_on_new_line = false 128 | # ij_typescript_for_brace_force = never 129 | # ij_typescript_for_statement_new_line_after_left_paren = false 130 | # ij_typescript_for_statement_right_paren_on_new_line = false 131 | # ij_typescript_for_statement_wrap = off 132 | # ij_typescript_force_quote_style = false 133 | # ij_typescript_force_semicolon_style = false 134 | # ij_typescript_function_expression_brace_style = end_of_line 135 | # ij_typescript_if_brace_force = never 136 | # ij_typescript_import_merge_members = global 137 | # ij_typescript_import_prefer_absolute_path = global 138 | # ij_typescript_import_sort_members = true 139 | # ij_typescript_import_sort_module_name = false 140 | # ij_typescript_import_use_node_resolution = true 141 | # ij_typescript_imports_wrap = on_every_item 142 | # ij_typescript_indent_case_from_switch = true 143 | # ij_typescript_indent_chained_calls = true 144 | # ij_typescript_indent_package_children = 0 145 | # ij_typescript_jsdoc_include_types = false 146 | # ij_typescript_jsx_attribute_value = braces 147 | # ij_typescript_keep_blank_lines_in_code = 2 148 | # ij_typescript_keep_first_column_comment = true 149 | # ij_typescript_keep_indents_on_empty_lines = false 150 | # ij_typescript_keep_line_breaks = true 151 | # ij_typescript_keep_simple_blocks_in_one_line = false 152 | # ij_typescript_keep_simple_methods_in_one_line = false 153 | # ij_typescript_line_comment_add_space = true 154 | # ij_typescript_line_comment_at_first_column = false 155 | # ij_typescript_method_brace_style = end_of_line 156 | # ij_typescript_method_call_chain_wrap = off 157 | # ij_typescript_method_parameters_new_line_after_left_paren = false 158 | # ij_typescript_method_parameters_right_paren_on_new_line = false 159 | # ij_typescript_method_parameters_wrap = off 160 | # ij_typescript_object_literal_wrap = on_every_item 161 | # ij_typescript_parentheses_expression_new_line_after_left_paren = false 162 | # ij_typescript_parentheses_expression_right_paren_on_new_line = false 163 | # ij_typescript_place_assignment_sign_on_next_line = false 164 | # ij_typescript_prefer_as_type_cast = false 165 | # ij_typescript_prefer_explicit_types_function_expression_returns = false 166 | # ij_typescript_prefer_explicit_types_function_returns = false 167 | # ij_typescript_prefer_explicit_types_vars_fields = false 168 | # ij_typescript_prefer_parameters_wrap = false 169 | # ij_typescript_reformat_c_style_comments = false 170 | # ij_typescript_space_after_colon = true 171 | # ij_typescript_space_after_comma = true 172 | # ij_typescript_space_after_dots_in_rest_parameter = false 173 | # ij_typescript_space_after_generator_mult = true 174 | # ij_typescript_space_after_property_colon = true 175 | # ij_typescript_space_after_quest = true 176 | # ij_typescript_space_after_type_colon = true 177 | # ij_typescript_space_after_unary_not = false 178 | # ij_typescript_space_before_async_arrow_lparen = true 179 | # ij_typescript_space_before_catch_keyword = true 180 | # ij_typescript_space_before_catch_left_brace = true 181 | # ij_typescript_space_before_catch_parentheses = true 182 | # ij_typescript_space_before_class_lbrace = true 183 | # ij_typescript_space_before_class_left_brace = true 184 | # ij_typescript_space_before_colon = true 185 | # ij_typescript_space_before_comma = false 186 | # ij_typescript_space_before_do_left_brace = true 187 | # ij_typescript_space_before_else_keyword = true 188 | # ij_typescript_space_before_else_left_brace = true 189 | # ij_typescript_space_before_finally_keyword = true 190 | # ij_typescript_space_before_finally_left_brace = true 191 | # ij_typescript_space_before_for_left_brace = true 192 | # ij_typescript_space_before_for_parentheses = true 193 | # ij_typescript_space_before_for_semicolon = false 194 | # ij_typescript_space_before_function_left_parenth = true 195 | # ij_typescript_space_before_generator_mult = false 196 | # ij_typescript_space_before_if_left_brace = true 197 | # ij_typescript_space_before_if_parentheses = true 198 | # ij_typescript_space_before_method_call_parentheses = false 199 | # ij_typescript_space_before_method_left_brace = true 200 | # ij_typescript_space_before_method_parentheses = false 201 | # ij_typescript_space_before_property_colon = false 202 | # ij_typescript_space_before_quest = true 203 | # ij_typescript_space_before_switch_left_brace = true 204 | # ij_typescript_space_before_switch_parentheses = true 205 | # ij_typescript_space_before_try_left_brace = true 206 | # ij_typescript_space_before_type_colon = false 207 | # ij_typescript_space_before_unary_not = false 208 | # ij_typescript_space_before_while_keyword = true 209 | # ij_typescript_space_before_while_left_brace = true 210 | # ij_typescript_space_before_while_parentheses = true 211 | # ij_typescript_spaces_around_additive_operators = true 212 | # ij_typescript_spaces_around_arrow_function_operator = true 213 | # ij_typescript_spaces_around_assignment_operators = true 214 | # ij_typescript_spaces_around_bitwise_operators = true 215 | # ij_typescript_spaces_around_equality_operators = true 216 | # ij_typescript_spaces_around_logical_operators = true 217 | # ij_typescript_spaces_around_multiplicative_operators = true 218 | # ij_typescript_spaces_around_relational_operators = true 219 | # ij_typescript_spaces_around_shift_operators = true 220 | # ij_typescript_spaces_around_unary_operator = false 221 | # ij_typescript_spaces_within_array_initializer_brackets = false 222 | # ij_typescript_spaces_within_brackets = false 223 | # ij_typescript_spaces_within_catch_parentheses = false 224 | # ij_typescript_spaces_within_for_parentheses = false 225 | # ij_typescript_spaces_within_if_parentheses = false 226 | # ij_typescript_spaces_within_imports = false 227 | # ij_typescript_spaces_within_interpolation_expressions = false 228 | # ij_typescript_spaces_within_method_call_parentheses = false 229 | # ij_typescript_spaces_within_method_parentheses = false 230 | # ij_typescript_spaces_within_object_literal_braces = false 231 | # ij_typescript_spaces_within_object_type_braces = true 232 | # ij_typescript_spaces_within_parentheses = false 233 | # ij_typescript_spaces_within_switch_parentheses = false 234 | # ij_typescript_spaces_within_type_assertion = false 235 | # ij_typescript_spaces_within_union_types = true 236 | # ij_typescript_spaces_within_while_parentheses = false 237 | # ij_typescript_special_else_if_treatment = true 238 | # ij_typescript_ternary_operation_signs_on_next_line = false 239 | # ij_typescript_ternary_operation_wrap = off 240 | # ij_typescript_union_types_wrap = on_every_item 241 | # ij_typescript_use_chained_calls_group_indents = false 242 | # ij_typescript_use_double_quotes = true 243 | # ij_typescript_use_explicit_js_extension = global 244 | # ij_typescript_use_path_mapping = always 245 | # ij_typescript_use_public_modifier = false 246 | # ij_typescript_use_semicolon_after_statement = true 247 | # ij_typescript_var_declaration_wrap = normal 248 | # ij_typescript_while_brace_force = never 249 | # ij_typescript_while_on_new_line = false 250 | # ij_typescript_wrap_comments = false 251 | 252 | [{*.bash, *.sh, *.zsh}] 253 | indent_size = 2 254 | tab_width = 2 255 | # ij_shell_binary_ops_start_line = false 256 | # ij_shell_keep_column_alignment_padding = false 257 | # ij_shell_minify_program = false 258 | # ij_shell_redirect_followed_by_space = false 259 | # ij_shell_switch_cases_indented = false 260 | 261 | [{*.cjs, *.js}] 262 | # ij_continuation_indent_size = 4 263 | # ij_javascript_align_imports = false 264 | # ij_javascript_align_multiline_array_initializer_expression = false 265 | # ij_javascript_align_multiline_binary_operation = false 266 | # ij_javascript_align_multiline_chained_methods = true 267 | # ij_javascript_align_multiline_extends_list = false 268 | # ij_javascript_align_multiline_for = true 269 | # ij_javascript_align_multiline_parameters = true 270 | # ij_javascript_align_multiline_parameters_in_calls = false 271 | # ij_javascript_align_multiline_ternary_operation = false 272 | # ij_javascript_align_object_properties = 1 273 | # ij_javascript_align_union_types = false 274 | # ij_javascript_align_var_statements = 2 275 | # ij_javascript_array_initializer_new_line_after_left_brace = false 276 | # ij_javascript_array_initializer_right_brace_on_new_line = false 277 | # ij_javascript_array_initializer_wrap = off 278 | # ij_javascript_assignment_wrap = off 279 | # ij_javascript_binary_operation_sign_on_next_line = false 280 | # ij_javascript_binary_operation_wrap = off 281 | # ij_javascript_blacklist_imports = rxjs/Rx,node_modules/**,**/node_modules/**,@angular/material,@angular/material/typings/** 282 | # ij_javascript_blank_lines_after_imports = 1 283 | # ij_javascript_blank_lines_around_class = 1 284 | # ij_javascript_blank_lines_around_field = 0 285 | # ij_javascript_blank_lines_around_function = 1 286 | # ij_javascript_blank_lines_around_method = 1 287 | # ij_javascript_block_brace_style = end_of_line 288 | # ij_javascript_call_parameters_new_line_after_left_paren = false 289 | # ij_javascript_call_parameters_right_paren_on_new_line = false 290 | # ij_javascript_call_parameters_wrap = off 291 | # ij_javascript_catch_on_new_line = false 292 | # ij_javascript_chained_call_dot_on_new_line = true 293 | # ij_javascript_class_brace_style = end_of_line 294 | # ij_javascript_comma_on_new_line = false 295 | # ij_javascript_do_while_brace_force = never 296 | # ij_javascript_else_on_new_line = false 297 | # ij_javascript_enforce_trailing_comma = remove 298 | # ij_javascript_extends_keyword_wrap = off 299 | # ij_javascript_extends_list_wrap = off 300 | # ij_javascript_field_prefix = _ 301 | # ij_javascript_file_name_style = relaxed 302 | # ij_javascript_finally_on_new_line = false 303 | # ij_javascript_for_brace_force = never 304 | # ij_javascript_for_statement_new_line_after_left_paren = false 305 | # ij_javascript_for_statement_right_paren_on_new_line = false 306 | # ij_javascript_for_statement_wrap = off 307 | # ij_javascript_force_quote_style = false 308 | # ij_javascript_force_semicolon_style = false 309 | # ij_javascript_function_expression_brace_style = end_of_line 310 | # ij_javascript_if_brace_force = never 311 | # ij_javascript_import_merge_members = global 312 | # ij_javascript_import_prefer_absolute_path = global 313 | # ij_javascript_import_sort_members = true 314 | # ij_javascript_import_sort_module_name = false 315 | # ij_javascript_import_use_node_resolution = true 316 | # ij_javascript_imports_wrap = on_every_item 317 | # ij_javascript_indent_case_from_switch = true 318 | # ij_javascript_indent_chained_calls = true 319 | # ij_javascript_indent_package_children = 0 320 | # ij_javascript_jsx_attribute_value = braces 321 | # ij_javascript_keep_blank_lines_in_code = 1 322 | # ij_javascript_keep_first_column_comment = true 323 | # ij_javascript_keep_indents_on_empty_lines = false 324 | # ij_javascript_keep_line_breaks = true 325 | # ij_javascript_keep_simple_blocks_in_one_line = false 326 | # ij_javascript_keep_simple_methods_in_one_line = false 327 | # ij_javascript_line_comment_add_space = false 328 | # ij_javascript_line_comment_at_first_column = true 329 | # ij_javascript_method_brace_style = end_of_line 330 | # ij_javascript_method_call_chain_wrap = off 331 | # ij_javascript_method_parameters_new_line_after_left_paren = false 332 | # ij_javascript_method_parameters_right_paren_on_new_line = false 333 | # ij_javascript_method_parameters_wrap = off 334 | # ij_javascript_object_literal_wrap = on_every_item 335 | # ij_javascript_parentheses_expression_new_line_after_left_paren = false 336 | # ij_javascript_parentheses_expression_right_paren_on_new_line = false 337 | # ij_javascript_place_assignment_sign_on_next_line = false 338 | # ij_javascript_prefer_as_type_cast = false 339 | # ij_javascript_prefer_explicit_types_function_expression_returns = false 340 | # ij_javascript_prefer_explicit_types_function_returns = false 341 | # ij_javascript_prefer_explicit_types_vars_fields = false 342 | # ij_javascript_prefer_parameters_wrap = false 343 | # ij_javascript_reformat_c_style_comments = false 344 | # ij_javascript_space_after_colon = true 345 | # ij_javascript_space_after_comma = true 346 | # ij_javascript_space_after_dots_in_rest_parameter = false 347 | # ij_javascript_space_after_generator_mult = true 348 | # ij_javascript_space_after_property_colon = true 349 | # ij_javascript_space_after_quest = true 350 | # ij_javascript_space_after_type_colon = true 351 | # ij_javascript_space_after_unary_not = false 352 | # ij_javascript_space_before_async_arrow_lparen = true 353 | # ij_javascript_space_before_catch_keyword = true 354 | # ij_javascript_space_before_catch_left_brace = true 355 | # ij_javascript_space_before_catch_parentheses = true 356 | # ij_javascript_space_before_class_lbrace = true 357 | # ij_javascript_space_before_class_left_brace = true 358 | # ij_javascript_space_before_colon = true 359 | # ij_javascript_space_before_comma = false 360 | # ij_javascript_space_before_do_left_brace = true 361 | # ij_javascript_space_before_else_keyword = true 362 | # ij_javascript_space_before_else_left_brace = true 363 | # ij_javascript_space_before_finally_keyword = true 364 | # ij_javascript_space_before_finally_left_brace = true 365 | # ij_javascript_space_before_for_left_brace = true 366 | # ij_javascript_space_before_for_parentheses = true 367 | # ij_javascript_space_before_for_semicolon = false 368 | # ij_javascript_space_before_function_left_parenth = true 369 | # ij_javascript_space_before_generator_mult = false 370 | # ij_javascript_space_before_if_left_brace = true 371 | # ij_javascript_space_before_if_parentheses = true 372 | # ij_javascript_space_before_method_call_parentheses = false 373 | # ij_javascript_space_before_method_left_brace = true 374 | # ij_javascript_space_before_method_parentheses = false 375 | # ij_javascript_space_before_property_colon = false 376 | # ij_javascript_space_before_quest = true 377 | # ij_javascript_space_before_switch_left_brace = true 378 | # ij_javascript_space_before_switch_parentheses = true 379 | # ij_javascript_space_before_try_left_brace = true 380 | # ij_javascript_space_before_type_colon = false 381 | # ij_javascript_space_before_unary_not = false 382 | # ij_javascript_space_before_while_keyword = true 383 | # ij_javascript_space_before_while_left_brace = true 384 | # ij_javascript_space_before_while_parentheses = true 385 | # ij_javascript_spaces_around_additive_operators = true 386 | # ij_javascript_spaces_around_arrow_function_operator = true 387 | # ij_javascript_spaces_around_assignment_operators = true 388 | # ij_javascript_spaces_around_bitwise_operators = true 389 | # ij_javascript_spaces_around_equality_operators = true 390 | # ij_javascript_spaces_around_logical_operators = true 391 | # ij_javascript_spaces_around_multiplicative_operators = true 392 | # ij_javascript_spaces_around_relational_operators = true 393 | # ij_javascript_spaces_around_shift_operators = true 394 | # ij_javascript_spaces_around_unary_operator = false 395 | # ij_javascript_spaces_within_array_initializer_brackets = false 396 | # ij_javascript_spaces_within_brackets = false 397 | # ij_javascript_spaces_within_catch_parentheses = false 398 | # ij_javascript_spaces_within_for_parentheses = false 399 | # ij_javascript_spaces_within_if_parentheses = false 400 | # ij_javascript_spaces_within_imports = true 401 | # ij_javascript_spaces_within_interpolation_expressions = false 402 | # ij_javascript_spaces_within_method_call_parentheses = false 403 | # ij_javascript_spaces_within_method_parentheses = false 404 | # ij_javascript_spaces_within_object_literal_braces = false 405 | # ij_javascript_spaces_within_object_type_braces = true 406 | # ij_javascript_spaces_within_parentheses = false 407 | # ij_javascript_spaces_within_switch_parentheses = false 408 | # ij_javascript_spaces_within_type_assertion = false 409 | # ij_javascript_spaces_within_union_types = true 410 | # ij_javascript_spaces_within_while_parentheses = false 411 | # ij_javascript_special_else_if_treatment = true 412 | # ij_javascript_ternary_operation_signs_on_next_line = false 413 | # ij_javascript_ternary_operation_wrap = off 414 | # ij_javascript_union_types_wrap = on_every_item 415 | # ij_javascript_use_chained_calls_group_indents = false 416 | # ij_javascript_use_double_quotes = false 417 | # ij_javascript_use_explicit_js_extension = global 418 | # ij_javascript_use_path_mapping = always 419 | # ij_javascript_use_public_modifier = false 420 | # ij_javascript_use_semicolon_after_statement = true 421 | # ij_javascript_var_declaration_wrap = normal 422 | # ij_javascript_while_brace_force = never 423 | # ij_javascript_while_on_new_line = false 424 | # ij_javascript_wrap_comments = false 425 | 426 | [{*.ctp, *.hphp, *.inc, *.module, *.php, *.php4, *.php5, *.phtml}] 427 | # ij_continuation_indent_size = 4 428 | # ij_php_align_assignments = false 429 | # ij_php_align_class_constants = false 430 | # ij_php_align_group_field_declarations = false 431 | # ij_php_align_inline_comments = false 432 | # ij_php_align_key_value_pairs = true 433 | # ij_php_align_multiline_array_initializer_expression = false 434 | # ij_php_align_multiline_binary_operation = false 435 | # ij_php_align_multiline_chained_methods = false 436 | # ij_php_align_multiline_extends_list = true 437 | # ij_php_align_multiline_for = true 438 | # ij_php_align_multiline_parameters = false 439 | # ij_php_align_multiline_parameters_in_calls = true 440 | # ij_php_align_multiline_ternary_operation = false 441 | # ij_php_align_phpdoc_comments = true 442 | # ij_php_align_phpdoc_param_names = true 443 | # ij_php_anonymous_brace_style = end_of_line 444 | # ij_php_api_weight = 28 445 | # ij_php_array_initializer_new_line_after_left_brace = true 446 | # ij_php_array_initializer_right_brace_on_new_line = true 447 | # ij_php_array_initializer_wrap = on_every_item 448 | # ij_php_assignment_wrap = off 449 | # ij_php_attributes_wrap = off 450 | # ij_php_author_weight = 28 451 | # ij_php_binary_operation_sign_on_next_line = false 452 | # ij_php_binary_operation_wrap = off 453 | # ij_php_blank_lines_after_class_header = 1 454 | # ij_php_blank_lines_after_function = 1 455 | # ij_php_blank_lines_after_imports = 1 456 | # ij_php_blank_lines_after_opening_tag = 1 457 | # ij_php_blank_lines_after_package = 1 458 | # ij_php_blank_lines_around_class = 1 459 | # ij_php_blank_lines_around_constants = 0 460 | # ij_php_blank_lines_around_field = 0 461 | # ij_php_blank_lines_around_method = 1 462 | # ij_php_blank_lines_before_class_end = 0 463 | # ij_php_blank_lines_before_imports = 1 464 | # ij_php_blank_lines_before_method_body = 0 465 | # ij_php_blank_lines_before_package = 1 466 | # ij_php_blank_lines_before_return_statement = 1 467 | # ij_php_blank_lines_between_imports = 1 468 | # ij_php_block_brace_style = end_of_line 469 | # ij_php_call_parameters_new_line_after_left_paren = true 470 | # ij_php_call_parameters_right_paren_on_new_line = true 471 | # ij_php_call_parameters_wrap = on_every_item 472 | # ij_php_catch_on_new_line = false 473 | # ij_php_category_weight = 28 474 | # ij_php_class_brace_style = next_line 475 | # ij_php_comma_after_last_array_element = false 476 | # ij_php_concat_spaces = true 477 | # ij_php_copyright_weight = 28 478 | # ij_php_deprecated_weight = 28 479 | # ij_php_do_while_brace_force = always 480 | # ij_php_else_if_style = combine 481 | # ij_php_else_on_new_line = false 482 | # ij_php_example_weight = 28 483 | # ij_php_extends_keyword_wrap = off 484 | # ij_php_extends_list_wrap = on_every_item 485 | # ij_php_fields_default_visibility = private 486 | # ij_php_filesource_weight = 28 487 | # ij_php_finally_on_new_line = false 488 | # ij_php_for_brace_force = always 489 | # ij_php_for_statement_new_line_after_left_paren = true 490 | # ij_php_for_statement_right_paren_on_new_line = true 491 | # ij_php_for_statement_wrap = off 492 | # ij_php_force_short_declaration_array_style = true 493 | # ij_php_getters_setters_naming_style = camel_case 494 | # ij_php_getters_setters_order_style = getters_first 495 | # ij_php_global_weight = 28 496 | # ij_php_group_use_wrap = on_every_item 497 | # ij_php_if_brace_force = always 498 | # ij_php_if_lparen_on_next_line = false 499 | # ij_php_if_rparen_on_next_line = false 500 | # ij_php_ignore_weight = 28 501 | # ij_php_import_sorting = alphabetic 502 | # ij_php_indent_break_from_case = true 503 | # ij_php_indent_case_from_switch = true 504 | # ij_php_indent_code_in_php_tags = false 505 | # ij_php_internal_weight = 28 506 | # ij_php_keep_blank_lines_after_lbrace = 0 507 | # ij_php_keep_blank_lines_before_right_brace = 0 508 | # ij_php_keep_blank_lines_in_code = 1 509 | # ij_php_keep_blank_lines_in_declarations = 1 510 | # ij_php_keep_control_statement_in_one_line = false 511 | # ij_php_keep_first_column_comment = false 512 | # ij_php_keep_indents_on_empty_lines = false 513 | # ij_php_keep_line_breaks = true 514 | # ij_php_keep_rparen_and_lbrace_on_one_line = true 515 | # ij_php_keep_simple_classes_in_one_line = false 516 | # ij_php_keep_simple_methods_in_one_line = false 517 | # ij_php_lambda_brace_style = next_line 518 | # ij_php_license_weight = 28 519 | # ij_php_line_comment_add_space = false 520 | # ij_php_line_comment_at_first_column = true 521 | # ij_php_link_weight = 28 522 | # ij_php_lower_case_boolean_const = true 523 | # ij_php_lower_case_keywords = true 524 | # ij_php_lower_case_null_const = true 525 | # ij_php_method_brace_style = next_line 526 | # ij_php_method_call_chain_wrap = off 527 | # ij_php_method_parameters_new_line_after_left_paren = true 528 | # ij_php_method_parameters_right_paren_on_new_line = true 529 | # ij_php_method_parameters_wrap = on_every_item 530 | # ij_php_method_weight = 28 531 | # ij_php_modifier_list_wrap = false 532 | # ij_php_multiline_chained_calls_semicolon_on_new_line = false 533 | # ij_php_namespace_brace_style = 2 534 | # ij_php_new_line_after_php_opening_tag = true 535 | # ij_php_null_type_position = in_the_end 536 | # ij_php_package_weight = 28 537 | # ij_php_param_weight = 0 538 | # ij_php_parameters_attributes_wrap = off 539 | # ij_php_parentheses_expression_new_line_after_left_paren = false 540 | # ij_php_parentheses_expression_right_paren_on_new_line = false 541 | # ij_php_phpdoc_blank_line_before_tags = false 542 | # ij_php_phpdoc_blank_lines_around_parameters = true 543 | # ij_php_phpdoc_keep_blank_lines = false 544 | # ij_php_phpdoc_param_spaces_between_name_and_description = 1 545 | # ij_php_phpdoc_param_spaces_between_tag_and_type = 1 546 | # ij_php_phpdoc_param_spaces_between_type_and_name = 1 547 | # ij_php_phpdoc_use_fqcn = false 548 | # ij_php_phpdoc_wrap_long_lines = true 549 | # ij_php_place_assignment_sign_on_next_line = false 550 | # ij_php_place_parens_for_constructor = 0 551 | # ij_php_property_read_weight = 28 552 | # ij_php_property_weight = 28 553 | # ij_php_property_write_weight = 28 554 | # ij_php_return_type_on_new_line = false 555 | # ij_php_return_weight = 1 556 | # ij_php_see_weight = 28 557 | # ij_php_since_weight = 28 558 | # ij_php_sort_phpdoc_elements = true 559 | # ij_php_space_after_colon = true 560 | # ij_php_space_after_colon_in_named_argument = true 561 | # ij_php_space_after_colon_in_return_type = true 562 | # ij_php_space_after_comma = true 563 | # ij_php_space_after_for_semicolon = true 564 | # ij_php_space_after_quest = true 565 | # ij_php_space_after_type_cast = false 566 | # ij_php_space_after_unary_not = false 567 | # ij_php_space_before_array_initializer_left_brace = false 568 | # ij_php_space_before_catch_keyword = true 569 | # ij_php_space_before_catch_left_brace = true 570 | # ij_php_space_before_catch_parentheses = true 571 | # ij_php_space_before_class_left_brace = true 572 | # ij_php_space_before_closure_left_parenthesis = true 573 | # ij_php_space_before_colon = true 574 | # ij_php_space_before_colon_in_named_argument = false 575 | # ij_php_space_before_colon_in_return_type = false 576 | # ij_php_space_before_comma = false 577 | # ij_php_space_before_do_left_brace = true 578 | # ij_php_space_before_else_keyword = true 579 | # ij_php_space_before_else_left_brace = true 580 | # ij_php_space_before_finally_keyword = true 581 | # ij_php_space_before_finally_left_brace = true 582 | # ij_php_space_before_for_left_brace = true 583 | # ij_php_space_before_for_parentheses = true 584 | # ij_php_space_before_for_semicolon = false 585 | # ij_php_space_before_if_left_brace = true 586 | # ij_php_space_before_if_parentheses = true 587 | # ij_php_space_before_method_call_parentheses = false 588 | # ij_php_space_before_method_left_brace = true 589 | # ij_php_space_before_method_parentheses = false 590 | # ij_php_space_before_quest = true 591 | # ij_php_space_before_short_closure_left_parenthesis = false 592 | # ij_php_space_before_switch_left_brace = true 593 | # ij_php_space_before_switch_parentheses = true 594 | # ij_php_space_before_try_left_brace = true 595 | # ij_php_space_before_unary_not = false 596 | # ij_php_space_before_while_keyword = true 597 | # ij_php_space_before_while_left_brace = true 598 | # ij_php_space_before_while_parentheses = true 599 | # ij_php_space_between_ternary_quest_and_colon = false 600 | # ij_php_spaces_around_additive_operators = true 601 | # ij_php_spaces_around_arrow = false 602 | # ij_php_spaces_around_assignment_in_declare = false 603 | # ij_php_spaces_around_assignment_operators = true 604 | # ij_php_spaces_around_bitwise_operators = true 605 | # ij_php_spaces_around_equality_operators = true 606 | # ij_php_spaces_around_logical_operators = true 607 | # ij_php_spaces_around_multiplicative_operators = true 608 | # ij_php_spaces_around_null_coalesce_operator = true 609 | # ij_php_spaces_around_relational_operators = true 610 | # ij_php_spaces_around_shift_operators = true 611 | # ij_php_spaces_around_unary_operator = false 612 | # ij_php_spaces_around_var_within_brackets = false 613 | # ij_php_spaces_within_array_initializer_braces = false 614 | # ij_php_spaces_within_brackets = false 615 | # ij_php_spaces_within_catch_parentheses = false 616 | # ij_php_spaces_within_for_parentheses = false 617 | # ij_php_spaces_within_if_parentheses = false 618 | # ij_php_spaces_within_method_call_parentheses = false 619 | # ij_php_spaces_within_method_parentheses = false 620 | # ij_php_spaces_within_parentheses = false 621 | # ij_php_spaces_within_short_echo_tags = true 622 | # ij_php_spaces_within_switch_parentheses = false 623 | # ij_php_spaces_within_while_parentheses = false 624 | # ij_php_special_else_if_treatment = false 625 | # ij_php_subpackage_weight = 28 626 | # ij_php_ternary_operation_signs_on_next_line = false 627 | # ij_php_ternary_operation_wrap = off 628 | # ij_php_throws_weight = 2 629 | # ij_php_todo_weight = 28 630 | # ij_php_unknown_tag_weight = 28 631 | # ij_php_upper_case_boolean_const = false 632 | # ij_php_upper_case_null_const = false 633 | # ij_php_uses_weight = 28 634 | # ij_php_var_weight = 28 635 | # ij_php_variable_naming_style = mixed 636 | # ij_php_version_weight = 28 637 | # ij_php_while_brace_force = always 638 | # ij_php_while_on_new_line = false 639 | 640 | [{*.har, *.jsb2, *.jsb3, *.json, .babelrc, .eslintrc, .stylelintrc, bowerrc, composer.lock, jest.config}] 641 | # indent_size = 2 642 | # ij_json_keep_blank_lines_in_code = 0 643 | # ij_json_keep_indents_on_empty_lines = false 644 | # ij_json_keep_line_breaks = true 645 | # ij_json_space_after_colon = true 646 | # ij_json_space_after_comma = true 647 | # ij_json_space_before_colon = true 648 | # ij_json_space_before_comma = false 649 | # ij_json_spaces_within_braces = false 650 | # ij_json_spaces_within_brackets = false 651 | # ij_json_wrap_long_lines = false 652 | 653 | [{*.htm, *.html, *.sht, *.shtm, *.shtml}] 654 | # ij_html_add_new_line_before_tags = body,div,p,form,h1,h2,h3 655 | # ij_html_align_attributes = true 656 | # ij_html_align_text = false 657 | # ij_html_attribute_wrap = normal 658 | # ij_html_block_comment_at_first_column = true 659 | # ij_html_do_not_align_children_of_min_lines = 0 660 | # ij_html_do_not_break_if_inline_tags = title,h1,h2,h3,h4,h5,h6,p 661 | # ij_html_do_not_indent_children_of_tags = ?php,? 662 | # ij_html_enforce_quotes = false 663 | # ij_html_inline_tags = a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,input,kbd,label,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var 664 | # ij_html_keep_blank_lines = 2 665 | # ij_html_keep_indents_on_empty_lines = false 666 | # ij_html_keep_line_breaks = true 667 | # ij_html_keep_line_breaks_in_text = true 668 | # ij_html_keep_whitespaces = false 669 | # ij_html_keep_whitespaces_inside = span,pre,textarea 670 | # ij_html_line_comment_at_first_column = true 671 | # ij_html_new_line_after_last_attribute = never 672 | # ij_html_new_line_before_first_attribute = never 673 | # ij_html_quote_style = double 674 | # ij_html_remove_new_line_before_tags = br 675 | # ij_html_space_after_tag_name = false 676 | # ij_html_space_around_equality_in_attribute = false 677 | # ij_html_space_inside_empty_tag = false 678 | # ij_html_text_wrap = normal 679 | # ij_html_uniform_ident = false 680 | 681 | [{*.markdown, *.md}] 682 | trim_trailing_whitespace = false 683 | # ij_markdown_force_one_space_after_blockquote_symbol = true 684 | # ij_markdown_force_one_space_after_header_symbol = true 685 | # ij_markdown_force_one_space_after_list_bullet = true 686 | # ij_markdown_force_one_space_between_words = true 687 | # ij_markdown_keep_indents_on_empty_lines = false 688 | # ij_markdown_max_lines_around_block_elements = 1 689 | # ij_markdown_max_lines_around_header = 1 690 | # ij_markdown_max_lines_between_paragraphs = 1 691 | # ij_markdown_min_lines_around_block_elements = 1 692 | # ij_markdown_min_lines_around_header = 1 693 | # ij_markdown_min_lines_between_paragraphs = 1 694 | 695 | [{*.yaml, *.yml}] 696 | indent_size = 2 697 | ij_yaml_align_values_properties = do_not_align 698 | # ij_yaml_autoinsert_sequence_marker = true 699 | # ij_yaml_block_mapping_on_new_line = false 700 | # ij_yaml_indent_sequence_value = true 701 | ij_yaml_keep_indents_on_empty_lines = false 702 | ij_yaml_keep_line_breaks = true 703 | # ij_yaml_sequence_on_new_line = false 704 | # ij_yaml_space_before_colon = false 705 | ij_yaml_spaces_within_braces = true 706 | ij_yaml_spaces_within_brackets = true 707 | 708 | # Handle minified files extra 709 | [*.min.*] 710 | insert_final_newline = false 711 | 712 | [.gitignore] 713 | insert_final_newline = false 714 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": false, 4 | "es2021": true 5 | }, 6 | "extends": ["eslint:recommended", "prettier"], 7 | "parser": "@babel/eslint-parser", 8 | "parserOptions": { 9 | "ecmaVersion": 12, 10 | "sourceType": "script" 11 | }, 12 | "plugins": ["@babel", "sort-destructure-keys"], 13 | "rules": { 14 | "accessor-pairs": "error", 15 | "array-bracket-newline": "error", 16 | "array-bracket-spacing": "error", 17 | "array-callback-return": "error", 18 | "array-element-newline": "off", 19 | "arrow-body-style": "error", 20 | "arrow-parens": "error", 21 | "arrow-spacing": "error", 22 | 23 | "block-scoped-var": "error", 24 | "block-spacing": "error", 25 | "brace-style": "error", 26 | "callback-return": "error", 27 | "camelcase": "error", 28 | "capitalized-comments": "off", 29 | "class-methods-use-this": "off", 30 | "comma-dangle": "off", 31 | "comma-spacing": [ 32 | "error", 33 | { 34 | "after": true, 35 | "before": false 36 | } 37 | ], 38 | "comma-style": "error", 39 | "complexity": "error", 40 | "computed-property-spacing": "error", 41 | "consistent-return": "error", 42 | "consistent-this": "error", 43 | "curly": "error", 44 | "default-case": "error", 45 | "default-case-last": "error", 46 | "default-param-last": "error", 47 | "dot-location": "off", 48 | "dot-notation": "error", 49 | "eol-last": "error", 50 | "eqeqeq": "error", 51 | "func-call-spacing": "error", 52 | "func-name-matching": "error", 53 | "func-names": "error", 54 | "func-style": "error", 55 | "function-call-argument-newline": "off", 56 | "function-paren-newline": ["error", "multiline-arguments"], 57 | "generator-star-spacing": "error", 58 | "global-require": "error", 59 | "grouped-accessor-pairs": "error", 60 | "guard-for-in": "error", 61 | "handle-callback-err": "error", 62 | "id-blacklist": "error", 63 | "id-denylist": "error", 64 | "id-length": "off", 65 | "id-match": "error", 66 | "implicit-arrow-linebreak": "off", 67 | "indent": "off", 68 | "indent-legacy": "off", 69 | "init-declarations": "error", 70 | "jsx-quotes": "error", 71 | "key-spacing": "error", 72 | "keyword-spacing": "error", 73 | "line-comment-position": "off", 74 | "linebreak-style": ["error", "unix"], 75 | "lines-around-comment": "off", 76 | "lines-around-directive": "error", 77 | "lines-between-class-members": ["off", "never"], 78 | "max-classes-per-file": "error", 79 | "max-depth": "error", 80 | "max-len": "off", 81 | "max-lines": "off", 82 | "max-lines-per-function": "off", 83 | "max-nested-callbacks": "error", 84 | "max-params": ["error", 6], 85 | "max-statements": ["error", 20], 86 | "max-statements-per-line": "error", 87 | "multiline-comment-style": ["error", "separate-lines"], 88 | "multiline-ternary": "off", 89 | "new-cap": "warn", 90 | "new-parens": "error", 91 | "newline-after-var": "off", 92 | "newline-before-return": "error", 93 | "newline-per-chained-call": "error", 94 | "no-alert": "error", 95 | "no-array-constructor": "error", 96 | "no-await-in-loop": "warn", 97 | "no-bitwise": "error", 98 | "no-buffer-constructor": "error", 99 | "no-caller": "error", 100 | "no-catch-shadow": "error", 101 | "no-confusing-arrow": "error", 102 | "no-console": "off", 103 | "no-constructor-return": "error", 104 | "no-continue": "error", 105 | "no-div-regex": "error", 106 | "no-duplicate-imports": "error", 107 | "no-else-return": "error", 108 | "no-empty-function": "error", 109 | "no-eq-null": "error", 110 | "no-eval": "error", 111 | "no-extend-native": "error", 112 | "no-extra-bind": "error", 113 | "no-extra-label": "error", 114 | "no-extra-parens": "error", 115 | "no-floating-decimal": "error", 116 | "no-implicit-coercion": "error", 117 | "no-implicit-globals": "error", 118 | "no-implied-eval": "error", 119 | "no-inline-comments": "off", 120 | "no-invalid-this": "error", 121 | "no-iterator": "error", 122 | "no-label-var": "error", 123 | "no-labels": "error", 124 | "no-lone-blocks": "error", 125 | "no-lonely-if": "error", 126 | "no-loop-func": "error", 127 | "no-loss-of-precision": "error", 128 | "no-magic-numbers": ["error", { "ignore": [60000, 500, 200, 0] }], 129 | "no-mixed-operators": "error", 130 | "no-mixed-requires": "error", 131 | "no-multi-assign": "error", 132 | "no-multi-spaces": "error", 133 | "no-multi-str": "error", 134 | "no-multiple-empty-lines": "error", 135 | "no-native-reassign": "error", 136 | "no-negated-condition": "off", 137 | "no-negated-in-lhs": "error", 138 | "no-nested-ternary": "error", 139 | "no-new": "error", 140 | "no-new-func": "error", 141 | "no-new-object": "error", 142 | "no-new-require": "error", 143 | "no-new-wrappers": "error", 144 | "no-nonoctal-decimal-escape": "error", 145 | "no-octal-escape": "error", 146 | "no-param-reassign": "error", 147 | "no-path-concat": "error", 148 | "no-plusplus": "error", 149 | "no-process-env": "off", 150 | "no-process-exit": "off", 151 | "no-promise-executor-return": "error", 152 | "no-proto": "error", 153 | "no-restricted-exports": "error", 154 | "no-restricted-globals": "error", 155 | "no-restricted-imports": "error", 156 | "no-restricted-modules": "error", 157 | "no-restricted-properties": "error", 158 | "no-restricted-syntax": "error", 159 | "no-return-assign": "error", 160 | "no-return-await": "off", 161 | "no-script-url": "error", 162 | "no-self-compare": "error", 163 | "no-sequences": "error", 164 | "no-shadow": "error", 165 | "no-spaced-func": "error", 166 | "no-sync": "error", 167 | "no-tabs": "error", 168 | "no-template-curly-in-string": "error", 169 | "no-ternary": "off", 170 | "no-throw-literal": "error", 171 | "no-trailing-spaces": "error", 172 | "no-undef-init": "error", 173 | "no-undefined": "off", 174 | "no-underscore-dangle": "off", 175 | "no-unmodified-loop-condition": "error", 176 | "no-unneeded-ternary": "error", 177 | "no-unreachable-loop": "error", 178 | "no-unused-expressions": "error", 179 | "no-unused-vars": "warn", 180 | "no-use-before-define": "error", 181 | "no-useless-backreference": "error", 182 | "no-useless-call": "error", 183 | "no-useless-computed-key": "error", 184 | "no-useless-concat": "error", 185 | "no-useless-constructor": "off", 186 | "no-useless-rename": "error", 187 | "no-useless-return": "error", 188 | "no-var": "error", 189 | "no-void": "error", 190 | "no-warning-comments": "off", 191 | "no-whitespace-before-property": "error", 192 | "nonblock-statement-body-position": "error", 193 | "object-curly-newline": "error", 194 | "object-curly-spacing": ["error", "always"], 195 | "object-property-newline": "off", 196 | "object-shorthand": "error", 197 | "one-var": "off", 198 | "one-var-declaration-per-line": "error", 199 | "operator-assignment": "error", 200 | "operator-linebreak": "error", 201 | "padded-blocks": "off", 202 | "padding-line-between-statements": "error", 203 | "prefer-arrow-callback": "error", 204 | "prefer-const": "error", 205 | "prefer-destructuring": "error", 206 | "prefer-exponentiation-operator": "error", 207 | "prefer-named-capture-group": "off", 208 | "prefer-numeric-literals": "error", 209 | "prefer-object-spread": "error", 210 | "prefer-promise-reject-errors": "error", 211 | "prefer-reflect": "error", 212 | "prefer-regex-literals": "error", 213 | "prefer-rest-params": "error", 214 | "prefer-spread": "error", 215 | "prefer-template": "error", 216 | "quote-props": "off", 217 | "quotes": ["error", "double", { "allowTemplateLiterals": true }], 218 | "radix": "error", 219 | "require-atomic-updates": "warn", 220 | "require-await": "error", 221 | "require-jsdoc": "error", 222 | "require-unicode-regexp": "error", 223 | "rest-spread-spacing": "error", 224 | "semi": "error", 225 | "semi-spacing": "error", 226 | "semi-style": "error", 227 | "sort-imports": "off", 228 | "sort-vars": "error", 229 | "space-before-blocks": "error", 230 | "space-before-function-paren": "off", 231 | "space-in-parens": ["error", "never"], 232 | "space-infix-ops": "error", 233 | "space-unary-ops": "error", 234 | "spaced-comment": ["error", "always"], 235 | "strict": "error", 236 | "switch-colon-spacing": "error", 237 | "symbol-description": "error", 238 | "template-curly-spacing": "error", 239 | "template-tag-spacing": "error", 240 | "unicode-bom": ["error", "never"], 241 | "valid-jsdoc": "error", 242 | "vars-on-top": "error", 243 | "wrap-iife": "error", 244 | "wrap-regex": "error", 245 | "yield-star-spacing": "error", 246 | "yoda": "error", 247 | "sort-keys": ["error", "asc", { "caseSensitive": true, "natural": true, "minKeys": 5 }], 248 | "sort-destructure-keys/sort-destructure-keys": ["warn", { "caseSensitive": true }] 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | patreon: crittr 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Environment (please complete the following information):** 24 | - OS: [e.g. Ubuntu] 25 | - Version [e.g. 18.04] 26 | 27 | **Additional context** 28 | Add any other context about the problem here. 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.github/workflows/close_stale_issues.yml: -------------------------------------------------------------------------------- 1 | name: 'Close stale issues and PRs' 2 | on: 3 | schedule: 4 | - cron: '0 0 * * *' 5 | 6 | jobs: 7 | stale: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/stale@v4 11 | with: 12 | stale-issue-message: 'This issue is stale because it has been open 20 days with no activity. Remove stale label or comment or this will be closed in 5 days.' 13 | stale-pr-message: 'This PR is stale because it has been open 20 days with no activity. Remove stale label or comment or this will be closed in 5 days.' 14 | close-issue-message: 'This issue was closed because it has been stalled for 5 days with no activity.' 15 | close-pr-message: 'This PR was closed because it has been stalled for 5 days with no activity.' 16 | days-before-issue-stale: 20 17 | days-before-pr-stale: 20 18 | days-before-issue-close: 5 19 | days-before-pr-close: 5 20 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Run Tests 5 | 6 | on: 7 | pull_request: 8 | branches: [master] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | 14 | strategy: 15 | matrix: 16 | node-version: [18.x, 20.x] 17 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Use Node.js ${{ matrix.node-version }} 22 | uses: actions/setup-node@v4 23 | with: 24 | node-version: ${{ matrix.node-version }} 25 | - run: npm ci 26 | - run: npm run build 27 | - run: npm test 28 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages 3 | 4 | name: Publish NPM Package 5 | 6 | on: 7 | workflow_dispatch: 8 | branches: 9 | - master 10 | release: 11 | types: [created] 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: actions/setup-node@v4 19 | with: 20 | node-version: 20 21 | - run: npm ci 22 | - run: npm test 23 | 24 | publish-npm: 25 | needs: build 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v4 29 | - uses: actions/setup-node@v4 30 | with: 31 | node-version: 20 32 | registry-url: https://registry.npmjs.org/ 33 | - run: npm ci 34 | - run: npm publish 35 | env: 36 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 37 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | name: Versioning and Tagging (release-please) 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | 9 | permissions: 10 | contents: write 11 | pull-requests: write 12 | 13 | jobs: 14 | release-please: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: googleapis/release-please-action@v4 18 | with: 19 | token: ${{ secrets.ACTION_ACCESS_TOKEN }} 20 | # this is a built-in strategy in release-please, see "Action Inputs" 21 | # for more options 22 | release-type: node 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | node_modules 4 | tmp/* 5 | yarn-error.log 6 | test.js 7 | .vscode 8 | test/results/* 9 | !test/results/.gitkeep 10 | test/*.css -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | echo "Commit Linting - Please follow the commit message format of conventional-commits!" 3 | commitlint --edit $1 4 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | npm test 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | ./test 2 | ./tmp 3 | .gitignore 4 | .idea 5 | jest.config.js 6 | _config.yml -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.yml 3 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "all", 3 | "tabWidth": 4, 4 | "useTabs": false, 5 | "semi": true, 6 | "singleQuote": true, 7 | "printWidth": 140, 8 | "quoteProps": "as-needed", 9 | "bracketSpacing": true, 10 | "jsxBracketSameLine": false, 11 | "arrowParens": "avoid", 12 | "endOfLine": "lf" 13 | } 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [2.0.2](https://github.com/philipp-winterle/crittr/compare/v2.0.1...v2.0.2) (2024-06-17) 4 | 5 | 6 | ### Bug Fixes 7 | 8 | * release please need to update the package version aswell ([20506ac](https://github.com/philipp-winterle/crittr/commit/20506ac62fd54de518af137f2cebe45443615706)) 9 | 10 | ## [2.0.1](https://github.com/philipp-winterle/crittr/compare/v2.0.0...v2.0.1) (2024-06-17) 11 | 12 | 13 | ### Bug Fixes 14 | 15 | * missing "ci" in npm call ([e5e1d7d](https://github.com/philipp-winterle/crittr/commit/e5e1d7d5f0ebe81ce308bfabffdf424be8ee9212)) 16 | * missing yarn calls in actions ([9e567d6](https://github.com/philipp-winterle/crittr/commit/9e567d60ab0c69f6c5695bfdb21de2787d55c3e1)) 17 | * release please need to update the package version aswell ([20506ac](https://github.com/philipp-winterle/crittr/commit/20506ac62fd54de518af137f2cebe45443615706)) 18 | * switching token for versioning to personal access token to trigger follow up actions ([9e567d6](https://github.com/philipp-winterle/crittr/commit/9e567d60ab0c69f6c5695bfdb21de2787d55c3e1)) 19 | 20 | ## [2.0.1](https://github.com/philipp-winterle/crittr/compare/v2.0.0...v2.0.1) (2024-06-17) 21 | 22 | 23 | ### Bug Fixes 24 | 25 | * missing "ci" in npm call ([e5e1d7d](https://github.com/philipp-winterle/crittr/commit/e5e1d7d5f0ebe81ce308bfabffdf424be8ee9212)) 26 | * missing yarn calls in actions ([9e567d6](https://github.com/philipp-winterle/crittr/commit/9e567d60ab0c69f6c5695bfdb21de2787d55c3e1)) 27 | * switching token for versioning to personal access token to trigger follow up actions ([9e567d6](https://github.com/philipp-winterle/crittr/commit/9e567d60ab0c69f6c5695bfdb21de2787d55c3e1)) 28 | 29 | ## [2.0.0](https://github.com/philipp-winterle/crittr/compare/1.5.3...v2.0.0) (2024-06-17) 30 | 31 | 32 | ### ⚠ BREAKING CHANGES 33 | 34 | * changed crittr to ESM 35 | * Minimum nodejs version is 18 36 | 37 | ### Bug Fixes 38 | 39 | * added master branch for github action ([5f682d5](https://github.com/philipp-winterle/crittr/commit/5f682d54bbfc67bfad9c1e5762620694e54f778e)) 40 | * forgot adding release-please to scripts ([af9c307](https://github.com/philipp-winterle/crittr/commit/af9c307f46983b67808c3dc88287edb4eeb29e2c)) 41 | * tests where also transformed and fixed ([b7ec137](https://github.com/philipp-winterle/crittr/commit/b7ec1373ec4067a64242e69a8b70cccb4152eda2)) 42 | * updated github actions to fit node version ([3efd76c](https://github.com/philipp-winterle/crittr/commit/3efd76c00d394fc8b9f15030860dc427301bd7c1)) 43 | 44 | 45 | ### Miscellaneous Chores 46 | 47 | * changed crittr to ESM ([b7ec137](https://github.com/philipp-winterle/crittr/commit/b7ec1373ec4067a64242e69a8b70cccb4152eda2)) 48 | * Minimum nodejs version is 18 ([b7ec137](https://github.com/philipp-winterle/crittr/commit/b7ec1373ec4067a64242e69a8b70cccb4152eda2)) 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # crittr 2 | 3 | ![CI Build Status](https://github.com/hummal/crittr/workflows/Node.js%20CI/badge.svg?branch=master) 4 | ![GitHub release](https://img.shields.io/github/release/hummal/crittr.svg?style=flat-square) 5 | ![npm](https://img.shields.io/npm/dt/crittr.svg?style=flat-square&label=NPM+Downloads) 6 | ![Github Releases](https://img.shields.io/github/downloads/hummal/crittr/total.svg?style=flat-square&label=Github+Downloads) 7 | 8 | [![NPM](https://nodei.co/npm/crittr.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/crittr/) 9 | 10 | > High performance critical css extraction library with a multiple url support. 11 | > crittr enables you to extract the critical path stylesheet rules of a single or multiple urls with lightning speed. Multiple urls are the unique selling point of this library due to the fact that nearly every website using one css file for multiple sub pages. Now you are able to gather the critical css of all pages in one extracting process. And this blazing fast even with rich internet applications! :muscle: 12 | 13 | #### Feature Facts 14 | 15 | - Amazing speed 16 | - Designed to be used by power users as a nodejs module (no useless browser usage) 17 | - :boom: **Only library which is able to extract summarized critical css from multiple urls which has a common use case -> Most of the websites using one css file for multiple subpages** :boom: :metal: 18 | - When using multiple urls a max concurrency of extraction is adjustable. For machines with less power 19 | - Ongoing maintenance because of being used in enterprise environment 20 | - Returns not only the critical css. Also returns the remaining css of your given file. You don't need to include the full css on your page or reduce the css on your own :heart: 21 | 22 | ## Performance 23 | 24 | If you use many urls to check against a single css file it will slow down the process. Anyway this is the scenario where crittr can shine. The only thing you need to take care of is the power of the machine you're running crittr on. 25 | 26 | ## Comparison 27 | 28 | There are some other libraries out there dealing with the topic of extracting the critical css. Crittr has it's own approach of dealing with this topic. Many features allow users to forget about using any other libraries because crittr already deal with the most things which are important for extracting critical css. 29 | 30 | ![Comparison](/docs/img/comp_table.png) 31 | 32 | ## Getting Started 33 | 34 | ### Requirements 35 | 36 | - minimum nodejs > 12 | recommended nodejs 16+ 37 | - async/await 38 | - Promises 39 | - puppeteer dependecies on UNIX bases OS (including MacOSX) 40 | 41 | > Due to some dependencies of crittr you may need to install some additional software. 42 | > Puppeteer has some special requirements if you are running on an UNIX based operation system. You can read more about this fact here. Including a list of what to install: [Puppeteer Troubleshooting](https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md#chrome-headless-doesnt-launch) 43 | 44 | ### Installation 45 | 46 | To use crittr as a module or cli in your nodejs environment just install it with 47 | 48 | ```shell 49 | npm i crittr 50 | ``` 51 | 52 | ### Usage 53 | 54 | #### Modul usage 55 | 56 | To use crittr as a module just require it and choose your [options](#options). 57 | 58 | The crittr module has the expects an object as input parameter and returns an array with 2 css strings. The first one is the criticalCss string and the second one is the remaining css without the critical selectors. 59 | 60 | ```javascript 61 | // async/await 62 | (async () => { 63 | const { critical, rest } = await crittr(options); 64 | })(); 65 | 66 | // Promise 67 | crittr(options).then(({ critical, rest }) => { 68 | // handle css 69 | }); 70 | ``` 71 | 72 | ##### Basic 73 | 74 | ```javascript 75 | const Crittr = require('crittr'); 76 | 77 | Crittr({ 78 | urls: ['https://github.com/'], 79 | css: `.header-logo-invertocat { 80 | margin: -1px 15px -1px -2px; 81 | color: #fff; 82 | white-space: nowrap; 83 | }`, 84 | device: { 85 | width: 1920, 86 | height: 1080, 87 | }, 88 | }) 89 | .then(({ critical, rest }) => { 90 | console.log(critical); 91 | }) 92 | .catch(err => { 93 | console.error(err); 94 | }); 95 | ``` 96 | 97 | As you can also read in the [options](#options) section there is the possibility to use a css file as a path instead of a string. If the path provided ends with `.css` it is treated as a file path. 98 | 99 | ```javascript 100 | const Crittr = require('crittr'); 101 | 102 | Crittr({ 103 | urls: ['https://github.com/'], 104 | css: './test/data/test.css', 105 | }).then(({ critical, rest }) => { 106 | console.log(critical); 107 | }); 108 | ``` 109 | 110 | Due to the fact, that crittr is returning a **Promise** you can also use async/await syntax to handle the result. 111 | 112 | ```javascript 113 | (async () => { 114 | const Crittr = require('crittr'); 115 | try { 116 | const { critical, rest } = await Crittr({ 117 | urls: ['https://github.com/'], 118 | css: './test/data/test.css', 119 | }); 120 | } catch (err) { 121 | console.error(err); 122 | } 123 | })(); 124 | ``` 125 | 126 | ##### Basic - Whithout css 127 | 128 | You can skip adding CSS. Crittr will collect all styles (external and inline) from the first url in your list as base CSS. 129 | 130 | ```javascript 131 | Crittr({ 132 | urls: ['https://github.com'], 133 | device: { 134 | width: 1920, 135 | height: 1080, 136 | }, 137 | }) 138 | .then(({ critical, rest }) => { 139 | console.log(critical); 140 | }) 141 | .catch(err => { 142 | console.error(err); 143 | }); 144 | ``` 145 | 146 | ##### Advanced - Multiple urls 147 | 148 | To use the full power of crittr and get the most of the performance advantage you should pass in multiple urls. As of the fact that the most websites use one css file for multiple pages this is the ultimate way to get the critical css for all of them! 149 | 150 | ```javascript 151 | const Crittr = require('crittr'); 152 | 153 | const urls = ['https://example.com/page1', 'https://example.com/page2', 'https://example.com/about', 'https://example.com/shop']; 154 | 155 | Crittr({ 156 | urls: urls, 157 | css: './example.com/css/main.css', 158 | }).then(({ critical, rest }) => { 159 | // criticalCss contains all the above the fold css 160 | // restCss is the rest remaining after excluding the criticalCss. 161 | // You can start including it directly as a defered css without 162 | // any need to calculate it on your own 163 | console.log(critical); 164 | }); 165 | ``` 166 | 167 | You can see the output of the time measurement after every run. So you will be able to check you overall processing time. 168 | 169 | ```shell 170 | ▶ Crittr Run Initialized timer... 171 | ◼ Crittr Run Timer run for: 2.33s 172 | ``` 173 | 174 | #### CLI Usage 175 | 176 | The CLI usage is not implemented yet :scream:. At the moment there is no need of cli usage, but if you need it just open an issue and I will try to get it done! :heart: 177 | 178 | ## Options 179 | 180 | | Property | Values | Description | 181 | | ----------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 182 | | **urls** | Array | An array containing the urls to check the css against. Has to be at least 1 url. | 183 | | css | String | Optional. Can be a plain css string or path to a css file or empty. If it is a path it has to end with `.css`! Otherwise it is not recognized as a path. If not set, the whole website css will be taken. | 184 | | timeout | Number | Optional. Integer number of milliseconds to wait for a page to navigate to. After timeout is reached the page navigation is aborted. **ATTENTION**: The critical css of the url timed out is not included. Default: 30000 | 185 | | pageLoadTimeout | Number | Optional. After the page load event is fired the pageLoadTimeout is started. After the amount of milliseconds the ongoing loading of assets or xhr requests is stopped and the extraction continues. Default: 2000 | 186 | | outputRemainingCss | Boolean | Optional. If set to false the result obj will not contain any rest css. Only an empty string will be given. Default: true | 187 | | browser | Object | Optional. Configuration object of browser. E.g. userAgent, ... See documentation for [browser object](#browser-options). | 188 | | device | Object | Optional. Configuration object of device. E.g. width, height, ... See documentation for [device object](#device-options). | 189 | | puppeteer | Object | Optional. Configuration object of puppeteer options like an already existing browser instance or a path to a Chrome instead of the used Chromium. See documentation for [puppeteer object](#puppeteer-options). | 190 | | printBrowserConsole | Boolean | Optional. If set to true prints console output of urls to the stdoutput. Defaults: false | 191 | | dropKeyframes | Boolean | Optional. If set to false keeps keyframes as critical css content. Otherwise they are removed. Default: false | 192 | | takeScreenshots | Boolean | Optional. If set a screenshot is taken for every url processed. Default: false | 193 | | screenshotPath | String | Optional. The path the screenshots will be saved to. Default: "." (execution path) | 194 | | screenshotNameGenerator | (url: string) => Promise | Optional. Function that receives the processed URL as an argument and returns a `Promise` that resolves with the name to be used for the screenshot. When not provided, the URL's name will be sanitized and used as a filename. | 195 | | keepSelectors | Array | Optional. Every CSS Selector in this array will be kept as part of the critical css even if they are not part of it. You can use wildcards (%) to capture more rules with one entry. [Read more](#wildcards). Default: [] | 196 | | removeSelectors: | Array | Optional. Every CSS Selector in this array will be removed of the critical css even if they are part of it. You can use wildcards (%) to capture more rules with one entry. [Read more](#wildcards). Default: [] | 197 | | blockRequests | Array | Optional. Some of the requests made by pages are an | 198 | 199 | ### Browser options 200 | 201 | | Property | Values | Description | 202 | | -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 203 | | userAgent | String | Optional. Can be set to any existing user agent | 204 | | isCacheEnabled | Boolean | Optional. If set to false the browser will cache the result assets as normal behaviour. Default: true | 205 | | isJsEnabled: | Boolean | Optional. If set to false the execution of Javascript in the browser page is prevented. Default: true | 206 | | concurrentTabs | Number | Optional. Sets the maximal allowed concurrent tabs being opened at the same time in the browser. This is a useful option if the system has only low performance and to prevent high load. Default: 10 (Can also be set to "Infinity") | 207 | 208 | ### Device options 209 | 210 | | Property | Values | Description | 211 | | ------------ | ------- | ------------------------------------------------------------------------------------------------- | 212 | | width | Number | Optional. Browser window width in px. Default: 1200 | 213 | | height | Number | Optional. Browser window height in px. Default: 1080 | 214 | | scaleFactor: | Number | Optional. Scaling factor of page. Only needed for mobile device emulation like iPhone. Default: 1 | 215 | | isMobile | Boolean | Optional. If set to true the device type for checking pages is set to mobile. Default: false | 216 | | isLandscape | Boolean | Optional. If set to true the device orientation is set to landscape. Default: false | 217 | | hasTouch | Boolean | Optional. If set to true the device viewing the page is assumed having touch. Default: false | 218 | 219 | ### Puppeteer options 220 | 221 | | Property | Values | Description | 222 | | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 223 | | browser | Promise | Optional. If you already have an puppeteer browser instance created you can use it with this options to prevent crittr from creating a new one. Just for performance!. Default: null | 224 | | chromePath | String | Optional. Path to other Chrome or Chromium executable/bin file to use. . Default: Default Chromium shipped with puppeteer | 225 | | headless: | Boolean | Optional. If set to false the browser will launch with GUI to be visible while processing. Default: true | 226 | 227 | ## Wildcards 228 | 229 | You are already able to define the selectors to force keep or remove. With wildcards you can define a range of selectors to match against one entry in force selectors. The wildcard symbol is the `%` character. It can put at the beginning or end of a string. Take care of whitespaces between the selector string and the `%` as it will count as a character. Let's have a quick example: 230 | 231 | ```javascript 232 | const { critical, rest } = await Crittr({ 233 | urls: urls, 234 | css: css, 235 | keepSelectors: ['.test %'], 236 | }); 237 | ``` 238 | 239 | This keepSelectors options will match every selector that begins with `.test` and has no further selectors attached. Means `.test.test2`wouldn't match because there is a whitespace in there. But it will match `.test .test2 .test3`. Also this example wouldn't match selectors like this: 240 | 241 | ```css 242 | .pre .test .test2 { 243 | } /* no match */ 244 | .pre.test .test2 { 245 | } /* no match */ 246 | .test .test2 { 247 | } /* match */ 248 | .test.test2 { 249 | } /* no match */ 250 | .test .test2:before { 251 | } /* match */ 252 | ``` 253 | 254 | ## FAQ :confused: 255 | 256 | - Why do I need to put my css file in when I only want to extract the critical css? 257 | You don't need to but if you don't set your css file as an option you may not receive all vendor prefixes you may expect. This is due testing with only one browser engine which drop other prefixes. 258 | - After including the remaining css aswell my page starts looking different. Why is that? 259 | If you progress more than 1 url at the same time crittr can not determinate where a rule has to be positioned in the whole css to not get in conflict with other rules overwriting them. You have to write clean css to prevent such an behaviour. Overwriting rules should always have longer selectors than the rules they are overwriting to raise priority. 260 | 261 | ## Upcoming :trumpet: 262 | 263 | - [ ] :star: cookie includes 264 | - [x] :star: wildcards 265 | - [x] :+1: compress output option 266 | - [x] :fire: return of the remaining css aswell 267 | - [x] :grey_question: multi selector partial matches 268 | - [x] :tea: returning of remaining css aswell (optional) 269 | - [x] :clock2: performance boost for large css 270 | 271 | ## Known Bugs :shit: 272 | 273 | None yet 274 | 275 | ## Troubleshooting 276 | 277 | #### WSL / Windows Linux Subsystem Support 278 | 279 | Some unkown reasons prevent puppeteer to run properly in a WSL environment. If you have any errors please try to use your default OS command shell or equivalent. If the error still exists don't hesitate to create an issue ticket. 280 | 281 | ## Inspiration 282 | 283 | :star: [puppeteer](https://github.com/GoogleChrome/puppeteer) 284 | :star: [penthouse](https://github.com/pocketjoso/penthouse) 285 | :star: [critical](https://github.com/addyosmani/critical) 286 | :star: [criticalCSS](https://github.com/filamentgroup/criticalCSS) 287 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | theme: jekyll-theme-cayman 3 | plugins: 4 | - jemoji -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | export default {extends: ['@commitlint/config-conventional']}; 2 | -------------------------------------------------------------------------------- /docs/html/comp_table.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Roboto; 3 | font-size: 13px; 4 | color: #666; 5 | font-weight: 300; 6 | padding: 10px; 7 | } 8 | 9 | .comparison-table { 10 | border-collapse: collapse; 11 | margin: 50px; 12 | } 13 | .comparison-table .empty-cell { 14 | border: none; 15 | background: none; 16 | } 17 | .comparison-table td, 18 | .comparison-table th { 19 | padding: 10px 15px; 20 | border: 1px solid #e9e9e9; 21 | min-width: 130px; 22 | max-width: 300px; 23 | text-align: center; 24 | } 25 | .comparison-table .comparison-table-section-header td { 26 | font-weight: 500; 27 | font-size: 12px; 28 | padding-top: 20px; 29 | color: #222; 30 | text-transform: uppercase; 31 | background: #f9f9f9; 32 | letter-spacing: 1px; 33 | } 34 | .comparison-table .comparison-table-desc { 35 | display: block; 36 | font-size: 11px; 37 | color: #aaa; 38 | max-height: 0; 39 | overflow: hidden; 40 | margin: 0; 41 | } 42 | .comparison-table tr:hover .comparison-table-desc { 43 | max-height: 100px; 44 | color: #eee; 45 | padding-top: 8px; 46 | transition: max-height 0.3s ease-in; 47 | } 48 | .comparison-table th { 49 | background: #f9f9f9; 50 | font-weight: 500; 51 | text-transform: uppercase; 52 | color: #666; 53 | padding-top: 20px; 54 | padding-bottom: 20px; 55 | letter-spacing: 2px; 56 | font-size: 14px; 57 | } 58 | .comparison-table .comparison-table-pro { 59 | background: #fc6262; 60 | color: white; 61 | border-color: #fc6262; 62 | } 63 | 64 | .comparison-table .comparison-table-pro-bg { 65 | background: rgba(252, 98, 98, 0.1); 66 | color: white; 67 | border-color: rgba(252, 98, 98, 0.1); 68 | } 69 | .comparison-table td:first-child { 70 | text-align: left; 71 | } 72 | .comparison-table .fa-check { 73 | color: #7ab55c; 74 | } 75 | .comparison-table .fa-times { 76 | color: #b55c68; 77 | } 78 | 79 | .comparison-table tr.comparison-table-row:hover { 80 | background: #7ab55c; 81 | } 82 | .comparison-table tr.comparison-table-row:hover td { 83 | border-color: #7ab55c; 84 | } 85 | .comparison-table tr.comparison-table-row:hover td, 86 | .comparison-table tr.comparison-table-row:hover td .fa { 87 | color: #fff; 88 | } 89 | -------------------------------------------------------------------------------- /docs/html/comp_table.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 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 |
critcalcsscritcalpenthousecrittr
Features
Extracing of critical css
Force include selectors
Local files
Use a single url against a css file
Great meta data configs (device, browser)
Inline css into html
Force exclude selectors
Compressed output
Use multiple urls to check against a css file
Returning of remaining css
Block request urls
Can be used to generate one critical css and remaining css file for a whole website in one task
119 | 120 | 121 | -------------------------------------------------------------------------------- /docs/img/comp_table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipp-winterle/crittr/8d2f3322e8600bdadb6efe8e66d51e053a4c2b91/docs/img/comp_table.png -------------------------------------------------------------------------------- /docs/img/crittr_benchmark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipp-winterle/crittr/8d2f3322e8600bdadb6efe8e66d51e053a4c2b91/docs/img/crittr_benchmark.png -------------------------------------------------------------------------------- /examples/basic.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const path = require('path'); 3 | const fs = require('fs-extra'); 4 | const Crittr = require('../index'); 5 | const rootDir = path.join(__dirname, '..'); 6 | 7 | console.log('Server listening'); 8 | Crittr({ 9 | urls: ['https://github.com/'], 10 | css: `.header-logo-invertocat { 11 | margin: -1px 15px -1px -2px; 12 | color: #fff; 13 | white-space: nowrap; 14 | }`, 15 | device: { 16 | width: 1920, 17 | height: 1080, 18 | }, 19 | }) 20 | .then(({ critical, rest }) => { 21 | fs.writeFileSync(path.join(rootDir, './examples/basic.css'), critical, 'utf-8'); 22 | }) 23 | .catch(err => { 24 | console.error(err); 25 | }); 26 | -------------------------------------------------------------------------------- /examples/basic_no_css.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const path = require('path'); 3 | const fs = require('fs-extra'); 4 | const Crittr = require('../index'); 5 | const rootDir = path.join(__dirname, '..'); 6 | 7 | Crittr({ 8 | urls: ['https://github.com'], 9 | device: { 10 | width: 1920, 11 | height: 1080, 12 | }, 13 | }) 14 | .then(({ critical, rest }) => { 15 | fs.writeFileSync(path.join(rootDir, './examples/basic_no_css.css'), critical, 'utf-8'); 16 | }) 17 | .catch(err => { 18 | console.error(err); 19 | }); 20 | -------------------------------------------------------------------------------- /examples/benchmark.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You need to install penthouse first to run this benchmark 3 | * npm i penthouse criticalcss critical --no-save 4 | * 5 | * node ./examples/benchmark.js 6 | */ 7 | 8 | 'use strict'; 9 | const path = require('path'); 10 | const Crittr = require('../index'); 11 | const rootDir = path.join(__dirname, '..'); 12 | const staticServer = require('../lib/helper/localFileServer')(rootDir); 13 | 14 | staticServer 15 | .listen(8000, async () => { 16 | console.log('Server listening'); 17 | 18 | const urls = [ 19 | 'http://localhost:8000/test/data/test.html?1', 20 | 'http://localhost:8000/test/data/test.html?2', 21 | 'http://localhost:8000/test/data/test.html?3', 22 | 'http://localhost:8000/test/data/test.html?4', 23 | 'http://localhost:8000/test/data/test.html?1', 24 | 'http://localhost:8000/test/data/test.html?2', 25 | 'http://localhost:8000/test/data/test.html?3', 26 | 'http://localhost:8000/test/data/test.html?4', 27 | 'http://localhost:8000/test/data/test.html?1', 28 | 'http://localhost:8000/test/data/test.html?2', 29 | 'http://localhost:8000/test/data/test.html?3', 30 | 'http://localhost:8000/test/data/test.html?4', 31 | 'http://localhost:8000/test/data/test.html?1', 32 | 'http://localhost:8000/test/data/test.html?2', 33 | 'http://localhost:8000/test/data/test.html?3', 34 | 'http://localhost:8000/test/data/test.html?4', 35 | 'http://localhost:8000/test/data/test.html?1', 36 | 'http://localhost:8000/test/data/test.html?2', 37 | 'http://localhost:8000/test/data/test.html?3', 38 | 'http://localhost:8000/test/data/test.html?4', 39 | ]; 40 | 41 | try { 42 | console.log('Start Critter Benchmark'); 43 | console.time('Crittr'); 44 | const { critical, rest } = await Crittr({ 45 | urls: urls, 46 | css: rootDir + '/test/data/test.css', 47 | device: { 48 | width: 1920, 49 | height: 1080, 50 | }, 51 | keepSelectors: ['.forceInclude'], 52 | removeSelectors: ['.forceExclude'], 53 | browser: { 54 | concurrentTabs: Infinity, 55 | }, 56 | }); 57 | console.timeEnd('Crittr'); 58 | } catch (err) { 59 | console.error(err); 60 | } 61 | 62 | /** 63 | * PENTHOUSE 64 | */ 65 | console.log('Start Penthouse Benchmark'); 66 | const penthouse = require('penthouse'); 67 | console.time('Penthouse'); 68 | for (const url of urls) { 69 | try { 70 | const extracedCss = await penthouse({ 71 | url: url, 72 | css: rootDir + '/test/data/test.css', 73 | width: 1920, 74 | height: 1080, 75 | forceInclude: ['.forceInclude'], 76 | blockJsRequests: false, 77 | }); 78 | } catch (err) { 79 | console.error(err); 80 | } 81 | } 82 | console.timeEnd('Penthouse'); 83 | 84 | /** 85 | * CRITICALCSS 86 | */ 87 | console.log('Start CriticalCss Benchmark'); 88 | const criticalcss = require('criticalcss'); 89 | console.time('CriticalCss'); 90 | const criticalCssWrapper = async () => { 91 | for (const url of urls) { 92 | await new Promise(resolve => { 93 | criticalcss.getRules(path.join(rootDir, '/test/data/test.css'), function (err, output) { 94 | criticalcss.findCritical( 95 | url, 96 | { 97 | rules: JSON.parse(output), 98 | width: 1920, 99 | height: 1080, 100 | forceInclude: ['.forceInclude'], 101 | }, 102 | function (err, output) { 103 | if (err) { 104 | throw new Error(err); 105 | } else { 106 | resolve(output); 107 | } 108 | }, 109 | ); 110 | }); 111 | }); 112 | } 113 | }; 114 | await criticalCssWrapper(); 115 | console.timeEnd('CriticalCss'); 116 | 117 | /** 118 | * CRITICALCSS 119 | */ 120 | console.log('Start Critical Benchmark'); 121 | const critical = require('critical'); 122 | console.time('Critical'); 123 | for (const url of urls) { 124 | critical.generate({ 125 | base: './', 126 | src: './test/data/test.html', 127 | dest: './test/data/test.css', 128 | width: 1920, 129 | height: 1080, 130 | include: ['.forceInclude'], 131 | }); 132 | } 133 | console.timeEnd('Critical'); 134 | 135 | staticServer.close(); 136 | process.exit(0); 137 | }) 138 | .on('error', err => { 139 | console.error(err); 140 | }); 141 | -------------------------------------------------------------------------------- /examples/local_urls.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const path = require('path'); 3 | const fs = require('fs-extra'); 4 | const Crittr = require('../index'); 5 | const rootDir = path.join(__dirname, '..'); 6 | const staticServer = require('../lib/helper/localFileServer')(rootDir); 7 | 8 | const testCase = { 9 | urls: [ 10 | 'http://localhost:8000/test/data/test.html?1', 11 | 'http://localhost:8000/test/data/test.html?2', 12 | 'http://localhost:8000/test/data/test.html?3', 13 | 'http://localhost:8000/test/data/test.html?4', 14 | ], 15 | css: rootDir + '/test/data/test.css', 16 | }; 17 | 18 | staticServer 19 | .listen(8000, async () => { 20 | console.log('Server listening'); 21 | try { 22 | const { critical, rest } = await Crittr({ 23 | urls: testCase.urls, 24 | css: testCase.css, 25 | timeout: 30000, 26 | device: { 27 | width: 1920, 28 | height: 1080, 29 | }, 30 | browser: { 31 | concurrentTabs: Infinity, 32 | }, 33 | keepSelectors: ['.forceInclude'], 34 | removeSelectors: ['.forceExclude'], 35 | }); 36 | fs.writeFileSync(path.join(rootDir, './examples/local_urls.css'), critical, 'utf-8'); 37 | } catch (err) { 38 | console.error(err); 39 | } 40 | staticServer.close(); 41 | process.exit(0); 42 | }) 43 | .on('error', err => { 44 | console.error(err); 45 | }); 46 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import { createRequire } from 'node:module'; 2 | import log from '@dynamicabot/signales'; 3 | import path from 'path'; 4 | import url from 'url'; 5 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 6 | const NODE_ENV = process.env.NODE_ENV || 'production'; 7 | 8 | let IS_NPM_PACKAGE = false; 9 | try { 10 | const require = createRequire(import.meta.url); 11 | IS_NPM_PACKAGE = !!require.resolve('crittr'); 12 | } catch (e) {} 13 | 14 | const pathToCrittr = NODE_ENV === 'development' && !IS_NPM_PACKAGE ? 'lib' : 'lib'; // Only keep for later browser support? 15 | 16 | /** 17 | * 18 | * @param options 19 | * @returns {Promise<[, ]>} 20 | */ 21 | export default async options => { 22 | log.time('Crittr Run'); 23 | const { Crittr } = await import(path.join(__dirname, pathToCrittr, 'classes', 'Crittr.class.js')); 24 | 25 | let crittr; 26 | let resultObj = { critical: null, rest: null }; 27 | 28 | crittr = new Crittr(options); 29 | 30 | resultObj = await crittr.run(); 31 | 32 | log.timeEnd('Crittr Run'); 33 | return resultObj; 34 | }; 35 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // jest.config.js 2 | export default { 3 | projects: [ 4 | { 5 | displayName: 'Basic', 6 | globalSetup: './test/setup.js', 7 | globalTeardown: './test/teardown.js', 8 | roots: [''], 9 | testMatch: ['**/test/tests/**/*.test.js?(x)'], 10 | testEnvironmentOptions: { 11 | url: 'http://localhost', 12 | }, 13 | }, 14 | ], 15 | transform: {}, 16 | }; 17 | -------------------------------------------------------------------------------- /lib/Constants.js: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import { createRequire } from 'module'; 3 | import url from 'url'; 4 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 5 | const require = createRequire(import.meta.url); 6 | const package_json = require(path.join('..', 'package.json')); 7 | 8 | export default { 9 | // DEFAULTS 10 | PROJECT_DIR: path.resolve(__dirname, '..'), 11 | 12 | // CRITTR BASED 13 | 14 | PRINT_BROWSER_CONSOLE: false, 15 | DROP_KEYFRAMES: true, 16 | PUPPETEER_HEADLESS: 'new', 17 | BROWSER_USER_AGENT: 'Crittr ' + package_json.version, 18 | BROWSER_CACHE_ENABLED: true, 19 | BROWSER_JS_ENABLED: true, 20 | BROWSER_CONCURRENT_TABS: 10, 21 | DEVICE_WIDTH: 1200, 22 | DEVICE_HEIGHT: 1080, 23 | DEVICE_SCALE_FACTOR: 1, 24 | DEVICE_IS_MOBILE: false, 25 | DEVICE_HAS_TOUCH: false, 26 | DEVICE_IS_LANDSCAPE: false, 27 | TIMEOUT: 30000, 28 | PAGE_LOAD_TIMEOUT: 2000, 29 | PAGE_RENDER_TIMEOUT: 300, 30 | PAGE_SCREENSHOT: false, 31 | OUTPUT_REMAINING_CSS: true, 32 | 33 | // CODE BASED 34 | RULE_SEPARATOR: '-#-', 35 | 36 | SCREENSHOT_NAME_GENERATOR: null, 37 | }; 38 | -------------------------------------------------------------------------------- /lib/classes/Ast.class.js: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import Rule from './Rule.class.js'; 3 | import hash from 'object-hash'; 4 | 5 | // PRIVATE VARS 6 | const REMOVEABLE_PROPS = ['position']; 7 | 8 | // PRIVATE FUNCTIONS 9 | const cleanUnusedProperties = obj => { 10 | for (let prop in obj) { 11 | if (REMOVEABLE_PROPS.includes(prop)) { 12 | delete obj[prop]; 13 | } 14 | 15 | const item = obj[prop]; 16 | if (Array.isArray(item) || typeof item === 'object') { 17 | cleanUnusedProperties(item); 18 | } 19 | } 20 | }; 21 | 22 | const handleRule = (ruleObj, map) => { 23 | // Ignore comments 24 | if (!Rule.isComment(ruleObj)) { 25 | cleanUnusedProperties(ruleObj); // Remove position. We don't need that any longer 26 | 27 | // Handle MediaQuery 28 | if (Rule.isMediaRule(ruleObj)) { 29 | const media = Ast.MEDIA_PREFIX + ruleObj.media; 30 | const mediaRulesArr = map.get(media); 31 | const mRules = ruleObj.rules; 32 | 33 | // There are already media rules in our set 34 | if (mediaRulesArr && mediaRulesArr.length > 0) { 35 | // Filter the rules of the proccessed media query for already existing and only return 36 | // rules that does not exist in the mq map 37 | const newRules = mRules 38 | .filter(mRule => { 39 | const objHash = hash.MD5(mRule); 40 | return !mediaRulesArr.some(ruleObj => ruleObj.hash === objHash); 41 | }) 42 | .map(mRule => { 43 | const objHash = hash.MD5(mRule); 44 | return { 45 | hash: objHash, 46 | rule: mRule, 47 | }; 48 | }); 49 | map.set(media, [...mediaRulesArr, ...newRules]); 50 | } else { 51 | // Fresh media rules can be created 52 | map.set( 53 | media, 54 | mRules.map(mRule => { 55 | const objHash = hash.MD5(mRule); 56 | return { 57 | hash: objHash, 58 | rule: mRule, 59 | }; 60 | }), 61 | ); 62 | } 63 | } else { 64 | const ruleKey = Rule.generateRuleKey(ruleObj); 65 | const rulesArray = map.get(ruleKey); 66 | const objHash = hash.MD5(ruleObj); 67 | 68 | if (rulesArray) { 69 | // If this rule object (hash) already exists in this ruleKey ignore else insert 70 | if (!rulesArray.some(ruleObj => ruleObj.hash === objHash)) { 71 | rulesArray.push({ 72 | hash: objHash, 73 | rule: ruleObj, 74 | }); 75 | } 76 | } else { 77 | map.set(ruleKey, [ 78 | { 79 | hash: objHash, 80 | rule: ruleObj, 81 | }, 82 | ]); 83 | } 84 | } 85 | } 86 | }; 87 | 88 | /** 89 | * Rule Class with static functions to handle ast management 90 | * 91 | * @static 92 | */ 93 | class Ast { 94 | static generateRuleMap(ast, ruleMap = new Map()) { 95 | if (ast.type && ast.type === 'stylesheet' && ast.stylesheet && Array.isArray(ast.stylesheet.rules)) { 96 | const restRules = ast.stylesheet.rules; 97 | 98 | for (const ruleObj of restRules) { 99 | handleRule(ruleObj, ruleMap); 100 | } 101 | } 102 | 103 | return ruleMap; 104 | } 105 | 106 | static getAstOfRuleMap(ruleMap) { 107 | const ast = { 108 | type: 'stylesheet', 109 | stylesheet: { 110 | rules: [], 111 | }, 112 | }; 113 | const astRules = ast.stylesheet.rules; 114 | 115 | for (let [ruleKey, rulesObj] of ruleMap) { 116 | // Empty declarations break reworkcss/css. https://github.com/reworkcss/css/issues/92 117 | if (rulesObj[0].rule.hasOwnProperty('declarations') && !rulesObj[0].rule.declarations.length) { 118 | break; 119 | } 120 | 121 | if (rulesObj[0].rule.type === 'rule' && !rulesObj[0].rule.hasOwnProperty('declarations')) { 122 | break; 123 | } 124 | 125 | // Is this rule a media query? 126 | if (ruleKey.includes(Ast.MEDIA_PREFIX)) { 127 | const mqStr = ruleKey.replace(Ast.MEDIA_PREFIX, ''); 128 | astRules.push({ 129 | type: 'media', 130 | media: mqStr, 131 | rules: rulesObj.map(ruleObj => { 132 | return ruleObj.rule; 133 | }), 134 | }); 135 | } else { 136 | astRules.push(...rulesObj.map(ruleObj => ruleObj.rule)); 137 | } 138 | } 139 | 140 | return ast; 141 | } 142 | 143 | static isMediaObj(ruleKey) { 144 | return ruleKey.includes(Ast.MEDIA_PREFIX); 145 | } 146 | } 147 | 148 | Ast.TYPES_TO_REMOVE = ['comment']; 149 | 150 | Ast.MEDIA_PREFIX = '@media '; 151 | 152 | export default Ast; 153 | -------------------------------------------------------------------------------- /lib/classes/CssTransformator.class.js: -------------------------------------------------------------------------------- 1 | import doDebug from 'debug'; 2 | import log from '@dynamicabot/signales'; 3 | import merge from 'deepmerge'; 4 | import css from 'css'; 5 | import Rule from './Rule.class.js'; 6 | 7 | const debug = doDebug('crittr:css-transformator'); 8 | 9 | /** 10 | * 11 | */ 12 | class CssTransformator { 13 | constructor(options) { 14 | options = options || {}; 15 | this.options = { 16 | silent: true, 17 | source: null, 18 | }; 19 | 20 | this.options = merge(this.options, options); 21 | 22 | const pseudoSelectorsToKeep = [':before', ':after', ':visited', ':first-letter', ':first-line']; 23 | 24 | this.CRITICAL_TYPES_TO_KEEP = ['media', 'rule', 'charset', 'font-face', 'supports']; 25 | 26 | this.GROUP_SEPERATOR = '-##-'; 27 | } 28 | 29 | getAst(cssContent) { 30 | let astObj = null; 31 | try { 32 | debug('getAst - Try parsing css to ast ...'); 33 | astObj = css.parse(cssContent, { 34 | silent: this.options.silent, 35 | source: this.options.source, 36 | }); 37 | debug('getAst - Css successfully parsed to ast ...'); 38 | } catch (err) { 39 | log.error(err); 40 | } 41 | return astObj; 42 | } 43 | 44 | getCssFromAst(ast) { 45 | return css.stringify(ast, { 46 | indent: ' ', 47 | compress: false, 48 | sourcemap: true, 49 | inputSourcemaps: true, 50 | }).code; 51 | } 52 | 53 | getCriticalRuleSelectors(rule, selectorMap, groupPrefix = '') { 54 | const ruleKey = Rule.generateRuleKey(rule, groupPrefix); 55 | 56 | if (selectorMap.has(ruleKey)) { 57 | const critObj = selectorMap.get(ruleKey); 58 | return rule.selectors.filter(selector => critObj.selectors.includes(selector)); 59 | } 60 | 61 | return []; 62 | } 63 | 64 | isGroupType(rule) { 65 | // AST RULES have a interface GroupingRule 66 | // developer.mozilla.org/en-US/docs/Web/API/CSSGroupingRule 67 | https: return rule.type !== 'rule' && rule.rules !== undefined; 68 | } 69 | 70 | getRuleType(rule) { 71 | return rule.type || ''; 72 | } 73 | 74 | getGroupRuleId(rule) { 75 | const type = this.getRuleType(rule); 76 | const typeString = rule[type] || ''; 77 | 78 | return `${type}${typeString}`; 79 | } 80 | 81 | processRuleCollection({ rules, selectorMap, criticalSelectorsMap, isCritical = false, groupPrefix = '' }) { 82 | const processedRules = []; 83 | 84 | for (let rule of rules) { 85 | if (this.isGroupType(rule)) { 86 | // Grouped rule handling 87 | const prefix = this.getGroupRuleId(rule); 88 | 89 | rule.rules = this.processRuleCollection({ 90 | rules: rule.rules, 91 | selectorMap, 92 | criticalSelectorsMap, 93 | isCritical, 94 | groupPrefix: prefix, 95 | }); 96 | 97 | // If media query is empty remove 98 | if (rule.rules.length === 0) { 99 | rule = null; 100 | } 101 | } else { 102 | // Single rule -> can be processed 103 | if (isCritical) { 104 | rule = this.processCriticalRule(rule, selectorMap, criticalSelectorsMap, groupPrefix); 105 | } else { 106 | rule = this.processNonCriticalRule(rule, criticalSelectorsMap, groupPrefix); 107 | } 108 | } 109 | 110 | // Fill new Array if no empty rule 111 | if (rule !== null) { 112 | processedRules.push(rule); 113 | } 114 | } 115 | 116 | // Remove empty rules 117 | 118 | return processedRules; 119 | } 120 | 121 | processCriticalRule(rule, selectorMap, criticalSelectorsMap, groupPrefix) { 122 | // Get rule key 123 | const ruleKey = Rule.generateRuleKey(rule, groupPrefix); 124 | // Get the critical selectors of this media internal rule 125 | rule.selectors = this.getCriticalRuleSelectors(rule, selectorMap, groupPrefix); 126 | // Create Map entry for exclude of remaining ast 127 | criticalSelectorsMap.set(ruleKey, rule.selectors); 128 | 129 | // If there are no critical selectors mark this rule as removed and set it to null 130 | if (rule.type === 'rule' && rule.selectors.length === 0) { 131 | return null; 132 | } 133 | 134 | return rule; 135 | } 136 | 137 | processNonCriticalRule(rule, criticalSelectorsMap, groupPrefix) { 138 | // Get rule key 139 | const ruleKey = Rule.generateRuleKey(rule, groupPrefix); 140 | 141 | if (criticalSelectorsMap.has(ruleKey)) { 142 | const criticalSelectorsOfRule = criticalSelectorsMap.get(ruleKey); 143 | const selectors = rule.selectors || []; 144 | const newSelectors = []; 145 | for (const selector of selectors) { 146 | if (!criticalSelectorsOfRule.includes(selector)) { 147 | newSelectors.push(selector); 148 | } 149 | } 150 | 151 | rule.selectors = newSelectors; 152 | } 153 | 154 | if (rule.type === 'rule' && rule.selectors.length === 0) { 155 | rule = null; 156 | } 157 | 158 | return rule; 159 | } 160 | 161 | /** 162 | * Filters the AST Object with the selectorMap containing selectors. 163 | * Returns a new AST Object without those selectors. Does NOT mutate the AST. 164 | * 165 | * @param {Object} ast 166 | * @param {Map} selectorMap 167 | * @returns {Object} AST 168 | */ 169 | filterByMap(ast, selectorMap) { 170 | let _ast = JSON.parse(JSON.stringify(ast)); 171 | let _astRest = JSON.parse(JSON.stringify(ast)); 172 | const _astRoot = _ast.stylesheet; 173 | const _astRestRoot = _astRest.stylesheet; 174 | const criticalSelectorsMap = new Map(); 175 | 176 | // Filter rule types we don't want in critical 177 | let newRules = _astRoot.rules.filter(rule => { 178 | return this.CRITICAL_TYPES_TO_KEEP.includes(rule.type); 179 | }); 180 | 181 | // HANDLE CRITICAL CSS 182 | newRules = this.processRuleCollection({ 183 | rules: newRules, 184 | selectorMap: selectorMap, 185 | criticalSelectorsMap: criticalSelectorsMap, 186 | isCritical: true, 187 | }); 188 | 189 | // HANDLE REST CSS 190 | const astRestRules = _astRestRoot.rules; 191 | let restRules = this.processRuleCollection({ 192 | rules: astRestRules, 193 | criticalSelectorsMap: criticalSelectorsMap, 194 | isCritical: false, 195 | }); 196 | 197 | _astRoot.rules = newRules; 198 | _astRestRoot.rules = restRules; 199 | 200 | // Return the new AST Object 201 | return [_ast, _astRest]; 202 | } 203 | } 204 | 205 | export default CssTransformator; 206 | -------------------------------------------------------------------------------- /lib/classes/Rule.class.js: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import log from '@dynamicabot/signales'; 3 | import CONSTANTS from '../Constants.js'; 4 | 5 | /** 6 | * Rule Class with static functions to handle rule comparision and more 7 | * 8 | * @static 9 | */ 10 | class Rule { 11 | /** 12 | * Checks if rule is a native duplicate. Checks all properties but excluded 13 | * @static 14 | * 15 | * @param rule1 16 | * @param rule2 17 | * @param excludedProperties 18 | * 19 | * @return {boolean} 20 | */ 21 | static isRuleDuplicate(rule1, rule2, excludedProperties) { 22 | excludedProperties = excludedProperties || []; 23 | 24 | const hasSameProperties = _.isEqualWith(rule1, rule2, (value1, value2, propKey) => { 25 | if (excludedProperties.includes(propKey)) return true; 26 | }); 27 | 28 | return hasSameProperties; 29 | } 30 | 31 | /** 32 | * Compares 2 ast rules by type 33 | * 34 | * @static 35 | * @param {!Object} rule1 36 | * @param {!Object} rule2 37 | * @returns {boolean} 38 | */ 39 | static isSameRuleType(rule1, rule2) { 40 | return rule1.type === rule2.type; 41 | } 42 | 43 | /** 44 | * Returns true if rule is of type "media" 45 | * 46 | * @static 47 | * @param {Object} rule 48 | * @returns {boolean} 49 | */ 50 | static isMediaRule(rule) { 51 | return rule.type === 'media'; 52 | } 53 | 54 | static isSupportsRule(rule) { 55 | return rule.type === 'supports'; 56 | } 57 | 58 | static isRule(rule) { 59 | return rule.type === 'rule'; 60 | } 61 | 62 | static isStyleRule(rule) { 63 | return rule.type === 'rule'; 64 | } 65 | 66 | static isKeyframe(rule) { 67 | return rule.type === 'keyframe'; 68 | } 69 | 70 | static isKeyframes(rule) { 71 | return rule.type === 'keyframes'; 72 | } 73 | 74 | static isCharset(rule) { 75 | return rule.type === 'charset'; 76 | } 77 | 78 | static isComment(rule) { 79 | return rule.type === 'comment'; 80 | } 81 | 82 | static isFontFace(rule) { 83 | return rule.type === 'font-face'; 84 | } 85 | 86 | static isGroupRule(rule) { 87 | return rule[rule.type] !== undefined; 88 | } 89 | 90 | static isStylesheet(rule) { 91 | return rule.type === 'stylesheet'; 92 | } 93 | 94 | static isImportantRule(rule) { 95 | return Rule.isMediaRule(rule) || Rule.isRule(rule); 96 | } 97 | 98 | /** 99 | * Returns true if selector_1 is matching selector_2 as a media rule selector. 100 | * Also checks valid differences between media selectors that mean the same. 101 | * "all and " is not needed for the same result. Therefor we need to check the rules more gracefully 102 | * 103 | * @static 104 | * @param selector_1 105 | * @param selector_2 106 | * @returns {boolean} 107 | */ 108 | static isMatchingMediaRuleSelector(selector_1, selector_2) { 109 | return ( 110 | selector_1 === selector_2 || 111 | selector_1 === selector_2.replace('all and ', '') || 112 | selector_2 === selector_1.replace('all and ', '') || 113 | selector_1.replace('all and ', '') === selector_2.replace('all and ', '') 114 | ); 115 | } 116 | 117 | static generateRuleKey(rule, groupPrefix = '', withKeySeparator = false) { 118 | const keySeparator = withKeySeparator ? CONSTANTS.RULE_SEPARATOR : ''; 119 | let ruleStr = 'default'; 120 | 121 | if (Rule.isRule(rule) && rule.selectors) { 122 | ruleStr = rule.selectors.join(); 123 | } else if (Rule.isCharset(rule)) { 124 | ruleStr = rule.charset; 125 | } else if (Rule.isKeyframes(rule)) { 126 | ruleStr = rule.name; 127 | } else if (Rule.isKeyframe(rule)) { 128 | ruleStr = rule.values.join(); 129 | } else if (Rule.isMediaRule(rule)) { 130 | ruleStr = `${rule.type} ${rule.media}`; 131 | } else if (Rule.isSupportsRule(rule)) { 132 | ruleStr = `${rule.type} ${rule.supports}`; 133 | } else if (Rule.isFontFace(rule)) { 134 | ruleStr = rule.type; 135 | } else if (Rule.isComment(rule)) { 136 | return false; 137 | } else if (Rule.isGroupRule(rule)) { 138 | ruleStr = `${rule.type} ${rule[rule.type]}`; 139 | } else { 140 | //log.error("Can not generate rule key of rule without selectors! Setting default key!", rule); 141 | return ruleStr; 142 | } 143 | 144 | return groupPrefix + keySeparator + ruleStr; 145 | } 146 | } 147 | 148 | export default Rule; 149 | -------------------------------------------------------------------------------- /lib/evaluation/extract_critical_with_css.js: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | /** 4 | * Used to extract critical css with the help of a source css. This will result in larger size because every vendor 5 | * prefix is used. 6 | * 7 | * @param sourceAst 8 | * @param renderTimeout 9 | * @param keepSelectors 10 | * @returns {Promise>} 11 | */ 12 | export default async ({ sourceAst, loadTimeout, keepSelectors, removeSelectors }) => { 13 | return new Promise((resolve, reject) => { 14 | // PRE CONFIG VARS 15 | const usedSelectorTypes = ['supports', 'media', 'rule']; 16 | 17 | const pseudoSelectors = ['after', 'before', 'first-line', 'first-letter', 'selection', 'visited']; 18 | 19 | const pseudoExcludes = ['root']; 20 | 21 | const PSEUDO_DEFAULT_REGEX = new RegExp( 22 | pseudoSelectors.map(s => ':?:' + s).reduce((acc, cur) => acc + '|' + cur), 23 | 'g', 24 | ); 25 | const PSEUDO_EXCLUDED_REGEX = new RegExp( 26 | pseudoExcludes.map(s => ':?:' + s).reduce((acc, cur) => acc + '|' + cur), 27 | 'g', 28 | ); 29 | const PSEUDO_BROWSER_REGEX = new RegExp(/:?:-[a-z-]*/g); 30 | 31 | // ADJUSTMENTS 32 | keepSelectors = keepSelectors || []; 33 | removeSelectors = removeSelectors || []; 34 | loadTimeout = loadTimeout || 2000; 35 | 36 | // innerHeight of window to determine if in viewport 37 | const height = window.innerHeight; 38 | 39 | // Nodes in above the fold content 40 | const criticalNodes = new Set(); 41 | // Final result Map 42 | const criticalSelectors = new Map(); 43 | 44 | const stopPageLoadAfterTimeout = (start, timeout) => { 45 | window.requestAnimationFrame(() => { 46 | const timePassed = Date.now() - start; 47 | if (timePassed >= timeout) { 48 | window.stop(); 49 | } else { 50 | stopPageLoadAfterTimeout(start, timeout); 51 | } 52 | }); 53 | }; 54 | stopPageLoadAfterTimeout(Date.now(), loadTimeout); 55 | 56 | const isSelectorCritical = selector => { 57 | if (isSelectorForceIncluded(selector)) return true; 58 | if (isSelectorForceExcluded(selector)) return false; 59 | 60 | // clean selector from important pseudo classes to get him tracked as critical 61 | const cleanedSelector = getCleanedSelector(selector); 62 | 63 | let elements; 64 | try { 65 | elements = document.querySelectorAll(cleanedSelector); 66 | } catch (e) { 67 | // Selector not valid 68 | return false; 69 | } 70 | 71 | // selector has > 0 elements matching -> check for above the fold - break on success 72 | const elemLength = elements.length; 73 | for (let i = 0; i < elemLength; i++) { 74 | if (isElementAboveTheFold(elements[i])) { 75 | return true; 76 | } 77 | } 78 | return false; 79 | }; 80 | 81 | const isStyleSheet = rule => { 82 | return rule.stylesheet !== undefined; 83 | }; 84 | 85 | /** 86 | * Clean selector of pseudo classes 87 | * 88 | * @param selector 89 | * @returns selector {String} 90 | */ 91 | const getCleanedSelector = selector => { 92 | // We wont clean selectors without ":" because its faster as to replace all 93 | if (selector.indexOf(':' > -1)) { 94 | selector = selector.replace(PSEUDO_DEFAULT_REGEX, ''); 95 | } 96 | // Remove browser pseudo selectors 97 | if (selector.indexOf(':' > -1)) { 98 | selector = selector.replace(PSEUDO_BROWSER_REGEX, ''); 99 | } 100 | // Remove excluded pseudo selectors 101 | if (selector.indexOf(':' > -1)) { 102 | selector = selector.replace(PSEUDO_EXCLUDED_REGEX, ''); 103 | } 104 | 105 | return selector; 106 | }; 107 | 108 | /** 109 | * If selector is purely pseudo (f.e. ::-moz-placeholder) -> KEEP IT. 110 | * But don't keep excludedPseudos by default 111 | * 112 | * @param selector 113 | * @returns {boolean} 114 | */ 115 | const isPurePseudo = selector => selector.startsWith(':') && selector.match(PSEUDO_EXCLUDED_REGEX) === null; 116 | 117 | /** 118 | * Creates a regex out of a wildcard selector. Returns the normal regex for a non wildcard selector 119 | * 120 | * @param {string} selector 121 | * @returns {RegExp} {RegExp} 122 | */ 123 | const getRegexOfSelector = selector => { 124 | selector = '^' + selector.replace(/([.*><+~])/g, '\\$1').replace(/%/g, '.*') + '$'; 125 | return new RegExp(selector, 'gm'); 126 | }; 127 | 128 | const isSelectorForceIncluded = selector => { 129 | return ( 130 | keepSelectors.includes(selector) || 131 | keepSelectors.some(tmpSel => { 132 | const selectorWcRegex = getRegexOfSelector(tmpSel); // transform wildcards into regex 133 | return selectorWcRegex.test(selector); 134 | }) 135 | ); 136 | }; 137 | 138 | const isSelectorForceExcluded = selector => { 139 | return ( 140 | removeSelectors.includes(selector) || 141 | removeSelectors.some(tmpSel => { 142 | const selectorWcRegex = getRegexOfSelector(tmpSel); // transform wildcards into regex 143 | return selectorWcRegex.test(selector); 144 | }) 145 | ); 146 | }; 147 | 148 | const isElementAboveTheFold = element => { 149 | if (criticalNodes.has(element)) return true; 150 | 151 | const isAboveTheFold = element.getBoundingClientRect().top < height; 152 | 153 | if (isAboveTheFold) { 154 | criticalNodes.add(element); 155 | return true; 156 | } 157 | 158 | return false; 159 | }; 160 | 161 | const isGroupRule = rule => { 162 | return rule.type !== 'rule' && rule.rules !== undefined; 163 | }; 164 | 165 | const getRuleType = rule => { 166 | return rule.type; 167 | }; 168 | 169 | const getGroupRuleId = rule => { 170 | const type = getRuleType(rule) || ''; 171 | const typeString = rule[type] || ''; 172 | 173 | return `${type}${typeString}`; 174 | }; 175 | 176 | /** 177 | * Working criticalSelectors Map 178 | * @param ast 179 | */ 180 | const fillCriticalSelectorsMap = (rule, groupIdPrefix = '') => { 181 | if (isGroupRule(rule)) { 182 | if (groupIdPrefix) { 183 | groupIdPrefix = `${groupIdPrefix}-##-`; 184 | } 185 | // Get rule prefix for grouped rule 186 | const rulePrefix = `${groupIdPrefix}${getGroupRuleId(rule)}`; 187 | // Grouped rules always having rules 188 | const rules = rule.rules; 189 | 190 | // Iterate rules 191 | for (let rule of rules) { 192 | // Get ruletype 193 | const ruleType = getRuleType(rule); 194 | 195 | // Is rule part of useful rule types 196 | if (usedSelectorTypes.includes(ruleType)) { 197 | // Call recursive 198 | fillCriticalSelectorsMap(rule, rulePrefix); 199 | } else { 200 | console.debug('DEBUG: UNPROCESSED RULE TYPE: ' + rule.type); 201 | } 202 | } 203 | } else { 204 | // Handle a single rule 205 | 206 | // Get ruletype 207 | const ruleType = getRuleType(rule); 208 | 209 | // Is rule part of useful rule types 210 | if (usedSelectorTypes.includes(ruleType)) { 211 | // Normal rules have selectors 212 | const selectors = rule.selectors || []; 213 | 214 | // Key for identify 215 | const ruleKey = groupIdPrefix + selectors.join(); 216 | 217 | for (let selector of selectors) { 218 | // Check if selector is pure pseudo or a critical match 219 | // NOTE: Check if we are in trouble with doubled selectors with different content 220 | 221 | if (isPurePseudo(selector) || isSelectorCritical(selector)) { 222 | if (criticalSelectors.has(ruleKey)) { 223 | const critSel = criticalSelectors.get(ruleKey); 224 | if (!critSel.selectors.includes(selector)) { 225 | critSel.selectors.push(selector); 226 | } 227 | } else { 228 | criticalSelectors.set(ruleKey, { 229 | selectors: [selector], 230 | type: rule.type, 231 | rule: rule, // Needed? maybe for doubled rules 232 | }); 233 | } 234 | } 235 | } 236 | } else { 237 | console.debug('DEBUG: UNPROCESSED RULE TYPE: ' + rule.type); 238 | } 239 | } 240 | }; 241 | 242 | console.log('STARTING EXTRACTION'); 243 | 244 | // Root knot handling 245 | if (isStyleSheet(sourceAst)) { 246 | _astRoot = sourceAst.stylesheet; 247 | fillCriticalSelectorsMap(_astRoot); 248 | } else { 249 | console.warn('Missing ast stylesheet!!!', ast.type, ast.stylesheet); 250 | } 251 | 252 | return resolve([...criticalSelectors]); 253 | }).catch(error => { 254 | console.log('Extraction Error'); 255 | console.error(error.name); 256 | console.error(error.message); 257 | }); 258 | }; 259 | -------------------------------------------------------------------------------- /lib/evaluation/extract_critical_without_css.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Used to get the current live critical css without any impact of css 3 | * 4 | * @param options 5 | * @returns {*} 6 | */ 7 | export default options => { 8 | // ADJUSTMENTS 9 | const removePseudoSelectors = !!options.removePseudoSelectors; 10 | const keepSelectors = options.keepSelectors || []; 11 | const renderTimeout = options.renderTimeout || 300; 12 | const dropKeyframes = !!options.dropKeyframes; 13 | 14 | // innerHeight of window to determine if in viewport 15 | const height = window.innerHeight; 16 | //Setup our Pseudo selector killer, view height and critical nodes 17 | const removePseudo = removePseudoSelectors ? /([^\s,\:\(])\:\:?(?!not)[a-zA-Z\-]{1,}(?:\(.*?\))?/g : /(.*)/; 18 | const criticalNodes = []; 19 | 20 | // Get a list of all the elements in the view. 21 | const walker = document.createTreeWalker( 22 | document, 23 | NodeFilter.SHOW_ELEMENT, 24 | { 25 | acceptNode: function (node) { 26 | return NodeFilter.FILTER_ACCEPT; 27 | }, 28 | }, 29 | true, 30 | ); 31 | 32 | while (walker.nextNode()) { 33 | const node = walker.currentNode; 34 | 35 | const keep = keepSelectors.find(selector => { 36 | // TODO: wildcard 37 | // node.matches('[class*="te"]') 38 | // node.matches('[id*="te"]') 39 | // node.matches('[*="te"]') 40 | return node.matches(selector); 41 | }); 42 | 43 | if (keep) { 44 | criticalNodes.push(node); 45 | } else { 46 | const rect = node.getBoundingClientRect(); 47 | if (rect.top < height) { 48 | criticalNodes.push(node); 49 | } 50 | } 51 | } 52 | 53 | // Grab loaded stylesheets 54 | const sheets = document.styleSheets; 55 | 56 | const filterNodes = (nodes, rule, replace) => { 57 | return ( 58 | nodes.filter(function (e) { 59 | return e.matches(rule.selectorText.replace(replace, '$1')); 60 | }).length > 0 61 | ); 62 | }; 63 | 64 | const getGroupingRulePrefix = groupingRule => { 65 | switch (groupingRule) { 66 | case groupingRule instanceof CSSMediaRule: 67 | return '@media'; 68 | case groupingRule instanceof CSSSupportsRule: 69 | return '@supports'; 70 | } 71 | 72 | return ''; 73 | }; 74 | 75 | const outCss = Array.prototype.map 76 | .call(sheets, function (sheet) { 77 | const rules = sheet.rules || sheet.cssRules; 78 | // If there are rules 79 | if (rules) { 80 | return { 81 | sheet: sheet, 82 | rules: Array.prototype.map 83 | .call(rules, function (rule) { 84 | // Convert each CSSRule into a string 85 | try { 86 | if (rule instanceof CSSConditionRule) { 87 | // CSSConditionRule is a inherited from CSSGroupingRule which always contains cssRules 88 | // CSSConditionRule only has two objects that derive from it CSSMediaRule and CSSSupportsRule 89 | let subRules = rule.cssRules || []; 90 | 91 | let css = Array.prototype.filter 92 | .call(subRules, rule => { 93 | return filterNodes(criticalNodes, rule, removePseudo); 94 | }) 95 | .map(rule => { 96 | return rule.cssText; 97 | }) 98 | .reduce((ruleCss, init) => { 99 | return init + '\n' + ruleCss; 100 | }, ''); 101 | 102 | const rulePrefix = getGroupingRulePrefix(rule); 103 | const conditionText = rule.conditionText; 104 | 105 | return css ? `${rulePrefix} ${conditionText}{ ${css} }` : null; 106 | } else if (rule instanceof CSSStyleRule) { 107 | if ( 108 | rule.selectorText.indexOf( 109 | '.c24-travel-main-cnt .c24-travel-extended-fieldset, .c24-travel-main-cnt .c24-travel-searchform-wrapper', 110 | ) !== -1 111 | ) { 112 | console.log(rule.cssText); 113 | } 114 | 115 | return filterNodes(criticalNodes, rule, removePseudo) ? rule.cssText : null; 116 | } else if (dropKeyframes && (rule instanceof CSSKeyframeRule || rule instanceof CSSKeyframesRule)) { 117 | // Drop keyframes because they are NOT needed for critical css 118 | return ''; 119 | } else { 120 | return rule.cssText; 121 | } 122 | } catch (e) { 123 | console.error('Bad CSS rule', rule.selectorText); 124 | throw e; 125 | } 126 | }) 127 | .filter(function (e) { 128 | return e; 129 | }), 130 | }; 131 | } else { 132 | return null; 133 | } 134 | }) 135 | .filter(function (cssEntry) { 136 | return cssEntry && cssEntry.rules.length > 0; 137 | }) 138 | .map(function (cssEntry) { 139 | return cssEntry.rules.join(''); 140 | }) 141 | .reduce(function (css, out) { 142 | return out + css; 143 | }, ''); 144 | 145 | return outCss.replace(/\n/g, '').replace(/content\: \"(.)\"/g, function (a, e) { 146 | return 'content: "\\' + encodeURI(e).substr(2) + '"'; 147 | }); 148 | }; 149 | -------------------------------------------------------------------------------- /lib/helper/localFileServer.js: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import http from 'http'; 3 | import fs from 'fs-extra'; 4 | 5 | const staticServerFunc = rootPath => { 6 | return http.createServer((req, res) => { 7 | // parse URL 8 | 9 | const parsedUrl = new URL(req.url, 'http://localhost:8000'); 10 | 11 | // extract URL path 12 | let pathname = `${rootPath}${parsedUrl.pathname}`; 13 | 14 | // maps file extention to MIME types 15 | const mimeType = { 16 | '.ico': 'image/x-icon', 17 | '.html': 'text/html', 18 | '.js': 'text/javascript', 19 | '.json': 'application/json', 20 | '.css': 'text/css', 21 | '.png': 'image/png', 22 | '.jpg': 'image/jpeg', 23 | '.wav': 'audio/wav', 24 | '.mp3': 'audio/mpeg', 25 | '.svg': 'image/svg+xml', 26 | '.pdf': 'application/pdf', 27 | '.doc': 'application/msword', 28 | '.eot': 'appliaction/vnd.ms-fontobject', 29 | '.ttf': 'aplication/font-sfnt', 30 | }; 31 | fs.access(pathname, fs.constants.F_OK, err => { 32 | if (err) { 33 | // if the file is not found, return 404 34 | res.statusCode = 404; 35 | res.end(`File ${pathname} not found!`); 36 | console.log('404 - FILE NOT FOUND', pathname); 37 | return; 38 | } 39 | // if is a directory, then look for index.html 40 | if (fs.statSync(pathname).isDirectory()) { 41 | pathname += '/index.html'; 42 | } 43 | // read file from file system 44 | fs.readFile(pathname, (err, data) => { 45 | if (err) { 46 | res.statusCode = 500; 47 | res.end(`Error getting the file: ${err}.`); 48 | console.log('500 - ERROR GETTING FILE', pathname); 49 | } else { 50 | // based on the URL path, extract the file extention. e.g. .js, .doc, ... 51 | const ext = path.parse(pathname).ext; 52 | // if the file is found, set Content-type and send data 53 | res.setHeader('Content-type', mimeType[ext] || 'text/plain'); 54 | res.end(data); 55 | } 56 | }); 57 | }); 58 | }); 59 | }; 60 | 61 | const createStaticServer = rootPath => { 62 | const staticServer = staticServerFunc(rootPath); 63 | staticServer.setTimeout(1000); 64 | return staticServer; 65 | }; 66 | 67 | export { createStaticServer }; 68 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "crittr", 3 | "version": "2.0.2", 4 | "description": "Crittr is a high performance critical css extraction library with a multiple url support.", 5 | "author": "Philipp Winterle", 6 | "license": "GPL-3.0", 7 | "private": false, 8 | "type": "module", 9 | "bugs": { 10 | "url": "https://github.com/hummal/crittr/issues" 11 | }, 12 | "homepage": "https://hummal.github.io/crittr/", 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/hummal/crittr.git" 16 | }, 17 | "keywords": [ 18 | "critical", 19 | "css", 20 | "above the fold", 21 | "atf", 22 | "stylesheets", 23 | "extraction", 24 | "critical css", 25 | "performance", 26 | "penthouse", 27 | "extract" 28 | ], 29 | "engines": { 30 | "node": ">=18" 31 | }, 32 | "main": "index.js", 33 | "dependencies": { 34 | "@dynamicabot/signales": "^2.1.1", 35 | "@types/jest": "^29.5.11", 36 | "chalk": "^5.3.0", 37 | "clean-css": "^5.3.3", 38 | "css": "^3.0.0", 39 | "debug": "^4.3.4", 40 | "deepmerge": "^4.3.1", 41 | "fs-extra": "^11.2.0", 42 | "is-plain-object": "^5.0.0", 43 | "lodash": "^4.17.21", 44 | "object-hash": "^3.0.0", 45 | "postcss": "^8.4.33", 46 | "postcss-sort-media-queries": "^5.2.0", 47 | "puppeteer": "^22.11.1", 48 | "puppeteer-extra": "^3.3.6", 49 | "puppeteer-extra-plugin-stealth": "^2.11.2", 50 | "release-please": "^16.12.0", 51 | "run-queue": "^2.0.1", 52 | "signale": "^1.4.0" 53 | }, 54 | "devDependencies": { 55 | "@changesets/cli": "^2.27.5", 56 | "@commitlint/cli": "^19.3.0", 57 | "@commitlint/config-conventional": "^19.2.2", 58 | "@types/node": "^20.14.2", 59 | "cross-env": "^7.0.3", 60 | "eslint": "^9.5.0", 61 | "eslint-config-prettier": "^9.1.0", 62 | "eslint-plugin-sort-destructure-keys": "^2.0.0", 63 | "husky": "^9.0.11", 64 | "jest": "^29.7.0", 65 | "prettier": "^3.2.4" 66 | }, 67 | "scripts": { 68 | "test": "cross-env NODE_ENV=development node --experimental-vm-modules node_modules/jest/bin/jest.js --bail --verbose", 69 | "build": "echo 'build is not configured for package. Skipping.'", 70 | "prepare": "husky" 71 | }, 72 | "files": [ 73 | "docs", 74 | "lib", 75 | "examples" 76 | ], 77 | "directories": { 78 | "doc": "docs", 79 | "example": "examples", 80 | "lib": "lib", 81 | "test": "test" 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /postcss.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [ 3 | require('postcss-sort-media-queries')({ 4 | sort: 'mobile-first', // default value 5 | }), 6 | ], 7 | }; 8 | -------------------------------------------------------------------------------- /test/data/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipp-winterle/crittr/8d2f3322e8600bdadb6efe8e66d51e053a4c2b91/test/data/favicon.ico -------------------------------------------------------------------------------- /test/data/test.css: -------------------------------------------------------------------------------- 1 | @charset "UTF-8"; 2 | 3 | @font-face { 4 | font-family: 'Keep Critical'; 5 | src: url('ONLY TEST'); 6 | } 7 | 8 | body { 9 | font-size: 1em; 10 | font-weight: 400; 11 | font-style: normal; 12 | } 13 | 14 | .standard-selector { 15 | color: black; 16 | } 17 | 18 | /* FOR DUPLICATE TEST */ 19 | .standard-selector { 20 | color: black; 21 | } 22 | 23 | #id-selector { 24 | color: blue; 25 | } 26 | 27 | div { 28 | color: darkgrey; 29 | } 30 | 31 | .child-selector > * { 32 | color: brown; 33 | } 34 | 35 | .sibling-selector + .sibling { 36 | color: green; 37 | } 38 | 39 | .sibling-general-selector ~ .sibling { 40 | color: aqua; 41 | } 42 | 43 | .property-selector[data-test='test'] { 44 | color: bisque; 45 | } 46 | 47 | .group-selector .deep1 .deep2 { 48 | color: chartreuse; 49 | } 50 | 51 | .multi-selector, 52 | .multi-selector-1, 53 | .multi-selector-2 { 54 | color: darkmagenta; 55 | } 56 | 57 | .multi-selector, 58 | .no-atf-css { 59 | color: red; 60 | } 61 | 62 | .no-atf-css-default { 63 | color: tomato; 64 | } 65 | 66 | .forceInclude { 67 | color: deeppink; 68 | } 69 | 70 | .multi-selector, 71 | .forceInclude, 72 | .multi-selector-not-exists { 73 | content: 'forceIncludeMultiSelector'; 74 | } 75 | 76 | .forceExclude { 77 | color: royalblue; 78 | } 79 | 80 | .multi-selector, 81 | .forceExclude, 82 | .multi-selector-1 { 83 | content: 'forceExcludeMultiSelector'; 84 | } 85 | 86 | :root .not-existing-selector { 87 | content: 'should not be included'; 88 | } 89 | 90 | h1, 91 | h2, 92 | h3, 93 | h4, 94 | h5, 95 | h6 { 96 | font-size: 22px; 97 | } 98 | 99 | .vendor_prefix { 100 | -webkit-box-sizing: border-box; 101 | -moz-box-sizing: border-box; 102 | box-sizing: border-box; 103 | } 104 | 105 | .pseudo-selector::after { 106 | color: limegreen; 107 | content: 'pseudo :after'; 108 | } 109 | 110 | .pseudo-selector::before { 111 | color: silver; 112 | content: 'pseudo ::before'; 113 | } 114 | 115 | .multi-selector, 116 | .not-exists .remaining-css, 117 | .multi-selector-1 { 118 | content: 'should only have multi-selector and multi-selector-1 in criticalcss'; 119 | } 120 | 121 | .pre .wildcard_test_1 .post { 122 | content: 'wildcard test [not included in HTML] - SHOULD BE INCLUDED'; 123 | } 124 | 125 | .pre .wildcard_test_2 .post { 126 | content: 'wildcard test [not included in HTML] - SHOULD NOT BE INCLUDED'; 127 | } 128 | 129 | .wildcard_test_3.space { 130 | content: 'SHOULD NOT BE INCLUDED'; 131 | } 132 | 133 | @supports (display: flex) { 134 | .supports-selector { 135 | content: 'supports test - should be included'; 136 | } 137 | } 138 | 139 | @supports (display: flex) { 140 | .supports-selector-not-included { 141 | content: 'supports test - not included'; 142 | } 143 | } 144 | 145 | @media (min-width: 1024px) { 146 | .standard-selector { 147 | color: black; 148 | content: '.standard-selector 1024'; 149 | } 150 | 151 | #id-selector { 152 | color: blue; 153 | content: '#id-selector 1024'; 154 | } 155 | 156 | div { 157 | color: darkgrey; 158 | content: 'div 1024'; 159 | } 160 | 161 | .pseudo-selector::after { 162 | color: limegreen; 163 | content: 'pseudo 1024 :after'; 164 | } 165 | 166 | .pseudo-selector::before { 167 | color: silver; 168 | content: 'pseudo 1024 ::before'; 169 | } 170 | 171 | .no-atf-css-default-1024 { 172 | color: tomato; 173 | } 174 | 175 | .forceInclude { 176 | color: deeppink; 177 | } 178 | 179 | .forceExclude { 180 | color: royalblue; 181 | } 182 | 183 | .multi-selector, 184 | .not-exists-mq-1024 .remaining-css, 185 | .multi-selector-1 { 186 | content: 'should only have multi-selector and multi-selector-1 in criticalcss'; 187 | } 188 | } 189 | 190 | @media (min-width: 1024px) { 191 | .standard-selector { 192 | content: 'double media query 1024 .standard-selector'; 193 | } 194 | } 195 | 196 | @media (min-width: 1024px) { 197 | .standard-selector { 198 | content: 'double media query 1024 .standard-selector'; 199 | } 200 | } 201 | 202 | @media (min-width: 900px) { 203 | .no-atf-css-default { 204 | color: gold; 205 | } 206 | 207 | .standard-selector { 208 | color: black; 209 | content: '.standard-selector 800'; 210 | } 211 | } 212 | 213 | @media (min-width: 800px) { 214 | .standard-selector { 215 | color: black; 216 | content: '.standard-selector 800'; 217 | } 218 | 219 | #id-selector { 220 | color: blue; 221 | content: '#id-selector 800'; 222 | } 223 | 224 | div { 225 | color: darkgrey; 226 | content: 'div 800'; 227 | } 228 | 229 | .no-atf-css-default-800 { 230 | color: tomato; 231 | } 232 | 233 | .forceInclude { 234 | color: deeppink; 235 | } 236 | 237 | .forceExclude { 238 | color: royalblue; 239 | } 240 | 241 | @supports (display: flex) { 242 | .supports-selector { 243 | content: 'supports test mq - should be included'; 244 | } 245 | } 246 | 247 | @supports (display: flex) { 248 | .supports-selector-not-included { 249 | content: 'supports test - not included'; 250 | } 251 | } 252 | } 253 | 254 | @media (max-width: 1337px) { 255 | .no-selector { 256 | content: 'just no'; 257 | } 258 | .standard-selector { 259 | color: black; 260 | content: '.standard-selector 800'; 261 | } 262 | } 263 | 264 | @media (max-width: 337px) { 265 | .no-selector { 266 | content: 'just no'; 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /test/data/test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | TestPage 6 | 7 | 8 | 9 | 10 |
Class .standard-selector
11 |
Class .supports-selector
12 |
ID id-selector
13 |
div selector
14 |
15 | 16 |
17 | 18 |
19 | Class .child-selector Child 20 |
21 | 22 |
23 | 24 |
Class .sibling-selector
25 |
Class .sibling
26 | 27 |
28 | 29 |
Class .sibling-general-selector
30 |
31 |
Class .sibling
32 | 33 |
34 | 35 |
Class .property-selector[data-test="test"]
36 | 37 |
38 | 39 |
40 |
41 | Class .deep1 42 |
Class .deep2
43 |
44 |
45 | 46 |
47 | 48 |
Class .multi-selector
49 |
Class .multi-selector1
50 |
Class .multi-selector2
51 | 52 |

Element h1

53 | 54 |
Class .vendor_prefix
55 | 56 | 57 |
Class .forceExclude
58 | 59 | 60 |
61 | This DIV should simulate content. Content below is not included in ATF 62 |
63 | 64 | 65 |
Class .forceInclude
66 | 67 |

Element h2

68 |

Element h3

69 | 70 |
Class .supports-selector-not-included
71 | 72 | 73 | -------------------------------------------------------------------------------- /test/helpers.js: -------------------------------------------------------------------------------- 1 | import Rule from '../lib/classes/Rule.class.js'; 2 | 3 | const isGroupRule = rule => { 4 | return rule.type !== 'rule' && rule.rules !== undefined; 5 | }; 6 | 7 | const addCriticalRule = (rule, criticalSelectorRules, rulePrefix = '') => { 8 | if (isGroupRule(rule)) { 9 | const ruleKey = Rule.generateRuleKey(rule); 10 | rulePrefix = `${rulePrefix}${ruleKey}===`; 11 | 12 | // CSSGroupingRule has cssRules as main property. .rules is deprecated 13 | const rules = rule.rules || []; 14 | 15 | for (const rule of rules) { 16 | addCriticalRule(rule, criticalSelectorRules, rulePrefix); 17 | } 18 | } else if (Rule.isStyleRule(rule)) { 19 | const pairedSelector = `${rulePrefix}${rule.selectors.join(',')}`; 20 | 21 | if (criticalSelectorRules.has(pairedSelector)) { 22 | let count = criticalSelectorRules.get(pairedSelector); 23 | criticalSelectorRules.set(pairedSelector, ++count); 24 | } else { 25 | criticalSelectorRules.set(pairedSelector, 1); 26 | } 27 | } else { 28 | if (criticalSelectorRules.has(rule.type)) { 29 | let count = criticalSelectorRules.get(rule.type); 30 | criticalSelectorRules.set(rule.type, ++count); 31 | } else { 32 | criticalSelectorRules.set(rule.type, 1); 33 | } 34 | } 35 | }; 36 | 37 | /** 38 | * 39 | * @param {CSSRuleList} astRules 40 | * @returns Map 41 | */ 42 | const getAstRules = astRules => { 43 | const criticalSelectorRules = new Map(); 44 | // Gather all Selectors of result CSS 45 | for (const rule of astRules) { 46 | addCriticalRule(rule, criticalSelectorRules); 47 | } 48 | 49 | return criticalSelectorRules; 50 | }; 51 | 52 | export default { 53 | getAstRules: getAstRules, 54 | }; 55 | -------------------------------------------------------------------------------- /test/results/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipp-winterle/crittr/8d2f3322e8600bdadb6efe8e66d51e053a4c2b91/test/results/.gitkeep -------------------------------------------------------------------------------- /test/setup.js: -------------------------------------------------------------------------------- 1 | import Critter from '../index.js'; 2 | import fs from 'fs-extra'; 3 | import path from 'path'; 4 | import merge from 'deepmerge'; 5 | import crypto from 'crypto'; 6 | import { createStaticServer } from '../lib/helper/localFileServer.js'; 7 | import url from 'url'; 8 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 9 | const rootDir = path.join(__dirname, '..'); 10 | const testResultDir = path.join(rootDir, 'test', 'results'); 11 | const staticServer = createStaticServer(rootDir); 12 | 13 | const testData = { 14 | urls: ['./test/data/test.html?1', './test/data/test.html?2', './test/data/test.html?3', './test/data/test.html?4'], 15 | css: rootDir + '/test/data/test.css', 16 | }; 17 | 18 | const testDataNoCSS = { 19 | urls: [ 20 | 'http://localhost:8000/test/data/test.html?1', 21 | 'http://localhost:8000/test/data/test.html?2', 22 | 'http://localhost:8000/test/data/test.html?3', 23 | 'http://localhost:8000/test/data/test.html?4', 24 | ], 25 | }; 26 | 27 | const defaultOptions = { 28 | device: { 29 | width: 1920, 30 | height: 1080, 31 | }, 32 | keepSelectors: ['.forceInclude', '%.wildcard_test_1 %', '.wildcard_test_2 %', '.wildcard_test_3 %'], 33 | removeSelectors: ['.forceExclude'], 34 | }; 35 | 36 | const standardOptions = merge(defaultOptions, { 37 | urls: testData.urls, 38 | css: testData.css, 39 | }); 40 | 41 | const noCssOptions = merge(defaultOptions, { 42 | urls: testDataNoCSS.urls, 43 | css: null, 44 | }); 45 | 46 | const screenshotOptions = merge(defaultOptions, { 47 | urls: [ 48 | 'http://localhost:8000/test/data/test.html?1', 49 | 'http://localhost:8000/test/data/test.html?2', 50 | 'http://localhost:8000/test/data/test.html?3', 51 | 'http://localhost:8000/test/data/test.html?4', 52 | ], 53 | css: testData.css, 54 | takeScreenshots: true, 55 | screenshotPath: path.join(testResultDir, 'screenshots', 'normal'), 56 | }); 57 | 58 | const screenNameGenerator = async url => { 59 | const sha1HashGen = crypto.createHash('sha1'); 60 | sha1HashGen.update(url); 61 | return sha1HashGen.digest('hex'); 62 | }; 63 | const screenshotWithFunctionOptions = merge(defaultOptions, { 64 | urls: [ 65 | 'http://localhost:8000/test/data/test.html?1', 66 | 'http://localhost:8000/test/data/test.html?2', 67 | 'http://localhost:8000/test/data/test.html?3', 68 | 'http://localhost:8000/test/data/test.html?4', 69 | ], 70 | css: testData.css, 71 | takeScreenshots: true, 72 | screenshotPath: path.join(testResultDir, 'screenshots', 'withFunction'), 73 | screenshotNameGenerator: screenNameGenerator, 74 | }); 75 | 76 | export default () => { 77 | return new Promise(async (resolve, reject) => { 78 | const server = staticServer 79 | .listen(8000, async () => { 80 | try { 81 | const { critical: defaultCss, rest: defaultRest } = await Critter(standardOptions); 82 | 83 | fs.writeFileSync(path.join(testResultDir, './test_result.css'), defaultCss, 'utf-8'); 84 | 85 | fs.writeFileSync(path.join(testResultDir, './test_result_remaining.css'), defaultRest, 'utf-8'); 86 | 87 | // Second Run for URL 88 | let { critical: noCssCritical, rest: noCssRest } = await Critter(noCssOptions); 89 | 90 | fs.writeFileSync(path.join(testResultDir, './test_result_noCss.css'), noCssCritical, 'utf-8'); 91 | 92 | fs.writeFileSync(path.join(testResultDir, './test_result_noCss_remaining.css'), noCssRest, 'utf-8'); 93 | 94 | // Third Run for URL 95 | let { critical: screenshotCssCritical, rest: screenshotCssRest } = await Critter(screenshotOptions); 96 | 97 | fs.writeFileSync(path.join(testResultDir, './test_result_screenshotCss.css'), screenshotCssCritical, 'utf-8'); 98 | 99 | fs.writeFileSync(path.join(testResultDir, './test_result_screenshotCss_remaining.css'), screenshotCssRest, 'utf-8'); 100 | 101 | // Fourth Run for URL 102 | let { critical: screenshotWithFunctionCssCritical, rest: screenshotWithFunctionCssRest } = 103 | await Critter(screenshotWithFunctionOptions); 104 | 105 | fs.writeFileSync( 106 | path.join(testResultDir, './test_result_screenshotWithFunctionCss.css'), 107 | screenshotWithFunctionCssCritical, 108 | 'utf-8', 109 | ); 110 | 111 | fs.writeFileSync( 112 | path.join(testResultDir, './test_result_screenshotWithFunctionCss_remaining.css'), 113 | screenshotWithFunctionCssRest, 114 | 'utf-8', 115 | ); 116 | 117 | resolve(); 118 | } catch (err) { 119 | reject(err); 120 | } 121 | 122 | server.close(); 123 | }) 124 | .on('error', err => { 125 | reject(err); 126 | }); 127 | }); 128 | }; 129 | -------------------------------------------------------------------------------- /test/teardown.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import url from 'url'; 4 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 5 | const rootDir = path.join(__dirname, '..'); 6 | 7 | export default async function () { 8 | // Cleans up artifacts (`.css` files and `screenshots` folder from `test`) 9 | const files = await fs.readdir(__dirname); 10 | await Promise.all( 11 | files 12 | .filter(fileOrFolder => fileOrFolder.endsWith('.css') || fileOrFolder === 'screenshots') 13 | .map(fileOrFolder => fs.remove(path.join('./test/', fileOrFolder))), 14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /test/tests/basic.test.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import css from 'css'; 4 | import helpers from './../helpers.js'; 5 | import Rule from '../../lib/classes/Rule.class.js'; 6 | import url from 'url'; 7 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 8 | const rootDir = path.join(__dirname, '..', '..'); 9 | const testResultDir = path.join(rootDir, 'test', 'results'); 10 | 11 | describe('Basic Test', () => { 12 | describe('Check Results', () => { 13 | const resultCSS = fs.readFileSync(path.join(testResultDir, 'test_result.css'), 'utf8'); 14 | 15 | const remainingCSS = fs.readFileSync(path.join(testResultDir, 'test_result_remaining.css'), 'utf8'); 16 | 17 | const resultAstRules = css.parse(resultCSS).stylesheet.rules; 18 | const remainingAstRules = css.parse(remainingCSS).stylesheet.rules; 19 | 20 | const criticalSelectorRules = helpers.getAstRules(resultAstRules); 21 | 22 | // Selectors to search for 23 | const mustHaveSelectors = { 24 | standard: [ 25 | '.standard-selector', 26 | '#id-selector', 27 | 'div', 28 | '.child-selector > *', 29 | '.sibling-selector + .sibling', 30 | '.sibling-general-selector ~ .sibling', 31 | `.property-selector[data-test='test']`, 32 | '.group-selector .deep1 .deep2', 33 | '.multi-selector,.multi-selector-1,.multi-selector-2', 34 | '.forceInclude', 35 | 'h1', 36 | '.vendor_prefix', 37 | '.pseudo-selector::after', 38 | '.pseudo-selector::before', 39 | '.pre .wildcard_test_1 .post', 40 | ], 41 | media1024: [ 42 | '.standard-selector', 43 | '#id-selector', 44 | 'div', 45 | '.forceInclude', 46 | '.pseudo-selector::after', 47 | '.pseudo-selector::before', 48 | ], 49 | media800: ['.standard-selector', '#id-selector', '.forceInclude'], 50 | supports: ['.supports-selector'], 51 | media800_supports: ['.supports-selector'], 52 | }; 53 | 54 | const mustMissSelectors = { 55 | standard: [ 56 | '.forceExclude', 57 | '.no-atf-css-default', 58 | ':root .not-existing-selector', 59 | 'h2,h3,h4,h5,h6', 60 | '.pre .wildcard_test_2 .post', 61 | '.wildcard_test_3.space', 62 | ], 63 | media1024: ['.forceExclude', '.no-atf-css-default-1024'], 64 | media800: ['.forceExclude', '.no-atf-css-default-800'], 65 | supports: ['.supports-selector-not-included'], 66 | media800_supports: ['.supports-selector-not-included'], 67 | }; 68 | 69 | test('Standard selectors should be included', () => { 70 | const missingSelectors = []; 71 | for (const selector of mustHaveSelectors.standard) { 72 | if (!criticalSelectorRules.has(selector)) { 73 | missingSelectors.push(selector); 74 | } 75 | } 76 | expect(missingSelectors).toHaveLength(0); 77 | }); 78 | 79 | test('Standard selectors should NOT be included', () => { 80 | const falseIncludedSelectors = []; 81 | for (const selector of mustMissSelectors.standard) { 82 | if (criticalSelectorRules.has(selector)) { 83 | falseIncludedSelectors.push(selector); 84 | } 85 | } 86 | expect(falseIncludedSelectors).toHaveLength(0); 87 | }); 88 | 89 | test('Supports selectors should be included', () => { 90 | const missingSelectors = []; 91 | const selectorPrefix = 'supports (display: flex)==='; 92 | for (const selector of mustHaveSelectors.supports) { 93 | const selectorStr = selectorPrefix + selector; 94 | if (!criticalSelectorRules.has(selectorStr)) { 95 | missingSelectors.push(selectorStr); 96 | } 97 | } 98 | expect(missingSelectors).toHaveLength(0); 99 | }); 100 | 101 | test('Supports selectors should NOT be included', () => { 102 | const selectorPrefix = 'supports (display: flex)==='; 103 | const falseIncludedSelectors = []; 104 | for (const selector of mustMissSelectors.supports) { 105 | const selectorStr = selectorPrefix + selector; 106 | if (criticalSelectorRules.has(selectorStr)) { 107 | falseIncludedSelectors.push(selectorStr); 108 | } 109 | } 110 | expect(falseIncludedSelectors).toHaveLength(0); 111 | }); 112 | 113 | test("There shouldn't be any duplicate media query delcarations", () => { 114 | const duplicateMediaQuery = []; 115 | const mqCounter = []; 116 | for (const rule of resultAstRules) { 117 | if (rule.type === 'media') { 118 | if (mqCounter.includes(rule.media)) { 119 | duplicateMediaQuery.push(rule.media); 120 | } else { 121 | mqCounter.push(rule.media); 122 | } 123 | } 124 | } 125 | expect(duplicateMediaQuery).toHaveLength(0); 126 | }); 127 | 128 | test('MediaQuery 1024 selectors should be included', () => { 129 | const missingSelectors = []; 130 | const selectorPrefix = 'media (min-width: 1024px)==='; 131 | for (const selector of mustHaveSelectors.media1024) { 132 | if (!criticalSelectorRules.has(selectorPrefix + selector)) { 133 | missingSelectors.push(selectorPrefix + selector); 134 | } 135 | } 136 | expect(missingSelectors).toHaveLength(0); 137 | }); 138 | 139 | test('MediaQuery 1024 selectors should NOT be included', () => { 140 | const falseIncludedSelectors = []; 141 | const selectorPrefix = 'media (min-width: 1024px)==='; 142 | for (const selector of mustMissSelectors.media1024) { 143 | if (criticalSelectorRules.has(selectorPrefix + selector)) { 144 | falseIncludedSelectors.push(selectorPrefix + selector); 145 | } 146 | } 147 | expect(falseIncludedSelectors).toHaveLength(0); 148 | }); 149 | 150 | test('MediaQuery 800 selectors should be included', () => { 151 | const missingSelectors = []; 152 | const selectorPrefix = 'media (min-width: 800px)==='; 153 | for (const selector of mustHaveSelectors.media800) { 154 | if (!criticalSelectorRules.has(selectorPrefix + selector)) { 155 | missingSelectors.push(selectorPrefix + selector); 156 | } 157 | } 158 | expect(missingSelectors).toHaveLength(0); 159 | }); 160 | 161 | test('MediaQuery 800 selectors should NOT be included', () => { 162 | const falseIncludedSelectors = []; 163 | const selectorPrefix = 'media (min-width: 800px)==='; 164 | for (const selector of mustMissSelectors.media800) { 165 | if (criticalSelectorRules.has(selectorPrefix + selector)) { 166 | falseIncludedSelectors.push(selectorPrefix + selector); 167 | } 168 | } 169 | expect(falseIncludedSelectors).toHaveLength(0); 170 | }); 171 | 172 | test('MediaQuery 800 @supports should be included', () => { 173 | const missingSelectors = []; 174 | const selectorPrefix = 'media (min-width: 800px)===supports (display: flex)==='; 175 | for (const selector of mustHaveSelectors.media800_supports) { 176 | if (!criticalSelectorRules.has(selectorPrefix + selector)) { 177 | missingSelectors.push(selectorPrefix + selector); 178 | } 179 | } 180 | expect(missingSelectors).toHaveLength(0); 181 | }); 182 | 183 | test('MediaQuery 800 @supports should NOT be included', () => { 184 | const falseIncludedSelectors = []; 185 | const selectorPrefix = 'media (min-width: 800px)===supports (display: flex)==='; 186 | for (const selector of mustMissSelectors.media800_supports) { 187 | if (criticalSelectorRules.has(selectorPrefix + selector)) { 188 | falseIncludedSelectors.push(selectorPrefix + selector); 189 | } 190 | } 191 | expect(falseIncludedSelectors).toHaveLength(0); 192 | }); 193 | 194 | test('There should not be duplicates of rules', () => { 195 | const getDeepDuplicates = (rules, excludedProps, media) => { 196 | let duplicatedRules = []; 197 | media = media || ''; 198 | 199 | for (const rule of rules) { 200 | if (rule.type === 'media') { 201 | duplicatedRules = duplicatedRules.concat(getDeepDuplicates(rule.rules, excludedProps, rule.media)); 202 | } else { 203 | let duplicateCount = 0; 204 | for (const innerRule of rules) { 205 | if (Rule.isRuleDuplicate(rule, innerRule, excludedProps)) { 206 | duplicateCount++; 207 | } 208 | } 209 | if (duplicateCount > 1) { 210 | // Put the rule into the duplicate Array but reduce the count by one because one is still needed :) 211 | const index = rule.type + (media ? ' ' + media + ' ' : '') + (rule.selectors ? rule.selectors.join(' ') : ''); 212 | if (!duplicatedRules.includes(index)) { 213 | duplicatedRules.push(index); 214 | } 215 | } 216 | } 217 | } 218 | 219 | return duplicatedRules; 220 | }; 221 | 222 | const excludedProps = ['position']; 223 | const duplicateRules = getDeepDuplicates(resultAstRules, excludedProps); 224 | expect(duplicateRules).toHaveLength(0); 225 | }); 226 | 227 | test('There should not exist any empty selectors', () => { 228 | const emptyRules = []; 229 | for (const rule of resultAstRules) { 230 | if (Rule.isMediaRule(rule)) { 231 | if (rule.rules && rule.rules.length === 0) { 232 | emptyRules.push(rule.media); 233 | } 234 | } else { 235 | if (rule.declarations && rule.declarations.length === 0) { 236 | emptyRules.push(rule.selectors.join(' ')); 237 | } 238 | } 239 | } 240 | 241 | expect(emptyRules).toHaveLength(0); 242 | }); 243 | 244 | test('There should not exist any non critical partial selectors in critical css', () => { 245 | let exists = resultAstRules.some(rule => { 246 | return rule.selectors && rule.selectors.includes('.not-exists .remaining-css'); 247 | }); 248 | 249 | expect(exists).not.toBeTruthy(); 250 | }); 251 | 252 | test('There should not exist any non critical partial mq rule selectors in remaining css', () => { 253 | let exists = resultAstRules.some(rule => { 254 | if (rule.type === 'media') { 255 | return rule.rules.some(rule => rule.selectors && rule.selectors.includes('.not-exists-mq-1024 .remaining-css')); 256 | } 257 | }); 258 | 259 | expect(exists).not.toBeTruthy(); 260 | }); 261 | 262 | test('There should exist any non critical partial selectors in remaining css', () => { 263 | let exists = remainingAstRules.some(rule => rule.selectors && rule.selectors.includes('.not-exists .remaining-css')); 264 | expect(exists).toBeTruthy(); 265 | }); 266 | 267 | test('There should exist any non critical partial mq rule selectors in remaining css', () => { 268 | let exists = remainingAstRules.some(rule => { 269 | if (rule.type === 'media') { 270 | return rule.rules.some(rule => rule.selectors && rule.selectors.includes('.not-exists-mq-1024 .remaining-css')); 271 | } 272 | }); 273 | 274 | expect(exists).toBeTruthy(); 275 | }); 276 | 277 | test('Font-Face should be in critical css', () => { 278 | const exists = criticalSelectorRules.has('font-face'); 279 | expect(exists).toBeTruthy(); 280 | }); 281 | }); 282 | }); 283 | -------------------------------------------------------------------------------- /test/tests/basic_nocss.test.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import css from 'css'; 4 | import helpers from './../helpers.js'; 5 | import Rule from '../../lib/classes/Rule.class.js'; 6 | import url from 'url'; 7 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 8 | const rootDir = path.join(__dirname, '..', '..'); 9 | const testResultDir = path.join(rootDir, 'test', 'results'); 10 | 11 | describe('Basic NoCSS Test', () => { 12 | describe('Check Results', () => { 13 | const resultCSS = fs.readFileSync(path.join(testResultDir, 'test_result_noCss.css'), 'utf8'); 14 | 15 | const remainingCSS = fs.readFileSync(path.join(testResultDir, 'test_result_noCss_remaining.css'), 'utf8'); 16 | 17 | const resultAstRules = css.parse(resultCSS).stylesheet.rules; 18 | const remainingAstRules = css.parse(remainingCSS).stylesheet.rules; 19 | 20 | const criticalSelectorRules = helpers.getAstRules(resultAstRules); 21 | 22 | // Selectors to search for 23 | const mustHaveSelectors = { 24 | standard: [ 25 | '.standard-selector', 26 | '#id-selector', 27 | 'div', 28 | '.child-selector > *', 29 | '.sibling-selector + .sibling', 30 | '.sibling-general-selector ~ .sibling', 31 | '.property-selector[data-test="test"]', 32 | '.group-selector .deep1 .deep2', 33 | '.multi-selector,.multi-selector-1,.multi-selector-2', 34 | '.forceInclude', 35 | 'h1', 36 | '.vendor_prefix', 37 | '.pseudo-selector::after', 38 | '.pseudo-selector::before', 39 | '.pre .wildcard_test_1 .post', 40 | ], 41 | media1024: [ 42 | '.standard-selector', 43 | '#id-selector', 44 | 'div', 45 | '.forceInclude', 46 | '.pseudo-selector::after', 47 | '.pseudo-selector::before', 48 | ], 49 | media800: ['.standard-selector', '#id-selector', '.forceInclude'], 50 | }; 51 | 52 | const mustMissSelectors = { 53 | standard: [ 54 | '.forceExclude', 55 | '.no-atf-css-default', 56 | ':root .not-existing-selector', 57 | 'h2,h3,h4,h5,h6', 58 | '.pre .wildcard_test_2 .post', 59 | '.wildcard_test_3.space', 60 | ], 61 | media1024: ['.forceExclude', '.no-atf-css-default-1024'], 62 | media800: ['.forceExclude', '.no-atf-css-default-800'], 63 | }; 64 | 65 | test('Standard selectors should be included', () => { 66 | const missingSelectors = []; 67 | for (const selector of mustHaveSelectors.standard) { 68 | if (!criticalSelectorRules.has(selector)) { 69 | missingSelectors.push(selector); 70 | } 71 | } 72 | expect(missingSelectors).toHaveLength(0); 73 | }); 74 | 75 | test('Standard selectors should NOT be included', () => { 76 | const falseIncludedSelectors = []; 77 | for (const selector of mustMissSelectors.standard) { 78 | if (criticalSelectorRules.has(selector)) { 79 | falseIncludedSelectors.push(selector); 80 | } 81 | } 82 | expect(falseIncludedSelectors).toHaveLength(0); 83 | }); 84 | 85 | test("There shouldn't be any duplicate media query delcarations", () => { 86 | const duplicateMediaQuery = []; 87 | const mqCounter = []; 88 | for (const rule of resultAstRules) { 89 | if (rule.type === 'media') { 90 | if (mqCounter.includes(rule.media)) { 91 | duplicateMediaQuery.push(rule.media); 92 | } else { 93 | mqCounter.push(rule.media); 94 | } 95 | } 96 | } 97 | expect(duplicateMediaQuery).toHaveLength(0); 98 | }); 99 | 100 | test('MediaQuery 1024 selectors should be included', () => { 101 | const missingSelectors = []; 102 | const selectorPrefix = 'media (min-width: 1024px)==='; 103 | for (const selector of mustHaveSelectors.media1024) { 104 | if (!criticalSelectorRules.has(selectorPrefix + selector)) { 105 | missingSelectors.push(selectorPrefix + selector); 106 | } 107 | } 108 | expect(missingSelectors).toHaveLength(0); 109 | }); 110 | 111 | test('MediaQuery 1024 selectors should NOT be included', () => { 112 | const falseIncludedSelectors = []; 113 | const selectorPrefix = 'media (min-width: 1024px)==='; 114 | for (const selector of mustMissSelectors.media1024) { 115 | if (criticalSelectorRules.has(selectorPrefix + selector)) { 116 | falseIncludedSelectors.push(selectorPrefix + selector); 117 | } 118 | } 119 | expect(falseIncludedSelectors).toHaveLength(0); 120 | }); 121 | 122 | test('MediaQuery 800 selectors should be included', () => { 123 | const missingSelectors = []; 124 | const selectorPrefix = 'media (min-width: 800px)==='; 125 | for (const selector of mustHaveSelectors.media800) { 126 | if (!criticalSelectorRules.has(selectorPrefix + selector)) { 127 | missingSelectors.push(selectorPrefix + selector); 128 | } 129 | } 130 | expect(missingSelectors).toHaveLength(0); 131 | }); 132 | 133 | test('MediaQuery 800 selectors should NOT be included', () => { 134 | const falseIncludedSelectors = []; 135 | const selectorPrefix = 'media (min-width: 800px)==='; 136 | for (const selector of mustMissSelectors.media800) { 137 | if (criticalSelectorRules.has(selectorPrefix + selector)) { 138 | falseIncludedSelectors.push(selectorPrefix + selector); 139 | } 140 | } 141 | expect(falseIncludedSelectors).toHaveLength(0); 142 | }); 143 | 144 | test('There should not be duplicates of rules', () => { 145 | const getDeepDuplicates = (rules, excludedProps, media) => { 146 | let duplicatedRules = []; 147 | media = media || ''; 148 | 149 | for (const rule of rules) { 150 | if (Rule.isMediaRule(rule)) { 151 | duplicatedRules = duplicatedRules.concat(getDeepDuplicates(rule.rules, excludedProps, rule.media)); 152 | } else { 153 | let duplicateCount = 0; 154 | for (const innerRule of rules) { 155 | if (Rule.isRuleDuplicate(rule, innerRule, excludedProps)) { 156 | duplicateCount++; 157 | } 158 | } 159 | if (duplicateCount > 1) { 160 | // Put the rule into the duplicate Array but reduce the count by one because one is still needed :) 161 | const index = rule.type + (media ? ' ' + media + ' ' : '') + (rule.selectors ? rule.selectors.join(' ') : ''); 162 | if (!duplicatedRules.includes(index)) { 163 | duplicatedRules.push(index); 164 | } 165 | } 166 | } 167 | } 168 | 169 | return duplicatedRules; 170 | }; 171 | 172 | const excludedProps = ['position']; 173 | const duplicateRules = getDeepDuplicates(resultAstRules, excludedProps); 174 | expect(duplicateRules).toHaveLength(0); 175 | }); 176 | 177 | test('There should not exist any empty selectors', () => { 178 | const emptyRules = []; 179 | for (const rule of resultAstRules) { 180 | if (Rule.isMediaRule(rule)) { 181 | if (rule.rules && rule.rules.length === 0) { 182 | emptyRules.push(rule.media); 183 | } 184 | } else { 185 | if (rule.declarations && rule.declarations.length === 0) { 186 | emptyRules.push(rule.selectors.join(' ')); 187 | } 188 | } 189 | } 190 | 191 | expect(emptyRules).toHaveLength(0); 192 | }); 193 | 194 | test('There should not exist any non critical partial selectors in critical css', () => { 195 | let exists = resultAstRules.some(rule => { 196 | return rule.selectors && rule.selectors.includes('.not-exists .remaining-css'); 197 | }); 198 | 199 | expect(exists).not.toBeTruthy(); 200 | }); 201 | 202 | test('There should not exist any non critical partial mq rule selectors in remaining css', () => { 203 | let exists = resultAstRules.some(rule => { 204 | if (rule.type === 'media') { 205 | return rule.rules.some(rule => rule.selectors && rule.selectors.includes('.not-exists-mq-1024 .remaining-css')); 206 | } 207 | }); 208 | 209 | expect(exists).not.toBeTruthy(); 210 | }); 211 | 212 | test('There should exist any non critical partial selectors in remaining css', () => { 213 | let exists = remainingAstRules.some(rule => rule.selectors && rule.selectors.includes('.not-exists .remaining-css')); 214 | expect(exists).toBeTruthy(); 215 | }); 216 | 217 | test('There should exist any non critical partial mq rule selectors in remaining css', () => { 218 | let exists = remainingAstRules.some(rule => { 219 | if (rule.type === 'media') { 220 | return rule.rules.some(rule => rule.selectors && rule.selectors.includes('.not-exists-mq-1024 .remaining-css')); 221 | } 222 | }); 223 | 224 | expect(exists).toBeTruthy(); 225 | }); 226 | 227 | test('Font-Face should be in critical css', () => { 228 | const exists = criticalSelectorRules.has('font-face'); 229 | expect(exists).toBeTruthy(); 230 | }); 231 | }); 232 | }); 233 | -------------------------------------------------------------------------------- /test/tests/mq.test.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import css from 'css'; 4 | import url from 'url'; 5 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 6 | const rootDir = path.join(__dirname, '..', '..'); 7 | const testResultDir = path.join(rootDir, 'test', 'results'); 8 | 9 | describe('Media Query Special Tests', () => { 10 | describe('Media Query Order', () => { 11 | const resultCSS = fs.readFileSync(path.join(testResultDir, 'test_result.css'), 'utf8'); 12 | const remainingCSS = fs.readFileSync(path.join(testResultDir, 'test_result_remaining.css'), 'utf8'); 13 | const resultAstRules = css.parse(resultCSS).stylesheet.rules; 14 | const remainingAstRules = css.parse(remainingCSS).stylesheet.rules; 15 | 16 | let mediaRulesArr = []; 17 | for (const rule of resultAstRules) { 18 | if (rule.type === 'media') { 19 | mediaRulesArr.push(rule.media); 20 | } 21 | } 22 | 23 | test('Media Queries exists', () => { 24 | const rule = mediaRulesArr[0] || null; 25 | expect(rule).not.toBeNull(); 26 | }); 27 | 28 | test('First Media Query is 800px', () => { 29 | const rule = mediaRulesArr[0] || null; 30 | expect(rule).toContain('800px'); 31 | }); 32 | 33 | test('Second Media Query is 900px', () => { 34 | const rule = mediaRulesArr[1] || null; 35 | expect(rule).toContain('900px'); 36 | }); 37 | 38 | test('Third Media Query is 1024px', () => { 39 | const rule = mediaRulesArr[2] || null; 40 | expect(rule).toContain('1024px'); 41 | }); 42 | 43 | test('Last Media Query is MaxWidth 1337px', () => { 44 | const rule = mediaRulesArr[mediaRulesArr.length - 1] || null; 45 | expect(rule).toContain('max-width: 1337px'); 46 | }); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /test/tests/mq_nocss.test.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import css from 'css'; 4 | import url from 'url'; 5 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 6 | const rootDir = path.join(__dirname, '..', '..'); 7 | const testResultDir = path.join(rootDir, 'test', 'results'); 8 | 9 | 10 | 11 | describe('Media Query Special Tests', () => { 12 | describe('Media Query Order', () => { 13 | const resultCSS = fs.readFileSync(path.join(testResultDir, 'test_result_noCss.css'), 'utf8'); 14 | const remainingCSS = fs.readFileSync(path.join(testResultDir, 'test_result_noCss_remaining.css'), 'utf8'); 15 | const resultAstRules = css.parse(resultCSS).stylesheet.rules; 16 | const remainingAstRules = css.parse(remainingCSS).stylesheet.rules; 17 | 18 | let mediaRulesArr = []; 19 | for (const rule of resultAstRules) { 20 | if (rule.type === 'media') { 21 | mediaRulesArr.push(rule.media); 22 | } 23 | } 24 | 25 | test('Media Queries exists', () => { 26 | const rule = mediaRulesArr[0] || null; 27 | expect(rule).not.toBeNull(); 28 | }); 29 | 30 | test('First Media Query is 800px', () => { 31 | const rule = mediaRulesArr[0] || null; 32 | expect(rule).toContain('800px'); 33 | }); 34 | 35 | test('Second Media Query is 900px', () => { 36 | const rule = mediaRulesArr[1] || null; 37 | expect(rule).toContain('900px'); 38 | }); 39 | 40 | test('Third Media Query is 1024px', () => { 41 | const rule = mediaRulesArr[2] || null; 42 | expect(rule).toContain('1024px'); 43 | }); 44 | 45 | test('Last Media Query is MaxWidth 1337px', () => { 46 | const rule = mediaRulesArr[mediaRulesArr.length - 1] || null; 47 | expect(rule).toContain('max-width: 1337px'); 48 | }); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /test/tests/screenshot.test.js: -------------------------------------------------------------------------------- 1 | import crypto from 'crypto'; 2 | import fs from 'fs-extra'; 3 | import path from 'path'; 4 | import url from 'url'; 5 | 6 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 7 | const rootDir = path.join(__dirname, '..', '..'); 8 | const testResultDir = path.join(rootDir, 'test', 'results'); 9 | 10 | const urls = [ 11 | 'http://localhost:8000/test/data/test.html?1', 12 | 'http://localhost:8000/test/data/test.html?2', 13 | 'http://localhost:8000/test/data/test.html?3', 14 | 'http://localhost:8000/test/data/test.html?4', 15 | ]; 16 | 17 | describe('Screenshots', () => { 18 | describe('Check screenshot names', () => { 19 | test('Check that the normal screenshots were generated with the name based on the URL', async () => { 20 | const files = await fs.readdir(path.join(testResultDir, 'screenshots', 'normal')); 21 | expect( 22 | urls.every(url => { 23 | const expectedScreenName = url.replace(/[^\w\s]/gi, '_') + '.png'; 24 | return files.includes(expectedScreenName); 25 | }), 26 | ).toBeTruthy(); 27 | }); 28 | 29 | test('Check that the screenshots with a name generator function were generated with the name as the URL SHA1 hashed', async () => { 30 | const files = await fs.readdir(path.join(testResultDir, 'screenshots', 'withFunction')); 31 | expect( 32 | urls.every(url => { 33 | const sha1 = crypto.createHash('sha1'); 34 | sha1.update(url); 35 | const expectedScreenName = `${sha1.digest('hex')}.png`; 36 | return files.includes(expectedScreenName); 37 | }), 38 | ).toBeTruthy(); 39 | }); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /test/tests/vendor_prefix.test.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import css from 'css'; 4 | import url from 'url'; 5 | 6 | const __dirname = url.fileURLToPath(new URL('.', import.meta.url)); 7 | const rootDir = path.join(__dirname, '..', '..'); 8 | const testResultDir = path.join(rootDir, 'test', 'results'); 9 | 10 | describe('Vendor Prefix Test', () => { 11 | describe('Check Vendor Prefix Exists', () => { 12 | const resultCSS = fs.readFileSync(path.join(testResultDir, 'test_result.css'), 'utf8'); 13 | 14 | const resultAstRules = css.parse(resultCSS).stylesheet.rules; 15 | 16 | test('Vendor prefixes still exists', () => { 17 | const vendorPrefixRule = resultAstRules.find(rule => rule.type === 'rule' && rule.selectors.includes('.vendor_prefix')); 18 | const vendorPrefixExists = 19 | vendorPrefixRule.declarations.some(declaration => declaration.property.startsWith('-webkit-')) === true && 20 | vendorPrefixRule.declarations.some(declaration => declaration.property.startsWith('-moz-')) === true; 21 | 22 | expect(vendorPrefixExists).toBeTruthy(); 23 | }); 24 | }); 25 | }); 26 | --------------------------------------------------------------------------------