|
| 1 | +import { type Cell } from "../cell.ts"; |
| 2 | +import { type Action } from "../scheduler.ts"; |
| 3 | +import type { IRuntime } from "../runtime.ts"; |
| 4 | +import type { |
| 5 | + IExtendedStorageTransaction, |
| 6 | + MemorySpace, |
| 7 | +} from "../storage/interface.ts"; |
| 8 | +import type { EntityId } from "../create-ref.ts"; |
| 9 | +import { ALL_CHARMS_ID } from "./well-known.ts"; |
| 10 | +import type { JSONSchema } from "../builder/types.ts"; |
| 11 | + |
| 12 | +type WishResolution = { |
| 13 | + entityId: EntityId; |
| 14 | + path?: readonly string[]; |
| 15 | +}; |
| 16 | + |
| 17 | +const WISH_TARGETS: Record<string, WishResolution> = { |
| 18 | + "#/allCharms": { entityId: { "/": ALL_CHARMS_ID } }, |
| 19 | +}; |
| 20 | + |
| 21 | +function resolveWishTarget( |
| 22 | + wish: string, |
| 23 | + runtime: IRuntime, |
| 24 | + space: MemorySpace, |
| 25 | + tx: IExtendedStorageTransaction, |
| 26 | +): Cell<unknown> | undefined { |
| 27 | + const target = WISH_TARGETS[wish]; |
| 28 | + if (!target) return undefined; |
| 29 | + |
| 30 | + const path = target.path ? [...target.path] : []; |
| 31 | + return runtime.getCellFromEntityId( |
| 32 | + space, |
| 33 | + target.entityId, |
| 34 | + path, |
| 35 | + undefined, |
| 36 | + tx, |
| 37 | + ); |
| 38 | +} |
| 39 | + |
| 40 | +const TARGET_SCHEMA = { |
| 41 | + type: "string", |
| 42 | + default: "", |
| 43 | +} as const satisfies JSONSchema; |
| 44 | + |
| 45 | +export function wish( |
| 46 | + inputsCell: Cell<[unknown, unknown]>, |
| 47 | + sendResult: (tx: IExtendedStorageTransaction, result: unknown) => void, |
| 48 | + _addCancel: (cancel: () => void) => void, |
| 49 | + _cause: Cell<any>[], |
| 50 | + parentCell: Cell<any>, |
| 51 | + runtime: IRuntime, |
| 52 | +): Action { |
| 53 | + return (tx: IExtendedStorageTransaction) => { |
| 54 | + const inputsWithTx = inputsCell.withTx(tx); |
| 55 | + const values = inputsWithTx.get() ?? []; |
| 56 | + const target = inputsWithTx.key(0).asSchema(TARGET_SCHEMA).get(); |
| 57 | + const defaultValue = values.length >= 2 ? values[1] : undefined; |
| 58 | + const hasDefault = defaultValue !== undefined && defaultValue !== null; |
| 59 | + const defaultCell = hasDefault ? inputsWithTx.key(1) : undefined; |
| 60 | + |
| 61 | + const wishTarget = typeof target === "string" ? target.trim() : ""; |
| 62 | + |
| 63 | + if (wishTarget === "") { |
| 64 | + sendResult(tx, hasDefault ? defaultCell : undefined); |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + const resolvedCell = resolveWishTarget( |
| 69 | + wishTarget, |
| 70 | + runtime, |
| 71 | + parentCell.space, |
| 72 | + tx, |
| 73 | + ); |
| 74 | + |
| 75 | + if (!resolvedCell) { |
| 76 | + console.error(`Wish target "${wishTarget}" is not recognized.`); |
| 77 | + sendResult(tx, hasDefault ? defaultCell : undefined); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + sendResult(tx, resolvedCell.withTx(tx)); |
| 82 | + }; |
| 83 | +} |
0 commit comments