jsminifier.pp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. { *********************************************************************
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 2016 Michael Van Canneyt.
  4. Javascript minifier
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. { ---------------------------------------------------------------------
  12. Javascript minifier, based on an implementation by Douglas Crockford,
  13. see original copyright.
  14. ---------------------------------------------------------------------}
  15. { jsmin.c
  16. 2013-03-29
  17. Copyright (c) 2002 Douglas Crockford (www.crockford.com)
  18. Permission is hereby granted, free of charge, to any person obtaining a copy of
  19. this software and associated documentation files (the "Software"), to deal in
  20. the Software without restriction, including without limitation the rights to
  21. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  22. of the Software, and to permit persons to whom the Software is furnished to do
  23. so, subject to the following conditions:
  24. The above copyright notice and this permission notice shall be included in all
  25. copies or substantial portions of the Software.
  26. The Software shall be used for Good, not Evil.
  27. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  30. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  33. SOFTWARE.
  34. }
  35. unit jsminifier;
  36. {$mode objfpc}{$H+}
  37. {$inline on}
  38. interface
  39. uses sysutils,classes,bufstream;
  40. Const
  41. EOS = #0;
  42. Type
  43. { TJSONMinifier }
  44. EJSONMinifier = Class(Exception);
  45. TJSONMinifier = Class(TComponent)
  46. Private
  47. FA : char;
  48. FB : char;
  49. FFileHeader: TStrings;
  50. FLookahead : char;
  51. FX : char;
  52. FY : char ;
  53. Fin : TStream;
  54. Fout : TStream;
  55. procedure SetFileHeader(AValue: TStrings);
  56. Protected
  57. // Token reading routines
  58. function Peek : char;
  59. function Get : char;inline;
  60. function Next : char;
  61. // Token writing routines
  62. procedure Putc(c: char);inline;
  63. Procedure Reset;
  64. procedure DoHeader; virtual;
  65. procedure Error(Const Msg: string);
  66. Class Function isAlphaNum(c: char): boolean;
  67. Class Function iif(B : Boolean; Const ifTrue,ifFalse : integer) : integer; inline;
  68. procedure Action(d: Byte);
  69. procedure Minify;
  70. Public
  71. Constructor Create(AOwner : TComponent); override;
  72. Destructor Destroy; override;
  73. Procedure Execute(Const SourceFilename,DestFilename : String);
  74. Procedure Execute(Source,Dest : TStream);
  75. Procedure Execute(SourceFilenames : TStrings; Const DestFilename : String);
  76. Procedure Execute(SourceFileNames : Array of string; Const DestFilename : String);
  77. Published
  78. Property FileHeader : TStrings Read FFileHeader Write SetFileHeader;
  79. end;
  80. Implementation
  81. Resourcestring
  82. SErrUnterminatedComment = 'Unterminated comment.';
  83. SErrUnterminatedStringLiteral = 'Unterminated string literal.';
  84. SErrUnterminatedSetInRegexp = 'Unterminated set in Regular Expression literal.';
  85. SerrUnterminatedRegexp = 'Unterminated Regular Expression literal.';
  86. class function TJSONMinifier.iif(B: Boolean; const ifTrue, ifFalse: integer
  87. ): integer;
  88. begin
  89. if B then
  90. Result:=ifTrue
  91. else
  92. Result:=ifFalse;
  93. end;
  94. procedure TJSONMinifier.Error(const Msg: string);
  95. begin
  96. Raise EJSONMinifier.Create('JSMIN Error: '+Msg);
  97. end;
  98. procedure TJSONMinifier.SetFileHeader(AValue: TStrings);
  99. begin
  100. if FFileHeader=AValue then Exit;
  101. FFileHeader.Assign(AValue);
  102. end;
  103. procedure TJSONMinifier.Reset;
  104. begin
  105. FA:=EOS;
  106. FB:=EOS;
  107. FLookahead:=EOS;
  108. FX:=EOS;
  109. FY:=EOS;
  110. end;
  111. class function TJSONMinifier.isAlphaNum(c: char): boolean;
  112. begin
  113. Result:= (C in ['a'..'z']) or (c in ['0'..'9']) or (c in ['A'..'Z']) or (C in ['_','$','\']) or (c > #126);
  114. end;
  115. function TJSONMinifier.Get: char;
  116. begin
  117. Result:=FLookahead;
  118. FLookahead:=EOS;
  119. if (Result=EOS) then
  120. if Fin.Read(Result,sizeof(Result))=0 then exit;
  121. if (Result>' ') or (Result in [#10,EOS]) then
  122. Exit;
  123. if (Result=#13) then
  124. Result:=#10
  125. else
  126. Result:=' ';
  127. end;
  128. function TJSONMinifier.Peek: char;
  129. begin
  130. FLookahead := get();
  131. result:=FLookahead;
  132. end;
  133. function TJSONMinifier.Next: char;
  134. var
  135. c : char;
  136. begin
  137. c:= get();
  138. if (c='/') then
  139. case peek of
  140. '/': Repeat
  141. c := get();
  142. until (c <= #10);
  143. '*':
  144. begin
  145. Get();
  146. while (c <> ' ') do
  147. case get of
  148. '*':
  149. begin
  150. if (peek()= '/') then
  151. begin
  152. get();
  153. c:=' ';
  154. end;
  155. end;
  156. EOS:
  157. Error(SErrUnterminatedComment);
  158. end;
  159. end;
  160. end;
  161. FY:=FX;
  162. FX:=c;
  163. Result:=c;
  164. end;
  165. procedure TJSONMinifier.Putc(c: char);
  166. begin
  167. Fout.writebuffer(c,sizeof(c));
  168. end;
  169. procedure TJSONMinifier.Action(d : Byte);
  170. Procedure Do1;
  171. begin
  172. putc(FA);
  173. if ((FY in [#10,' '])
  174. and (FA in ['+','-','*','/'])
  175. and (FB in ['+','-','*','/'])) then
  176. putc(FY);
  177. end;
  178. Procedure Do2;
  179. begin
  180. FA:=FB;
  181. if (FA in ['''','"','`']) then
  182. While true do
  183. begin
  184. putc(FA);
  185. FA:= get();
  186. if (FA=FB) then
  187. break;
  188. if (FA='\') then
  189. begin
  190. putc(FA);
  191. FA:=get();
  192. end;
  193. if (FA=EOS) then
  194. Error(SErrUnterminatedStringLiteral);
  195. end;
  196. end;
  197. begin
  198. if (D=1) then
  199. Do1;
  200. if (D in [1,2]) then
  201. Do2;
  202. FB := next();
  203. if (FB='/') and (FA in ['(',',','=',':','[','!','&','|','?','+','-','~','*','/','{',#10]) then
  204. begin
  205. putc(FA);
  206. if (FA in ['/','*']) then
  207. putc(' ');
  208. putc(FB);
  209. While true do
  210. begin
  211. FA := get();
  212. if (FA='[') then
  213. begin
  214. While true do
  215. begin
  216. putc(FA);
  217. FA := get();
  218. if (FA = ']') then
  219. break;
  220. if (FA = '\') then
  221. begin
  222. putc(FA);
  223. FA := get();
  224. end;
  225. if (FA = EOS) then
  226. Error(SErrUnterminatedSetInRegexp);
  227. end
  228. end
  229. else if (FA = '/') then
  230. begin
  231. case (peek()) of
  232. '/', '*':
  233. Error(SErrUnterminatedSetInRegexp);
  234. end;
  235. Break;
  236. end
  237. else if (FA ='\') then
  238. begin
  239. putc(FA);
  240. FA := get();
  241. end;
  242. if (FA = EOS) then
  243. Error(SErrUnterminatedRegexp);
  244. putc(FA);
  245. end;
  246. FB := next();
  247. end;
  248. end;
  249. procedure TJSONMinifier.Minify;
  250. begin
  251. if (peek()= #$EF) then
  252. begin
  253. get();
  254. get();
  255. get();
  256. end;
  257. FA:=#10;
  258. action(3);
  259. while (FA <> EOS) do
  260. begin
  261. case (FA) of
  262. ' ':
  263. action(iif(isAlphanum(FB),1,2));
  264. #10:
  265. case (FB) of
  266. '{', '[', '(', '+', '-', '!', '~':
  267. Action(1);
  268. ' ':
  269. Action(3);
  270. else
  271. Action(iif(isAlphanum(FB), 1 , 2));
  272. end;
  273. else
  274. case (FB) of
  275. ' ':
  276. Action(iif(isAlphanum(FA),1,3));
  277. #10:
  278. case (FA) of
  279. '}',']',')','+','-','"', '''', '`':
  280. Action(1);
  281. else
  282. Action(iif(isAlphanum(FA), 1, 3));
  283. end;
  284. else
  285. Action(1);
  286. end;
  287. end;
  288. end;
  289. end;
  290. constructor TJSONMinifier.Create(AOwner: TComponent);
  291. begin
  292. inherited Create(AOwner);
  293. FFileHeader:=TStringList.Create;
  294. end;
  295. destructor TJSONMinifier.Destroy;
  296. begin
  297. FreeAndNil(FFileHeader);
  298. inherited Destroy;
  299. end;
  300. procedure TJSONMinifier.Execute(const SourceFilename, DestFilename: String);
  301. Var
  302. Src,Dest : TBufStream;
  303. begin
  304. Dest:=Nil;
  305. Src:=TReadBufStream.Create(TFileStream.Create(SourceFileName,fmOpenRead or fmShareDenyWrite),1000);
  306. try
  307. Src.SourceOwner:=True;
  308. Dest:=TWriteBufStream.Create(TFileStream.create(DestFileName,fmCreate),1000);
  309. Dest.SourceOwner:=True;
  310. Execute(Src,Dest);
  311. finally
  312. Src.Free;
  313. Dest.Free;
  314. end;
  315. end;
  316. procedure TJSONMinifier.DoHeader;
  317. Var
  318. S,L : String;
  319. begin
  320. For S in FFileHeader do
  321. begin
  322. L:='// '+S+sLineBreak;
  323. Fout.WriteBuffer(L[1],Length(L));
  324. end;
  325. end;
  326. procedure TJSONMinifier.Execute(Source, Dest: TStream);
  327. begin
  328. Fin:=Source;
  329. Fout:=Dest;
  330. try
  331. Reset;
  332. DoHeader;
  333. Minify;
  334. finally
  335. Fin:=Nil;
  336. Fout:=Nil;
  337. end;
  338. end;
  339. procedure TJSONMinifier.Execute(SourceFilenames: TStrings;const DestFilename: String);
  340. Var
  341. Src,Dest : TBufStream;
  342. I : Integer;
  343. begin
  344. Dest:=Src;
  345. Dest:=TWriteBufStream.Create(TFileStream.create(DestFileName,fmCreate),1000);
  346. try
  347. Dest.SourceOwner:=True;
  348. for I:=0 to SourceFileNames.Count-1 do
  349. begin
  350. Src:=TReadBufStream.Create(TFileStream.Create(SourceFileNames[i],fmOpenRead or fmShareDenyWrite),1000);
  351. Src.SourceOwner:=True;
  352. Execute(Src,Dest);
  353. FreeAndNil(Src);
  354. end;
  355. finally
  356. FreeAndNil(Src);
  357. FreeAndNil(Dest);
  358. end;
  359. end;
  360. procedure TJSONMinifier.Execute(SourceFileNames: array of string;
  361. const DestFilename: String);
  362. Var
  363. S : TStrings;
  364. begin
  365. S:=TStringList.Create;
  366. try
  367. S.AddStrings(SourceFileNames);
  368. Execute(S,DestFileName);
  369. finally
  370. S.Free;
  371. end;
  372. end;
  373. end.