exaV / screeps-kotlin-starter

A starting point for a Screeps AI written in Kotlin
MIT License
46 stars 63 forks source link

`globalThis` is only defined in simulation #18

Open Zomis opened 3 weeks ago

Zomis commented 3 weeks ago

In the persistent world I got this in the console:

> globalThis
ReferenceError: globalThis is not defined
    at eval (eval at <anonymous> (_console1726734043946_0:1:46), <anonymous>:2:1)
    at _console1726734043946_0:1:46
    at _console1726734043946_0:1:60
    at Object.exports.evalCode (<runtime>:15348:63)
    at Object.exports.run (<runtime>:20993:41)

While in simulation I got this in the console:

> globalThis
[object DedicatedWorkerGlobalScope]

This makes the compiled JavaScript not work in the persistent world, only in the simulation.

So if I try to use my Kotlin code compiled to JavaScript in the persistent world, I get this:

ReferenceError: globalThis is not defined
    at Object.885 (main:1:22236)
    at n (main:1:25332)
    at main:1:25358
    at t.235.Object.defineProperty.value (main:1:117)
    at main:1:267
    at main:3:3
    at Object.exports.evalCode (<runtime>:15382:76)
    at Object.requireFn (<runtime>:21032:28)
    at Object.exports.run (<runtime>:20975:60)

If I turn off minification, I can see where exactly the error is:

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) {
  if (true)
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(36), __webpack_require__(711)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
        __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
        (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
        __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  else {}
}(globalThis, function (_, kotlin_kotlin, kotlin_io_github_exav_screeps_kotlin_types) { // <--- Error is on this line
  'use strict';
  //region block: imports
  var Unit_instance = kotlin_kotlin.$_$.c;
Zomis commented 3 weeks ago

A workaround for this problem:

Change in build.gradle.kts

val modules = mutableMapOf<String, String>()
modules["main"] = main.readText()

to

val modules = mutableMapOf<String, String>()
val fixGlobalThis = "if (!Game.rooms['sim']) globalThis = this;"
modules["main"] = fixGlobalThis + main.readText()