├── .gitignore ├── demo ├── package.json ├── foo.js ├── index.html ├── base64.js └── yarn.lock ├── yarn.lock ├── package.json ├── README.md ├── utils.js ├── cjs-loader.js └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | 4 | -------------------------------------------------------------------------------- /demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "glob": "^7.1.2", 4 | "handlebars": "^4.0.10", 5 | "left-pad": "^1.1.3", 6 | "node-glob": "^1.2.0" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /demo/foo.js: -------------------------------------------------------------------------------- 1 | 2 | define('foo', ['./base64.js'], function(base64) { 3 | console.info('foo got base64', base64, 'required', require('./base64.js')); 4 | return {foo: 'i am foo', base64}; 5 | }); 6 | -------------------------------------------------------------------------------- /yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | rollup@^0.49.2: 6 | version "0.49.2" 7 | resolved "https://registry.yarnpkg.com/rollup/-/rollup-0.49.2.tgz#a18f07595cde3b11875c9fece45b25ad3b220d1a" 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cjs-loader", 3 | "version": "0.1.0", 4 | "description": "Transitively includes commonJS modules for use on the web", 5 | "main": "cjs-loader.js", 6 | "repository": "https://github.com/samthor/cjs-loader.git", 7 | "author": "Sam Thorogood ", 8 | "license": "Apache-2" 9 | } 10 | -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 35 | 41 | 42 | 43 | 44 | 45 |

Note: tested on Chrome 61.

46 | 47 |

48 | If you see a message below (generated by Handlebars), the demo worked. 49 | Open the Developer Tools to see the network requests being made—there's about 35 to go, so it's slow on the first load. 50 |

51 | 52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | cjs-loader transitively includes commonJS modules for use on the web, and is useful for developers wanting to migrate to ES6 modules who still have legacy dependencies. 2 | [Go here for a demo](https://samthor.github.io/cjs-loader/demo/index.html) (needs a browser with native modules support—Safari 10.1+, or Chrome 61+). 3 | 4 | We do this using just your browser, without a compile step, by implementing `require()` and other methods just while loading the module code. 5 | For users of cjs-loader, we provide `load(moduleName)` that returns a `Promise` of the exports. 6 | 7 | 🔥👨‍💻🔥 This is an interesting, successful but terrible idea and should not be used by anyone. 8 | It reqiures support for ES6 Modules 🛠️ and has only really been tested on Chrome 61+. 9 | 10 | # Usage 11 | 12 | First, install any public modules you want to use with NPM or Yarn. 13 | Then, use the loader: 14 | 15 | ```html 16 | 24 | ``` 25 | 26 | (This assumes `npm-package-name` is in the path `./node_modules/npm-package-name`. You can also `require()` a relative path.) 27 | 28 | For example, to use Handlebars ([as per the demo](https://samthor.github.io/cjs-loader/demo/index.html)): 29 | 30 | ```js 31 | load('handlebars').then((handlebars) => { 32 | const Handlebars = handlebars.create(); 33 | 34 | const source = '

Hello {{name}}, you have {{name.length}} letters

'; 35 | const template = Handlebars.compile(source); 36 | console.info(template({name: 'Sam'})); 37 | }); 38 | ``` 39 | 40 | Handlebars internally fetches about ~35 modules (via `require()`), which all get wrapped. 41 | 42 | # Implementation 43 | 44 | 1. Stub out `module.exports`, `require()` etc. 45 | 2. Load the target module as an ES6 module^1 46 | * If a further dependency is unavailable in `require()`, throw a known exception^2 47 | * Catch in a global handler, and load the dependency via step 2 48 | * Retry running the target module when done 49 | 50 | ^1 more or less 51 | 52 | ^2 `require()` is synchronous, so we can't block to load more code 53 | 54 | ## Specific Hacks 55 | 56 | [We abuse](https://gist.github.com/samthor/8c5ebf3239bfeaca6c92299bb12b2a79) the fact that Chrome reruns but does _not_ need to reload script files with the same path, but a different hash. 57 | This allows for "efficient" retries. 58 | e.g.: 59 | 60 | ```js 61 | import * as foo1 from './foo.js#1'; 62 | import * as foo2 from './foo.js#2'; 63 | foo1 !== foo2 // not the same, but only caused one network request 64 | ``` 65 | 66 | *TODO: document more hacks* 67 | 68 | # Notes 69 | 70 | Things that we can't fix: 71 | 72 | * Don't use this in production. 73 | It's horrible. 74 | 75 | * Modules can't _really_ determine their path, so if one of your dependenies is from a 302 etc, all bets are off 76 | 77 | * Runtime `require()` (i.e., not run on initial import) calls will fail if the code isn't available 78 | 79 | ## TODOs 80 | 81 | Things that we can fix: 82 | 83 | * Built-in Node packages don't work (`fs`, `path` etc) 84 | 85 | * We should coalesce multiple failures to `require()` (just return `null` until an actual error occurs) and request further code in parallel 86 | 87 | * This code is forked from [cjs-faker](https://github.com/samthor/cjs-faker), and still supports AMD, but calling an unplanned `require()` from within `define()` doesn't work yet 88 | 89 | -------------------------------------------------------------------------------- /utils.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Google Inc. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 | * use this file except in compliance with the License. You may obtain a copy of 6 | * the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations under 14 | * the License. 15 | */ 16 | 17 | const functionMatch = /^(?:async\s*|)function\s*\*?\s*\w*\s*\(([\w\s,]+)\) {/; 18 | const arrowFunctionMatch = /^(?:async\s*|)(?:\(([\w\s,]+)\)|(\w+))\s+=>/; 19 | 20 | /** 21 | * Extracts the simple argument names from the passed function object. Returns an empty array if 22 | * none could be determined, or they were complex (default values, {}'s etc) 23 | * 24 | * @param {!Function} fn 25 | * @return {!Array} array of simple arg names (no =, ... etc) 26 | */ 27 | function argNames(fn) { 28 | const s = fn.toString(); 29 | const match = functionMatch.exec(s) || arrowFunctionMatch.exec(s); 30 | if (!match) { 31 | return []; 32 | } 33 | const raw = match[1] || match[2] || ''; 34 | const args = raw.split(',').map((x) => x.trim()); 35 | if (args.length && args[args.length - 1] === '') { 36 | args.pop(); 37 | } 38 | return args; 39 | } 40 | 41 | /** 42 | * Extracts the args from a define() cal. Throws TypeError on invalid arguments. 43 | * 44 | * @param {!Array<(string|!Array|!Function)>} args should be between 1 and 3 45 | * @return {{id: ?string, deps: !Array, fn: !Function}} 46 | */ 47 | export function argsForDefine(args) { 48 | let id = null, deps = null; 49 | 50 | if (typeof args[0] === 'string') { 51 | id = args.shift(); 52 | } 53 | if (typeof args[0] === 'object' && 'length' in args[0]) { 54 | deps = args.shift(); 55 | } 56 | if (args.length !== 1 || typeof args[0] !== 'function') { 57 | throw new TypeError('got unexpected args: wanted [id,][deps,]func'); 58 | } 59 | const fn = args.shift(); 60 | if (args.length || fn === undefined) { 61 | throw new TypeError('got unexpected args count: wanted 1-3'); 62 | } 63 | 64 | // no deps or simple deps 65 | if (!fn.length && deps === null) { 66 | deps = []; 67 | } else if (deps === null) { 68 | // look for 'Simplified CommonJS Wrapper' 69 | deps = argNames(fn); 70 | const s = deps.join(','); 71 | if (s !== 'require' && s !== 'require,exports,module') { 72 | throw new TypeError( 73 | `expected callback args: 'require'/'require,exports,module', was: '${s}'`); 74 | } 75 | } 76 | 77 | return {id, deps, fn}; 78 | } 79 | 80 | /** 81 | * @param {string} path 82 | * @return {string} path 83 | */ 84 | export function normalize(path) { 85 | const parts = path.split('/'); 86 | 87 | let i = 1; 88 | while (i < parts.length) { 89 | const curr = parts[i]; 90 | 91 | if (curr === '.' || curr === '') { 92 | parts.splice(i, 1); 93 | continue; 94 | } else if (curr !== '..') { 95 | ++i; 96 | continue; 97 | } 98 | 99 | const prev = parts[i - 1]; 100 | if (prev === '') { 101 | // at root 102 | parts.splice(i, 1); 103 | } else if (prev === '..') { 104 | // can't eat prev .. 105 | ++i; 106 | } else if (prev === '.') { 107 | // left is relative 108 | parts.splice(i-1, 1); 109 | } else { 110 | // eat both 111 | parts.splice(--i, 2); 112 | } 113 | } 114 | 115 | return parts.join('/'); 116 | } 117 | 118 | /** 119 | * @param {string} content to use for code 120 | * @return {!HTMLScriptElement} 121 | */ 122 | export function insertModuleScript(content) { 123 | const s = document.createElement('script'); 124 | s.type = 'module'; 125 | s.async = false; 126 | s.textContent = content; 127 | document.head.appendChild(s); 128 | s.remove(); // remove immediately, runs anyway 129 | return s; 130 | } 131 | 132 | /** 133 | * @param {!Object} object to return if it has keys 134 | * @return {Object} object if it had keys 135 | */ 136 | export function withKeys(object) { 137 | for (let k in object) { 138 | return object; 139 | } 140 | return null; 141 | } 142 | -------------------------------------------------------------------------------- /demo/base64.js: -------------------------------------------------------------------------------- 1 | /*! https://mths.be/base64 v0.1.0 by @mathias | MIT license */ 2 | ;(function(root) { 3 | 4 | // Detect free variables `exports`. 5 | var freeExports = typeof exports == 'object' && exports; 6 | 7 | // Detect free variable `module`. 8 | var freeModule = typeof module == 'object' && module && 9 | module.exports == freeExports && module; 10 | 11 | // Detect free variable `global`, from Node.js or Browserified code, and use 12 | // it as `root`. 13 | var freeGlobal = typeof global == 'object' && global; 14 | if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { 15 | root = freeGlobal; 16 | } 17 | 18 | /*--------------------------------------------------------------------------*/ 19 | 20 | var InvalidCharacterError = function(message) { 21 | this.message = message; 22 | }; 23 | InvalidCharacterError.prototype = new Error; 24 | InvalidCharacterError.prototype.name = 'InvalidCharacterError'; 25 | 26 | var error = function(message) { 27 | // Note: the error messages used throughout this file match those used by 28 | // the native `atob`/`btoa` implementation in Chromium. 29 | throw new InvalidCharacterError(message); 30 | }; 31 | 32 | var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 33 | // http://whatwg.org/html/common-microsyntaxes.html#space-character 34 | var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g; 35 | 36 | // `decode` is designed to be fully compatible with `atob` as described in the 37 | // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob 38 | // The optimized base64-decoding algorithm used is based on @atk’s excellent 39 | // implementation. https://gist.github.com/atk/1020396 40 | var decode = function(input) { 41 | input = String(input) 42 | .replace(REGEX_SPACE_CHARACTERS, ''); 43 | var length = input.length; 44 | if (length % 4 == 0) { 45 | input = input.replace(/==?$/, ''); 46 | length = input.length; 47 | } 48 | if ( 49 | length % 4 == 1 || 50 | // http://whatwg.org/C#alphanumeric-ascii-characters 51 | /[^+a-zA-Z0-9/]/.test(input) 52 | ) { 53 | error( 54 | 'Invalid character: the string to be decoded is not correctly encoded.' 55 | ); 56 | } 57 | var bitCounter = 0; 58 | var bitStorage; 59 | var buffer; 60 | var output = ''; 61 | var position = -1; 62 | while (++position < length) { 63 | buffer = TABLE.indexOf(input.charAt(position)); 64 | bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer; 65 | // Unless this is the first of a group of 4 characters… 66 | if (bitCounter++ % 4) { 67 | // …convert the first 8 bits to a single ASCII character. 68 | output += String.fromCharCode( 69 | 0xFF & bitStorage >> (-2 * bitCounter & 6) 70 | ); 71 | } 72 | } 73 | return output; 74 | }; 75 | 76 | // `encode` is designed to be fully compatible with `btoa` as described in the 77 | // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa 78 | var encode = function(input) { 79 | input = String(input); 80 | if (/[^\0-\xFF]/.test(input)) { 81 | // Note: no need to special-case astral symbols here, as surrogates are 82 | // matched, and the input is supposed to only contain ASCII anyway. 83 | error( 84 | 'The string to be encoded contains characters outside of the ' + 85 | 'Latin1 range.' 86 | ); 87 | } 88 | var padding = input.length % 3; 89 | var output = ''; 90 | var position = -1; 91 | var a; 92 | var b; 93 | var c; 94 | var d; 95 | var buffer; 96 | // Make sure any padding is handled outside of the loop. 97 | var length = input.length - padding; 98 | 99 | while (++position < length) { 100 | // Read three bytes, i.e. 24 bits. 101 | a = input.charCodeAt(position) << 16; 102 | b = input.charCodeAt(++position) << 8; 103 | c = input.charCodeAt(++position); 104 | buffer = a + b + c; 105 | // Turn the 24 bits into four chunks of 6 bits each, and append the 106 | // matching character for each of them to the output. 107 | output += ( 108 | TABLE.charAt(buffer >> 18 & 0x3F) + 109 | TABLE.charAt(buffer >> 12 & 0x3F) + 110 | TABLE.charAt(buffer >> 6 & 0x3F) + 111 | TABLE.charAt(buffer & 0x3F) 112 | ); 113 | } 114 | 115 | if (padding == 2) { 116 | a = input.charCodeAt(position) << 8; 117 | b = input.charCodeAt(++position); 118 | buffer = a + b; 119 | output += ( 120 | TABLE.charAt(buffer >> 10) + 121 | TABLE.charAt((buffer >> 4) & 0x3F) + 122 | TABLE.charAt((buffer << 2) & 0x3F) + 123 | '=' 124 | ); 125 | } else if (padding == 1) { 126 | buffer = input.charCodeAt(position); 127 | output += ( 128 | TABLE.charAt(buffer >> 2) + 129 | TABLE.charAt((buffer << 4) & 0x3F) + 130 | '==' 131 | ); 132 | } 133 | 134 | return output; 135 | }; 136 | 137 | var base64 = { 138 | 'encode': encode, 139 | 'decode': decode, 140 | 'version': '0.1.0' 141 | }; 142 | 143 | // Some AMD build optimizers, like r.js, check for specific condition patterns 144 | // like the following: 145 | if ( 146 | typeof define == 'function' && 147 | typeof define.amd == 'object' && 148 | define.amd 149 | ) { 150 | define(function() { 151 | return base64; 152 | }); 153 | } else if (freeExports && !freeExports.nodeType) { 154 | if (freeModule) { // in Node.js or RingoJS v0.8.0+ 155 | freeModule.exports = base64; 156 | } else { // in Narwhal or RingoJS v0.7.0- 157 | for (var key in base64) { 158 | base64.hasOwnProperty(key) && (freeExports[key] = base64[key]); 159 | } 160 | } 161 | } else { // in Rhino or a web browser 162 | root.base64 = base64; 163 | } 164 | 165 | }(this)); 166 | -------------------------------------------------------------------------------- /demo/yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | align-text@^0.1.1, align-text@^0.1.3: 6 | version "0.1.4" 7 | resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" 8 | dependencies: 9 | kind-of "^3.0.2" 10 | longest "^1.0.1" 11 | repeat-string "^1.5.2" 12 | 13 | amdefine@>=0.0.4: 14 | version "1.0.1" 15 | resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" 16 | 17 | async@^1.3.0, async@^1.4.0: 18 | version "1.5.2" 19 | resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" 20 | 21 | balanced-match@^1.0.0: 22 | version "1.0.0" 23 | resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" 24 | 25 | brace-expansion@^1.1.7: 26 | version "1.1.8" 27 | resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.8.tgz#c07b211c7c952ec1f8efd51a77ef0d1d3990a292" 28 | dependencies: 29 | balanced-match "^1.0.0" 30 | concat-map "0.0.1" 31 | 32 | camelcase@^1.0.2: 33 | version "1.2.1" 34 | resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" 35 | 36 | center-align@^0.1.1: 37 | version "0.1.3" 38 | resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" 39 | dependencies: 40 | align-text "^0.1.3" 41 | lazy-cache "^1.0.3" 42 | 43 | cliui@^2.1.0: 44 | version "2.1.0" 45 | resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" 46 | dependencies: 47 | center-align "^0.1.1" 48 | right-align "^0.1.1" 49 | wordwrap "0.0.2" 50 | 51 | concat-map@0.0.1: 52 | version "0.0.1" 53 | resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" 54 | 55 | decamelize@^1.0.0: 56 | version "1.2.0" 57 | resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" 58 | 59 | fs.realpath@^1.0.0: 60 | version "1.0.0" 61 | resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" 62 | 63 | glob-to-regexp@^0.1.0: 64 | version "0.1.0" 65 | resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.1.0.tgz#e0369d426578fd456d47dc23b09de05c1da9ea5d" 66 | 67 | glob@^7.1.2: 68 | version "7.1.2" 69 | resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" 70 | dependencies: 71 | fs.realpath "^1.0.0" 72 | inflight "^1.0.4" 73 | inherits "2" 74 | minimatch "^3.0.4" 75 | once "^1.3.0" 76 | path-is-absolute "^1.0.0" 77 | 78 | handlebars@^4.0.10: 79 | version "4.0.10" 80 | resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.10.tgz#3d30c718b09a3d96f23ea4cc1f403c4d3ba9ff4f" 81 | dependencies: 82 | async "^1.4.0" 83 | optimist "^0.6.1" 84 | source-map "^0.4.4" 85 | optionalDependencies: 86 | uglify-js "^2.6" 87 | 88 | inflight@^1.0.4: 89 | version "1.0.6" 90 | resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" 91 | dependencies: 92 | once "^1.3.0" 93 | wrappy "1" 94 | 95 | inherits@2: 96 | version "2.0.3" 97 | resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" 98 | 99 | is-buffer@^1.1.5: 100 | version "1.1.5" 101 | resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.5.tgz#1f3b26ef613b214b88cbca23cc6c01d87961eecc" 102 | 103 | kind-of@^3.0.2: 104 | version "3.2.2" 105 | resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" 106 | dependencies: 107 | is-buffer "^1.1.5" 108 | 109 | lazy-cache@^1.0.3: 110 | version "1.0.4" 111 | resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" 112 | 113 | left-pad@^1.1.3: 114 | version "1.1.3" 115 | resolved "https://registry.yarnpkg.com/left-pad/-/left-pad-1.1.3.tgz#612f61c033f3a9e08e939f1caebeea41b6f3199a" 116 | 117 | longest@^1.0.1: 118 | version "1.0.1" 119 | resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" 120 | 121 | minimatch@^3.0.4: 122 | version "3.0.4" 123 | resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" 124 | dependencies: 125 | brace-expansion "^1.1.7" 126 | 127 | minimist@~0.0.1: 128 | version "0.0.10" 129 | resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" 130 | 131 | node-glob@^1.2.0: 132 | version "1.2.0" 133 | resolved "https://registry.yarnpkg.com/node-glob/-/node-glob-1.2.0.tgz#5240ffedefc6d663ce8515e5796a4d47a750c0d5" 134 | dependencies: 135 | async "^1.3.0" 136 | glob-to-regexp "^0.1.0" 137 | 138 | once@^1.3.0: 139 | version "1.4.0" 140 | resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" 141 | dependencies: 142 | wrappy "1" 143 | 144 | optimist@^0.6.1: 145 | version "0.6.1" 146 | resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" 147 | dependencies: 148 | minimist "~0.0.1" 149 | wordwrap "~0.0.2" 150 | 151 | path-is-absolute@^1.0.0: 152 | version "1.0.1" 153 | resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" 154 | 155 | repeat-string@^1.5.2: 156 | version "1.6.1" 157 | resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" 158 | 159 | right-align@^0.1.1: 160 | version "0.1.3" 161 | resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" 162 | dependencies: 163 | align-text "^0.1.1" 164 | 165 | source-map@^0.4.4: 166 | version "0.4.4" 167 | resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" 168 | dependencies: 169 | amdefine ">=0.0.4" 170 | 171 | source-map@~0.5.1: 172 | version "0.5.7" 173 | resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" 174 | 175 | uglify-js@^2.6: 176 | version "2.8.29" 177 | resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd" 178 | dependencies: 179 | source-map "~0.5.1" 180 | yargs "~3.10.0" 181 | optionalDependencies: 182 | uglify-to-browserify "~1.0.0" 183 | 184 | uglify-to-browserify@~1.0.0: 185 | version "1.0.2" 186 | resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" 187 | 188 | window-size@0.1.0: 189 | version "0.1.0" 190 | resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" 191 | 192 | wordwrap@0.0.2: 193 | version "0.0.2" 194 | resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" 195 | 196 | wordwrap@~0.0.2: 197 | version "0.0.3" 198 | resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" 199 | 200 | wrappy@1: 201 | version "1.0.2" 202 | resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" 203 | 204 | yargs@~3.10.0: 205 | version "3.10.0" 206 | resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" 207 | dependencies: 208 | camelcase "^1.0.2" 209 | cliui "^2.1.0" 210 | decamelize "^1.0.0" 211 | window-size "0.1.0" 212 | -------------------------------------------------------------------------------- /cjs-loader.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Google Inc. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 | * use this file except in compliance with the License. You may obtain a copy of 6 | * the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations under 14 | * the License. 15 | */ 16 | 17 | /** 18 | * @fileoverview Transitively includes commonJS modules for use on the web. 19 | * 20 | * This is a successful but terrible idea and should not be used by anyone. 21 | */ 22 | 23 | import * as utils from './utils.js'; 24 | 25 | const config = { 26 | global: window, 27 | location: window.location.href, // take initial copy 28 | modules: 'node_modules', 29 | path: null, 30 | }; 31 | 32 | config.global.define = define; 33 | config.global.require = require; 34 | 35 | let state = undefined; 36 | let globalExports = undefined; 37 | let defined = undefined; 38 | 39 | Object.defineProperty(config.global, 'exports', { 40 | get() { 41 | // we were fetched, great 42 | if (globalExports === undefined) { 43 | globalExports = {}; 44 | } 45 | return globalExports; 46 | }, 47 | set(v) { 48 | // we were set, that's also fine, implicitly clears undefined 49 | globalExports = v; 50 | }, 51 | }) 52 | 53 | config.global.module = { 54 | get exports() { 55 | return config.global.exports; 56 | }, 57 | set exports(v) { 58 | config.global.exports = v; 59 | }, 60 | }; 61 | 62 | class CacheEntry { 63 | /** 64 | * @param {*=} value 65 | */ 66 | constructor(value = undefined) { 67 | this.value = value; 68 | this.done = null; 69 | 70 | if (value === undefined) { 71 | this.p = new Promise((resolve, reject) => { 72 | this.done = (v) => { 73 | v instanceof Error ? reject(v) : resolve(v); 74 | this.done = null; 75 | }; 76 | }); 77 | this.p.then((v) => this.value = v); 78 | this.p.catch((err) => this.value = err); 79 | } else { 80 | this.p = Promise.resolve(value); 81 | } 82 | } 83 | } 84 | 85 | /** 86 | * @type {!Object} 87 | */ 88 | const cache = { 89 | 'require': new CacheEntry(require), 90 | 'module': new CacheEntry(config.global.module), 91 | }; 92 | 93 | class FakeRequireError { 94 | constructor(state, required) { 95 | this.state = state; 96 | this.required = required; 97 | } 98 | } 99 | window.addEventListener('error', (ev) => { 100 | const e = ev.error; 101 | if (!(e instanceof FakeRequireError)) { return; } 102 | 103 | ev.preventDefault(); 104 | ev.stopPropagation(); 105 | 106 | // load the module that was require()'d, and then reload the thing it depended on 107 | load(e.required).then(() => { 108 | reload(e.state.id, e.state.url); 109 | }); 110 | }); 111 | 112 | /** 113 | * @param {string} id 114 | * @return {*} literally anything exported 115 | */ 116 | function require(id) { 117 | let url = resolvePath(id); 118 | if (url !== null) { 119 | id = url; 120 | } 121 | 122 | const entry = cache[id]; 123 | if (entry === undefined) { 124 | // TODO: don't throw immediately, get as many require() calls as possible 125 | throw new FakeRequireError(state, id); 126 | } else if (entry.value === undefined) { 127 | throw new TypeError(`require() module not ready: ${id}`); 128 | } else if (entry.value instanceof Error) { 129 | throw entry.value; 130 | } 131 | return entry.value; 132 | } 133 | 134 | /** 135 | * @param {...(string|!Array|!Function)} args 136 | */ 137 | function define(...args) { 138 | if (defined !== undefined) { 139 | // TODO: this could be supported (although we only know 'requester' ID) 140 | throw new Error('cjs-loader had define() called multiple times') 141 | } 142 | defined = utils.argsForDefine(args); // store for later 143 | } 144 | 145 | /** 146 | * https://github.com/jquery/jquery/pull/331#issue-779774 147 | * 148 | * @type {!Object} 149 | */ 150 | define.amd = {jQuery: true}; 151 | 152 | export async function load(id) { 153 | let url = resolvePath(id); 154 | if (url === null) { 155 | // this is actually a node module, fetch package.json 156 | const request = await config.global.fetch(`./${config.modules}/${id}/package.json`); 157 | const json = await request.json(); 158 | const cand = `./${config.modules}/${id}/${(json['main'] || 'index.js')}`; 159 | url = resolvePath(cand); 160 | } else { 161 | id = url; // absolute fetch uses URL as id 162 | } 163 | 164 | if (id in cache) { 165 | return cache[id].p; 166 | } 167 | const entry = new CacheEntry(); 168 | cache[id] = entry; 169 | 170 | reload(id, url); 171 | 172 | return entry.p; 173 | } 174 | 175 | let scriptCount = 0; // used to force rerun, but _not_ reload 176 | 177 | function reload(id, url) { 178 | if (!config.path) { 179 | throw new Error('cjs-loader needs setup() called with its path') 180 | } 181 | const escape = (s) => s.replace(/'/g, '\\\''); 182 | 183 | // insert early script to setup scope 184 | utils.insertModuleScript(` 185 | import {env} from '${escape(config.path)}'; 186 | env('${escape(id)}', '${escape(url)}'); 187 | `); 188 | // TODO: we can use above to create/teardown globals 189 | 190 | // insert actual script 191 | const script = utils.insertModuleScript(` 192 | import {faker} from '../cjs-loader.js'; 193 | import '${escape(url)}#${++scriptCount}'; 194 | faker('${escape(id)}'); 195 | `); 196 | script.onerror = cache[id].done; // only for network/other errors 197 | } 198 | 199 | /** 200 | * @param {string} id 201 | * @return {string} absolute path, including domain 202 | */ 203 | function resolvePath(id) { 204 | try { 205 | // look for http://.. or similar 206 | const absolute = new URL(id); 207 | return absolute.href; 208 | } catch (e) { 209 | // nothing, this is fine 210 | } 211 | 212 | if (!id.includes('/')) { 213 | return null; // module 214 | } 215 | 216 | let pathname; 217 | const leadingPart = id.split('/', 1)[0]; 218 | switch (leadingPart) { 219 | case '': 220 | pathname = id; 221 | break; 222 | 223 | case '.': 224 | case '..': 225 | if (state) { 226 | // remove last component 227 | const dirname = state.url.substr(0, state.url.lastIndexOf('/')); 228 | pathname = `${dirname}/${id}`; 229 | } else { 230 | pathname = `${config.location}/${id}`; 231 | } 232 | break; 233 | 234 | default: 235 | pathname = `${config.location}/${config.modules}/${id}`; 236 | } 237 | 238 | // poor man's normalize 239 | const u = new URL(pathname, config.location); 240 | u.pathname = u.pathname.replace(/\/+/g, '/'); 241 | 242 | // FIXME: ugly hack to assume .js, needed for Handlebars, will break .json loading 243 | if (!u.pathname.endsWith('.js')) { 244 | u.pathname += '.js'; 245 | } 246 | return u.href; 247 | } 248 | 249 | /** 250 | * Store the current execution path until a call to faker. 251 | * 252 | * @param {string} id 253 | * @param {string} url 254 | */ 255 | export function env(id, url) { 256 | state = {id, url}; 257 | } 258 | 259 | /** 260 | * @param {string} id 261 | * @return {*} literally anything exported 262 | */ 263 | export function faker(id) { 264 | if (state.id !== id) { 265 | throw new Error(`invalid state.id=${state.id} id=${id}`); 266 | } 267 | state = undefined; 268 | const entry = cache[id]; 269 | 270 | if (defined === undefined) { 271 | entry.done(globalExports); 272 | globalExports = undefined; // clear 273 | return; 274 | } 275 | 276 | // TODO: check id vs defined for AMD 277 | const local = defined; 278 | const heldExports = globalExports; // in case the AMD module mucked with them before running 279 | defined = undefined; 280 | globalExports = undefined; 281 | 282 | // resolve dependencies 283 | const passedExports = {}; 284 | const passed = local.deps.map((dep) => { 285 | return dep === 'exports' ? passedExports : load(dep); 286 | }); 287 | entry.done(Promise.all(passed).then((all) => { 288 | // performs exports dance, see requireJS for some guidance: 289 | // https://github.com/requirejs/requirejs/blob/master/require.js#L886 290 | globalExports = heldExports; 291 | const returnedExports = local.fn.apply(config.global, all); 292 | const localExports = utils.withKeys(exports); // if global exports has no keys, assume unused 293 | globalExports = undefined; 294 | return returnedExports || localExports || passedExports; 295 | })); 296 | } 297 | 298 | /** 299 | * @param {string} path to cjs-loader 300 | */ 301 | export function setup(path) { 302 | config.path = path; 303 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------