Skip to content

JavaScript Scripting

EmakiStrengthen registers a scripting module through the CoreLib scripting system. The module ID is strengthen. Inside a script you obtain the module facade with emaki.module("strengthen") to read strengthen state and register strengthen chance rules and result hooks.

This page covers only the EmakiStrengthen-specific script methods, registration fields, context and examples. For the generic scripting mechanism see CoreLib JavaScript Scripting.

Always guard with available() before calling any business method. EmakiStrengthen is a CoreLib softdepend.

Obtaining the module

js
function main(ctx) {
  const strengthen = emaki.module("strengthen");
  if (!strengthen.available()) {
    return { skipped: true, message: "EmakiStrengthen unavailable" };
  }
  // ...
  return true;
}

Probe methods

MethodReturnsDescription
available()booleanWhether the module is available.

The EmakiStrengthen module facade only exposes available(); it has no ready() / apiVersion() / pluginName().

Item queries and rebuild

The methods below take an itemKey, which resolves an ItemStack from the current action context by attribute key. The available keys are determined by the module that triggers the script.

MethodReturnsDescription
canStrengthen(itemKey)booleanWhether the item can be strengthened.
readState(itemKey)mapRead the strengthen state summary.
rebuild(itemKey)mapRebuild the item and return an item summary (type / amount / displayName).

Fields returned by readState(itemKey):

FieldTypeDescription
eligiblebooleanWhether the item can be strengthened.
eligibleReasonstringReason key when not eligible.
hasLayerbooleanWhether a strengthen layer exists.
baseSourcestringBase item source.
baseSourceSignaturestringBase item source signature.
recipeIdstringMatched strengthen recipe id.
currentStarintCurrent star.
crackLevelintTemper level.
milestoneFlagslistStars already reached.
successCountintTotal successes.
failureCountintTotal failures.
lastAttemptAtlongTimestamp of the last attempt.
branchPathstringBranch path.
fractureLevelintFracture level.

Returns an empty map when called inside a script worker boundary.

Strengthen chance rules

Chance rules run during strengthen resolution. They can read the context and modify the success rate, the resulting star on failure, the temper value on failure and whether protection is applied.

MethodReturnsDescription
registerChanceRule(definition)booleanRegister a chance rule.
registerChanceRule(id, definition)booleanOverload: merge id into the definition, then register.
unregisterChanceRule(id)voidUnregister a rule by id.
registeredChanceRules()listReturn the list of registered chance rule ids.

Rule definition fields

FieldTypeRequiredDefaultDescription
idstringyesnoneUnique rule id (normalized); registration fails when blank.
functionstringnomodifyChanceRule callback function name; execute also works.
priorityintno0Priority; lower runs first, ties broken by id.
timeoutMillislongnoengine defaultPer-call script timeout.

Rule callback ctx fields

FieldTypeDescription
ruleIdstringCurrent rule id.
playerUuidstringPlayer UUID.
playerNamestringPlayer name.
recipeIdstringStrengthen recipe id.
currentStarintCurrent star level.
targetStarintTarget star level.
temperLevelintCurrent temper / crack value.
originalSuccessRatedoubleOriginal success rate.
successRatedoubleCurrent accumulated success rate.
failureStarintResulting star on failure.
failureTemperintResulting temper on failure.
protectionAppliedbooleanWhether protection is applied.
targetItemmapSummary of the item being strengthened: type / amount / displayName, optional lore (plain lines) / customModelData.
requiredMaterialslistRequired materials, each with item / requiredAmount / availableAmount / consumedAmount / optional / protection / temperBoost.
optionalMaterialslistOptional materials, same fields as requiredMaterials.
traceslistTraces from previous rules, each with id / before / after / message.

A rule only runs when the current strengthen preview is eligible.

Rule callback return fields

Return fieldTypeDescription
successRate or chancenumberSet the success rate directly (takes priority).
successBonusnumberAdd to the current success rate (when no successRate).
successMultipliernumberMultiply the current success rate (applied after bonus).
failureStarintOverride the resulting star on failure.
failureTemperintOverride the resulting temper on failure.
protectionAppliedbooleanOverride whether protection is applied.
failureProtectedbooleanFailure-protection alias: applies protection and pins the resulting star to the current star.
downgradeProtectedbooleanDowngrade-protection alias, same effect as failureProtected.
extraCostslistExtra cost entries (read-only exposure for display/audit; not actually consumed in this batch).
messagestringMessage written to the trace.

The final success rate is clamped to 0~100. Multiple rules accumulate serially in ascending priority order.

Strengthen result hooks

Result hooks fire after strengthen resolution, for side effects such as rewards and broadcasts.

MethodReturnsDescription
onResult(definition)booleanRegister a strengthen result hook.
onResult(id, definition)booleanOverload: merge id into the definition, then register.
unregisterResultHook(id)voidUnregister a result hook by id.
registeredResultHooks()listReturn the list of registered result hook ids.

Hook definition fields

FieldTypeRequiredDefaultDescription
idstringyesnoneUnique hook id; registration fails when blank.
functionstringnoonStrengthenResultCallback function name; execute also works.
timeoutMillislongnoengine defaultPer-call script timeout.

Result hooks have no priority field; multiple hooks fire in id lexical order.

Hook callback event fields

FieldTypeDescription
hookIdstringHook id.
playerUuidstringPlayer UUID.
playerNamestringPlayer name.
successbooleanWhether the strengthen succeeded.
errorKeystringFailure error key.
resultingStarintResulting star level.
resultingTemperintResulting temper value.
newlyReachedStarslistStar levels newly reached this attempt.
replacementsmapText replacement map.

When the attempt carries preview information, the event also includes recipeId, currentStar, targetStar, successRate, failureStar, failureTemper, protectionApplied and maxLevel (boolean, whether the resulting star already reached the recipe's maximum star).

The hook callback may return { actions: [...] }, where actions is an array of action-line strings that the plugin runs in order through the CoreLib ActionExecutor. The action-line syntax matches the actions used in recipes, e.g. "sendmessage text=\"<green>...\"", "playsound sound=minecraft:... volume=1 pitch=1". A failure only logs a warning to the console and does not affect the completed strengthen result.

Placeholders available in action lines:

PlaceholderDescription
%success%Whether the attempt succeeded.
%strengthen_star%Resulting star level.
%strengthen_temper%Resulting temper value.
%strengthen_recipe_id%Strengthen recipe id.

Example returning actions:

js
function onStrengthenResult(event) {
  if (event.success) {
    return {
      actions: [
        "sendmessage text=\"<green>Strengthen succeeded, now %strengthen_star% stars\"",
        "playsound sound=minecraft:entity.player.levelup volume=1 pitch=1"
      ]
    };
  }
  return {};
}

Full example

EmakiStrengthen ships the example script scripts/examples/strengthen_success.js:

js
function register() {
  const strengthen = emaki.module("strengthen");

  strengthen.registerChanceRule({
    id: "example_vip_bonus",
    priority: 10,
    function: "modifyChance"
  });

  strengthen.onResult({
    id: "example_result_notice",
    function: "onStrengthenResult"
  });
}

function modifyChance(ctx) {
  if (ctx.playerName && ctx.targetStar >= 5) {
    return {
      successBonus: 2.5,
      message: "Example: +2.5% success rate above 5 stars"
    };
  }
  return {};
}

function onStrengthenResult(event) {
  emaki.logger.info("Strengthen result hook: recipe=" + event.recipeId + ", success=" + event.success + ", star=" + event.resultingStar);
}

Enabling extension scripts

Put the script into CoreLib's global extension directory and reload:

text
plugins/EmakiCoreLib/scripts/extensions/global/strengthen_success.js
text
/corelib script reload

The example file is released to plugins/EmakiCoreLib/scripts/examples/ by default and is not auto-enabled.

Script debugging

When you enable the debug submodule named script, EmakiStrengthen writes the per-rule execution trace to the server console every time its JS rules run, which helps server administrators debug script rules.

Enable command:

text
/estrengthen debug module script

Available debug submodules: attempt, state, gui, script, pdc.

Trace fields: rule id, before (value before execution), after (value after execution) and message. This output goes to the server console for server administrators to debug; it is not shown to players.

Notes

  • Every registration method requires the CoreLib scripting system to be enabled; otherwise registration returns false or is silently skipped.
  • When CoreLib is missing the module degrades gracefully: rules and hooks have no effect but raise no error.
  • Chance rules run in ascending priority order (lower first).