This repository has been archived by the owner on Mar 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjvm-npm.js
293 lines (261 loc) · 7.54 KB
/
jvm-npm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
* Copyright 2014-2016 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Since we intend to use the Function constructor.
/* jshint evil: true */
//module = (typeof module === 'undefined') ? {} : module;
let java = Packages.java
let NativeRequire = {}
let require = {}
let module = {}
var System = java.lang.System
var Scanner = java.util.Scanner
var File = java.io.File
NativeRequire = typeof NativeRequire === 'undefined' ? {} : NativeRequire
if (typeof require === 'function' && !NativeRequire.require) {
NativeRequire.require = require
}
class Module {
constructor(id, parent, core) {
this.id = id
this.core = core
this.parent = parent
this.children = []
this.filename = id
this.loaded = false
Object.defineProperty(this, 'exports', {
get: function () {
return this._exports
}.bind(this),
set: function (val) {
Require.cache[this.filename] = val
this._exports = val
}.bind(this),
})
this.exports = {}
if (parent && parent.children) parent.children.push(this)
this.require = function (id) {
return Require(id, this)
}.bind(this)
}
static _load(file, parent, core, main) {
var module = new Module(file, parent, core)
var body = readFile(module.filename, module.core)
var dir = new File(module.filename).getParent()
var args = ['exports', 'module', 'require', '__filename', '__dirname']
var func = new Function(args, body)
func.apply(module, [module.exports, module, module.require, module.filename, dir])
module.loaded = true
module.main = main
return module.exports
}
static runMain(main) {
var file = Require.resolve(main)
Module._load(file, undefined, false, true)
}
}
function Require(id, parent) {
var core
var native_
var file = Require.resolve(id, parent)
if (!file) {
if (typeof NativeRequire.require === 'function') {
if (Require.debug) {
System.out.println(['Cannot resolve', id, 'defaulting to native'].join(' '))
}
native_ = NativeRequire.require(id)
if (native_) return native_
}
System.err.println('Cannot find module ' + id)
throw new ModuleError('Cannot find module ' + id, 'MODULE_NOT_FOUND')
}
if (file.core) {
file = file.path
core = true
}
try {
if (Require.cache[file]) {
return Require.cache[file]
} else if (file.endsWith('.js')) {
return Module._load(file, parent, core)
} else if (file.endsWith('.json')) {
return loadJSON(file)
}
} catch (ex) {
if (ex instanceof java.lang.Exception) {
throw new ModuleError('Cannot load module ' + id, 'LOAD_ERROR', ex)
} else {
System.out.println('Cannot load module ' + id + ' LOAD_ERROR')
throw ex
}
}
}
Require.resolve = function (id, parent) {
var roots = findRoots(parent)
for (var i = 0; i < roots.length; ++i) {
var root = roots[i]
var result =
resolveCoreModule(id, root) ||
resolveAsFile(id, root, '.js') ||
resolveAsFile(id, root, '.json') ||
resolveAsDirectory(id, root) ||
resolveAsNodeModule(id, root)
if (result) {
return result
}
}
return false
}
//Require.root = System.getProperty('user.dir');
Require.root = [compat.path, 'DIC'].join('/')
Require.NODE_PATH = undefined
function findRoots(parent) {
var r = []
r.push(findRoot(parent))
return r.concat(Require.paths())
}
function parsePaths(paths) {
if (!paths) {
return []
}
if (paths === '') {
return []
}
var osName = java.lang.System.getProperty('os.name').toLowerCase()
var separator
if (osName.indexOf('win') >= 0) {
separator = ';'
} else {
separator = ':'
}
return paths.split(separator)
}
Require.paths = function () {
var r = []
r.push(java.lang.System.getProperty('user.home') + '/.node_modules')
r.push(java.lang.System.getProperty('user.home') + '/.node_libraries')
if (Require.NODE_PATH) {
r = r.concat(parsePaths(Require.NODE_PATH))
} else {
var NODE_PATH = java.lang.System.getenv().NODE_PATH
if (NODE_PATH) {
r = r.concat(parsePaths(NODE_PATH))
}
}
// r.push( $PREFIX + "/node/library" )
return r
}
function findRoot(parent) {
if (!parent || !parent.id) {
return Require.root
}
var pathParts = parent.id.split(/[\/|\\,]+/g)
pathParts.pop()
return pathParts.join('/')
}
Require.debug = true
Require.cache = {}
Require.extensions = {}
require = Require
module.exports = Module
function loadJSON(file) {
var json = JSON.parse(readFile(file))
Require.cache[file] = json
return json
}
function resolveAsNodeModule(id, root) {
var base = [root, 'node_modules'].join('/')
return (
resolveAsFile(id, base) ||
resolveAsDirectory(id, base) ||
(root ? resolveAsNodeModule(id, new File(root).getParent()) : false)
)
}
function resolveAsDirectory(id, root) {
var base = [root, id].join('/')
var file = new File([base, 'package.json'].join('/'))
if (file.exists()) {
try {
var body = readFile(file.getCanonicalPath())
var package_ = JSON.parse(body)
if (package_.main) {
return resolveAsFile(package_.main, base) || resolveAsDirectory(package_.main, base)
}
// if no package.main exists, look for index.js
return resolveAsFile('index.js', base)
} catch (ex) {
throw new ModuleError('Cannot load JSON file', 'PARSE_ERROR', ex)
}
}
return resolveAsFile('index.js', base)
}
function resolveAsFile(id, root, ext) {
var file
if (id.length > 0 && id[0] === '/') {
file = new File(normalizeName(id, ext || '.js'))
if (!file.exists()) {
return resolveAsDirectory(id)
}
} else {
file = new File([root, normalizeName(id, ext || '.js')].join('/'))
}
if (file.exists()) {
return file.getCanonicalPath()
}
}
function resolveCoreModule(id, root) {
var name = normalizeName(id)
var classloader = java.lang.Thread.currentThread().getContextClassLoader()
if (classloader.getResource(name)) {
return { path: name, core: true }
}
}
function normalizeName(fileName, ext) {
var extension = ext || '.js'
if (fileName.endsWith(extension)) {
return fileName
}
return fileName + extension
}
function readFile(filename, core) {
var input
try {
if (core) {
var classloader = java.lang.Thread.currentThread().getContextClassLoader()
input = classloader.getResourceAsStream(filename)
} else {
input = new File(filename)
}
// TODO: I think this is not very efficient
return new Scanner(input).useDelimiter('\\A').next()
} catch (e) {
throw new ModuleError('Cannot read file [' + input + ']: ', 'IO_ERROR', e)
}
}
class ModuleError {
constructor(message, code, cause) {
this.code = code || 'UNDEFINED'
this.message = message || 'Error loading module'
this.cause = cause
}
}
// Helper function until ECMAScript 6 is complete
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
if (!suffix) return false
return this.indexOf(suffix, this.length - suffix.length) !== -1
}
}
ModuleError.prototype = new Error()