als-require
Advanced tools
Comparing version 0.1.0 to 0.2.0
41
index.js
@@ -1,39 +0,4 @@ | ||
const fs = require('fs') | ||
const { join } = require('path') | ||
function calledFrom() { | ||
const err = new Error() | ||
const stack = (err.stack || err.stacktrace) | ||
const pathes = [] | ||
const r = new RegExp(`${process.cwd().replace(/\\/g, '\\\\')}.*\.js`, 'g') | ||
stack.replace(r, (path) => { pathes.push(path) }) | ||
return pathes[pathes.length - 1] | ||
} | ||
const getModule = require('./lib/get-module') | ||
const Require = require('./lib/require') | ||
function getRequire(path, varName) { | ||
const calledPath = calledFrom() | ||
if (!path.endsWith('.js')) path += '.js' | ||
const fullPath = join(calledPath.split(/\\|\//).slice(0, -1).join('\\'), path) | ||
try { | ||
require(fullPath); | ||
} catch (error) { | ||
throw new Error(`Error loading module at ${fullPath}: ${error.message}`); | ||
} | ||
const modulPaths = new Set() | ||
let curModule = module.children.filter(mod => mod.filename.replace(/\\/g, '/').endsWith(path.replace(/^\./, '')))[0] | ||
function addFilename(mod) { | ||
if (modulPaths.has(mod.filename)) return | ||
modulPaths.add(mod.filename) | ||
mod.children.forEach(child => { | ||
addFilename(child) | ||
}); | ||
} | ||
addFilename(curModule) | ||
const obj = {} | ||
modulPaths.forEach(path => { | ||
obj[path.replace(__dirname, '').replace(/\\/g, '/')] = fs.readFileSync(path, 'utf-8') | ||
}); | ||
return `const ${varName} = getModule.buildModules(${JSON.stringify(obj)})` | ||
} | ||
module.exports = getRequire | ||
module.exports = { getModule, Require } |
{ | ||
"name": "als-require", | ||
"version": "0.1.0", | ||
"version": "0.2.0", | ||
"description": "A utility for using CommonJS require in the browser and creating bundles.", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -48,9 +48,9 @@ # als-require | ||
<body> | ||
<script src="node_modules/als-require/require.js"></script> | ||
<script> | ||
getModule('./module1/a.js') | ||
.then(exports => { | ||
window.test = exports.test(); | ||
}); | ||
</script> | ||
<script src="node_modules/als-require/require.js"></script> | ||
<script> | ||
getModule('./module1/a.js') | ||
.then(someExport => { | ||
window.someExport = someExport; | ||
}); | ||
</script> | ||
</body> | ||
@@ -68,4 +68,4 @@ </html> | ||
const fs = require('fs'); | ||
const getRequire = require('als-require'); | ||
const script = getRequire('./module1/a', 'test'); | ||
const { getModule , Require } = require('als-require'); | ||
const script = getModule('./module1/a', 'test'); // generates bundle from module | ||
fs.writeFileSync('test.js', script); | ||
@@ -77,5 +77,7 @@ ``` | ||
```javascript | ||
const content = getRequire('./module1/a', 'test'); | ||
const modules = new Require() | ||
modules.require('./module1/a', 'module1') | ||
modules.require('./some/b', 'module2') | ||
app.get('/bundle.js', (req, res) => { | ||
res.send(content); | ||
res.send(modules.script); // indludes browser's script (require.js) | ||
}); | ||
@@ -99,3 +101,3 @@ ``` | ||
```javascript | ||
const config = getRequire('./config', 'config'); | ||
const config = getModule('./config', 'config'); | ||
console.log(config); | ||
@@ -108,3 +110,3 @@ ``` | ||
try { | ||
const result = getRequire('./invalid/path', 'test'); | ||
const result = getModule('./invalid/path', 'test'); | ||
} catch (error) { | ||
@@ -111,0 +113,0 @@ console.error('Failed to load module:', error.message); |
const fs = require('fs') | ||
const {join} = require('path') | ||
const getRequire = require('../index') | ||
const script = getRequire('./module1/a','test') | ||
fs.writeFileSync(join(__dirname,'test.js'),script) | ||
const { join } = require('path') | ||
const { Require } = require('../index') | ||
const modules = new Require() | ||
modules.require('./module1/a','test') | ||
fs.writeFileSync(join(__dirname, 'test.js'), modules.script) |
const b = require('./sub/b') | ||
const c = require('./c') | ||
require('suncalc') | ||
// require('suncalc') | ||
const a = 'aaa' + b | ||
@@ -5,0 +5,0 @@ function test() { |
@@ -1,1 +0,62 @@ | ||
const test = getModule.buildModules({"/tests/module1/a.js":"const b = require('./sub/b')\r\nconst c = require('./c')\r\nrequire('suncalc')\r\nconst a = 'aaa' + b\r\nfunction test() {\r\n return a\r\n}\r\n\r\nmodule.exports = test","/tests/module1/sub/b.js":"const c = require('../c')\r\nconst b = 'bbb'+c\r\nmodule.exports = b\r\n","/tests/module1/c.js":"const c = 'ccc'\r\n\r\nmodule.exports = c","/node_modules/suncalc/suncalc.js":"/*\n (c) 2011-2015, Vladimir Agafonkin\n SunCalc is a JavaScript library for calculating sun/moon position and light phases.\n https://github.com/mourner/suncalc\n*/\n\n(function () { 'use strict';\n\n// shortcuts for easier to read formulas\n\nvar PI = Math.PI,\n sin = Math.sin,\n cos = Math.cos,\n tan = Math.tan,\n asin = Math.asin,\n atan = Math.atan2,\n acos = Math.acos,\n rad = PI / 180;\n\n// sun calculations are based on http://aa.quae.nl/en/reken/zonpositie.html formulas\n\n\n// date/time constants and conversions\n\nvar dayMs = 1000 * 60 * 60 * 24,\n J1970 = 2440588,\n J2000 = 2451545;\n\nfunction toJulian(date) { return date.valueOf() / dayMs - 0.5 + J1970; }\nfunction fromJulian(j) { return new Date((j + 0.5 - J1970) * dayMs); }\nfunction toDays(date) { return toJulian(date) - J2000; }\n\n\n// general calculations for position\n\nvar e = rad * 23.4397; // obliquity of the Earth\n\nfunction rightAscension(l, b) { return atan(sin(l) * cos(e) - tan(b) * sin(e), cos(l)); }\nfunction declination(l, b) { return asin(sin(b) * cos(e) + cos(b) * sin(e) * sin(l)); }\n\nfunction azimuth(H, phi, dec) { return atan(sin(H), cos(H) * sin(phi) - tan(dec) * cos(phi)); }\nfunction altitude(H, phi, dec) { return asin(sin(phi) * sin(dec) + cos(phi) * cos(dec) * cos(H)); }\n\nfunction siderealTime(d, lw) { return rad * (280.16 + 360.9856235 * d) - lw; }\n\nfunction astroRefraction(h) {\n if (h < 0) // the following formula works for positive altitudes only.\n h = 0; // if h = -0.08901179 a div/0 would occur.\n\n // formula 16.4 of \"Astronomical Algorithms\" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.\n // 1.02 / tan(h + 10.26 / (h + 5.10)) h in degrees, result in arc minutes -> converted to rad:\n return 0.0002967 / Math.tan(h + 0.00312536 / (h + 0.08901179));\n}\n\n// general sun calculations\n\nfunction solarMeanAnomaly(d) { return rad * (357.5291 + 0.98560028 * d); }\n\nfunction eclipticLongitude(M) {\n\n var C = rad * (1.9148 * sin(M) + 0.02 * sin(2 * M) + 0.0003 * sin(3 * M)), // equation of center\n P = rad * 102.9372; // perihelion of the Earth\n\n return M + C + P + PI;\n}\n\nfunction sunCoords(d) {\n\n var M = solarMeanAnomaly(d),\n L = eclipticLongitude(M);\n\n return {\n dec: declination(L, 0),\n ra: rightAscension(L, 0)\n };\n}\n\n\nvar SunCalc = {};\n\n\n// calculates sun position for a given date and latitude/longitude\n\nSunCalc.getPosition = function (date, lat, lng) {\n\n var lw = rad * -lng,\n phi = rad * lat,\n d = toDays(date),\n\n c = sunCoords(d),\n H = siderealTime(d, lw) - c.ra;\n\n return {\n azimuth: azimuth(H, phi, c.dec),\n altitude: altitude(H, phi, c.dec)\n };\n};\n\n\n// sun times configuration (angle, morning name, evening name)\n\nvar times = SunCalc.times = [\n [-0.833, 'sunrise', 'sunset' ],\n [ -0.3, 'sunriseEnd', 'sunsetStart' ],\n [ -6, 'dawn', 'dusk' ],\n [ -12, 'nauticalDawn', 'nauticalDusk'],\n [ -18, 'nightEnd', 'night' ],\n [ 6, 'goldenHourEnd', 'goldenHour' ]\n];\n\n// adds a custom time to the times config\n\nSunCalc.addTime = function (angle, riseName, setName) {\n times.push([angle, riseName, setName]);\n};\n\n\n// calculations for sun times\n\nvar J0 = 0.0009;\n\nfunction julianCycle(d, lw) { return Math.round(d - J0 - lw / (2 * PI)); }\n\nfunction approxTransit(Ht, lw, n) { return J0 + (Ht + lw) / (2 * PI) + n; }\nfunction solarTransitJ(ds, M, L) { return J2000 + ds + 0.0053 * sin(M) - 0.0069 * sin(2 * L); }\n\nfunction hourAngle(h, phi, d) { return acos((sin(h) - sin(phi) * sin(d)) / (cos(phi) * cos(d))); }\nfunction observerAngle(height) { return -2.076 * Math.sqrt(height) / 60; }\n\n// returns set time for the given sun altitude\nfunction getSetJ(h, lw, phi, dec, n, M, L) {\n\n var w = hourAngle(h, phi, dec),\n a = approxTransit(w, lw, n);\n return solarTransitJ(a, M, L);\n}\n\n\n// calculates sun times for a given date, latitude/longitude, and, optionally,\n// the observer height (in meters) relative to the horizon\n\nSunCalc.getTimes = function (date, lat, lng, height) {\n\n height = height || 0;\n\n var lw = rad * -lng,\n phi = rad * lat,\n\n dh = observerAngle(height),\n\n d = toDays(date),\n n = julianCycle(d, lw),\n ds = approxTransit(0, lw, n),\n\n M = solarMeanAnomaly(ds),\n L = eclipticLongitude(M),\n dec = declination(L, 0),\n\n Jnoon = solarTransitJ(ds, M, L),\n\n i, len, time, h0, Jset, Jrise;\n\n\n var result = {\n solarNoon: fromJulian(Jnoon),\n nadir: fromJulian(Jnoon - 0.5)\n };\n\n for (i = 0, len = times.length; i < len; i += 1) {\n time = times[i];\n h0 = (time[0] + dh) * rad;\n\n Jset = getSetJ(h0, lw, phi, dec, n, M, L);\n Jrise = Jnoon - (Jset - Jnoon);\n\n result[time[1]] = fromJulian(Jrise);\n result[time[2]] = fromJulian(Jset);\n }\n\n return result;\n};\n\n\n// moon calculations, based on http://aa.quae.nl/en/reken/hemelpositie.html formulas\n\nfunction moonCoords(d) { // geocentric ecliptic coordinates of the moon\n\n var L = rad * (218.316 + 13.176396 * d), // ecliptic longitude\n M = rad * (134.963 + 13.064993 * d), // mean anomaly\n F = rad * (93.272 + 13.229350 * d), // mean distance\n\n l = L + rad * 6.289 * sin(M), // longitude\n b = rad * 5.128 * sin(F), // latitude\n dt = 385001 - 20905 * cos(M); // distance to the moon in km\n\n return {\n ra: rightAscension(l, b),\n dec: declination(l, b),\n dist: dt\n };\n}\n\nSunCalc.getMoonPosition = function (date, lat, lng) {\n\n var lw = rad * -lng,\n phi = rad * lat,\n d = toDays(date),\n\n c = moonCoords(d),\n H = siderealTime(d, lw) - c.ra,\n h = altitude(H, phi, c.dec),\n // formula 14.1 of \"Astronomical Algorithms\" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.\n pa = atan(sin(H), tan(phi) * cos(c.dec) - sin(c.dec) * cos(H));\n\n h = h + astroRefraction(h); // altitude correction for refraction\n\n return {\n azimuth: azimuth(H, phi, c.dec),\n altitude: h,\n distance: c.dist,\n parallacticAngle: pa\n };\n};\n\n\n// calculations for illumination parameters of the moon,\n// based on http://idlastro.gsfc.nasa.gov/ftp/pro/astro/mphase.pro formulas and\n// Chapter 48 of \"Astronomical Algorithms\" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.\n\nSunCalc.getMoonIllumination = function (date) {\n\n var d = toDays(date || new Date()),\n s = sunCoords(d),\n m = moonCoords(d),\n\n sdist = 149598000, // distance from Earth to Sun in km\n\n phi = acos(sin(s.dec) * sin(m.dec) + cos(s.dec) * cos(m.dec) * cos(s.ra - m.ra)),\n inc = atan(sdist * sin(phi), m.dist - sdist * cos(phi)),\n angle = atan(cos(s.dec) * sin(s.ra - m.ra), sin(s.dec) * cos(m.dec) -\n cos(s.dec) * sin(m.dec) * cos(s.ra - m.ra));\n\n return {\n fraction: (1 + cos(inc)) / 2,\n phase: 0.5 + 0.5 * inc * (angle < 0 ? -1 : 1) / Math.PI,\n angle: angle\n };\n};\n\n\nfunction hoursLater(date, h) {\n return new Date(date.valueOf() + h * dayMs / 24);\n}\n\n// calculations for moon rise/set times are based on http://www.stargazing.net/kepler/moonrise.html article\n\nSunCalc.getMoonTimes = function (date, lat, lng, inUTC) {\n var t = new Date(date);\n if (inUTC) t.setUTCHours(0, 0, 0, 0);\n else t.setHours(0, 0, 0, 0);\n\n var hc = 0.133 * rad,\n h0 = SunCalc.getMoonPosition(t, lat, lng).altitude - hc,\n h1, h2, rise, set, a, b, xe, ye, d, roots, x1, x2, dx;\n\n // go in 2-hour chunks, each time seeing if a 3-point quadratic curve crosses zero (which means rise or set)\n for (var i = 1; i <= 24; i += 2) {\n h1 = SunCalc.getMoonPosition(hoursLater(t, i), lat, lng).altitude - hc;\n h2 = SunCalc.getMoonPosition(hoursLater(t, i + 1), lat, lng).altitude - hc;\n\n a = (h0 + h2) / 2 - h1;\n b = (h2 - h0) / 2;\n xe = -b / (2 * a);\n ye = (a * xe + b) * xe + h1;\n d = b * b - 4 * a * h1;\n roots = 0;\n\n if (d >= 0) {\n dx = Math.sqrt(d) / (Math.abs(a) * 2);\n x1 = xe - dx;\n x2 = xe + dx;\n if (Math.abs(x1) <= 1) roots++;\n if (Math.abs(x2) <= 1) roots++;\n if (x1 < -1) x1 = x2;\n }\n\n if (roots === 1) {\n if (h0 < 0) rise = i + x1;\n else set = i + x1;\n\n } else if (roots === 2) {\n rise = i + (ye < 0 ? x2 : x1);\n set = i + (ye < 0 ? x1 : x2);\n }\n\n if (rise && set) break;\n\n h0 = h2;\n }\n\n var result = {};\n\n if (rise) result.rise = hoursLater(t, rise);\n if (set) result.set = hoursLater(t, set);\n\n if (!rise && !set) result[ye > 0 ? 'alwaysUp' : 'alwaysDown'] = true;\n\n return result;\n};\n\n\n// export as Node module / AMD module / browser variable\nif (typeof exports === 'object' && typeof module !== 'undefined') module.exports = SunCalc;\nelse if (typeof define === 'function' && define.amd) define(SunCalc);\nelse window.SunCalc = SunCalc;\n\n}());\n"}) | ||
async function getModule(path, errors = []) { | ||
const modules = {} | ||
const dependencies = [] | ||
async function getContent(path, relative) { | ||
if(!path.startsWith('.')) return // don't include node_modules modules | ||
path = getModule.getFullPath(path, relative) | ||
if(relative !== '') { | ||
if(dependencies.includes(relative+path)) throw `cyclic dependency between ${relative} and ${path}` | ||
else dependencies.push(path+relative) | ||
} | ||
if (modules[path] !== undefined) return | ||
const children = [] | ||
let response = await fetch(path) | ||
if(!response.ok) throw new Error(`HTTP error! status: ${response.status}`); | ||
const content = await response.text() | ||
content.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm, (match, modulePath) => { | ||
children.push(modulePath); | ||
}); | ||
modules[path] = content | ||
for (let childPath of children) { | ||
await getContent(childPath, path) | ||
} | ||
} | ||
if(path) await getContent(path, '') | ||
return getModule.buildModules(modules,errors) | ||
} | ||
getModule.getFullPath = function getFullPath(path, relative) { | ||
let sliceTo = -1 | ||
if (path.startsWith('../')) { | ||
path = path.slice(1) | ||
sliceTo = -2 | ||
} | ||
if (!path.endsWith('.js')) path = path + '.js' | ||
if (relative !== '') { | ||
let dir = relative.split('/').slice(0, sliceTo).join('/') | ||
path = dir + path.replace(/^\.\//, '/') | ||
} | ||
return path | ||
} | ||
getModule.buildModules = function buildModules(modules,errors = []) { | ||
let currentModule = ''; | ||
function require(path) { | ||
path = getModule.getFullPath(path, currentModule) | ||
return modules[path] | ||
} | ||
const keys = Object.keys(modules).reverse() | ||
keys.forEach(path => { | ||
const module = {} | ||
currentModule = path | ||
try { new Function('module', 'require', modules[path])(module, require) } | ||
catch (error) { errors.push(error) } | ||
if (module.exports) modules[path] = module.exports | ||
else modules[path] = module | ||
}) | ||
const result = modules[keys[keys.length - 1]] | ||
return result | ||
} | ||
const test = getModule.buildModules({"E:/Dropbox/Projects/npm/node/als-require/0.2.0/tests/module1/a.js":"const b = require('./sub/b')\r\nconst c = require('./c')\r\n// require('suncalc')\r\nconst a = 'aaa' + b\r\nfunction test() {\r\n return a\r\n}\r\n\r\nmodule.exports = test","E:/Dropbox/Projects/npm/node/als-require/0.2.0/tests/module1/sub/b.js":"const c = require('../c')\r\nconst b = 'bbb'+c\r\nmodule.exports = b\r\n","E:/Dropbox/Projects/npm/node/als-require/0.2.0/tests/module1/c.js":"const c = 'ccc'\r\n\r\nmodule.exports = c"}) |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
17
194
111
13528
5
3