Shattered Codex

Wiki

← Back to the SC - Simple Sockets guide

Developer reference

SC - Simple Sockets API Reference

Build macros and integrations with SC - Simple Sockets: manage sockets and gems, handle results and options, and use interactive helpers and hooks.

For installation, settings, and everyday use, start with the module guide.

For installation, configuration, and socket workflows, see the SC - Simple Sockets guide.

Public API reference

The module registers its public API during Foundry's ready hook. Call it from a macro or integration after the world is ready:

js
const api = game.modules.get("sc-simple-sockets")?.api;
const sockets = api?.sockets;
const macroApi = api?.macro;

Every socket API method is asynchronous except isGemDataBroken and repairGemData. itemOrUuid accepts an Item document or an Item UUID. Slot indexes are zero-based: 0 is the first socket.

Socket API methods and parameters

Expand a method to see what each parameter accepts, its default value, and the returned value.

getItemSlots(itemOrUuid, options?)Lists every socket on an item, including empty slots.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

options.includeSnapshotsbooleandefault: false

When true, keeps the internal _gemData snapshot inside each returned slot. Leave false unless an integration needs the stored gem data.

Returns

Promise<Array<{ slotIndex, hasGem, slot }>>. Returns an empty array when the item cannot be resolved.

getItemGems(itemOrUuid, options?)Lists only the gems currently inserted into the host item.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

options.includeSnapshotsbooleandefault: false

Includes the stored _gemData snapshot inside each returned slot when true.

Returns

Promise<Array<{ slotIndex, name, img, tags, uuid, sourceUuid, slot }>>. Tags are normalized; uuid and sourceUuid are currently null.

hasItemGemTag(itemOrUuid, tag)Checks whether at least one inserted gem has a matching normalized tag.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

tagstring

The tag to search for. The module normalizes spaces and casing, so Dynamo Battery matches dynamo-battery.

Returns

Promise<boolean>. Returns false for an unresolved item or an empty tag.

canEditSockets(itemOrUuid, options?)Checks whether a user is allowed to modify sockets on an item.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

options.userIdstring | nulldefault: null

The Foundry user ID to check. When omitted, checks the current user.

options.actionstring | nulldefault: null

One of addSlot, removeSlot, addGem, or removeGem. When omitted, the result covers adding and removing slots.

Returns

Promise<boolean>. GM status, the module permission settings, and Item ownership are considered.

addSlot(itemOrUuid, options?)Creates one empty socket at the end of the host item's socket list.
Parameters
itemOrUuidItem | string

The socketable host Item document or its UUID.

options.slotConfigobjectdefault: {}

Configures name, description, condition, color, frameImg, hidden, and deleteGemOnRemoval for the new slot.

options.bypassPermissionbooleandefault: false

Bypasses the module edit-permission check. Use only in trusted automation.

options.bypassWorldSocketLimitbooleandefault: false

Allows this call to exceed Maximum Number of Sockets per Item.

options.ignoreMaxSocketsbooleandefault: false

Alias for bypassWorldSocketLimit.

options.notifybooleandefault: true

Set false to suppress module notifications.

Returns

Promise<Result>. On success, data contains the zero-based slotIndex and the new totalSlots.

Example
const result = await sockets.addSlot(item, { slotConfig: { name: 'Ruby Socket', color: '#9f1239' } });
removeSlot(itemOrUuid, slotIndex, options?)Low-level removal for a socket that the caller has already confirmed is empty.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

slotIndexnumber

Zero-based index of an empty socket.

options.bypassPermissionbooleandefault: false

Bypasses the module edit-permission check.

Returns

Promise<Result>. Success data contains slotIndex and totalSlots. This method does not clean up a filled slot; use removeSlotWithContents whenever contents may exist.

removeSlotWithContents(itemOrUuid, slotIndex, options?)Removes a socket and first cleans up its inserted gem, effects, and activities.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

slotIndexnumber

Zero-based index of the socket to remove.

options.modestringdefault: default

Gem removal mode: default follows settings, keep returns the gem, and delete destroys it.

options.bypassPermissionbooleandefault: false

Bypasses the module edit-permission check.

options.notifybooleandefault: true

Set false to suppress the gem-removal notification when a filled slot is cleaned up.

Returns

Promise<Result>. The gem follows the selected removal mode before the socket is deleted.

addGem(itemOrUuid, gemOrUuid, slotIndex?, options?)Inserts a compatible gem and transfers its supported behavior to the host item.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

gemOrUuidItem | string

The gem Item document or its UUID. It must be recognized as a configured gem.

slotIndexnumber | nulldefault: null

Zero-based target slot. When omitted, the first empty slot is used; the API does not skip a conditionally rejected first empty slot.

options.notifybooleandefault: true

Controls module notifications.

options.bypassPermissionbooleandefault: false

Bypasses the module edit-permission check.

Returns

Promise<Result>. Compatibility, allowed-item-type, and slot-condition checks still apply; successful data contains slotIndex.

Example
const result = await sockets.addGem(item, gem); // first empty slot
removeGem(itemOrUuid, slotIndex, options?)Extracts a gem from a filled socket and removes its transferred behavior.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

slotIndexnumber

Zero-based index of a filled socket.

options.modestringdefault: default

Use default for slot/world settings, keep to return the gem, or delete to destroy it.

options.notifybooleandefault: true

Set false to suppress the unsocketed notification.

options.bypassPermissionbooleandefault: false

Bypasses the module edit-permission check. Use only for trusted automation.

Returns

Promise<Result>. Success reason is gem-removed.

removeGemKeepingItem(itemOrUuid, slotIndex, options?)The explicit keep variant of removeGem.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

slotIndexnumber

Zero-based index of a filled socket.

optionsobjectdefault: {}

Additional removal options. The method always overrides mode to keep.

Returns

Promise<Result>. The gem is returned to the actor inventory instead of being deleted.

updateSlotConfig(itemOrUuid, slotIndex, config?, options?)Updates one existing socket without replacing its inserted gem.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

slotIndexnumber

Zero-based index of the socket to update.

configobjectdefault: {}

Fields are name, description, condition, color, frameImg, hidden, and deleteGemOnRemoval. Hex colors normalize to uppercase #RRGGBB.

options.bypassPermissionbooleandefault: false

Bypasses the module edit-permission check.

Returns

Promise<Result>. Success reason is slot-config-updated.

isGemBroken(gemOrUuid)Checks whether a gem item is broken.
Parameters
gemOrUuidItem | string

The gem Item document or its UUID.

Returns

Promise<boolean>.

breakGem(gemOrUuid)Marks a loose gem as broken. The whole stack is affected.
Parameters
gemOrUuidItem | string

The gem Item document or its UUID. The caller must be a GM or own the gem.

Returns

Promise<Result>. Reason is gem-broken, or unchanged when nothing changed. Socketed gems are never broken.

repairGem(gemOrUuid)Repairs a broken loose gem.
Parameters
gemOrUuidItem | string

The gem Item document or its UUID. The caller must be a GM or own the gem.

Returns

Promise<Result>. Reason is gem-repaired, or unchanged when the gem was not broken.

isGemDataBroken(itemData)Synchronous. Reads the broken state from plain item data, for integrations that hold gems as stored data instead of documents.
Parameters
itemDataobject

Plain item data for a gem.

Returns

boolean.

repairGemData(itemData)Synchronous. Returns a repaired copy of plain item data without modifying the input.
Parameters
itemDataobject

Plain item data for a gem.

Returns

object. A copy of the data without the broken marker.

Use removeSlot only after confirming the target slot is empty. It removes the stored slot directly and does not perform gem, effect, or activity cleanup. removeSlotWithContents is the safe general-purpose choice when the slot may be filled.

Mutation methods return this stable shape:

js
{
  success: true,
  changed: true,
  reason: "slot-added",
  data: { slotIndex: 0, totalSlots: 1 }
}

Common reason values include slot-added, slot-removed, slot-not-removed, gem-added, gem-removed, slot-config-updated, slot-config-not-updated, item-not-found, invalid-slot-index, empty-slot, no-available-slot, cannot-resolve-item, host-not-socketable, not-a-gem, gem-incompatible, gem-broken, socket-condition-failed, socket-condition-error, permission-denied, and max-sockets-reached. When gem checks are enabled, results can also carry insertion-check-failed, removal-check-failed, removal-check-required, gem-removed-broken, and gem-lost. Check success before using data.

Common mutation options are:

OptionType and defaultEffect
`bypassPermission``boolean`, `false`Bypasses the module's socket-edit permission check. Use only for trusted automation.
`bypassWorldSocketLimit``boolean`, `false`Allows `addSlot` to ignore the configured maximum.
`ignoreMaxSockets``boolean`, `false`Alias accepted by the module for bypassing the configured maximum.
`notify``boolean`, default enabledSet to `false` to suppress notifications on methods that emit them.
`mode``"default"`, `"keep"`, or `"delete"`Controls gem removal. `default` follows slot and world settings.
`slotConfig``object`, `{}`Used by `addSlot`; fields are `name`, `description`, `condition`, `color`, `frameImg`, `hidden`, and `deleteGemOnRemoval`.

Slot colors accept three- or six-digit hexadecimal values and are normalized to uppercase #RRGGBB. Slot conditions are JavaScript expressions evaluated by the module; invalid code blocks the operation.

API examples

Add a configured socket and inspect the result:

js
const sockets = game.modules.get("sc-simple-sockets")?.api?.sockets;
const result = await sockets?.addSlot(item, {
  slotConfig: {
    name: "Ruby Socket",
    description: "Accepts one adornment ruby.",
    condition: "return hasGemTag('adornment-ruby');",
    color: "#9f1239",
    deleteGemOnRemoval: false
  }
});
 
if (!result?.success) {
  ui.notifications.warn(`Could not add socket: ${result?.reason}`);
}

Insert a gem into the first empty slot, or choose slot 1 explicitly:

js
const automatic = await sockets.addGem(item, gem);
const selected = await sockets.addGem(item.uuid, gem.uuid, 1);
console.log(automatic.data?.slotIndex, selected.data?.slotIndex);

Remove a gem while always returning it to the actor's inventory:

js
const result = await sockets.removeGemKeepingItem(item.uuid, 0);
if (result.success) console.log("Gem removed and kept.");

Check a normalized gem tag in a conditional activity:

js
const sockets = game.modules.get("sc-simple-sockets")?.api?.sockets;
return sockets && await sockets.hasItemGemTag(item, "Dynamo Battery");

Interactive macro API

The macro API is intended for workflows that ask the user to select an item or socket in the Foundry interface:

Interactive macro API parameters

Expand a method to see what each parameter accepts, its default value, and the returned value.

addSocketInteractive(options?)Waits for the user to click a supported item, then adds a socket after confirmation.
Parameters
options.notificationsbooleandefault: true

Shows the selection, success, warning, and error notifications.

options.promptSlotConfigbooleandefault: false

Opens the slot configuration dialog before creating the socket.

options.slotConfigobjectdefault: {}

Default name, description, condition, color, visibility, and removal behavior for the new slot.

options.cursorClassstring

Optional CSS cursor class used during item selection.

options.cursorUrlstringdefault: ""

Optional image URL used as the selection cursor.

options.bypassWorldSocketLimitbooleandefault: false

Allows the interactive workflow to exceed the configured maximum.

options.ignoreMaxSocketsbooleandefault: false

Alias for bypassWorldSocketLimit.

options.targetValidatorfunctiondefault: null

Optional async validator. Return false or { ok: false } to reject the selected item.

Returns

Promise<{ success, reason, item? }>. Cancellation returns reason cancelled; a successful workflow returns reason added.

Example
await macroApi.addSocketInteractive({ promptSlotConfig: true });
extractGemInteractive(options?)Lets the user click a filled socket and extracts its gem without deleting it.
Parameters
options.notificationsbooleandefault: true

Shows selection, cancellation, success, and error notifications.

Returns

Promise<{ success, reason, item?, slotIndex?, gemName? }>. The extracted gem is always kept.

selectItemForSocket(options?)Activates the item-selection cursor used by interactive socket workflows.
Parameters
options.notificationsbooleandefault: true

Shows the selection prompt.

options.cursorClassstring

Optional CSS cursor class.

options.cursorUrlstringdefault: ""

Optional cursor image URL.

options.messageKeystring

Optional localization key for the selection prompt.

options.messageFallbackstring

Optional fallback prompt when messageKey is not localized.

Returns

Promise<Item | null>. Resolves the clicked Item document, or null when the selection is cancelled.

removeGemWithoutDeleting(itemOrUuid, slotIndex, options?)Removes a gem by API coordinates while forcing the keep behavior.
Parameters
itemOrUuidItem | string

The host Item document or its UUID.

slotIndexnumber

Zero-based index of the filled socket.

optionsobjectdefault: {}

Additional removal options. mode is always overridden to keep.

Returns

Promise<Result>. The gem is returned to the actor inventory.

Example:

js
await game.modules.get("sc-simple-sockets")?.api?.macro?.addSocketInteractive({
  notifications: true,
  promptSlotConfig: true,
  slotConfig: {
    name: "Runeword Socket",
    description: "Accepts one curated rune.",
    color: "#C44D24"
  }
});

The hook constants are also exposed through api.sockets:

js
const sockets = game.modules.get("sc-simple-sockets")?.api?.sockets;
console.log(sockets.HOOK_SOCKET_ADDED);   // "sc-simple-sockets.socketAdded"
console.log(sockets.HOOK_SOCKET_REMOVED); // "sc-simple-sockets.socketRemoved"

Both hooks receive an object with item, itemId, itemUuid, actor, actorId, slotIndex, slot, totalSlots, and userId. The slot value is a cloned socket snapshot from before removal or after creation.

Use the same names with Foundry's Hooks.on:

js
Hooks.on("sc-simple-sockets.socketAdded", ({ item, slotIndex, totalSlots }) => {
  console.log(`Socket ${slotIndex} added to ${item?.name}; total: ${totalSlots}`);
});
 
Hooks.on("sc-simple-sockets.socketRemoved", ({ item, slotIndex, totalSlots }) => {
  console.log(`Socket ${slotIndex} removed from ${item?.name}; total: ${totalSlots}`);
});