package com.thebrokenrail.scriptcraft.core.quickjs; import com.thebrokenrail.scriptcraft.core.ScriptCraftCore; import com.thebrokenrail.scriptcraft.core.ScriptCraftEntryPoint; import net.fabricmc.loader.api.FabricLoader; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @SuppressWarnings("unused") public class QuickJSModules { private static boolean isDirectory(String data, String path, Class clazz) { String[] lines = data.split("\n"); for (String line : lines) { InputStream stream = clazz.getResourceAsStream(path + File.separator + line); return stream != null; } return false; } public static String loadModule(String name) { List mods = FabricLoader.getInstance().getEntrypoints(ScriptCraftCore.NAMESPACE, ScriptCraftEntryPoint.class); for (ScriptCraftEntryPoint mod : mods) { //noinspection CatchMayIgnoreException try { String path = File.separator + ScriptCraftCore.NAMESPACE + File.separator + name; InputStream stream = mod.getClass().getResourceAsStream(path); if (stream != null) { StringBuilder textBuilder = new StringBuilder(); try (Reader reader = new BufferedReader(new InputStreamReader(stream))) { int c; while ((c = reader.read()) != -1) { textBuilder.append((char) c); } } stream.close(); return isDirectory(textBuilder.toString(), path, mod.getClass()) ? null : textBuilder.toString(); } } catch (IOException e) { } } return null; } private static final String[] SUPPORTED_EXTENSIONS; static { final String[] supportedExtensions = new String[]{"", ".js", ".json", ".mjs"}; SUPPORTED_EXTENSIONS = new String[supportedExtensions.length * 2]; for (int i = 0; i < supportedExtensions.length; i++) { SUPPORTED_EXTENSIONS[i + supportedExtensions.length] = File.separator + "index" + supportedExtensions[i]; SUPPORTED_EXTENSIONS[i] = supportedExtensions[i]; } } public static String normalizeModule(String baseName, String name) { String normalizedPath; baseName = baseName.replaceAll("/", File.separator); name = name.replaceAll("/", File.separator); if (name.startsWith(".")) { Path parentPath = Paths.get(baseName).getParent(); if (parentPath == null) { parentPath = Paths.get(File.separator); } normalizedPath = Paths.get(parentPath.toString(), name).normalize().toString(); if (normalizedPath.charAt(0) == File.separatorChar) { normalizedPath = normalizedPath.substring(1); } } else { normalizedPath = name; } for (String extension : SUPPORTED_EXTENSIONS) { if (loadModule(normalizedPath + extension) != null) { return normalizedPath + extension; } } return normalizedPath; } }