Skip to content

Latest commit

 

History

History
87 lines (61 loc) · 10.2 KB

coding.md

File metadata and controls

87 lines (61 loc) · 10.2 KB

NekoJS coding guide

Project-specific conventions, runtime invariants, error codes, and verification commands. See AGENTS.md for repo layout and top-level boundaries.

Key terms

Only the terms people commonly mix up:

  • Plugin Hook vs. Script Event: a Plugin Hook is a Java method on NekoJSPlugin (wrapping an Extension Point or lifecycle callback); a Script Event is a JS callback registered on an Event Group (ServerEvents.xxx(event => {})).
  • Extension Point vs. Contributor: an Extension Point collects one kind of plugin contribution (e.g. bindings, events, recipe schemas); a Contributor is the interface a plugin implements to supply items to that point.
  • global vs. shared vs. globalThis: global is in-memory state shared across scripts of one ScriptType (STARTUP, SERVER, CLIENT, TEST); shared is in-memory state shared across ScriptTypes in one runtime. Neither is JS globalThis, and neither is persisted to saves or synced over the network.

Script API

Keep existing public names and overloads backwards-compatible unless a breaking migration is planned (document migrations in the wiki, not in runtime error messages).

  • Event groups (example: ServerEvents.java; Java plugin publication, @ScriptOutput, and compiler/preflight hooks: plugins.md):
    • Scripts subscribe via EventGroupName.eventName(event => {}) (lower camel case), with required selectors before the callback. Put event-specific data/actions on event and general helpers on a Binding.
    • Define groups in Java with EventGroup.of(...), declare all events before freezing, and register the group once in registerEvents (or registerClientEvents for client).
    • Plain group.server(...) / client(...) / startup(...) declarations publish to versioned by default; stable requires a portable declared payload or .view(...) converter.
  • Bindings (example: NekoJSCorePlugin.java):
    • Register in registerBinding(BindingRegistry). Third-party Binding modules use nekojs/plugins/<owner>/api/stable or nekojs/plugins/<owner>/api/version (separate from event virtual modules).
    • For dynamic proxies, pass the exposed interface via Binding.of(name, value, valueType) so generated declarations match runtime access.
  • Builders: put identifying arguments first and the configuration callback last (event.create(id, build => { build.displayName = "Example"; })). Keep the event object and builder separate, and don't require a trailing .build() unless an existing API already does.
  • Bean properties: expose JavaBean accessors as properties (getXxx() -> obj.xxx, setXxx(v) -> obj.xxx = v) matching actual read/write support, keeping parameterized methods as methods. Verify property access on the actual script-visible wrapper or proxy—a Java getter/setter name alone doesn't guarantee exposure.

Runtime, threads, and state

Keep these invariants when touching engine lifecycle, reload, threading, or persistence:

  • Root vs. plugin ownership: NekoRuntimeRoot owns root-level resources. NekoPluginRuntime survives ordinary script reloads and is not re-bootstrapped on reload.
  • Generation cleanup: every per-generation GraalJS Context, listener, timer, and handle must belong to ResourceTracker with an explicit cleanup path. Closing an old generation must not tear down root-owned plugin resources.
  • Safe reload handoff: build and validate the candidate generation before swapping it to active on the owning thread. Keep live callbacks, timers, bindings, and registry mutations on active until the swap. On failure, dispose the candidate and keep active running with no duplicate callbacks.
  • Thread confinement: GraalJS Context and guest objects are single-threaded—concurrent collections do not make them thread-safe. Marshal cross-thread calls to the owning thread and serialize evaluate, reload, and close per ScriptType, with close taking priority.
  • User-file safety: on error, preserve existing user files (configs, saves, pdata, packs, workspace files) instead of overwriting them or silently falling back to empty defaults. Persistent migrations must back up first and replace atomically.
  • Shared state: GlobalStateStores tracks top-level keys only for global and shared during reload—nested object mutations, world/file side effects, and cross-process sync are neither rolled back nor synchronized.

Adding a plugin collection point

Keep direct callback hooks separate from collection points. Adding a collection point requires updating four places together:

  1. Its Extension Point definition.
  2. The default hook on NekoJSPlugin.
  3. Registration in NekoBuiltinPointsPlugin.
  4. Pairing coverage in PluginHookPairingTest.

Comments and Java doc syntax

Write all new or modified Java/Gradle/script code comments, /// doc comments, TODOs, and test assertion messages in English—do not mimic Chinese from surrounding legacy comments or let a Chinese prompt bleed into source files (only untouched legacy comments, localization files, and exact test fixtures stay in Chinese).

For Java documentation comments, use /// Markdown syntax (JEP 467) instead of /** ... */ across every module—including Java 21 modules like common/ and common-api-processor/ (javac 21 accepts /// as line comments, and /// avoids /* ... */ block-comment conflicts inside Stonecutter //? if guards; example: Binding.java):

  • Use standard Markdown (`code`, fenced ``` blocks, lists, and [Type#member] / [param] references) instead of HTML tags (<p>, <ul>) or {@code} / {@link}.
  • @param, @return, and @throws tags still work inside /// when needed; leave untouched /** ... */ comments as-is unless already editing them.

Logging, i18n, and diagnostic codes

Prefer i18n whenever the target surface supports localization (Component.translatable / TextValue.translatable backed by assets/nekojs/lang/{en_us,zh_cn}.json for player chat, command feedback, and in-game UI); otherwise write messages in English (developer logs, Java exceptions, CLI output, and standalone compile-time/annotation-processor diagnostics)—never hardcode Chinese text in Java code.

Use the module's logger (no System.out or printStackTrace). Problem logs should state what failed, the outcome, and locating context (file/line, ScriptType, generation, phase, owner), attaching the cause once at the reporting layer.

Every developer-facing runtime problem log or exception needs a stable [NEKO-nnnn] code (routine progress logs and localized player UI/chat messages have no code):

  • Stability: never renumber a code when rewording or reuse it for a different failure. Use the same code for the same failure across all call sites and nodes.
  • Areas (pick the next free code in the wiki table): 1xxx script loading/reload · 2xxx log limits & data fallbacks · 3xxx script sync · 4xxx registration/bindings · 5xxx recipes/data · 6xxx client JSX UI visual/resources · 7xxx client JSX UI runtime/lifecycle · 8xxx UI inspector.
  • Message language: write new or rewritten messages in English ([NEKO-10xx] Failed to reload SERVER scripts at server_scripts/main.js:42; generation 12 remains active.). Leave untouched legacy Chinese messages intact, and keep any message asserted verbatim by existing tests unchanged.
  • Wiki sync: update both wiki/error-reference_us.md and wiki/error-reference_cn.md in the same change.

Verification

Full CI commands and the active node matrix live in ci-build.yml and package.json. On Windows, use gradlew.bat (or ./gradlew.bat in PowerShell). CI gate CLI:

python3 tools/nekojs-ci-gates.py <all|subsets|processor|declaration|nodes|selftest>
python3 tools/nekojs-ci-gates.py source-roots --node <node>
Change area Commands / checks
Common engine, ownership, or isolation ./gradlew :common:check (runs isolation checks that :common:test skips); add guardLint for boundary/import/guard changes.
Annotation processor ./gradlew :common-api-processor:test plus affected node builds.
Version facades, guards, or source roots ./gradlew guardLint, affected :<node>:build, and python3 tools/nekojs-ci-gates.py <subsets|nodes|all> + source-roots --node <node>.
NBT codec ./gradlew :1.21.1:nbtSmokeTest :26.1.2:nbtSmokeTest :26.2.0:nbtSmokeTest (NeoForge nodes only).
Plugin API or collection channels PluginHookPairingTest and relevant plugin tests under :common:check.
Script API, declarations, or Probe ApiManifestGoldenTest, relevant surface tests, and npm run test:probe-types (after :common:check); add npm run test:probe-recipe-filter (after :1.21.1:nativeRecipeProbeTest) or npm run test:probe-native-jsx when touching those surfaces. For intentional golden updates, run ./gradlew :common:regenerateGoldens, review the diff, and rerun :common:check.
Runtime reload, state, persistence, or threading Targeted lifecycle/state/reload tests under :common:check; add :26.1.2:runGameTestServer when crossing into Minecraft.
Loader startup, Mixin, GUI/chat, or game behavior Affected :<node>:build, Fabric :<node>:runServer smoke, and ./gradlew :26.1.2:runGameTestServer (check All <N> required tests passed in versions/26.1.2/run/logs/).