├── .gitignore ├── .jshintrc ├── .travis.yml ├── LICENSE ├── README.md ├── docs └── API.md ├── example ├── README.md ├── css │ ├── a.css │ ├── b.css │ └── c.css ├── index.ejs ├── js │ ├── a.js │ ├── b.js │ └── c.js ├── prod │ ├── min.css │ └── min.js └── run.js ├── index.js ├── lib ├── compat.js └── connect-cachify.js ├── package.json └── test ├── compat-test.js ├── connect-cachify-test.js ├── express-test.js └── test-data └── test-file.js /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | #* 3 | node_modules -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "passfail": false, 3 | "maxerr": 100, 4 | "node": true, 5 | "forin": false, 6 | "boss": true, 7 | "noarg": true, 8 | "undef": true, 9 | "unused": true, 10 | "browser": true, 11 | "laxbreak": true, 12 | "laxcomma": true, 13 | "eqeqeq": true, 14 | "eqnull": true, 15 | "expr": true, 16 | "indent": 2, 17 | "predef": [ 18 | "exports", 19 | "require", 20 | "process" 21 | ], 22 | "es5": true, 23 | "esnext": true, 24 | "shadow": false, 25 | "supernew": false, 26 | "strict": false 27 | } 28 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 0.8 4 | - 0.10 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![build status](https://secure.travis-ci.org/mozilla/connect-cachify.png)](http://travis-ci.org/mozilla/connect-cachify) 2 | # Cachify # 3 | ``connect-cachify`` makes having proper browser cache and HTTP caching 4 | behavior for assets easier. 5 | 6 | It is a set of middleware and view helper functions for the Node.js express framework. 7 | 8 | This does not provide in-memory caching, middleware caching, or many other 9 | types of caching. Cachify is focused on reducing the number of HTTP requests 10 | to your web nodes. 11 | 12 | ## Installation ## 13 | 14 | npm install connect-cachify 15 | 16 | ## How to Use ## 17 | Instructions below are for Express 2, but Express 3 is also supported. 18 | 19 | var app, 20 | express = require('express'), 21 | cachify = require('connect-cachify'), 22 | 23 | app = express.createServer(); 24 | 25 | ## Middleware ## 26 | var assets = { 27 | "/js/main.min.js": [ 28 | '/js/lib/jquery.js', 29 | '/js/magick.js', 30 | '/js/laughter.js' 31 | ], 32 | "/css/home.min.css": [ 33 | '/css/reset.css', 34 | '/css/home.css' 35 | ], 36 | "/css/dashboard.min.css": [ 37 | '/css/reset.css', 38 | '/css/common.css', 39 | '/css/dashboard.css' 40 | ] 41 | }; 42 | 43 | var url_to_paths = { 44 | '/js/jquery.js': '/home/development/jquery/jquery.js', 45 | '/css/reset.css': '/home/development/css-reset/reset.css' 46 | }; 47 | 48 | app.use(cachify.setup(assets, { 49 | root: __dirname, 50 | url_to_paths: url_to_paths, 51 | production: your_config['use_minified_assets'] 52 | })); 53 | 54 | ``setup`` takes two parameters: assets and options. Assets is an associative 55 | array where the keys are your production urls, and the value is a list of 56 | development urls that produce the same asset. 57 | 58 | We'll discussion options in a section below. 59 | 60 | Cachify middleware is now enabled. Let's look at this after hooking up the view 61 | helpers. 62 | 63 | Note: You **must** put ``cachify.setup`` before static or other connect 64 | middleware which works with these same requests. 65 | 66 | ## In an EJS template 67 | 68 | ... 69 | 70 | Dashboard: Hamsters of North America 71 | <%- cachify_css('/css/dashboard.min.css') %> 72 | 73 | 74 | ... 75 | <%- cachify_js('/js/main.min.js') %> 76 | 77 | ... 78 | 79 | ## In a Jade template 80 | 81 | ... 82 | title= Dashboard: Hamsters of North America 83 | meta(charset='utf-8') 84 | | !{cachify_css('/css/dashboard.min.css')} 85 | ... 86 | body 87 | ... 88 | | !{cachify_js('/js/main.min.js')} 89 | block scripts 90 | 91 | In production mode, a call to ``cachify_js`` will produce a single script tag 92 | like: 93 | 94 | 95 | 96 | When production was set to false, ``cachify_js`` will produce: 97 | 98 | 99 | 100 | 101 | 102 | The middleware makes caching transparent. A request for 103 | ``/fa6d51a13a245a90aeb48eeca0e52396/js/main.min.js`` will have the req.url 104 | rewritten to ``/js/main.min.js``, so that other middleware will work properly. 105 | 106 | The middleware sets the cache expiration headers to the Mayan Apocalypse, and 107 | does it's best to ensure browsers won't request that version of 108 | ``/js/main.min.js`` again. 109 | 110 | A goal is for this module to work well with other connect compilers, such as 111 | [LESS](http://lesscss.org/) or 112 | [connect-assets](https://github.com/TrevorBurnham/connect-assets). 113 | 114 | ## Options ## 115 | The following are optional config for ``cachify.setup`` 116 | 117 | * root - Path where static assets are stored on disk. Same value as you'd pass 118 | to the ``static`` middleware. 119 | 120 | * url_to_paths - an associative array of URLs to absolute filename paths. 121 | Useful to specify paths to files that are not in the ``root`` directory. 122 | 123 | * production - Boolean indicating if your in development or production mode. 124 | Effects how links for js and css files are generated. 125 | 126 | * debug - Boolean indicating we should always re-write urls with a hash. 127 | 128 | For full details, see the [API documentation](docs/API.md). 129 | 130 | ## Magick ## 131 | So how does cachify work? 132 | 133 | When you cachify a url, it adds an MD5 hash of the file's contents into the URL 134 | it generates: 135 | 136 | http://example.com/cbcb1e865e61c08a68a4e0bfa293e806/stylo.css 137 | 138 | Incoming requests are checked for this MD5 hash. If present and if we' know 139 | about the resource (either via options or the file exists on disk), then the 140 | request path is rewritten back to ``/stylo.css``, so that another route can 141 | process the request. 142 | 143 | These requests are served up with expires headers that are very long lived, so a user's browser will only request them once. 144 | 145 | Cachify **doesn't** attempt to **find an older version** of your resource, 146 | if the MD5 has was for an older file. 147 | 148 | ## Status ## 149 | 150 | This module is brand spanking new. Please file 151 | [issues](https://github.com/mozilla/connect-cachify/issues) with ideas, bugs, 152 | etc. 153 | 154 | It was created as part of the [BrowserID](https://github.com/mozilla/browserid) 155 | project. 156 | 157 | ## Debugging ## 158 | To debug cachify's hashed url behavior, pass in the following parameter in 159 | your options block: 160 | 161 | setup({ debug: true, ...}); 162 | 163 | Now even in development mode, cache busting URLs will be generated, so you 164 | can troubleshoot any problems cachify magick is causing you. 165 | 166 | ## Development ## 167 | 168 | Patches are welcome! To run unit tests... 169 | 170 | nodeunit test 171 | 172 | ## Wordpress Cachify ## 173 | Does this all sound like gobbledygook? Maybe you're looking for [Wordpress cachify plugin](http://wordpress.org/extend/plugins/cachify/) instead of ``connect-cachify``. 174 | -------------------------------------------------------------------------------- /docs/API.md: -------------------------------------------------------------------------------- 1 | # connect-cachify API # 2 | 3 | The [README](../README.md) for this project has a good tutorial on using 4 | ``connect-cachify``. This documents the API and goes deep on all the options. 5 | 6 | ## setup(assets, [options]) ## 7 | 8 | Creates the cachify middleware and allows you to customizes how you'll use 9 | it in your Node.js app. 10 | 11 | ``assets`` is a dictionary where the keys are your production urls, 12 | and the value is a list of development urls that produce the same asset. 13 | See the example below for format. 14 | 15 | ``options`` is an optional dictionary with the following optional values: 16 | 17 | * ``debug`` - Boolean indicating we should always re-write urls with a hash. (**Default: false**) 18 | * ``prefix`` - String to prepend to the hash in links. (**Default: none**) 19 | * ``production`` - Boolean indicating if your in development or production mode. 20 | Effects how links for js and css files are generated. (**Defaults to ``true``**) 21 | * ``root`` - A fully qualified path which is a root where static 22 | resources are served up. This is the same value you'd send to the 23 | static middleware. (**Default: ``'.'``**) 24 | * ``url_to_paths`` - an associative array of URLs to absolute filename paths. 25 | Useful to specify paths to files that are not in the ``root`` directory. 26 | (**Default: ``{}``**) 27 | 28 | ### Example use of ``setup`` ### 29 | 30 | var assets = { 31 | '/js/main.min.js': ['/js/jquery.js', '/js/widget.js', '/js/main.js'], 32 | '/js/dashboard.js': ['/js/jquery.js', '/js/dashboard.js'], 33 | '/css/main.min.css': ['/css/reset.css', '/main.css'] }; 34 | app.use(cachify.setup(assets, { root: __dirname })); 35 | 36 | ### Using url_to_paths and root in ``setup`` ### 37 | 38 | ``url_to_paths`` is an associative array that specifies the absolute path of an asset. This is useful for files that are not located under the root directory. In the following example, both jquery.js and reset.css are located outside of the root directory and would not normally be found by connect-cachify. 39 | 40 | var assets = { 41 | '/js/main.min.js': ['/js/jquery.js', '/js/widget.js', '/js/main.js'], 42 | '/js/dashboard.js': ['/js/jquery.js', '/js/dashboard.js'], 43 | '/css/main.min.css': ['/css/reset.css', '/main.css'] }; 44 | 45 | // specify paths outside of the root directory to find files. 46 | var url_to_paths = { 47 | '/js/jquery.js': '/home/development/jquery/jquery.js', 48 | '/css/reset.css': '/home/development/css-reset/reset.css' 49 | }; 50 | 51 | app.use(cachify.setup(assets, { 52 | root: __dirname, 53 | url_to_paths: url_to_paths 54 | })); 55 | 56 | Both ``root`` and ``url_to_paths`` are optional, though it is safe to use them together. 57 | 58 | ## Middleware Helper Functions ## 59 | 60 | The ``setup`` middleware will expose several **helpers** to your views: 61 | 62 | * cachify_js 63 | * cachify_css 64 | * cachify 65 | 66 | Using the optional ``prefix`` will slightly improve middleware performance 67 | when attempting to detect if a request is safe to re-write it's request url. 68 | 69 | ## cachify_js(production_js_url, [options]) ## 70 | Helper function for generating ``script`` tags for your Javascript files. 71 | 72 | ``production_js_url`` is a url to your minified, production ready Javascript. 73 | 74 | ``options`` is an optional dictionary with the following optional value: 75 | 76 | * ``hash`` - MD5 hash to use instead of calculating from disk (**Default: none**) 77 | * ``defer`` - if true, adds the defer attribute to scripts in production mode. (**Default: false**) 78 | * ``async`` - if true, adds the async attribute to scripts in production mode. (**Default: false**) 79 | 80 | In production mode, a single script tag is generated, with a cache-busting 81 | url. In development mode (``production: false``), Multiple script tags are 82 | generated, one per dependent file from the ``assets`` argument to the ``setup`` function. 83 | 84 | ### Example EJS template: ### 85 | 86 |

87 | <%- cachify_js('/js/main.min.js') %> 88 | 89 | 90 | 91 | ## cachify_css(production_css_url, [options]) ## 92 | Helper function for generating ``link`` tags for your CSS files. 93 | 94 | ``production_css_url`` is a url to your minified, production ready CSS. 95 | 96 | ``options`` is an optional dictionary with the following optional value: 97 | 98 | * ``hash`` - MD5 hash to use instead of calculating from disk (**Default: none**) 99 | 100 | In production mode, a single link tag is generated, with a cache-busting 101 | url. In development mode (``production: false``), Multiple link tags are 102 | generated, one per dependent file from the ``assets`` argument to the ``setup`` function. 103 | 104 | ### Example EJS template: ### 105 | 106 |

107 | <%- cachify_css('/css/main.min.css') %> 108 | 109 | 110 | 111 | ## cachify(production_url, [options]) ## 112 | Lower level Helper function for generating HTML tags for your urls. 113 | 114 | ``production_url`` is a url to your minified, production asset. 115 | 116 | ``options`` is an optional dictionary with the following optional values: 117 | 118 | * ``hash`` - MD5 hash to use instead of calculating from disk (**Default: none**) 119 | * ``tag_format`` - String with one '%s' placeholder, which will be replaced each time with your production_url or development urls. 120 | 121 | In production mode, a single HTML tag is generated, with a cache-busting 122 | url. In development mode (``production: false``), Multiple tags are 123 | generated, one per dependent file from the ``assets`` argument to the ``setup`` function. 124 | 125 | ### Example EJS template: ### 126 | 127 |

128 | <%- cachify('/js/login.min.js', { 129 | tag_format: ''}) %> 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | A simple application that demonstrates cachify. 4 | 5 | * `run.js` - the express app that runs the show 6 | * `prod/` - where "production" minified resources are kept 7 | * `js/` or `css/` - where "development" sources are kept 8 | * `index.ejs` - a page that uses all the resources 9 | 10 | ## Running it 11 | 12 | $ ./run.js 13 | 14 | now look at `http://127.0.0.1:3000` in your browser, notice 15 | only one resource for css and one for js is served with a 16 | url containing a has based on file contents. Have a look at 17 | the HTTP headers too. 18 | 19 | $ DEV=true ./run.js 20 | 21 | now look at `http://127.0.0.1:3000` in your browser, notice 22 | the development resources are individually served. 23 | -------------------------------------------------------------------------------- /example/css/a.css: -------------------------------------------------------------------------------- 1 | /* a.css */ -------------------------------------------------------------------------------- /example/css/b.css: -------------------------------------------------------------------------------- 1 | /* b.css */ -------------------------------------------------------------------------------- /example/css/c.css: -------------------------------------------------------------------------------- 1 | /* c.css */ -------------------------------------------------------------------------------- /example/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | i love cachify 5 | <%- cachify_css('/prod/min.css') %> 6 | 7 | 8 | This is a page that uses cachify 9 | 10 | <%- cachify_js('/prod/min.js') %> 11 | 12 | -------------------------------------------------------------------------------- /example/js/a.js: -------------------------------------------------------------------------------- 1 | console.log("a.js"); 2 | -------------------------------------------------------------------------------- /example/js/b.js: -------------------------------------------------------------------------------- 1 | console.log("b.js"); 2 | -------------------------------------------------------------------------------- /example/js/c.js: -------------------------------------------------------------------------------- 1 | console.log("c.js"); 2 | -------------------------------------------------------------------------------- /example/prod/min.css: -------------------------------------------------------------------------------- 1 | /* a.css *//* b.css *//* c.css */ -------------------------------------------------------------------------------- /example/prod/min.js: -------------------------------------------------------------------------------- 1 | console.log("a.js"); 2 | console.log("b.js"); 3 | console.log("c.js"); 4 | -------------------------------------------------------------------------------- /example/run.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | var express = require('express'), 4 | cachify = require('../'); 5 | 6 | var app = express.createServer(); 7 | 8 | app.use(cachify.setup({ 9 | '/prod/min.css': [ 10 | "/css/a.css", 11 | "/css/b.css", 12 | "/css/c.css" 13 | ], 14 | '/prod/min.js': [ 15 | "/js/a.js", 16 | "/js/b.js", 17 | "/js/c.js" 18 | ] 19 | }, { 20 | root: __dirname, 21 | production: !process.env['DEV'] 22 | })); 23 | 24 | app.set('views', __dirname); 25 | app.set('view options', { layout: false }); 26 | app.get('/', function(req, res){ 27 | res.render('index.ejs'); 28 | }); 29 | 30 | app.use(express.static(__dirname)); 31 | 32 | app.listen(3000); 33 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./lib/connect-cachify'); 2 | -------------------------------------------------------------------------------- /lib/compat.js: -------------------------------------------------------------------------------- 1 | //var format = require('util').format; 2 | 3 | /** 4 | * Weak version of util.format supports only %s placeholders. 5 | * Fixes Issue#3 compatibility with node < 5.4 6 | */ 7 | exports.format = function (fmt, args) { 8 | if (fmt.indexOf('%d') != -1 || 9 | fmt.indexOf('%j') != -1) { 10 | throw "This format only supports %s placeholders"; 11 | } 12 | if (typeof arguments[0] != 'string') { 13 | throw "First argument to format, must be a format string"; 14 | } 15 | var i = 0; 16 | var params = arguments; 17 | return fmt.replace(/%s/g, function () { 18 | i++; 19 | if (params[i] === undefined) { 20 | throw "Number of arguments didn't match format placeholders."; 21 | } 22 | return params[i]; 23 | }); 24 | } -------------------------------------------------------------------------------- /lib/connect-cachify.js: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 | * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | /*jslint node: true, nomen: true, white: true*/ 6 | "use strict"; 7 | 8 | var crypto = require('crypto'), 9 | format = require('./compat').format, 10 | fs = require('fs'), 11 | path = require('path'), 12 | _ = require('underscore'), 13 | url = require('url'); 14 | 15 | var HASH_LENGTH = 10; 16 | 17 | var existsSync = fs.existsSync || path.existsSync, 18 | _opts, 19 | _assets, 20 | _cache = {}; 21 | 22 | exports.setup = function (assets, options) { 23 | _assets = assets; 24 | _opts = clean_options(options); 25 | 26 | var prefix = escape_regex(no_url(_opts.prefix)), 27 | fmt_regexp = new RegExp(format('^\\/%s[a-f0-9]{%s}', prefix, HASH_LENGTH)); 28 | 29 | var is_cachified_uri = function (uri) { 30 | var m = uri.match(fmt_regexp); 31 | return m && m.index === 0; 32 | }; 33 | 34 | var remove_prefix = function(url) { 35 | return url.replace(fmt_regexp, ''); 36 | }; 37 | 38 | var get_true_path = function (uri) { 39 | var _url = remove_prefix(uri); 40 | return _opts.url_to_paths[_url] || path.join(_opts.root, _url); 41 | }; 42 | 43 | var get_expected_hash = function(url) { 44 | // the +1's take care of the slashes. 45 | var start_char = prefix.length + 1; 46 | var end_char = start_char + HASH_LENGTH; 47 | return url.slice(start_char, end_char); 48 | }; 49 | 50 | return function (req, resp, next) { 51 | // If the first path element is a md5 hash AND one of the following: 52 | // * the path is _opts.prefix 53 | // * the filename is a key in our _opts[family] 54 | // * or the file exists on the filesystem 55 | set_locals(resp); 56 | 57 | var uri = get_uri(req.url); 58 | if (! is_cachified_uri(uri)) { 59 | return next(); 60 | } 61 | 62 | var true_path = get_true_path(uri); 63 | if(! check_exists(assets, true_path, uri)) { 64 | return next(); 65 | } 66 | 67 | 68 | // determine actual current hash of the file, it's worth the disk 69 | // read to ensure we never serve bogus resources and poison caches 70 | // issue #31 71 | var expected_hash = get_expected_hash(uri); 72 | does_file_match_expected_hash(true_path, expected_hash, function (is_good_hash) { 73 | if (! is_good_hash) { 74 | // invalid hash, let the 404 handler take control 75 | return next(); 76 | } 77 | 78 | req.url = remove_prefix(req.url); 79 | set_cache_headers(resp); 80 | 81 | // let the static middleware handle the rest 82 | next(); 83 | }); 84 | }; 85 | }; 86 | 87 | var get_uri = function (_url) { 88 | var req_url = url.parse(_url); 89 | return req_url.pathname || ''; 90 | }; 91 | 92 | var check_exists = function(assets, true_path, uri) { 93 | // custom prefix with non-file assets. 94 | if (_opts.prefix !== '' && uri.indexOf('/' + _opts.prefix) === 0) { 95 | return true; 96 | } else if (assets[true_path]) { 97 | return true; 98 | } else if (_cache[true_path]) { 99 | return _cache[true_path].exists; 100 | } else if (existsSync(true_path)) { 101 | // Would we ever want to use cachify for non-file resources? 102 | _cache[true_path] = {exists: true}; 103 | return true; 104 | } else { 105 | // Hmm potential DOS Attack here... maybe we shouldn't cache 106 | // checking disk every time isn't that bad - just like static 107 | // middleware 108 | // Or use an LRU? 109 | console.warn('Cachify like URL, but no file found'); 110 | _cache[true_path] = {exists: false}; 111 | } 112 | 113 | return false; 114 | }; 115 | 116 | var set_cache_headers = function (resp) { 117 | resp.setHeader('Cache-Control', 'public, max-age=31536000'); 118 | if (_opts.control_headers === true) { 119 | resp.on('header', function () { 120 | remove_other_cache_headers(resp); 121 | }); 122 | } 123 | }; 124 | 125 | var remove_other_cache_headers = function (resp) { 126 | // Relax other middleware... I got this one 127 | ['ETag', 'Last-Modified'].forEach(function (header) { 128 | if (resp.getHeader(header)) resp.removeHeader(header); 129 | if (resp.getHeader(header)) resp.removeHeader(header); 130 | }); 131 | }; 132 | 133 | var get_hash_for_contents = function (contents) { 134 | var md5 = crypto.createHash('md5'); 135 | 136 | if (contents) md5.update(contents); 137 | return md5.digest('hex').slice(0, HASH_LENGTH); 138 | }; 139 | 140 | // check whether the MD5 of the contents matches the expected hash. 141 | var do_contents_match_expected_hash = function (contents, expected_hash) { 142 | var actual_hash = get_hash_for_contents(contents); 143 | 144 | return expected_hash === actual_hash; 145 | }; 146 | 147 | var does_file_match_expected_hash = function (true_path, expected_hash, done) { 148 | // determine actual current hash of the file, it's worth the disk 149 | // read to ensure we never serve bogus resources and poison caches 150 | // issue #31 151 | fs.readFile(true_path, function (err, contents) { 152 | // ignore error 153 | 154 | done(do_contents_match_expected_hash(contents, expected_hash)); 155 | }); 156 | }; 157 | 158 | 159 | // clean the input options passed in by the user. 160 | var clean_options = function (options) { 161 | options = options || {}; 162 | var cleaned = options; 163 | 164 | if (options.production === undefined) { 165 | cleaned.production = true; 166 | } 167 | 168 | if (! options.root) { 169 | cleaned.root = '.'; 170 | } 171 | 172 | if (! options.url_to_paths) { 173 | cleaned.url_to_paths = {}; 174 | } 175 | 176 | if (! options.prefix) { 177 | cleaned.prefix = ''; 178 | // Must end with a '/' 179 | } else if (options.prefix.slice(-1) !== '/') { 180 | cleaned.prefix += '/'; 181 | } 182 | 183 | // Don't lead with a '/' 184 | if (cleaned.prefix.charAt(0) === '/') { 185 | cleaned.prefix = cleaned.prefix.slice(1); 186 | } 187 | 188 | if (options.control_headers === undefined) { 189 | cleaned.control_headers = false; 190 | } 191 | 192 | if (options.debug === undefined) { 193 | cleaned.debug = false; 194 | } 195 | 196 | return cleaned; 197 | }; 198 | 199 | 200 | /** 201 | * If filename is an absolute path (starts with a '/') The hash 202 | * will be pre-pended with be slashified. 203 | * Examples: 204 | * /foo.js -> /a998d8e98f/foo.js 205 | * foo.js -> a998d8e98f/foo.js 206 | * http://example.com/foo.js -> http://example.com/foo.js 207 | */ 208 | 209 | var should_skip_hashification = function (resource) { 210 | if (_opts.production !== true && _opts.debug === false) { 211 | return true; 212 | } 213 | 214 | // full URL, bail immediately. 215 | if (resource.indexOf('://') > -1) { 216 | return true; 217 | } 218 | }; 219 | 220 | var get_predefined_hash = function (hash) { 221 | return hash || _opts.global_hash; 222 | }; 223 | 224 | var url_to_filename = function (url) { 225 | // fragment identifiers on URLs are never sent to the server and they 226 | // should not exist on the filename. When looking up the resource on 227 | // disk, do so without the fragment identifier. 228 | var no_hash_url = url.replace(/#.*$/, ''); 229 | return _opts.url_to_paths[no_hash_url] || path.join(_opts.root, no_hash_url); 230 | }; 231 | 232 | var get_resource_hash = function(resource) { 233 | var filename = url_to_filename(resource); 234 | if (_cache[filename] && _cache[filename].hash) { 235 | return _cache[filename].hash; 236 | //console.info('cache hit ', filename); 237 | } else { 238 | //console.info('cache miss ', filename); 239 | try { 240 | var data = fs.readFileSync(filename); 241 | // Expensive, maintain in-memory cache 242 | if (! _cache[filename]) _cache[filename] = {exists: true}; 243 | return _cache[filename].hash = get_hash_for_contents(data); 244 | } catch (e) { 245 | // Not intersting to cache, programmer error? 246 | exports.uncached_resources.push(resource); 247 | console.error('Cachify bailing on hash... no such file ' + filename); 248 | console.error('Options: %s', JSON.stringify(_opts)); 249 | console.error(e); 250 | } 251 | } 252 | }; 253 | 254 | var generate_hashed_url = function (resource, hash) { 255 | if (_opts.prefix.indexOf('://') === -1 && resource[0] === '/') { 256 | return format('/%s%s%s', _opts.prefix, hash, resource); 257 | } 258 | 259 | if (resource[0] !== '/') { 260 | resource = '/' + resource; 261 | } 262 | 263 | return format('%s%s%s', _opts.prefix, hash, resource); 264 | }; 265 | 266 | 267 | var hashify = function (resource, hash) { 268 | if (typeof resource !== 'string') 269 | throw "cachify ERROR, expected string for resource, got " + resource; 270 | 271 | if (should_skip_hashification(resource)) { 272 | return resource; 273 | } 274 | 275 | hash = get_predefined_hash(hash) || get_resource_hash(resource); 276 | 277 | if (! hash) { 278 | return resource; 279 | } 280 | 281 | return generate_hashed_url(resource, hash); 282 | }; 283 | 284 | var should_use_development_resources = function (uri) { 285 | var uri_assets = _assets[uri]; 286 | return _opts.production !== true && uri_assets; 287 | }; 288 | 289 | var generate_tags_for_resources = function (resources, link_fmt, query, hash) { 290 | // generate one tag per resource, then combine them into one string. 291 | return _.map(resources, function (f) { 292 | var asset_url = url.parse(f); 293 | var asset_uri = format('%s%s%s', 294 | asset_url.pathname || '', 295 | query ? '?' + query : '', 296 | asset_url.hash || '' 297 | ); 298 | 299 | return format(link_fmt, hashify(asset_uri, hash)); 300 | }).join('\n'); 301 | }; 302 | 303 | var generate_tags_for_filename = function (filename, link_fmt, hash) { 304 | var req_url = url.parse(filename), 305 | uri = req_url.pathname || ''; 306 | 307 | var resources; 308 | 309 | if (should_use_development_resources(uri)) { 310 | resources = _assets[uri]; 311 | } else { 312 | resources = [filename]; 313 | } 314 | 315 | return generate_tags_for_resources(resources, link_fmt, req_url.query, hash); 316 | }; 317 | 318 | var cachify_js = exports.cachify_js = function (filename, options) { 319 | if (! options) options = {}; 320 | var link_fmt = '', 112 | "debug option puts hash in all urls"); 113 | 114 | links = cachify.cachify_js("/js/main.min.js", 115 | { defer: true }).split('\n'); 116 | test.equal(links[0], 117 | '', 118 | "defer: true does not add defer attribute with production=false"); 119 | 120 | links = cachify.cachify_js("/js/main.min.js", 121 | { async: true }).split('\n'); 122 | test.equal(links[0], 123 | '', 124 | "async: true does not async attribute with production=false"); 125 | 126 | files = cachify.cachify("/js/main.min.js", {tag_format: ''}).split('\n'); 127 | test.equal(files[0], ''); 128 | hints = cachify.cachify_prefetch("/js/main.min.js").split('\n'); 129 | test.equal(hints[0], ''); 130 | test.done(); 131 | }, 132 | "Development mode": function (test) { 133 | var assets = make_assets(), 134 | req = { 135 | url: '/d41d8cd98f/js/main.min.js' 136 | }, 137 | resp = get_resp(), 138 | mddlwr; 139 | mddlwr = cachify.setup(assets, { 140 | root: '/tmp', 141 | production: false 142 | }); 143 | var links = cachify.cachify_js("/js/main.min.js").split('\n'); 144 | test.equal(links.length, assets["/js/main.min.js"].length, 145 | "All script tags created"); 146 | test.equal(links[0], '', 147 | "No hashes in all urls during development"); 148 | test.equal(links[3], '', 149 | "Fragment identifier in URL is preserved"); 150 | test.equal(cachify.uncached_resources.indexOf("/js/font-loader.js#with_fragment_id"), -1, 151 | "Fragment identifiers are never sent to server, search on disk for resource by removing fragment id"); 152 | var files = cachify.cachify("/js/main.min.js").split('\n'); 153 | test.equal(files.length, assets["/js/main.min.js"].length, 154 | "All urls created"); 155 | test.equal(files[0], '/js/lib/jquery.js', 156 | "No hashes in all urls during development"); 157 | var hints = cachify.cachify_prefetch("/js/main.min.js").split('\n'); 158 | test.ok(hints.length, "Multiple link tags"); 159 | test.equal(hints[0], ''); 160 | mddlwr(req, resp, function () { 161 | test.ok(resp.state.cachify_prefetch); 162 | test.ok(resp.state.cachify_js); 163 | test.ok(resp.state.cachify_css); 164 | test.ok(resp.state.header > 0); 165 | test.done(); 166 | }); 167 | }, 168 | "Development mode with url query string": function (test) { 169 | var assets = make_assets(), 170 | mddlwr; 171 | mddlwr = cachify.setup(assets, { 172 | root: '/tmp', 173 | production: false 174 | }); 175 | var links = cachify.cachify_js("/js/main.min.js?triedPassive=true").split('\n'); 176 | test.equal(links.length, assets["/js/main.min.js"].length, 177 | "All script tags created"); 178 | test.equal(links[0], '', 179 | "No hashes in all urls during development"); 180 | test.equal(links[3], '', 181 | "Fragment identifier in URL is preserved"); 182 | test.equal(cachify.uncached_resources.indexOf("/js/font-loader.js?triedPassive=true#with_fragment_id"), -1, 183 | "Fragment identifiers are never sent to server, search on disk for resource by removing fragment id"); 184 | 185 | var files = cachify.cachify("/js/main.min.js?triedPassive=true").split('\n'); 186 | test.equal(files.length, assets["/js/main.min.js"].length, 187 | "All urls created"); 188 | test.equal(files[0], '/js/lib/jquery.js?triedPassive=true', 189 | "No hashes in all urls during development"); 190 | 191 | var hints = cachify.cachify_prefetch("/js/main.min.js?triedPassive=true").split('\n'); 192 | test.ok(hints.length, "Multiple link tags"); 193 | test.equal(hints[0], ''); 194 | test.done(); 195 | }, 196 | "Production mode": function (test) { 197 | var assets = make_assets(), 198 | req = { 199 | url: '/d41d8cd98f/js/main.min.js' 200 | }, 201 | resp = get_resp(), 202 | mddlwr; 203 | mddlwr = cachify.setup( 204 | assets, { 205 | root: '/tmp' 206 | }); 207 | var link = cachify.cachify_js("/js/main.min.js"); 208 | test.equal(link, '', 209 | "Hashes in all urls in production"); 210 | 211 | links = cachify.cachify_js("/js/main.min.js", 212 | { defer: true }).split('\n'); 213 | test.equal(links[0], 214 | '', 215 | "defer: true adds defer attribute with production=true"); 216 | 217 | links = cachify.cachify_js("/js/main.min.js", 218 | { async: true }).split('\n'); 219 | test.equal(links[0], 220 | '', 221 | "async: true adds async attribute with production=true"); 222 | 223 | var file = cachify.cachify("/js/main.min.js"); 224 | test.equal(file, "/d41d8cd98f/js/main.min.js"); 225 | var hint = cachify.cachify_prefetch("/js/main.min.js"); 226 | test.equal(hint, ''); 227 | mddlwr(req, resp, function () { 228 | test.ok(resp.state.cachify_prefetch); 229 | test.ok(resp.state.cachify_js); 230 | test.ok(resp.state.cachify_css); 231 | test.ok(resp.state.cachify); 232 | test.ok(resp.state.header > 0); 233 | test.equal(req.url, '/js/main.min.js'); 234 | test.done(); 235 | }); 236 | }, 237 | "Production mode with url query string" : function (test) { 238 | var assets = make_assets(), 239 | req = { 240 | url: '/d41d8cd98f/js/main.min.js?triedPassive=true' 241 | }, 242 | resp = get_resp(), 243 | mddlwr; 244 | mddlwr = cachify.setup( 245 | assets, { 246 | root: '/tmp' 247 | }); 248 | 249 | mddlwr(req, resp, function () { 250 | test.ok(resp.state.cachify_prefetch); 251 | test.ok(resp.state.cachify_js); 252 | test.ok(resp.state.cachify_css); 253 | test.ok(resp.state.cachify); 254 | test.ok(resp.state.header > 0); 255 | test.equal(req.url, '/js/main.min.js?triedPassive=true'); 256 | test.done(); 257 | }); 258 | }, 259 | "Production mode with absolute URL in prefix": function (test) { 260 | var assets = make_assets(), 261 | req = { 262 | url: '/v/d41d8cd98f/js/main.min.js' 263 | }, 264 | resp = get_resp(), 265 | mddlwr; 266 | mddlwr = cachify.setup( 267 | assets, { 268 | root: '/tmp', 269 | prefix: 'http://example.com/v/' 270 | }); 271 | var link = cachify.cachify_js("/js/main.min.js"); 272 | test.equal(link, '', 273 | "Hashes in all urls in production"); 274 | var file = cachify.cachify("/js/main.min.js"); 275 | test.equal(file, "http://example.com/v/d41d8cd98f/js/main.min.js"); 276 | var hint = cachify.cachify_prefetch("/js/main.min.js"); 277 | test.equal(hint, ''); 278 | mddlwr(req, resp, function () { 279 | test.ok(resp.state.cachify_prefetch); 280 | test.ok(resp.state.cachify_js); 281 | test.ok(resp.state.cachify_css); 282 | test.ok(resp.state.cachify); 283 | test.ok(resp.state.header > 0); 284 | test.equal(req.url, '/js/main.min.js'); 285 | test.done(); 286 | }); 287 | }, 288 | "Production mode with absolute URL in prefix and url query string" : function (test) { 289 | var assets = make_assets(), 290 | req = { 291 | url: '/v/d41d8cd98f/js/main.min.js?triedPassive=true' 292 | }, 293 | resp = get_resp(), 294 | mddlwr; 295 | mddlwr = cachify.setup( 296 | assets, { 297 | root: '/tmp', 298 | prefix: 'http://example.com/v/' 299 | }); 300 | 301 | mddlwr(req, resp, function () { 302 | test.ok(resp.state.cachify_prefetch); 303 | test.ok(resp.state.cachify_js); 304 | test.ok(resp.state.cachify_css); 305 | test.ok(resp.state.cachify); 306 | test.ok(resp.state.header > 0); 307 | test.equal(req.url, '/js/main.min.js?triedPassive=true'); 308 | test.done(); 309 | }); 310 | }, 311 | "Custom prefix works with non-file assets": function (test) { 312 | var assets = make_assets(), 313 | req = { 314 | url: '/cachify/d41d8cd98f/other' 315 | }, 316 | resp = get_resp(), 317 | mddlwr; 318 | 319 | mddlwr = cachify.setup( 320 | assets, { 321 | prefix: 'cachify', 322 | root: '/tmp' 323 | }); 324 | var link = cachify.cachify_js("/other", {hash: 'd41d8cd98f'}); 325 | test.equal(link, ''); 326 | 327 | mddlwr(req, resp, function () { 328 | test.ok(resp.state.cachify_prefetch); 329 | test.ok(resp.state.cachify_js); 330 | test.ok(resp.state.cachify_css); 331 | test.ok(resp.state.cachify); 332 | test.ok(resp.state.header > 0); 333 | test.equal(req.url, '/other'); 334 | test.done(); 335 | }); 336 | }, 337 | "Custom prefix with non-file assets and url query string": function (test) { 338 | var assets = make_assets(), 339 | req = { 340 | url: '/cachify/d41d8cd98f/other?triedPassive=true' 341 | }, 342 | resp = get_resp(), 343 | mddlwr; 344 | 345 | mddlwr = cachify.setup( 346 | assets, { 347 | prefix: 'cachify', 348 | root: '/tmp' 349 | }); 350 | var link = cachify.cachify_js("/other", {hash: 'd41d8cd98f'}); 351 | test.equal(link, ''); 352 | 353 | mddlwr(req, resp, function () { 354 | test.ok(resp.state.cachify_prefetch); 355 | test.ok(resp.state.cachify_js); 356 | test.ok(resp.state.cachify_css); 357 | test.ok(resp.state.cachify); 358 | test.ok(resp.state.header > 0); 359 | test.equal(req.url, '/other?triedPassive=true'); 360 | test.done(); 361 | }); 362 | }, 363 | "Production mode, mismatched checksum, not substituted": function (test) { 364 | var assets = make_assets(), 365 | req = { 366 | url: '/e41d8cd98f/js/main.min.js' 367 | }, 368 | resp = get_resp(), 369 | mddlwr; 370 | mddlwr = cachify.setup( 371 | assets, { 372 | root: '/tmp' 373 | }); 374 | // ensure that middleware does not re-write cachified urls that 375 | // don't match the current file contents. 376 | var before = req.url; 377 | mddlwr(req, resp, function () { 378 | test.ok(req.url == before); 379 | test.done(); 380 | }); 381 | }, 382 | "Production - look up paths in url_to_paths table": function (test) { 383 | var assets = make_assets(), 384 | url_to_paths = { 385 | // This file is permanently part of the repo. It's md5 checksum, as 386 | // reported by md5, is d31da114e3ea4076b2acec51c328806c. The first 10 387 | // characters are d31da114e3. 388 | '/js/test-file.js': path.join(__dirname, 'test-data', 'test-file.js') 389 | }, 390 | mddlwr = cachify.setup(assets, { 391 | url_to_paths: url_to_paths 392 | }); 393 | 394 | // ensure cachify_js generates a cachified link in production. 395 | // 396 | // If the link comes back cachified, it means the url_to_paths table was 397 | // used to look up the actual file to generate the SHA. 398 | var link = cachify.cachify_js("/js/test-file.js"); 399 | test.equal(link, ''); 400 | 401 | // ensure cachify generates the correct cachified path in production. 402 | var file = cachify.cachify("/js/test-file.js"); 403 | test.equal(file, "/d31da114e3/js/test-file.js"); 404 | 405 | // ensure the middleware responds to the cachified URL. 406 | var req = { 407 | url: '/d31da114e3/js/test-file.js' 408 | }, 409 | resp = get_resp(); 410 | 411 | mddlwr(req, resp, function () { 412 | // make sure the hash is stripped out so that another middleware can take 413 | // care of responding to the request. 414 | test.equal(req.url, '/js/test-file.js'); 415 | test.done(); 416 | }); 417 | }, 418 | "URLs without SHA won't be processed": function (test) { 419 | var assets = make_assets(), 420 | url_to_paths = { 421 | // This file is permanently part of the repo. It's md5 checksum, as 422 | // reported by md5, is d31da114e3ea4076b2acec51c328806c. The first 10 423 | // characters are d31da114e3. 424 | '/js/test-file.js': path.join(__dirname, 'test-data', 'test-file.js') 425 | }, 426 | mddlwr = cachify.setup(assets, { 427 | url_to_paths: url_to_paths 428 | }); 429 | 430 | // ensure the middleware responds to the cachified URL. 431 | var req = { 432 | url: '/some/unknown/code.js' 433 | }, 434 | resp = get_resp(); 435 | 436 | mddlwr(req, resp, function () { 437 | // Unknown paths do not get treated like SHAs and stripped. 438 | test.equal(req.url, '/some/unknown/code.js'); 439 | test.done(); 440 | }); 441 | } 442 | 443 | }); 444 | -------------------------------------------------------------------------------- /test/express-test.js: -------------------------------------------------------------------------------- 1 | /* Test Express 2.x to maintain compatability */ 2 | 3 | var cachify = require('../lib/connect-cachify'), 4 | express2, 5 | express3, 6 | express4, 7 | http = require('http'), 8 | nodeunit = require('nodeunit'), 9 | os = require('os'), 10 | path = require('path'), 11 | shell = require('shelljs'), 12 | spawn = require('child_process').spawn; 13 | 14 | var tmpDir = os.tmpDir ? os.tmpDir() : '/tmp'; 15 | 16 | var express2dir = path.join(tmpDir, 'connect-cachify-express2-test'); 17 | var express3dir = path.join(tmpDir, 'connect-cachify-express3-test'); 18 | var express4dir = path.join(tmpDir, 'connect-cachify-express4-test'); 19 | 20 | const EXPRESS_DIRS = [ express2dir, express3dir, express4dir ]; 21 | 22 | const EXPRESS_2_VER = '2.5.10'; 23 | const EXPRESS_3_VER = '3.0.0'; 24 | const EXPRESS_4_VER = '4.0.0'; 25 | 26 | const EXPRESS_DEPS = [ 27 | { 28 | dir: express2dir, 29 | ver: EXPRESS_2_VER 30 | }, 31 | { 32 | dir: express3dir, 33 | ver: EXPRESS_3_VER 34 | }, 35 | { 36 | dir: express4dir, 37 | ver: EXPRESS_4_VER 38 | } 39 | ]; 40 | 41 | var debug = function (data) { 42 | process.stdout.write(data.toString('utf8')); 43 | }; 44 | 45 | exports.setup = nodeunit.testCase({ 46 | setUp: function (cb) { 47 | var remaining = EXPRESS_DEPS.length; 48 | 49 | EXPRESS_DEPS.forEach(function (express, i) { 50 | console.log('Creating ' + express.dir); 51 | shell.mkdir('-p', express.dir); 52 | process.chdir(express.dir); 53 | 54 | var npm = spawn('npm', ['install', 'express@' + express.ver], {}); 55 | npm.stdout.on('data', debug); 56 | npm.stderr.on('data', debug); 57 | 58 | npm.on('exit', function (code) { 59 | if (0 !== code) { 60 | throw new Error('Unable to npm install express'); 61 | } 62 | 63 | if (0 === i) { 64 | express2 = require(path.join(express2dir, 'node_modules/express')); 65 | } else if (1 === i) { 66 | express3 = require(path.join(express3dir, 'node_modules/express')); 67 | } else { 68 | express4 = require(path.join(express4dir, 'node_modules/express')); 69 | } 70 | 71 | --remaining; 72 | debug('remaining: ' + remaining); 73 | if (! remaining) { 74 | cb(); 75 | } 76 | }); 77 | }); 78 | }, 79 | tearDown: function (cb) { 80 | EXPRESS_DIRS.forEach(function (expressDir) { 81 | console.log('Removing ' + expressDir); 82 | shell.rm('-rf', expressDir); 83 | }); 84 | cb(); 85 | }, 86 | "Run Server": function (test) { 87 | test.equal(express2.version, EXPRESS_2_VER); 88 | test.equal(express3.version, EXPRESS_3_VER); 89 | 90 | // Express 4 doesn't have a version so check for a property instead 91 | test.ok( !! express4.Router); 92 | 93 | var expresses = [express2, express3, express4]; 94 | function testNextServer() { 95 | var express = expresses.shift(); 96 | if (! express) return test.done(); 97 | 98 | testExpress(test, express, testNextServer); 99 | } 100 | 101 | testNextServer(); 102 | } 103 | }); 104 | 105 | function testExpress(test, express, done) { 106 | var app = express.createServer ? express.createServer() : express(); 107 | app.use(cachify.setup([])); 108 | app.use(function (req, res) { 109 | var locals = typeof res.locals === 'function' ? res.locals() : res.locals; 110 | test.ok(!! locals.cachify); 111 | test.ok(!! locals.cachify_css); 112 | test.ok(!! locals.cachify_js); 113 | test.ok(!! locals.cachify_prefetch); 114 | res.send('ok'); 115 | }); 116 | var server = app.listen(0); 117 | var port = server.address().port; 118 | debug('Started web server on port ' + port); 119 | var resText = ""; 120 | var req = http.request({ port: port, path: '/baddecafe1/foo.js'}, function (res) { 121 | test.equal(res.statusCode, 200); 122 | res.on('data', function (chunk) { 123 | resText += chunk; 124 | }); 125 | res.on('end', function () { 126 | test.equal(resText, 'ok'); 127 | app.close ? app.close() : server.close(); 128 | debug('Stopped web server on port ' + port); 129 | done(); 130 | }); 131 | }); 132 | req.end(); 133 | } 134 | -------------------------------------------------------------------------------- /test/test-data/test-file.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | console.log('this is a test file used to calculate an md5 to see if url_to_paths is working correctly.'); 3 | }()); 4 | --------------------------------------------------------------------------------