Debian Codegraph @

lib/JavaScript/Minifier.pm

raw symbols SCIP
1 package JavaScript::Minifier;
2
3 use strict;
4 use warnings;
5
6 our $VERSION = '1.17'; # VERSION
7
8 require Exporter;
9 our @ISA = qw(Exporter);
10 our @EXPORT = qw(minify);
11
12 # string 'return' as array to handle special case of returning a regexp from a function
13 my @return = qw(r e t u r n);
14
15 #return true if the character is allowed in identifier.
16 sub isAlphanum {
17 return ($_[0] =~ /[\w\$\\]/ || ord($_[0]) > 126);
18 }
19
20 sub isEndspace {
21 return ($_[0] eq "\n" || $_[0] eq "\r" || $_[0] eq "\f");
22 }
23
24 sub isWhitespace {
25 return ($_[0] eq ' ' || $_[0] eq "\t" || $_[0] eq "\n"
26 || $_[0] eq "\r" || $_[0] eq "\f");
27 }
28
29 # New line characters before or after these characters can be removed.
30 # Not + - / in this list because they require special care.
31 sub isInfix {
32 $_[0] =~ /[,;:=&%*<>\?\|\n]/;
33 }
34
35 # New line characters after these characters can be removed.
36 sub isPrefix {
37 return ($_[0] =~ /[\{\(\[!]/ || isInfix($_[0]));
38 }
39
40 # New line characters before these characters can removed.
41 sub isPostfix {
42 return ($_[0] =~ /[\}\)\]]/ || isInfix($_[0]));
43 }
44
45 # -----------------------------------------------------------------------------
46
47 sub _get {
48 my $s = shift;
49
50 if ($s->{inputType} eq 'file') {
51 my $char = getc($s->{input});
52 $s->{last_read_char} = $char
53 if defined $char;
54
55 return $char;
56 }
57 elsif ($s->{inputType} eq 'string') {
58 if ($s->{'inputPos'} < length($s->{input})) {
59 return $s->{last_read_char}
60 = substr($s->{input}, $s->{inputPos}++, 1);
61 }
62 else { # Simulate getc() when off the end of the input string.
63 return undef;
64 }
65 }
66 else {
67 die "no input";
68 }
69 }
70
71 sub _put {
72 my $s = shift;
73 my $x = shift;
74 my $outfile = ($s->{outfile});
75 if (defined($s->{outfile})) {
76 print $outfile $x;
77 }
78 else {
79 $s->{output} .= $x;
80 }
81 }
82
83 # -----------------------------------------------------------------------------
84
85 # print a
86 # move b to a
87 # move c to b
88 # move d to c
89 # new d
90 #
91 # i.e. print a and advance
92 sub action1 {
93 my $s = shift;
94 if (!isWhitespace($s->{a})) {
95 $s->{lastnws} = $s->{a};
96 }
97 $s->{last} = $s->{a};
98 action2($s);
99 }
100
101 # sneeky output $s->{a} for comments
102 sub action2 {
103 my $s = shift;
104 _put($s, $s->{a});
105 action3($s);
106 }
107
108 # move b to a
109 # move c to b
110 # move d to c
111 # new d
112 #
113 # i.e. delete a
114 sub action3 {
115 my $s = shift;
116 $s->{a} = $s->{b};
117 action4($s);
118 }
119
120 # move c to b
121 # move d to c
122 # new d
123 #
124 # i.e. delete b
125 sub action4 {
126 my $s = shift;
127 $s->{b} = $s->{c};
128 $s->{c} = $s->{d};
129 $s->{d} = _get($s);
130 }
131
132 # -----------------------------------------------------------------------------
133
134 # put string and regexp literals
135 # when this sub is called, $s->{a} is on the opening delimiter character
136 sub putLiteral {
137 my $s = shift;
138 my $delimiter = $s->{a}; # ', " or /
139 action1($s);
140 do {
141 while (defined($s->{a}) && $s->{a} eq '\\') { # escape character only escapes only the next one character
142 action1($s);
143 action1($s);
144 }
145 if ($s->{regexp_flag} && $s->{a} eq '[') { # note character class inside regexp, in character class inside regexp there could be unescaped delimiter
146 $s->{charclass_flag} = 1;
147 }
148 elsif ($s->{regexp_flag} && $s->{a} eq ']') {
149 $s->{charclass_flag} = 0;
150 }
151 action1($s);
152 } until ($s->{last} eq $delimiter && !($s->{regexp_flag} && $s->{charclass_flag}) || !defined($s->{a}));
153 if ($s->{last} ne $delimiter) { # ran off end of file before printing the closing delimiter
154 die 'unterminated ' . ($delimiter eq '\'' ? 'single quoted string' : $delimiter eq '"' ? 'double quoted string' : 'regular expression') . ' literal, stopped';
155 }
156 }
157
158 # -----------------------------------------------------------------------------
159
160 # If $s->{a} is a whitespace then collapse all following whitespace.
161 # If any of the whitespace is a new line then ensure $s->{a} is a new line
162 # when this function ends.
163 sub collapseWhitespace {
164 my $s = shift;
165 while (defined($s->{a}) && isWhitespace($s->{a}) &&
166 defined($s->{b}) && isWhitespace($s->{b})) {
167 if (isEndspace($s->{a}) || isEndspace($s->{b})) {
168 $s->{a} = "\n";
169 }
170 action4($s); # delete b
171 }
172 }
173
174 # Advance $s->{a} to non-whitespace or end of file.
175 # Doesn't print any of this whitespace.
176 sub skipWhitespace {
177 my $s = shift;
178 while (defined($s->{a}) && isWhitespace($s->{a})) {
179 action3($s);
180 }
181 }
182
183 # Advance $s->{a} to non-whitespace or end of file
184 # If any of the whitespace is a new line then print one new line.
185 sub preserveEndspace {
186 my $s = shift;
187 collapseWhitespace($s);
188 if (defined($s->{a}) && isEndspace($s->{a}) && defined($s->{b}) && !isPostfix($s->{b}) ) {
189 action1($s);
190 }
191 skipWhitespace($s);
192 }
193
194 sub onWhitespaceConditionalComment {
195 my $s = shift;
196 return (defined($s->{a}) && isWhitespace($s->{a}) &&
197 defined($s->{b}) && $s->{b} eq '/' &&
198 defined($s->{c}) && ($s->{c} eq '/' || $s->{c} eq '*') &&
199 defined($s->{d}) && $s->{d} eq '@');
200 }
201
202 # -----------------------------------------------------------------------------
203
204 sub minify {
205 my %h = @_;
206 # Immediately turn hash into a hash reference so that notation is the same in this function
207 # as others. Easier refactoring.
208 my $s = \%h; # hash reference for "state". This module is functional programming and the state is passed between functions.
209
210 # determine if the the input is a string or a file handle.
211 my $ref = \$s->{input};
212 if (defined($ref) && ref($ref) eq 'SCALAR'){
213 $s->{inputPos} = 0;
214 $s->{inputType} = 'string';
215 }
216 else {
217 $s->{inputType} = 'file';
218 }
219
220 # Determine if the output is to a string or a file.
221 if (!defined($s->{outfile})) {
222 $s->{output} = '';
223 }
224
225 # Print the copyright notice first
226 if ($s->{copyright}) {
227 _put($s, '/* ' . $s->{copyright} . ' */');
228 }
229
230 # Initialize the buffer.
231 do {
232 $s->{a} = _get($s);
233 } while (defined($s->{a}) && isWhitespace($s->{a}));
234 $s->{b} = _get($s);
235 $s->{c} = _get($s);
236 $s->{d} = _get($s);
237 $s->{regexp_flag} = 0;
238 $s->{charclass_flag} = 0;
239 $s->{return_flag} = 0;
240 $s->{return_string} = '';
241 $s->{last} = undef; # assign for safety
242 $s->{lastnws} = undef; # assign for safety
243
244 # local variables
245 my $ccFlag; # marks if a comment is an Internet Explorer conditional comment and should be printed to output
246
247 while (defined($s->{a})) { # on this line $s->{a} should always be a non-whitespace character or undef (i.e. end of file)
248
249 if (isWhitespace($s->{a})) { # check that this program is running correctly
250 die 'minifier bug: minify while loop starting with whitespace, stopped';
251 }
252
253 # track 'return' operator
254 if ($s->{a} ne '/') {
255 $s->{return_flag} = defined($return[length($s->{return_string})]) && $s->{a} eq $return[length($s->{return_string})];
256 $s->{return_string} = $s->{return_flag} ? $s->{return_string} . $s->{a} : '';
257 }
258
259 # Each branch handles trailing whitespace and ensures $s->{a} is on non-whitespace or undef when branch finishes
260 if ($s->{a} eq '/') { # a division, comment, or regexp literal
261 if (defined($s->{b}) && $s->{b} eq '/') { # slash-slash comment
262 $ccFlag = defined($s->{c}) && $s->{c} eq '@'; # tests in IE7 show no space allowed between slashes and at symbol
263 do {
264 $ccFlag ? action2($s) : action3($s);
265 } until (!defined($s->{a}) || isEndspace($s->{a}));
266 if (defined($s->{a})) { # $s->{a} is a new line
267 if ($ccFlag) {
268 action1($s); # cannot use preserveEndspace($s) here because it might not print the new line
269 skipWhitespace($s);
270 }
271 elsif (defined($s->{last}) && !isEndspace($s->{last}) && !isPrefix($s->{last})) {
272 preserveEndspace($s);
273 }
274 else {
275 skipWhitespace($s);
276 }
277 }
278 }
279 elsif (defined($s->{b}) && $s->{b} eq '*') { # slash-star comment
280 $ccFlag = defined($s->{c}) && $s->{c} eq '@'; # test in IE7 shows no space allowed between star and at symbol
281 do {
282 $ccFlag ? action2($s) : action3($s);
283 } until (!defined($s->{b}) || ($s->{a} eq '*' && $s->{b} eq '/'));
284 if (defined($s->{b})) { # $s->{a} is asterisk and $s->{b} is foreslash
285 if ($ccFlag) {
286 action2($s); # the *
287 action2($s); # the /
288 # inside the conditional comment there may be a missing terminal semi-colon
289 preserveEndspace($s);
290 }
291 else { # the comment is being removed
292 action3($s); # the *
293 $s->{a} = ' '; # the /
294 collapseWhitespace($s);
295 if (defined($s->{last}) && defined($s->{b}) &&
296 ((isAlphanum($s->{last}) && (isAlphanum($s->{b})||$s->{b} eq '.')) ||
297 ($s->{last} eq '+' && $s->{b} eq '+') || ($s->{last} eq '-' && $s->{b} eq '-'))) { # for a situation like 5-/**/-2 or a/**/a
298 # When entering this block $s->{a} is whitespace.
299 # The comment represented whitespace that cannot be removed. Therefore replace the now gone comment with a whitespace.
300 action1($s);
301 }
302 elsif (defined($s->{last}) && !isPrefix($s->{last})) {
303 preserveEndspace($s);
304 }
305 else {
306 skipWhitespace($s);
307 }
308 }
309 }
310 else {
311 die 'unterminated comment, stopped';
312 }
313 }
314 elsif ((defined($s->{lastnws}) && ($s->{lastnws} eq ')' || $s->{lastnws} eq ']' ||
315 $s->{lastnws} eq '.' || isAlphanum($s->{lastnws}))) && (!$s->{return_flag} || length($s->{return_string}) != scalar(@return))) { # division
316
317 action1($s);
318 collapseWhitespace($s);
319 # don't want a division to become a slash-slash comment with following conditional comment
320 onWhitespaceConditionalComment($s) ? action1($s) : preserveEndspace($s);
321 }
322 else { # regexp literal
323 $s->{regexp_flag} = 1;
324 putLiteral($s);
325 collapseWhitespace($s);
326 # don't want closing delimiter to become a slash-slash comment with following conditional comment
327 onWhitespaceConditionalComment($s) ? action1($s) : preserveEndspace($s);
328 }
329 }
330 elsif ($s->{a} eq '\'' || $s->{a} eq '"' ) { # string literal
331 $s->{regexp_flag} = 0;
332 putLiteral($s);
333 preserveEndspace($s);
334 }
335 elsif ($s->{a} eq '+' || $s->{a} eq '-') { # careful with + + and - -
336 action1($s);
337 collapseWhitespace($s);
338 if (defined($s->{a}) && isWhitespace($s->{a})) {
339 (defined($s->{b}) && $s->{b} eq $s->{last}) ? action1($s) : preserveEndspace($s);
340 }
341 }
342 elsif (isAlphanum($s->{a})) { # keyword, identifiers, numbers
343 action1($s);
344 collapseWhitespace($s);
345 if (defined($s->{a}) && isWhitespace($s->{a})) {
346 # if $s->{b} is '.' could be (12 .toString()) which is property invocation. If space removed becomes decimal point and error.
347 (defined($s->{b}) && (isAlphanum($s->{b}) || $s->{b} eq '.')) ? action1($s) : preserveEndspace($s);
348 }
349 }
350 elsif ($s->{a} eq ']' || $s->{a} eq '}' || $s->{a} eq ')') { # no need to be followed by space but maybe needs following new line
351 action1($s);
352 preserveEndspace($s);
353 }
354 elsif ($s->{stripDebug} && $s->{a} eq ';' &&
355 defined($s->{b}) && $s->{b} eq ';' &&
356 defined($s->{c}) && $s->{c} eq ';') {
357 action3($s); # delete one of the semi-colons
358 $s->{a} = '/'; # replace the other two semi-colons
359 $s->{b} = '/'; # so the remainder of line is removed
360 }
361 else { # anything else just prints and trailing whitespace discarded
362 action1($s);
363 skipWhitespace($s);
364 }
365 }
366
367 if ( defined $s->{last_read_char} and $s->{last_read_char} =~ /\n/ ) {
368 _put($s, "\n");
369 }
370
371 if (!defined($s->{outfile})) {
372 return $s->{output};
373 }
374
375 } # minify()
376
377 1;
378 __END__
379
380 =encoding utf8
381
382 =for stopwords Crockford ECMAScript JSMin stripDebug Minifying minification minifying minified minify
383
384 =head1 NAME
385
386 JavaScript::Minifier - Perl extension for minifying JavaScript code
387
388 =head1 SYNOPSIS
389
390 To minify a JavaScript file and have the output written directly to another file
391
392 use JavaScript::Minifier qw(minify);
393
394 open(my $in, 'myScript.js') or die;
395 open(my $out, '>', 'myScript-min.js') or die;
396
397 minify(input => $in, outfile => $out);
398
399 close($in);
400 close($out);
401
402 To minify a JavaScript string literal. Note that by omitting the outfile parameter a the minified code is returned as a string.
403
404 my $minifiedJavaScript = minify(input => 'var x = 2;');
405
406 To include a copyright comment at the top of the minified code.
407
408 minify(input => 'var x = 2;', copyright => 'BSD License');
409
410 To treat ';;;' as '//' so that debugging code can be removed. This is a common JavaScript convention for minification.
411
412 minify(input => 'var x = 2;', stripDebug => 1);
413
414 The "input" parameter is mandatory. The "output", "copyright", and "stripDebug" parameters are optional and can be used in any combination.
415
416 =head1 DESCRIPTION
417
418 This module removes unnecessary whitespace from JavaScript code. The primary requirement developing this module is to not break working code: if working JavaScript is in input then working JavaScript is output. It is ok if the input has missing semi-colons, snips like '++ +' or '12 .toString()', for example. Internet Explorer conditional comments are copied to the output but the code inside these comments will not be minified.
419
420 The ECMAScript specifications allow for many different whitespace characters: space, horizontal tab, vertical tab, new line, carriage return, form feed, and paragraph separator. This module understands all of these as whitespace except for vertical tab and paragraph separator. These two types of whitespace are not minimized.
421
422 For static JavaScript files, it is recommended that you minify during the build stage of web deployment. If you minify on-the-fly then it might be a good idea to cache the minified file. Minifying static files on-the-fly repeatedly is wasteful.
423
424 =head2 EXPORT
425
426 Exported by default: C<minifiy()>
427
428 =head1 SEE ALSO
429
430 This module is inspired by Douglas Crockford's JSMin:
431 L<http://www.crockford.com/javascript/jsmin.html>
432
433 You may also be interested in the L<CSS::Minifier> module also
434 available on CPAN.
435
436 =head1 REPOSITORY
437
438 You can obtain the latest source code and submit bug reports
439 on the github repository for this module:
440 L<https://github.com/zoffixznet/JavaScript-Minifier>
441
442 =head1 MAINTAINER
443
444 Zoffix Znet C<< <[email protected]> >> L<https://metacpan.org/author/ZOFFIX>
445
446 =head1 AUTHORS
447
448 Peter Michaux, E<lt>[email protected]<gt>
449
450 Eric Herrera, E<lt>[email protected]<gt>
451
452 =head1 CONTRIBUTORS
453
454 Miller 'tmhall' Hall
455
456 Вячеслав 'vti' Тихановский
457
458 Fedor A. 'faf' Fetisov
459
460 =head1 COPYRIGHT AND LICENSE
461
462 Copyright (C) 2007 by Peter Michaux
463
464 This library is free software; you can redistribute it and/or modify
465 it under the same terms as Perl itself, either Perl version 5.8.6 or,
466 at your option, any later version of Perl 5 you may have available.
467