Skip to content

Capability Pack API & Allowlist ​

SaiScratch's core (@sai/ir, @sai/runtime, @sai/compiler) has zero domain knowledge of sprites, physics, or audio. All domain blocks, Event Sheet sentences, TypeScript definitions, and runtime implementations come from Capability Packs (@sai/capability).


1. Defining a Pack (Pack & defineOp) ​

A Pack bundles operations (ops), ECS components (components), and systems (systems):

ts
import { defineOp, type Pack } from '@sai/capability';

const pingOp = defineOp({
  id: 'my-ext.ping@1',
  kind: 'reporter',
  tier: 'both',
  category: 'utility',
  params: {
    value: { type: 'number', default: 1 },
  },
  returns: 'number',
  label: { en: 'ping %1', vi: 'ping %1' },
  sheet: {
    sentence: { en: 'ping {value}', vi: 'ping {value}' },
    group: 'Utility',
  },
  impl(_ctx, _self, args) {
    return args.value + 1;
  },
});

export const myPack: Pack = {
  id: 'my-ext',
  version: '1.0.0',
  ops: [pingOp],
};

OpSpec Key Fields ​

  • id: <namespace>.<name>@<version> (must match /^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+@\d+$/).
  • kind: 'command' | 'reporter' | 'predicate' | 'hat'.
  • tier: 'kids' | 'pro' | 'both'.
  • params: Typed parameter specs (number, string, boolean, list, entity, asset, any).
  • impl(ctx, self, args): Deterministic runtime function receiving OpContext (tick, time, rng, keysDown, world).

2. Generators ​

From a single CapabilityRegistry, SaiScratch automatically generates:

  • toBlocklyJson(pack, locale) — Blockly block definitions.
  • toDts(pack) — TypeScript .d.ts ambient declarations for Monaco.
  • toToolSchema(pack) — JSON tool schemas for automation/AI assistants.

3. Third-Party Pack Allowlist (validateThirdPartyPack) ​

Before loading any third-party pack, the host validates it with validateThirdPartyPack(pack, allowlist) from @sai/capability:

ts
import { validateThirdPartyPack, type PackAllowlistEntry } from '@sai/capability';

const allowlist: PackAllowlistEntry[] = [
  { id: 'my-ext', versionRange: '^1.0.0', allowThirdParty: true },
];

const result = validateThirdPartyPack(myPack, allowlist);
if (!result.valid) {
  console.error('Pack rejected:', result.errors);
}

Enforced Sandbox Rules ​

  1. Allowlist Match: pack.id must be present in allowlist and not have allowThirdParty: false.
  2. Semver Range: pack.version must be valid MAJOR.MINOR.PATCH semver satisfying entry.versionRange (^, ~, >=, <=, >, <, exact, or *).
  3. Unique Valid Op IDs: Every op must match <ns>.<name>@<version> with no duplicates.
  4. No Compiler Code Injection (impl-only): Third-party ops must provide impl and must not define emit or inline (preventing arbitrary ESTree/JS injection into compiled worker bundles).
  5. Metadata Global Scan: String fields in op metadata are recursively scanned and rejected if they reference window, document, globalThis, XMLHttpRequest, WebSocket, localStorage, sessionStorage, indexedDB, importScripts, fetch(, eval(, new Function, <script, or javascript:.