Repository navigation
Expand file tree
/
Copy pathModule.java
More file actions
383 lines (314 loc) · 14 KB
/
Copy pathModule.java
File metadata and controls
383 lines (314 loc) · 14 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package com.tns;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
class Module {
private static String RootPackageDir;
private static String ApplicationFilesPath;
private static String ModulesFilesPath;
private static String NativeScriptModulesFilesPath;
private static int RootDirsCount;
private static boolean initialized = false;
private static String possibleException = null;
// cache the already resolved absolute paths to folder modules to prevent JSON parsing each time
private static final HashMap<String, String> folderAsModuleCache = new HashMap<String, String>();
private static boolean checkForExternalPath = false;
public static void init(Logger logger, File rootPackageDir, File applicationFilesDir) throws IOException {
if (initialized) {
return;
}
RootPackageDir = rootPackageDir.getCanonicalPath();
ApplicationFilesPath = applicationFilesDir.getCanonicalPath();
ModulesFilesPath = "/app/";
RootDirsCount = (ApplicationFilesPath + "/app").split("/").length;
NativeScriptModulesFilesPath = ApplicationFilesPath + "/app/tns_modules/tns-core-modules";
initialized = true;
}
static String getApplicationFilesPath() {
return ApplicationFilesPath;
}
/**
* Resolves an entry-module path for runModule. A non-absolute, scheme-less
* name is an app-root-relative module name (the @JavaScriptImplementation
* convention) and goes through the same resolution require uses - extension
* and directory probing included - so the native side only ever receives a
* loadable identity: an absolute path or a URL. Missing entries throw here,
* with require's wording, instead of failing against the process cwd.
*/
static String resolveEntryPath(String path) {
if (path.isEmpty() || path.startsWith("/") || path.contains("://")) {
return path;
}
String relative = (path.startsWith("./") || path.startsWith("../") || path.startsWith("~/"))
? path
: "./" + path;
return resolvePath(relative, ApplicationFilesPath + ModulesFilesPath);
}
@RuntimeCallable
private static String resolvePath(String path, String baseDir) {
// The baseDir is the directory path of the calling module.
checkForExternalPath = true;
File file = null;
try {
file = resolvePathHelper(path, baseDir);
} catch (IOException e) {
//probably cache failed because of getCanonicalPath
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
String resolvedPath;
try {
resolvedPath = file.getCanonicalPath();
} catch (IOException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
resolvedPath = file.getAbsolutePath();
}
return resolvedPath;
}
private static boolean isFileExternal(File source, File target) {
File currentParentDir = source.getParentFile();
while (currentParentDir != null) {
if (currentParentDir.equals(target)) {
return false;
}
currentParentDir = currentParentDir.getParentFile();
}
return true;
}
private static File resolvePathHelper(String path, String baseDir) throws NativeScriptException, IOException { //think about special require exception inheriting NativeScriptException
File foundModule = null;
if (baseDir == null || baseDir.isEmpty() || path.startsWith("~/")) {
baseDir = ApplicationFilesPath + ModulesFilesPath;
}
// relative or absolute path
if (path.startsWith("./") || path.startsWith("../") || path.startsWith("~/") || path.startsWith("/")) {
File possibleRelativeAbsoluteModule = prepareRelativeOrAbsoluteDir(path, baseDir);
//cache
if (folderAsModuleCache.containsKey(possibleRelativeAbsoluteModule.getCanonicalPath())) {
return new File(folderAsModuleCache.get(possibleRelativeAbsoluteModule.getCanonicalPath()));
}
if (possibleRelativeAbsoluteModule != null) {
foundModule = resolveFromFileOrDirectory(baseDir, path, possibleRelativeAbsoluteModule);
if (foundModule != null) {
return foundModule;
}
}
} else { //native modules or traverse node_modules possiblilities
File possibleNativeModule = new File(NativeScriptModulesFilesPath, path);
//cache
if (folderAsModuleCache.containsKey(possibleNativeModule.getCanonicalPath())) {
return new File(folderAsModuleCache.get(possibleNativeModule.getCanonicalPath()));
}
foundModule = resolveFromFileOrDirectory(NativeScriptModulesFilesPath, path, possibleNativeModule);
if (foundModule != null) {
return foundModule;
}
// resolve through node_modules
List<String> possibleSearchDirs = nodeModulesPaths(baseDir);
for (String possibleDir : possibleSearchDirs) {
File possibleRelativeModule = new File(possibleDir, path);
//cache
if (folderAsModuleCache.containsKey(possibleRelativeModule.getCanonicalPath())) {
return new File(folderAsModuleCache.get(possibleRelativeModule.getCanonicalPath()));
}
foundModule = resolveFromFileOrDirectory(possibleDir, path, possibleRelativeModule);
if (foundModule != null) {
return foundModule;
}
}
}
//TODO: plamen5kov: implement later if necessary
// if (checkForExternalPath && isFileExternal(file, projectRootDir))
// {
// throw new NativeScriptException("Module " + path + " is an external path. You can only load modules inside the application!");
// }
// throw error if file could not be resolved
throw new NativeScriptException(possibleException);
}
private static File prepareRelativeOrAbsoluteDir(String path, String baseDir) {
File fileOrDirectory = null;
if (path.startsWith("/")) {
fileOrDirectory = new File(path);
} else if (path.startsWith("~/")) {
fileOrDirectory = new File(ApplicationFilesPath + ModulesFilesPath, path.substring(2));
} else if (path.startsWith("./") || path.startsWith("../")) {
fileOrDirectory = new File(baseDir, path);
}
return fileOrDirectory;
}
private static File resolveFromFileOrDirectory(String baseDir, String path, File fileOrDirectory) throws IOException {
File foundModule = null;
foundModule = loadAsFile(fileOrDirectory);
if (foundModule != null) {
return foundModule;
} else {
if (path.startsWith("~/")) {
possibleException = "Failed to find module: \"" + path + "\", relative to: " + ModulesFilesPath;
} else {
possibleException = "Failed to find module: \"" + path + "\", relative to: " + baseDir.substring(ApplicationFilesPath.length() + 1) + "/";
}
}
foundModule = loadAsDirectory(baseDir, path, fileOrDirectory);
//cache resolved directory
if (foundModule != null) {
folderAsModuleCache.put(fileOrDirectory.getCanonicalPath(), foundModule.getCanonicalPath());
return foundModule;
}
return foundModule;
}
//tries to load the path as a file, returns null if that's not possible
private static File loadAsFile(File path) {
boolean isJSFile = path.getName().endsWith(".js");
boolean isMJSFile = path.getName().endsWith(".mjs");
boolean isSOFile = path.getName().endsWith(".so");
boolean isJSONFile = path.getName().endsWith(".json");
if (isJSFile || isMJSFile || isJSONFile || isSOFile) {
// File already has an extension, try as-is
try {
File canonicalFile = path.getCanonicalFile();
if (canonicalFile.exists() && canonicalFile.isFile()) {
return path;
}
} catch (IOException e) {
// continue to try with extensions
}
} else {
// No extension provided, try .js first, then .mjs
File jsFile = new File(path.getAbsolutePath() + ".js");
try {
File canonicalFile = jsFile.getCanonicalFile();
if (canonicalFile.exists() && canonicalFile.isFile()) {
return jsFile;
}
} catch (IOException e) {
// continue to try .mjs
}
// Try .mjs extension
File mjsFile = new File(path.getAbsolutePath() + ".mjs");
try {
File canonicalFile = mjsFile.getCanonicalFile();
if (canonicalFile.exists() && canonicalFile.isFile()) {
return mjsFile;
}
} catch (IOException e) {
// return null
}
}
return null;
//TODO: plamen5kov: implement later if necessary
// If X is a file, load X as JavaScript text. STOP
// If X.node is a file, load X.node as binary addon. STOP
}
private static File loadAsDirectory(String baseDir, String currentPath, File path) {
File packageFile = new File(path, "/package.json");
File foundFile = null;
if (packageFile.exists()) {
try {
JSONObject object = FileSystem.readJSONFile(packageFile);
if (object != null) {
String mainFile = object.getString("main");
File pathFromMain = new File(path, mainFile);
foundFile = resolveFromFileOrDirectory(baseDir, currentPath, pathFromMain);
if (foundFile != null) {
return foundFile;
}
}
} catch (IOException e) {
throw new NativeScriptException(e.getMessage());
} catch (JSONException e) {
if (!e.getMessage().contains("No value for main")) {
throw new NativeScriptException(e.getMessage());
}
}
}
//fallback to index.js
foundFile = new File(path, "index.js");
try {
if (foundFile.getCanonicalFile().exists()) {
return foundFile;
}
} catch (IOException e) {
// continue to try index.mjs
}
//fallback to index.mjs
foundFile = new File(path, "index.mjs");
try {
if (foundFile.getCanonicalFile().exists()) {
return foundFile;
}
} catch (IOException e) {
return null;
}
//TODO: plamen5kov: add later if necessary
// If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
// 4. If X/index.node is a file, load X/index.node as binary addon. STOP
return null;
}
// lists all possible node_modules directories starting from "startDir"
private static List<String> nodeModulesPaths(String startDir) {
File startFile = new File(startDir);
String[] startDirParts = startFile.getAbsolutePath().split("/");
List<String> dirs = new LinkedList<String>();
for (String part : startDirParts) {
dirs.add(part);
}
List<String> possibleDirectories = new ArrayList<String>();
while (dirs.size() >= RootDirsCount) {
String lastDir = dirs.get(dirs.size() - 1);
if (lastDir.equals("node_modules") || lastDir.equals("tns_modules")) {
dirs.remove(dirs.size() -1);
continue;
}
String currentDir = TextUtils.join("/", dirs);
String finalDir = currentDir + "/node_modules";
//TODO: plamen5kov revisit this if we decide to get rid of tns_modules folder
if (lastDir.equals("app")) {
finalDir = currentDir + "/tns_modules";
}
possibleDirectories.add(finalDir);
dirs.remove(dirs.size() -1);
}
return possibleDirectories;
}
static String bootstrapApp() {
// Bootstrap logic flows like:
// 1. Check for package.json -> `main` field
// 2. Check for index.js
// 3. Check for bootstrap.js
String notFoundMessage = "Application entry point file not found. Please specify the file in package.json otherwise make sure the file index.js or bootstrap.js exists.\\nIf using typescript make sure your entry point file is transpiled to javascript.";
// resolvePathHelper() never returns a non-existing file. Instead it throws an exception.
File bootstrapFile = null;
try {
bootstrapFile = resolvePathHelper("./", "");
} catch (NativeScriptException ex) {
throw new NativeScriptException(notFoundMessage, ex);
} catch (IOException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
if (bootstrapFile == null) {
try {
bootstrapFile = resolvePathHelper("./bootstrap", "");
return bootstrapFile.getAbsolutePath();
} catch (NativeScriptException ex) {
throw new NativeScriptException(notFoundMessage, ex);
} catch (IOException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
}
return bootstrapFile.getAbsolutePath();
}
}