Skip to content

Commit

Permalink
More local web server stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
LatvianModder committed Aug 11, 2024
1 parent 85a63f0 commit 3b7ed56
Show file tree
Hide file tree
Showing 30 changed files with 451 additions and 121 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,9 @@
import dev.latvian.mods.kubejs.util.Tristate;
import dev.latvian.mods.kubejs.util.UtilsJS;
import dev.latvian.mods.kubejs.util.registrypredicate.RegistryPredicate;
import dev.latvian.mods.kubejs.web.KJSHTTPContext;
import dev.latvian.mods.kubejs.web.WebServerRegistry;
import dev.latvian.mods.kubejs.web.local.KubeJSWeb;
import dev.latvian.mods.rhino.type.RecordTypeInfo;
import dev.latvian.mods.rhino.type.TypeInfo;
import net.minecraft.commands.arguments.selector.EntitySelector;
Expand Down Expand Up @@ -704,4 +707,9 @@ public void clearCaches() {
public void registerDataComponentTypeDescriptions(DataComponentTypeInfoRegistry registry) {
// DataComponents.ATTRIBUTE_MODIFIERS
}

@Override
public void registerLocalWebServer(WebServerRegistry<KJSHTTPContext> registry) {
KubeJSWeb.register(registry);
}
}
16 changes: 11 additions & 5 deletions src/main/java/dev/latvian/mods/kubejs/KubeJS.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import dev.latvian.mods.kubejs.script.ScriptType;
import dev.latvian.mods.kubejs.script.data.KubeFileResourcePack;
import dev.latvian.mods.kubejs.util.RecordDefaults;
import dev.latvian.mods.kubejs.web.KubeJSLocalWebServer;
import dev.latvian.mods.kubejs.web.WebServerProperties;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.IEventBus;
Expand Down Expand Up @@ -76,19 +78,19 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable {
try {
Files.writeString(KubeJSPaths.README, """
Find out more info on the website: https://kubejs.com/
Directory information:
assets - Acts as a resource pack, you can put any client resources in here, like textures, models, etc. Example: assets/kubejs/textures/item/test_item.png
data - Acts as a datapack, you can put any server resources in here, like loot tables, functions, etc. Example: data/kubejs/loot_tables/blocks/test_block.json
startup_scripts - Scripts that get loaded once during game startup - Used for adding items and other things that can only happen while the game is loading (Can be reloaded with /kubejs reload_startup_scripts, but it may not work!)
server_scripts - Scripts that get loaded every time server resources reload - Used for modifying recipes, tags, loot tables, and handling server events (Can be reloaded with /reload)
client_scripts - Scripts that get loaded every time client resources reload - Used for JEI events, tooltips and other client side things (Can be reloaded with F3+T)
config - KubeJS config storage. This is also the only directory that scripts can access other than world directory
exported - Data dumps like texture atlases end up here
You can find type-specific logs in logs/kubejs/ directory
""".trim()
);
Expand Down Expand Up @@ -159,5 +161,9 @@ public KubeJS(IEventBus bus, Dist dist, ModContainer mod) throws Throwable {

StartupEvents.INIT.post(ScriptType.STARTUP, KubeStartupEvent.BASIC);
// KubeJSRegistries.chunkGenerators().register(new ResourceLocation(KubeJS.MOD_ID, "flat"), () -> KJSFlatLevelSource.CODEC);

if (!datagen && WebServerProperties.get().enabled && (dist == Dist.CLIENT || !WebServerProperties.get().publicAddress.isEmpty())) {
KubeJSLocalWebServer.start();
}
}
}
4 changes: 4 additions & 0 deletions src/main/java/dev/latvian/mods/kubejs/KubeJSCommon.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,8 @@ public void runInMainThread(Runnable runnable) {

public void updateServerData(KubeServerData data) {
}

public String getWebServerWindowTitle() {
return "Dedicated Server";
}
}
1 change: 1 addition & 0 deletions src/main/java/dev/latvian/mods/kubejs/KubeJSPaths.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ static Path dir(Path dir) {
Path README = DIRECTORY.resolve("README.txt");
Path LOCAL = dir(GAMEDIR.resolve("local").resolve("kubejs"));
Path LOCAL_CACHE = dir(LOCAL.resolve("cache"));
Path LOCAL_WEB_IMG_CACHE = dir(LOCAL_CACHE.resolve("web/img"));
Path LOCAL_DEV_PROPERTIES = LOCAL.resolve("dev.json");
Path EXPORT = dir(LOCAL.resolve("export"));
Path EXPORTED_PACKS = dir(LOCAL.resolve("exported_packs"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

import dev.latvian.mods.kubejs.KubeJS;
import dev.latvian.mods.kubejs.bindings.event.ClientEvents;
import dev.latvian.mods.kubejs.client.web.KubeJSWeb;
import dev.latvian.mods.kubejs.event.EventGroupRegistry;
import dev.latvian.mods.kubejs.plugin.KubeJSPlugin;
import dev.latvian.mods.kubejs.script.BindingRegistry;
import dev.latvian.mods.kubejs.script.PlatformWrapper;
import dev.latvian.mods.kubejs.util.ScheduledEvents;
import dev.latvian.mods.kubejs.web.KJSHTTPContext;
import dev.latvian.mods.kubejs.web.WebServerRegistry;
import dev.latvian.mods.kubejs.web.local.client.KubeJSClientWeb;
import net.minecraft.client.Minecraft;
import net.neoforged.fml.ModList;

Expand All @@ -35,7 +35,7 @@ public void registerBindings(BindingRegistry bindings) {

@Override
public void registerLocalWebServer(WebServerRegistry<KJSHTTPContext> registry) {
KubeJSWeb.register(registry);
KubeJSClientWeb.register(registry);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,12 @@ public void updateServerData(KubeServerData data) {
}
}

@Override
public String getWebServerWindowTitle() {
var mc = Minecraft.getInstance();
return mc.getGameProfile().getName() + ", " + mc.kjs$getTitle();
}

public static void loadPostChains(Minecraft mc) {
KubedexHighlight.INSTANCE.loadPostChains(mc);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public void render(GuiGraphics g, int idx, int y, int x, int w, int h, int mx, i
var lines = new ArrayList<FormattedCharSequence>();

for (var line : line.sourceLines) {
lines.add(Component.literal(line.toString()).getVisualOrderText());
lines.add(Component.empty().append(Component.literal(line.source()).kjs$gray()).append("#" + line.line()).getVisualOrderText());
}

errorList.screen.setTooltipForNextRenderPass(lines);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,9 @@
import dev.latvian.mods.kubejs.item.ModifyItemTooltipsKubeEvent;
import dev.latvian.mods.kubejs.kubedex.KubedexHighlight;
import dev.latvian.mods.kubejs.registry.RegistryObjectStorage;
import dev.latvian.mods.kubejs.script.PlatformWrapper;
import dev.latvian.mods.kubejs.script.ScriptType;
import dev.latvian.mods.kubejs.text.tooltip.ItemTooltipData;
import dev.latvian.mods.kubejs.util.ID;
import dev.latvian.mods.kubejs.web.KubeJSLocalWebServer;
import dev.latvian.mods.kubejs.web.WebServerProperties;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
Expand Down Expand Up @@ -102,10 +99,6 @@ private static void setupClient0() {
var list = new ArrayList<ItemTooltipData>();
ItemEvents.MODIFY_TOOLTIPS.post(ScriptType.CLIENT, new ModifyItemTooltipsKubeEvent(list::add));
KubeJSClient.clientItemTooltips = List.copyOf(list);

if (!PlatformWrapper.isGeneratingData() && WebServerProperties.get().enabled) {
KubeJSLocalWebServer.start();
}
}

@SubscribeEvent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@

import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public interface DataComponentWrapper {
DynamicCommandExceptionType ERROR_UNKNOWN_COMPONENT = new DynamicCommandExceptionType((object) -> Component.translatableEscape("arguments.item.component.unknown", object));
Expand Down Expand Up @@ -58,6 +60,32 @@ public interface DataComponentWrapper {
return Map.copyOf(map);
});

Lazy<Set<DataComponentType<?>>> VISUAL_DIFFERENCE = Lazy.of(() -> {
var set = new HashSet<DataComponentType<?>>();

set.add(DataComponents.DAMAGE);
set.add(DataComponents.MAX_DAMAGE);
set.add(DataComponents.ENCHANTMENTS);
set.add(DataComponents.STORED_ENCHANTMENTS);
set.add(DataComponents.CUSTOM_MODEL_DATA);
set.add(DataComponents.ENCHANTMENT_GLINT_OVERRIDE);
set.add(DataComponents.DYED_COLOR);
set.add(DataComponents.MAP_COLOR);
set.add(DataComponents.POTION_CONTENTS);
set.add(DataComponents.TRIM);
set.add(DataComponents.ENTITY_DATA);
set.add(DataComponents.BLOCK_ENTITY_DATA);
set.add(DataComponents.FIREWORK_EXPLOSION);
set.add(DataComponents.FIREWORKS);
set.add(DataComponents.PROFILE);
set.add(DataComponents.BANNER_PATTERNS);
set.add(DataComponents.BASE_COLOR);
set.add(DataComponents.POT_DECORATIONS);
set.add(DataComponents.BLOCK_STATE);

return set;
});

static TypeInfo getTypeInfo(DataComponentType<?> type) {
return TYPE_INFOS.get().getOrDefault(type, TypeInfo.NONE);
}
Expand Down Expand Up @@ -292,4 +320,23 @@ static StringBuilder patchToString(StringBuilder builder, DynamicOps<Tag> dynami
builder.append(']');
return builder;
}

static void writeVisualComponentsForCache(StringBuilder builder, DynamicOps<?> ops, DataComponentMap map) {
for (var entry : map) {
if (DataComponentWrapper.VISUAL_DIFFERENCE.get().contains(entry.type())) {
builder.append(BuiltInRegistries.DATA_COMPONENT_TYPE.getKey(entry.type()));

if (entry.type().codec() != null) {
if (entry.value() instanceof CharSequence || entry.value() instanceof Number || entry.value() instanceof Boolean || entry.value() instanceof Tag) {
builder.append(entry.value());
} else {
var str = entry.type().codec().encodeStart(ops, Cast.to(entry.value())).result().map(Object::toString).orElse("");
builder.append(str.isEmpty() ? entry.value() : str);
}
} else {
builder.append(entry.value());
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ public class EmptyRecipeComponentException extends KubeRuntimeException {
public EmptyRecipeComponentException(RecipeComponent<?> component) {
super("Component '" + component + "' is not allowed to be empty!");
this.component = component;

customData("invalid_component", component.toString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ public class EmptyRecipeComponentValueException extends KubeRuntimeException {
public EmptyRecipeComponentValueException(RecipeComponent<?> component) {
super("Component '" + component + "' is not allowed to contain empty values!");
this.component = component;

customData("invalid_component", component.toString());
}
}
12 changes: 0 additions & 12 deletions src/main/java/dev/latvian/mods/kubejs/error/EmptyTagException.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,8 @@ public class InvalidRecipeComponentException extends KubeRuntimeException {
public InvalidRecipeComponentException(RecipeComponentValue<?> h, Throwable cause) {
super("Invalid component '" + h.key.name + "' (" + h.key.component + ")", cause);
this.componentValueHolder = h;

customData("key_name", h.key.name);
customData("key_component", h.key.component.toString());
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
package dev.latvian.mods.kubejs.error;

import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import dev.latvian.mods.kubejs.script.ConsoleLine;
import dev.latvian.mods.kubejs.script.SourceLine;
import dev.latvian.mods.kubejs.util.MutedError;
import dev.latvian.mods.rhino.RhinoException;

public class KubeRuntimeException extends RuntimeException implements MutedError {
public SourceLine sourceLine;
private SourceLine sourceLine;
private JsonObject customData;

public KubeRuntimeException(String m) {
super(m);
Expand Down Expand Up @@ -45,4 +52,41 @@ public KubeRuntimeException source(SourceLine sourceLine) {

return this;
}

public KubeRuntimeException customData(String key, JsonElement data) {
if (customData == null) {
customData = new JsonObject();
}

customData.add(key, data);
return this;
}

public KubeRuntimeException customData(String key, String value) {
return customData(key, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
}

public void apply(ConsoleLine line) {
Throwable c = this;

while (c != null) {
if (c instanceof KubeRuntimeException ex) {
line.withSourceLine(ex.sourceLine);

if (ex.customData != null) {
for (var entry : ex.customData.entrySet()) {
line.customData(entry.getKey(), entry.getValue(), false);
}
}
}

if (c instanceof RhinoException ex) {
if (ex.lineSource() != null) {
line.withSourceLine(ex.lineSource(), ex.lineNumber());
}
}

c = c.getCause();
}
}
}
24 changes: 21 additions & 3 deletions src/main/java/dev/latvian/mods/kubejs/script/ConsoleJS.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.latvian.mods.kubejs.script;

import com.google.gson.JsonArray;
import dev.latvian.mods.kubejs.DevProperties;
import dev.latvian.mods.kubejs.bindings.TextIcons;
import dev.latvian.mods.kubejs.error.KubeRuntimeException;
Expand All @@ -12,6 +13,7 @@
import dev.latvian.mods.kubejs.util.WrappedJS;
import dev.latvian.mods.kubejs.web.KJSHTTPContext;
import dev.latvian.mods.kubejs.web.http.HTTPResponse;
import dev.latvian.mods.kubejs.web.http.SimpleHTTPResponse;
import dev.latvian.mods.kubejs.web.ws.WSHandler;
import dev.latvian.mods.rhino.Context;
import dev.latvian.mods.rhino.ContextFactory;
Expand Down Expand Up @@ -176,7 +178,7 @@ private ConsoleLine line(LogType type, SourceLine sourceLine, Object object, @Nu
line.withSourceLine(sourceLine);

if (error instanceof KubeRuntimeException ex) {
line.withSourceLine(ex.sourceLine);
ex.apply(line);
}

if (error instanceof RhinoException ex) {
Expand Down Expand Up @@ -604,10 +606,26 @@ public int compareTo(VarFunc o) {
}

public HTTPResponse getErrorsResponse(KJSHTTPContext ctx) {
return HTTPResponse.NO_CONTENT;
return SimpleHTTPResponse.lazyJson(() -> {
var json = new JsonArray();

for (var error : errors) {
json.add(error.toJson());
}

return json;
});
}

public HTTPResponse getWarningsResponse(KJSHTTPContext ctx) {
return HTTPResponse.NO_CONTENT;
return SimpleHTTPResponse.lazyJson(() -> {
var json = new JsonArray();

for (var error : warnings) {
json.add(error.toJson());
}

return json;
});
}
}
Loading

0 comments on commit 3b7ed56

Please sign in to comment.