@platforma-sdk/model 1.96.4 → 1.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"block_storage_callbacks.cjs","names":["createBlockStorage","isBlockStorage","normalizeBlockStorage","getStorageData","updateStorageData","stringifyJson","obj","migrateBlockStorage","BLOCK_STORAGE_KEY","expandTemplateRefs","relocateBlockIds","parseArgsIssues"],"sources":["../src/block_storage_callbacks.ts"],"sourcesContent":["/**\n * BlockStorage Callback Implementations - wired to facade callbacks in BlockModelV3.done().\n *\n * Provides pure functions for storage operations (migration, initialization,\n * args derivation, updates, debug views). Each function takes its dependencies\n * explicitly as parameters.\n *\n * @module block_storage_callbacks\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n type PluginRegistry,\n type VersionedData,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n migrateBlockStorage,\n normalizeBlockStorage,\n updateStorageData,\n} from \"./block_storage\";\nimport type { PluginHandle } from \"./plugin_handle\";\n\nimport {\n stringifyJson,\n expandTemplateRefs,\n parseArgsIssues,\n relocateBlockIds,\n type ArgsIssue,\n type StringifiedJson,\n} from \"@milaboratories/pl-model-common\";\nimport type { DataVersioned, TransferRecord } from \"./block_migrations\";\nimport type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\n\n// =============================================================================\n// Hook interfaces for dependency injection\n// =============================================================================\n\n/** Dependencies for storage migration */\nexport interface MigrationHooks {\n migrateBlockData: (versioned: DataVersioned<unknown>) => DataVersioned<unknown> & {\n transfers: TransferRecord;\n };\n getPluginRegistry: () => PluginRegistry;\n migratePluginData: (\n handle: PluginHandle,\n versioned: DataVersioned<unknown>,\n ) => DataVersioned<unknown> | undefined;\n createPluginData: (\n handle: PluginHandle,\n transfer?: DataVersioned<unknown>,\n ) => DataVersioned<unknown>;\n}\n\n/** Dependencies for initial storage creation */\nexport interface InitialStorageHooks {\n getDefaultBlockData: () => DataVersioned<unknown>;\n getPluginRegistry: () => PluginRegistry;\n createPluginData: (handle: PluginHandle) => DataVersioned<unknown>;\n}\n\n/**\n * Result of storage normalization\n */\nexport interface NormalizeStorageResult {\n /** The normalized BlockStorage object */\n storage: BlockStorage;\n /** The extracted data (what developers see) */\n data: unknown;\n}\n\n/**\n * Normalizes raw storage data and extracts state.\n * Handles all formats:\n * - New BlockStorage format (has discriminator)\n * - Legacy V1/V2 format ({ args, uiState })\n * - Raw V3 state (any other format)\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns Object with normalized storage and extracted state\n */\nfunction normalizeStorage(rawStorage: unknown): NormalizeStorageResult {\n // Handle undefined/null\n if (rawStorage === undefined || rawStorage === null) {\n const storage = createBlockStorage({});\n return { storage, data: {} };\n }\n\n // Parse JSON string if needed\n let parsed = rawStorage;\n if (typeof rawStorage === \"string\") {\n try {\n parsed = JSON.parse(rawStorage);\n } catch {\n // If parsing fails, treat string as the data\n const storage = createBlockStorage(rawStorage);\n return { storage, data: rawStorage };\n }\n }\n\n // Check for BlockStorage format (has discriminator)\n if (isBlockStorage(parsed)) {\n const storage = normalizeBlockStorage(parsed);\n return { storage, data: getStorageData(storage) };\n }\n\n // Check for legacy V1/V2 format: { args, uiState }\n if (isLegacyModelV1ApiFormat(parsed)) {\n // For legacy format, the whole object IS the data\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n }\n\n // Raw V3 data - wrap it\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n}\n\n/**\n * Applies a state update to existing storage.\n * Used when setData is called from the frontend.\n *\n * @param currentStorageJson - Current storage as JSON string (must be defined)\n * @param payload - Update payload with operation type and value\n * @returns Updated storage as StringifiedJson<BlockStorage>\n */\nexport function applyStorageUpdate(\n currentStorageJson: string,\n payload: MutateStoragePayload,\n): StringifiedJson<BlockStorage> {\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n // Update data while preserving other storage fields (version, plugins)\n const updatedStorage = updateStorageData(currentStorage, payload);\n\n return stringifyJson(updatedStorage);\n}\n\n/**\n * Checks if data is in legacy Model API v1 format.\n * Legacy format has { args, uiState? } at top level without the BlockStorage discriminator.\n */\nfunction isLegacyModelV1ApiFormat(data: unknown): data is { args?: unknown } {\n if (data === null || typeof data !== \"object\") return false;\n if (isBlockStorage(data)) return false;\n\n const obj = data as Record<string, unknown>;\n return \"args\" in obj;\n}\n\n// =============================================================================\n// Facade Callback Implementations\n// =============================================================================\n\n/**\n * Gets storage debug view from raw storage data.\n * Returns structured debug info about the storage state.\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns JSON string with storage debug view\n */\nexport function getStorageDebugView(rawStorage: unknown): StringifiedJson<StorageDebugView> {\n const { storage } = normalizeStorage(rawStorage);\n const debugView: StorageDebugView = {\n dataVersion: storage.__dataVersion,\n data: storage.__data,\n };\n return stringifyJson(debugView);\n}\n\n// =============================================================================\n// Migration Support\n// =============================================================================\n\n/**\n * Result of storage migration.\n * Returned by __pl_storage_migrate callback.\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Runs storage migration using the provided hooks.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @param hooks - Migration dependencies (block/plugin data migration and creation functions)\n * @returns MigrationResult\n */\nexport function migrateStorage(\n currentStorageJson: string | undefined,\n hooks: MigrationHooks,\n): MigrationResult {\n // Normalize current storage\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n const newPluginRegistry = hooks.getPluginRegistry();\n\n // Perform atomic migration of block + all plugins\n const migrationResult = migrateBlockStorage(currentStorage, {\n migrateBlockData: hooks.migrateBlockData,\n migratePluginData: hooks.migratePluginData,\n newPluginRegistry,\n createPluginData: hooks.createPluginData,\n });\n\n if (!migrationResult.success) {\n return {\n error: `Migration failed at '${migrationResult.failedAt}': ${migrationResult.error}`,\n };\n }\n\n // Build info message\n const oldVersion = currentStorage.__dataVersion;\n const newVersion = migrationResult.storage.__dataVersion;\n const info =\n oldVersion === newVersion\n ? `No migration needed (${oldVersion})`\n : `Migrated ${oldVersion} -> ${newVersion}`;\n\n return {\n newStorageJson: stringifyJson(migrationResult.storage),\n info,\n };\n}\n\n// =============================================================================\n// Initial Storage Creation\n// =============================================================================\n\n/**\n * Creates complete initial storage (block data + all plugin data) atomically.\n *\n * @param hooks - Dependencies for creating initial block and plugin data\n * @returns Initial storage as branded JSON string\n * @throws If initialDataFn or createPluginData throws\n */\nexport function createInitialStorage(hooks: InitialStorageHooks): StringifiedJson<BlockStorage> {\n return assembleStorage(hooks.getDefaultBlockData(), hooks);\n}\n\n/**\n * Wraps freshly created block data and freshly created plugin data into storage.\n *\n * Shared by the two ways a block's first storage comes into being — from defaults\n * and from template params. Only the block's own data differs between them:\n * plugins have no params channel, so they are always created at their defaults.\n */\nfunction assembleStorage(\n blockData: DataVersioned<unknown>,\n hooks: Omit<InitialStorageHooks, \"getDefaultBlockData\">,\n): StringifiedJson<BlockStorage> {\n const pluginRegistry = hooks.getPluginRegistry();\n\n const plugins: Record<PluginHandle, VersionedData<unknown>> = {};\n for (const handle of Object.keys(pluginRegistry) as PluginHandle[]) {\n const initial = hooks.createPluginData(handle);\n plugins[handle] = { __dataVersion: initial.version, __data: initial.data };\n }\n\n const storage: BlockStorage = {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: blockData.version,\n __data: blockData.data,\n __pluginRegistry: pluginRegistry,\n __plugins: plugins,\n };\n return stringifyJson(storage);\n}\n\n/** Dependencies for creating storage from a template entry's params. */\nexport interface ParamsStorageHooks extends Omit<InitialStorageHooks, \"getDefaultBlockData\"> {\n /** The block's init factory, called with the entry's params. */\n getBlockDataFromParams: (params: unknown) => DataVersioned<unknown>;\n /**\n * The kind's runtime params check. Applied before the factory sees anything, and its\n * output is what the factory gets.\n */\n parseInitializationParams: (value: unknown) => unknown;\n}\n\n/** Result of checking params against their kind: the params to use, or why they lost. */\nexport type TemplateParamsValidationResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Check params against their kind's declared shape.\n *\n * The kind owns this rather than the block because the params contract belongs to the\n * kind: many block versions implement one kind, and a per-block check would let them\n * drift from each other and from the type.\n *\n * A parser rejects by throwing and accepts by returning the params to use, so its\n * output — not the input — is what flows onward. That is what lets a kind strip keys\n * it does not declare, which is the difference between a typo being ignored and a typo\n * being reported.\n *\n * Every kind declares a parser, so every set of params that reaches here is checked;\n * there is no pass-through path.\n *\n * @param value The params to check, references already in live form\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParams(\n value: unknown,\n parseInitializationParams: (value: unknown) => unknown,\n): TemplateParamsValidationResult {\n try {\n return { value: parseInitializationParams(value) };\n } catch (e) {\n // A rejection is an expected outcome for a hand-written file, so it is reported,\n // not thrown.\n return { error: `params do not match this block's kind: ${describeRejection(e)}` };\n }\n}\n\n/** One `{ path, message }` entry of a schema library's error. */\ntype IssueLike = { path?: unknown; message?: unknown };\n\n/**\n * Render whatever a parser threw as one readable line.\n *\n * An error carrying an `issues` array is unpacked rather than printed: that is the\n * shape zod (and several others) use, and its `message` is the whole issue list as\n * JSON — technically complete and unreadable in a dialog. Duck-typed on purpose, since\n * this package prescribes no schema library and takes no dependency on one; anything\n * else falls back to its own message.\n */\nfunction describeRejection(e: unknown): string {\n const issues = (e as { issues?: unknown }).issues;\n if (!Array.isArray(issues) || issues.length === 0) return messageOf(e);\n\n return issues\n .map((issue) => {\n const { path, message } = issue as IssueLike;\n const what = typeof message === \"string\" ? message : \"is invalid\";\n const where = Array.isArray(path) ? formatPath(path) : \"\";\n return where === \"\" ? what : `${where}: ${what}`;\n })\n .join(\"; \");\n}\n\n/** `[\"numbers\", 0]` → `numbers[0]` — how the params are written, not how they parse. */\nfunction formatPath(path: readonly unknown[]): string {\n return path.reduce<string>((acc, segment) => {\n if (typeof segment === \"number\") return `${acc}[${segment}]`;\n return acc === \"\" ? String(segment) : `${acc}.${String(segment)}`;\n }, \"\");\n}\n\n/**\n * Result of the `__pl_params_validate` callback.\n *\n * Carries no params back. The check is a pre-flight — its answer is \"may this entry be\n * applied\", and the params that actually reach the block are produced by\n * {@link createInitialStorageFromParams}, which parses again. One authoritative\n * producer, rather than two values that could differ.\n */\nexport type InitializationParamsValidateCallbackResult = { error: string } | { error?: undefined };\n\n/**\n * Check params that crossed into the model VM as text.\n *\n * The pre-flight entry point: a caller asks this before creating anything, once per\n * template entry, so params a kind rejects are reported while there is still no\n * project to half-build.\n *\n * The readable reference spelling is expanded here too, so what the kind checks is the shape it\n * declared. The ids it sees are the file's own — no block exists yet — which is why a kind must\n * not read meaning into a specific id.\n *\n * @param paramsJson The entry's params as JSON string\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParamsJson(\n paramsJson: string,\n parseInitializationParams: (value: unknown) => unknown,\n): InitializationParamsValidateCallbackResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Expanded before the kind sees anything, or a hand-written file would be rejected by every\n // kind that declares a reference: `{ block, name }` is not a `PlRef` and no contract accepts\n // one. Expansion needs nothing but the params, so this stays a two-argument check — the ids\n // are not known yet and are not needed to answer the question this asks.\n const result = validateTemplateParams(expandTemplateRefs(params), parseInitializationParams);\n if (result.error !== undefined) return { error: result.error };\n return {};\n}\n\nfunction messageOf(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Result of building initial storage from params.\n * Returned by the `__pl_storage_initialFromParams` callback.\n */\nexport type ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Creates complete initial storage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}: that projects storage\n * into params, this builds storage from them. The params are handed to the block's\n * init factory, whose output is versioned and wrapped exactly as\n * {@link createInitialStorage} wraps the defaults — so a block created from a\n * template is indistinguishable from one created in the UI and then edited.\n *\n * **This is where a template's references become the block's own**, and it is the only place in\n * a template's life where a reference is recognized at all. Params travel from the file\n * untouched — the engine carrying them neither marks a reference nor reads one, because\n * recognizing one means knowing the reference system, and that knowledge is here.\n *\n * Two things happen, in this order. The readable spelling a person may have written\n * (`{ block, name }`) is expanded into the `PlRef` it stands for. Then every reference naming\n * an entry that has a block is repointed at it: `blockIds` maps each template-local entry id to\n * the block id it was given, and an id it does not name is left alone, which is how a reference\n * to an entry created later ends up naming nothing rather than naming the wrong block.\n *\n * Relocation happens before the kind's parser and before the factory, so both see the ids the\n * block will actually hold. It is one step of this function rather than a callback of its own\n * precisely because nothing else wants its result: every VM call re-instantiates the runtime\n * and re-evaluates the whole model bundle, so a separate call would parse the block twice per\n * entry to produce a value only the next line reads.\n *\n * Params arrive as JSON text because this runs across the model-VM boundary, where\n * only strings pass. Anything the factory rejects is returned as an error rather\n * than thrown: applying a hand-written template is expected to surface bad params,\n * and the applier reports every entry's problem in one pass.\n *\n * @param paramsJson - The entry's params as JSON string, exactly as the file held them\n * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n * @param hooks - The block's init factory plus plugin creation\n * @returns The storage to write, or why the params could not produce any\n */\nexport function createInitialStorageFromParams(\n paramsJson: string,\n blockIdsJson: string,\n hooks: ParamsStorageHooks,\n): ParamsStorageResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Read separately from the params, and reported separately, because the two fail for\n // completely different reasons. Params are the file's and a bad one is the author's mistake;\n // this argument is the caller's, so the only way it arrives unreadable is a caller that does\n // not send it — a middle layer older than this block, which is a build to refresh rather than\n // anything to fix in the template. Folding both into one message sent the reader to the file.\n let blockIds: Map<string, string>;\n try {\n blockIds = new Map(Object.entries(JSON.parse(blockIdsJson) as Record<string, string>));\n } catch (e) {\n return {\n error:\n `this block was not told which blocks the template's references should point at ` +\n `(${messageOf(e)}). The application applying the template is older than the block; ` +\n `rebuild or update it.`,\n };\n }\n\n try {\n // Spelling first, ids second. Expansion turns `{ block, name }` into a `PlRef` naming an\n // ENTRY, which is exactly what relocation then repoints — so both spellings reach the\n // block through the same step and cannot diverge in how they behave.\n params = relocateBlockIds(expandTemplateRefs(params), blockIds);\n } catch (e) {\n return { error: `this entry's references could not be relocated: ${messageOf(e)}` };\n }\n\n // Checked here too, not only in the caller's pre-flight pass. The pre-flight is\n // about reporting every bad entry before anything is created; this is about the\n // factory never being handed a value the kind rejects, whichever path got here.\n const checked = validateTemplateParams(params, hooks.parseInitializationParams);\n if (checked.error !== undefined) return { error: checked.error };\n\n try {\n return { storageJson: assembleStorage(hooks.getBlockDataFromParams(checked.value), hooks) };\n } catch (e) {\n return { error: `init() threw on the given params: ${messageOf(e)}` };\n }\n}\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of a derivation that either produced a value or failed.\n * Returned by the __pl_initializationParams_derive callback.\n */\nexport type DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of args derivation from storage, returned by the __pl_args_derive callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is runnable args, `error` is no args.\n *\n * - `{ error }`: `args()` threw, so there are no args.\n * - `{ error, args, issues }`: args were built, but `argsIssues()` found errors in them, so the\n * block must not run. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args were built and nothing blocks the run; `issues` holds the warnings.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error: string; args: unknown; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/**\n * Result of prerun args derivation from storage, returned by the __pl_prerunArgs_derive\n * callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is args to stage, `error` skips staging.\n *\n * - `{ error }`: the lambda that builds the prerun args threw.\n * - `{ error, issues }`: prerun args were built, but the issues found in them include errors, so\n * the block is not staged. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args to stage; `issues` holds the warnings. A `value` of `undefined`\n * comes from a `prerunArgs()` that returned nothing, and skips staging.\n */\nexport type PrerunArgsDeriveResult =\n | { error: string }\n | { error: string; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/** The block's lambdas that turn its data into args and find what keeps those args from running. */\nexport interface ArgsDerivation {\n /** The block's `args()` lambda. */\n deriveArgs: (data: unknown) => unknown;\n /** The block's `argsIssues()` lambda; `undefined` when the block declares none. */\n argsIssues: ((input: { args: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** The block's own lambdas for staging: its `prerunArgs()` and the `prerunArgsIssues()` set after it. */\nexport interface OwnPrerunArgsDerivation {\n /** The block's `prerunArgs()` lambda. */\n derivePrerunArgs: (data: unknown) => unknown;\n /** The block's `prerunArgsIssues()` lambda; `undefined` when the block declares none. */\n prerunArgsIssues: ((input: { prerunArgs: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** {@link ArgsDerivation} plus the block's own lambdas for staging args. */\nexport interface PrerunArgsDerivation extends ArgsDerivation {\n /** The block's own staging lambdas; `undefined` when the block stages its args. */\n ownPrerunArgs: OwnPrerunArgsDerivation | undefined;\n}\n\n/**\n * Derives args from storage using the block's args function, then finds the issues in them\n * with the block's `argsIssues()`.\n *\n * A throw from `argsIssues()`, or a result that is not a list of issues, is one error carrying\n * the thrown or parser message, so a broken check keeps the block from running instead of\n * letting it run unchecked.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args and args issues lambdas\n * @returns ArgsDeriveResult with derived args and args issues, or error\n */\nexport function deriveArgsFromStorage(\n storageJson: string,\n derivation: ArgsDerivation,\n): ArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw: ${run.message}` };\n\n const { args, issues } = run;\n const errors = errorMessages(issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), args, issues };\n return { value: args, issues };\n}\n\n/**\n * Derives prerunArgs from storage.\n *\n * A block with its own `prerunArgs()` is staged with what it returns, unless its\n * `prerunArgsIssues()` finds errors in it; `argsIssues()` is not consulted then. A `prerunArgs()`\n * that returns `undefined` skips staging, and `prerunArgsIssues()` is not called for it.\n *\n * A block without its own `prerunArgs()` is staged with its args, unless `argsIssues()` finds\n * errors in them: args that may not run are not staged either.\n *\n * A throw from either issues lambda, or a result that is not a list of issues, is one error\n * carrying the thrown or parser message.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args, args issues and own staging lambdas\n * @returns PrerunArgsDeriveResult with derived prerunArgs and their issues, or error\n */\nexport function derivePrerunArgsFromStorage(\n storageJson: string,\n derivation: PrerunArgsDerivation,\n): PrerunArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n const { ownPrerunArgs } = derivation;\n\n if (ownPrerunArgs !== undefined) {\n const run = derivePrerunArgsWithIssues(data, ownPrerunArgs);\n if (run.type === \"threw\") return { error: `prerunArgs() threw: ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), issues: run.issues };\n return { value: run.args, issues: run.issues };\n }\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw (fallback): ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) {\n return {\n error: `argsIssues() found errors (fallback): ${errors.join(\"; \")}`,\n issues: run.issues,\n };\n }\n return { value: run.args, issues: run.issues };\n}\n\n// =============================================================================\n// Template Entry Derivation from Storage\n// =============================================================================\n\n/**\n * Derives this block's template-entry params from storage.\n *\n * The inverse of the data model's `init`: `init` turns `params` into data, this\n * turns data back into the params that would recreate it.\n *\n * The lambda returns ordinary live params — references as `PlRef`s, column identifiers as they\n * are stored — and that is exactly what gets written. Nothing is marked, normalized or\n * rewritten on the way out: a template holds what the block holds. Repointing those references\n * at another project is the business of {@link createInitialStorageFromParams}, on the way back\n * in, where the ids to point at are known.\n *\n * Every block declares the lambda, so every export produces params; a block with\n * nothing worth restoring returns `{}` rather than declining.\n *\n * @param storageJson - Storage as JSON string\n * @param deriveTemplateParams - The block's templateParams lambda\n * @returns DeriveResult holding the params exactly as the block projected them\n */\nexport function deriveTemplateParamsFromStorage<TP extends (data: unknown) => unknown>(\n storageJson: string,\n deriveTemplateParams: TP,\n): DeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n try {\n return { value: deriveTemplateParams(data) };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `templateParams() threw: ${errorMsg}` };\n }\n}\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n\n// =============================================================================\n// Internals\n// =============================================================================\n\n/** What a lambda building args, and the issues lambda checking them, made of a block's data. */\ntype ArgsWithIssues =\n | { type: \"threw\"; message: string }\n | { type: \"derived\"; args: unknown; issues: ArgsIssue[] };\n\nfunction deriveArgsWithIssues(data: unknown, derivation: ArgsDerivation): ArgsWithIssues {\n const { deriveArgs, argsIssues } = derivation;\n\n let args: unknown;\n try {\n args = deriveArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (argsIssues === undefined) return { type: \"derived\", args, issues: [] };\n return { type: \"derived\", args, issues: collectIssues(() => argsIssues({ args, data })) };\n}\n\nfunction derivePrerunArgsWithIssues(\n data: unknown,\n derivation: OwnPrerunArgsDerivation,\n): ArgsWithIssues {\n const { derivePrerunArgs, prerunArgsIssues } = derivation;\n\n let prerunArgs: unknown;\n try {\n prerunArgs = derivePrerunArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (prerunArgsIssues === undefined || prerunArgs === undefined) {\n return { type: \"derived\", args: prerunArgs, issues: [] };\n }\n return {\n type: \"derived\",\n args: prerunArgs,\n issues: collectIssues(() => prerunArgsIssues({ prerunArgs, data })),\n };\n}\n\n/**\n * Calls an issues lambda of the block. Its result is parsed rather than trusted: a block's types\n * do not hold at run time, and an entry that cannot be read must count as an error, not slip\n * past. A throw, or a result that cannot be read, is one error carrying its message.\n */\nfunction collectIssues(issuesOf: () => unknown): ArgsIssue[] {\n try {\n return parseArgsIssues(issuesOf());\n } catch (e) {\n return [{ severity: \"error\", message: messageOf(e) }];\n }\n}\n\nfunction errorMessages(issues: ArgsIssue[]): string[] {\n return issues.filter((issue) => issue.severity !== \"warning\").map((issue) => issue.message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAS,iBAAiB,YAA6C;CAErE,IAAI,eAAe,KAAA,KAAa,eAAe,MAE7C,OAAO;EAAE,SADOA,sBAAAA,mBAAmB,CAAC,CACrB;EAAG,MAAM,CAAC;CAAE;CAI7B,IAAI,SAAS;CACb,IAAI,OAAO,eAAe,UACxB,IAAI;EACF,SAAS,KAAK,MAAM,UAAU;CAChC,QAAQ;EAGN,OAAO;GAAE,SADOA,sBAAAA,mBAAmB,UACpB;GAAG,MAAM;EAAW;CACrC;CAIF,IAAIC,sBAAAA,eAAe,MAAM,GAAG;EAC1B,MAAM,UAAUC,sBAAAA,sBAAsB,MAAM;EAC5C,OAAO;GAAE;GAAS,MAAMC,sBAAAA,eAAe,OAAO;EAAE;CAClD;CAGA,IAAI,yBAAyB,MAAM,GAGjC,OAAO;EAAE,SADOH,sBAAAA,mBAAmB,MACpB;EAAG,MAAM;CAAO;CAKjC,OAAO;EAAE,SADOA,sBAAAA,mBAAmB,MACpB;EAAG,MAAM;CAAO;AACjC;;;;;;;;;AAUA,SAAgB,mBACd,oBACA,SAC+B;CAC/B,MAAM,EAAE,SAAS,mBAAmB,iBAAiB,kBAAkB;CAGvE,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getStorageData","updateStorageData","stringifyJson","obj","migrateBlockStorage","BLOCK_STORAGE_KEY","expandTemplateRefs","relocateBlockIds","parseArgsIssues"],"sources":["../src/block_storage_callbacks.ts"],"sourcesContent":["/**\n * BlockStorage Callback Implementations - wired to facade callbacks in BlockModelV3.done().\n *\n * Provides pure functions for storage operations (migration, initialization,\n * args derivation, updates, debug views). Each function takes its dependencies\n * explicitly as parameters.\n *\n * @module block_storage_callbacks\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n type PluginRegistry,\n type VersionedData,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n migrateBlockStorage,\n normalizeBlockStorage,\n updateStorageData,\n} from \"./block_storage\";\nimport type { PluginHandle } from \"./plugin_handle\";\n\nimport {\n stringifyJson,\n expandTemplateRefs,\n parseArgsIssues,\n relocateBlockIds,\n type ArgsIssue,\n type StringifiedJson,\n} from \"@milaboratories/pl-model-common\";\nimport type { DataVersioned, TransferRecord } from \"./block_migrations\";\nimport type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\n\n// =============================================================================\n// Hook interfaces for dependency injection\n// =============================================================================\n\n/** Dependencies for storage migration */\nexport interface MigrationHooks {\n migrateBlockData: (versioned: DataVersioned<unknown>) => DataVersioned<unknown> & {\n transfers: TransferRecord;\n };\n getPluginRegistry: () => PluginRegistry;\n migratePluginData: (\n handle: PluginHandle,\n versioned: DataVersioned<unknown>,\n ) => DataVersioned<unknown> | undefined;\n createPluginData: (\n handle: PluginHandle,\n transfer?: DataVersioned<unknown>,\n ) => DataVersioned<unknown>;\n}\n\n/** Dependencies for initial storage creation */\nexport interface InitialStorageHooks {\n getDefaultBlockData: () => DataVersioned<unknown>;\n getPluginRegistry: () => PluginRegistry;\n createPluginData: (handle: PluginHandle) => DataVersioned<unknown>;\n}\n\n/**\n * Result of storage normalization\n */\nexport interface NormalizeStorageResult {\n /** The normalized BlockStorage object */\n storage: BlockStorage;\n /** The extracted data (what developers see) */\n data: unknown;\n}\n\n/**\n * Normalizes raw storage data and extracts state.\n * Handles all formats:\n * - New BlockStorage format (has discriminator)\n * - Legacy V1/V2 format ({ args, uiState })\n * - Raw V3 state (any other format)\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns Object with normalized storage and extracted state\n */\nfunction normalizeStorage(rawStorage: unknown): NormalizeStorageResult {\n // Handle undefined/null\n if (rawStorage === undefined || rawStorage === null) {\n const storage = createBlockStorage({});\n return { storage, data: {} };\n }\n\n // Parse JSON string if needed\n let parsed = rawStorage;\n if (typeof rawStorage === \"string\") {\n try {\n parsed = JSON.parse(rawStorage);\n } catch {\n // If parsing fails, treat string as the data\n const storage = createBlockStorage(rawStorage);\n return { storage, data: rawStorage };\n }\n }\n\n // Check for BlockStorage format (has discriminator)\n if (isBlockStorage(parsed)) {\n const storage = normalizeBlockStorage(parsed);\n return { storage, data: getStorageData(storage) };\n }\n\n // Check for legacy V1/V2 format: { args, uiState }\n if (isLegacyModelV1ApiFormat(parsed)) {\n // For legacy format, the whole object IS the data\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n }\n\n // Raw V3 data - wrap it\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n}\n\n/**\n * Applies a state update to existing storage.\n * Used when setData is called from the frontend.\n *\n * @param currentStorageJson - Current storage as JSON string (must be defined)\n * @param payload - Update payload with operation type and value\n * @returns Updated storage as StringifiedJson<BlockStorage>\n */\nexport function applyStorageUpdate(\n currentStorageJson: string,\n payload: MutateStoragePayload,\n): StringifiedJson<BlockStorage> {\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n // Update data while preserving other storage fields (version, plugins)\n const updatedStorage = updateStorageData(currentStorage, payload);\n\n return stringifyJson(updatedStorage);\n}\n\n/**\n * Checks if data is in legacy Model API v1 format.\n * Legacy format has { args, uiState? } at top level without the BlockStorage discriminator.\n */\nfunction isLegacyModelV1ApiFormat(data: unknown): data is { args?: unknown } {\n if (data === null || typeof data !== \"object\") return false;\n if (isBlockStorage(data)) return false;\n\n const obj = data as Record<string, unknown>;\n return \"args\" in obj;\n}\n\n// =============================================================================\n// Facade Callback Implementations\n// =============================================================================\n\n/**\n * Gets storage debug view from raw storage data.\n * Returns structured debug info about the storage state.\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns JSON string with storage debug view\n */\nexport function getStorageDebugView(rawStorage: unknown): StringifiedJson<StorageDebugView> {\n const { storage } = normalizeStorage(rawStorage);\n const debugView: StorageDebugView = {\n dataVersion: storage.__dataVersion,\n data: storage.__data,\n };\n return stringifyJson(debugView);\n}\n\n// =============================================================================\n// Migration Support\n// =============================================================================\n\n/**\n * Result of storage migration.\n * Returned by __pl_storage_migrate callback.\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Runs storage migration using the provided hooks.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @param hooks - Migration dependencies (block/plugin data migration and creation functions)\n * @returns MigrationResult\n */\nexport function migrateStorage(\n currentStorageJson: string | undefined,\n hooks: MigrationHooks,\n): MigrationResult {\n // Normalize current storage\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n const newPluginRegistry = hooks.getPluginRegistry();\n\n // Perform atomic migration of block + all plugins\n const migrationResult = migrateBlockStorage(currentStorage, {\n migrateBlockData: hooks.migrateBlockData,\n migratePluginData: hooks.migratePluginData,\n newPluginRegistry,\n createPluginData: hooks.createPluginData,\n });\n\n if (!migrationResult.success) {\n return {\n error: `Migration failed at '${migrationResult.failedAt}': ${migrationResult.error}`,\n };\n }\n\n // Build info message\n const oldVersion = currentStorage.__dataVersion;\n const newVersion = migrationResult.storage.__dataVersion;\n const info =\n oldVersion === newVersion\n ? `No migration needed (${oldVersion})`\n : `Migrated ${oldVersion} -> ${newVersion}`;\n\n return {\n newStorageJson: stringifyJson(migrationResult.storage),\n info,\n };\n}\n\n// =============================================================================\n// Initial Storage Creation\n// =============================================================================\n\n/**\n * Creates complete initial storage (block data + all plugin data) atomically.\n *\n * @param hooks - Dependencies for creating initial block and plugin data\n * @returns Initial storage as branded JSON string\n * @throws If initialDataFn or createPluginData throws\n */\nexport function createInitialStorage(hooks: InitialStorageHooks): StringifiedJson<BlockStorage> {\n return assembleStorage(hooks.getDefaultBlockData(), hooks);\n}\n\n/**\n * Wraps freshly created block data and freshly created plugin data into storage.\n *\n * Shared by the two ways a block's first storage comes into being — from defaults\n * and from template params. Only the block's own data differs between them:\n * plugins have no params channel, so they are always created at their defaults.\n */\nfunction assembleStorage(\n blockData: DataVersioned<unknown>,\n hooks: Omit<InitialStorageHooks, \"getDefaultBlockData\">,\n): StringifiedJson<BlockStorage> {\n const pluginRegistry = hooks.getPluginRegistry();\n\n const plugins: Record<PluginHandle, VersionedData<unknown>> = {};\n for (const handle of Object.keys(pluginRegistry) as PluginHandle[]) {\n const initial = hooks.createPluginData(handle);\n plugins[handle] = { __dataVersion: initial.version, __data: initial.data };\n }\n\n const storage: BlockStorage = {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: blockData.version,\n __data: blockData.data,\n __pluginRegistry: pluginRegistry,\n __plugins: plugins,\n };\n return stringifyJson(storage);\n}\n\n/** Dependencies for creating storage from a template entry's params. */\nexport interface ParamsStorageHooks extends Omit<InitialStorageHooks, \"getDefaultBlockData\"> {\n /** The block's init factory, called with the entry's params. */\n getBlockDataFromParams: (params: unknown) => DataVersioned<unknown>;\n /**\n * The kind's runtime params check. Applied before the factory sees anything, and its\n * output is what the factory gets.\n */\n parseInitializationParams: (value: unknown) => unknown;\n}\n\n/** Result of checking params against their kind: the params to use, or why they lost. */\nexport type TemplateParamsValidationResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Check params against their kind's declared shape.\n *\n * The kind owns this rather than the block because the params contract belongs to the\n * kind: many block versions implement one kind, and a per-block check would let them\n * drift from each other and from the type.\n *\n * A parser rejects by throwing and accepts by returning the params to use, so its\n * output — not the input — is what flows onward. That is what lets a kind strip keys\n * it does not declare, which is the difference between a typo being ignored and a typo\n * being reported.\n *\n * Every kind declares a parser, so every set of params that reaches here is checked;\n * there is no pass-through path.\n *\n * @param value The params to check, references already in live form\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParams(\n value: unknown,\n parseInitializationParams: (value: unknown) => unknown,\n): TemplateParamsValidationResult {\n try {\n return { value: parseInitializationParams(value) };\n } catch (e) {\n // A rejection is an expected outcome for a hand-written file, so it is reported,\n // not thrown.\n return { error: `params do not match this block's kind: ${describeRejection(e)}` };\n }\n}\n\n/** One `{ path, message }` entry of a schema library's error. */\ntype IssueLike = { path?: unknown; message?: unknown };\n\n/**\n * Render whatever a parser threw as one readable line.\n *\n * An error carrying an `issues` array is unpacked rather than printed: that is the\n * shape zod (and several others) use, and its `message` is the whole issue list as\n * JSON — technically complete and unreadable in a dialog. Duck-typed on purpose, since\n * this package prescribes no schema library and takes no dependency on one; anything\n * else falls back to its own message.\n */\nfunction describeRejection(e: unknown): string {\n const issues = (e as { issues?: unknown }).issues;\n if (!Array.isArray(issues) || issues.length === 0) return messageOf(e);\n\n return issues\n .map((issue) => {\n const { path, message } = issue as IssueLike;\n const what = typeof message === \"string\" ? message : \"is invalid\";\n const where = Array.isArray(path) ? formatPath(path) : \"\";\n return where === \"\" ? what : `${where}: ${what}`;\n })\n .join(\"; \");\n}\n\n/** `[\"numbers\", 0]` → `numbers[0]` — how the params are written, not how they parse. */\nfunction formatPath(path: readonly unknown[]): string {\n return path.reduce<string>((acc, segment) => {\n if (typeof segment === \"number\") return `${acc}[${segment}]`;\n return acc === \"\" ? String(segment) : `${acc}.${String(segment)}`;\n }, \"\");\n}\n\n/**\n * Result of the `__pl_params_validate` callback.\n *\n * Carries no params back. The check is a pre-flight — its answer is \"may this entry be\n * applied\", and the params that actually reach the block are produced by\n * {@link createInitialStorageFromParams}, which parses again. One authoritative\n * producer, rather than two values that could differ.\n */\nexport type InitializationParamsValidateCallbackResult = { error: string } | { error?: undefined };\n\n/**\n * Check params that crossed into the model VM as text.\n *\n * The pre-flight entry point: a caller asks this before creating anything, once per\n * template entry, so params a kind rejects are reported while there is still no\n * project to half-build.\n *\n * The readable reference spelling is expanded here too, so what the kind checks is the shape it\n * declared. The ids it sees are the file's own — no block exists yet — which is why a kind must\n * not read meaning into a specific id.\n *\n * @param paramsJson The entry's params as JSON string\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParamsJson(\n paramsJson: string,\n parseInitializationParams: (value: unknown) => unknown,\n): InitializationParamsValidateCallbackResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Expanded before the kind sees anything, or a hand-written file would be rejected by every\n // kind that declares a reference: `{ block, name }` is not a `PlRef` and no contract accepts\n // one. Expansion needs nothing but the params, so this stays a two-argument check — the ids\n // are not known yet and are not needed to answer the question this asks.\n const result = validateTemplateParams(expandTemplateRefs(params), parseInitializationParams);\n if (result.error !== undefined) return { error: result.error };\n return {};\n}\n\nfunction messageOf(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Result of building initial storage from params.\n * Returned by the `__pl_storage_initialFromParams` callback.\n */\nexport type ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Creates complete initial storage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}: that projects storage\n * into params, this builds storage from them. The params are handed to the block's\n * init factory, whose output is versioned and wrapped exactly as\n * {@link createInitialStorage} wraps the defaults — so a block created from a\n * template is indistinguishable from one created in the UI and then edited.\n *\n * **This is where a template's references become the block's own**, and it is the only place in\n * a template's life where a reference is recognized at all. Params travel from the file\n * untouched — the engine carrying them neither marks a reference nor reads one, because\n * recognizing one means knowing the reference system, and that knowledge is here.\n *\n * Two things happen, in this order. The readable spelling a person may have written\n * (`{ block, name }`) is expanded into the `PlRef` it stands for. Then every reference naming\n * an entry that has a block is repointed at it: `blockIds` maps each template-local entry id to\n * the block id it was given, and an id it does not name is left alone, which is how a reference\n * to an entry created later ends up naming nothing rather than naming the wrong block.\n *\n * Relocation happens before the kind's parser and before the factory, so both see the ids the\n * block will actually hold. It is one step of this function rather than a callback of its own\n * precisely because nothing else wants its result: every VM call re-instantiates the runtime\n * and re-evaluates the whole model bundle, so a separate call would parse the block twice per\n * entry to produce a value only the next line reads.\n *\n * Params arrive as JSON text because this runs across the model-VM boundary, where\n * only strings pass. Anything the factory rejects is returned as an error rather\n * than thrown: applying a hand-written template is expected to surface bad params,\n * and the applier reports every entry's problem in one pass.\n *\n * @param paramsJson - The entry's params as JSON string, exactly as the file held them\n * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n * @param hooks - The block's init factory plus plugin creation\n * @returns The storage to write, or why the params could not produce any\n */\nexport function createInitialStorageFromParams(\n paramsJson: string,\n blockIdsJson: string,\n hooks: ParamsStorageHooks,\n): ParamsStorageResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Read separately from the params, and reported separately, because the two fail for\n // completely different reasons. Params are the file's and a bad one is the author's mistake;\n // this argument is the caller's, so the only way it arrives unreadable is a caller that does\n // not send it — a middle layer older than this block, which is a build to refresh rather than\n // anything to fix in the template. Folding both into one message sent the reader to the file.\n let blockIds: Map<string, string>;\n try {\n blockIds = new Map(Object.entries(JSON.parse(blockIdsJson) as Record<string, string>));\n } catch (e) {\n return {\n error:\n `this block was not told which blocks the template's references should point at ` +\n `(${messageOf(e)}). The application applying the template is older than the block; ` +\n `rebuild or update it.`,\n };\n }\n\n try {\n // Spelling first, ids second. Expansion turns `{ block, name }` into a `PlRef` naming an\n // ENTRY, which is exactly what relocation then repoints — so both spellings reach the\n // block through the same step and cannot diverge in how they behave.\n params = relocateBlockIds(expandTemplateRefs(params), blockIds);\n } catch (e) {\n return { error: `this entry's references could not be relocated: ${messageOf(e)}` };\n }\n\n // Checked here too, not only in the caller's pre-flight pass. The pre-flight is\n // about reporting every bad entry before anything is created; this is about the\n // factory never being handed a value the kind rejects, whichever path got here.\n const checked = validateTemplateParams(params, hooks.parseInitializationParams);\n if (checked.error !== undefined) return { error: checked.error };\n\n try {\n return { storageJson: assembleStorage(hooks.getBlockDataFromParams(checked.value), hooks) };\n } catch (e) {\n return { error: `init() threw on the given params: ${messageOf(e)}` };\n }\n}\n\n// =============================================================================\n// Params onto Live Data\n// =============================================================================\n\n/** Dependencies for putting params onto a block's live data. */\nexport interface ApplyParamsHooks {\n /** The data model's current version: the one `applyParams` takes and returns. */\n dataVersion: string;\n /** The block's `applyParams`, given data at {@link ApplyParamsHooks.dataVersion}. */\n applyParams: (data: unknown, params: unknown) => DataVersioned<unknown>;\n /** The kind's runtime params check; its output is what `applyParams` gets. */\n parseInitializationParams: (value: unknown) => unknown;\n}\n\n/**\n * Puts params onto the block's live data with the block's own `applyParams`, the\n * `__pl_storage_applyParams` callback.\n *\n * The params are checked as {@link createInitialStorageFromParams} checks them: the readable\n * reference spelling is expanded, then the kind's parser runs and its output is what\n * `applyParams` gets. They are live params, so no reference is relocated.\n *\n * The data is refused unless it is at the data model's current version: `applyParams` is written\n * against that type, and migrating here would leave plugin transfers half done. Everything but the\n * block's data — its version, plugins, registry — is kept as it is.\n *\n * @param storageJson - Current storage as JSON string\n * @param paramsJson - The new params as JSON string, whole\n * @param hooks - The block's `applyParams`, its data version, the kind's parser\n * @returns The storage with the params applied, or why there is none\n */\nexport function applyParamsToStorage(\n storageJson: string,\n paramsJson: string,\n hooks: ApplyParamsHooks,\n): ParamsStorageResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n const { storage, data } = normalizeStorage(storageJson);\n if (storage.__dataVersion !== hooks.dataVersion)\n return {\n error:\n `the block's data is at version ${storage.__dataVersion}, while applyParams() ` +\n `takes version ${hooks.dataVersion}: the data waits for a migration`,\n };\n\n try {\n params = expandTemplateRefs(params);\n } catch (e) {\n return { error: `the params' references could not be read: ${messageOf(e)}` };\n }\n const checked = validateTemplateParams(params, hooks.parseInitializationParams);\n if (checked.error !== undefined) return { error: checked.error };\n\n let applied: DataVersioned<unknown>;\n try {\n applied = hooks.applyParams(data, checked.value);\n } catch (e) {\n return { error: `applyParams() threw on the given params: ${messageOf(e)}` };\n }\n return {\n storageJson: stringifyJson({\n ...storage,\n __dataVersion: applied.version,\n __data: applied.data,\n }),\n };\n}\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of a derivation that either produced a value or failed.\n * Returned by the __pl_initializationParams_derive callback.\n */\nexport type DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of args derivation from storage, returned by the __pl_args_derive callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is runnable args, `error` is no args.\n *\n * - `{ error }`: `args()` threw, so there are no args.\n * - `{ error, args, issues }`: args were built, but `argsIssues()` found errors in them, so the\n * block must not run. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args were built and nothing blocks the run; `issues` holds the warnings.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error: string; args: unknown; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/**\n * Result of prerun args derivation from storage, returned by the __pl_prerunArgs_derive\n * callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is args to stage, `error` skips staging.\n *\n * - `{ error }`: the lambda that builds the prerun args threw.\n * - `{ error, issues }`: prerun args were built, but the issues found in them include errors, so\n * the block is not staged. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args to stage; `issues` holds the warnings. A `value` of `undefined`\n * comes from a `prerunArgs()` that returned nothing, and skips staging.\n */\nexport type PrerunArgsDeriveResult =\n | { error: string }\n | { error: string; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/** The block's lambdas that turn its data into args and find what keeps those args from running. */\nexport interface ArgsDerivation {\n /** The block's `args()` lambda. */\n deriveArgs: (data: unknown) => unknown;\n /** The block's `argsIssues()` lambda; `undefined` when the block declares none. */\n argsIssues: ((input: { args: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** The block's own lambdas for staging: its `prerunArgs()` and the `prerunArgsIssues()` set after it. */\nexport interface OwnPrerunArgsDerivation {\n /** The block's `prerunArgs()` lambda. */\n derivePrerunArgs: (data: unknown) => unknown;\n /** The block's `prerunArgsIssues()` lambda; `undefined` when the block declares none. */\n prerunArgsIssues: ((input: { prerunArgs: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** {@link ArgsDerivation} plus the block's own lambdas for staging args. */\nexport interface PrerunArgsDerivation extends ArgsDerivation {\n /** The block's own staging lambdas; `undefined` when the block stages its args. */\n ownPrerunArgs: OwnPrerunArgsDerivation | undefined;\n}\n\n/**\n * Derives args from storage using the block's args function, then finds the issues in them\n * with the block's `argsIssues()`.\n *\n * A throw from `argsIssues()`, or a result that is not a list of issues, is one error carrying\n * the thrown or parser message, so a broken check keeps the block from running instead of\n * letting it run unchecked.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args and args issues lambdas\n * @returns ArgsDeriveResult with derived args and args issues, or error\n */\nexport function deriveArgsFromStorage(\n storageJson: string,\n derivation: ArgsDerivation,\n): ArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw: ${run.message}` };\n\n const { args, issues } = run;\n const errors = errorMessages(issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), args, issues };\n return { value: args, issues };\n}\n\n/**\n * Derives prerunArgs from storage.\n *\n * A block with its own `prerunArgs()` is staged with what it returns, unless its\n * `prerunArgsIssues()` finds errors in it; `argsIssues()` is not consulted then. A `prerunArgs()`\n * that returns `undefined` skips staging, and `prerunArgsIssues()` is not called for it.\n *\n * A block without its own `prerunArgs()` is staged with its args, unless `argsIssues()` finds\n * errors in them: args that may not run are not staged either.\n *\n * A throw from either issues lambda, or a result that is not a list of issues, is one error\n * carrying the thrown or parser message.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args, args issues and own staging lambdas\n * @returns PrerunArgsDeriveResult with derived prerunArgs and their issues, or error\n */\nexport function derivePrerunArgsFromStorage(\n storageJson: string,\n derivation: PrerunArgsDerivation,\n): PrerunArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n const { ownPrerunArgs } = derivation;\n\n if (ownPrerunArgs !== undefined) {\n const run = derivePrerunArgsWithIssues(data, ownPrerunArgs);\n if (run.type === \"threw\") return { error: `prerunArgs() threw: ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), issues: run.issues };\n return { value: run.args, issues: run.issues };\n }\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw (fallback): ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) {\n return {\n error: `argsIssues() found errors (fallback): ${errors.join(\"; \")}`,\n issues: run.issues,\n };\n }\n return { value: run.args, issues: run.issues };\n}\n\n// =============================================================================\n// Template Entry Derivation from Storage\n// =============================================================================\n\n/**\n * Derives this block's template-entry params from storage.\n *\n * The inverse of the data model's `init`: `init` turns `params` into data, this\n * turns data back into the params that would recreate it.\n *\n * The lambda returns ordinary live params — references as `PlRef`s, column identifiers as they\n * are stored — and that is exactly what gets written. Nothing is marked, normalized or\n * rewritten on the way out: a template holds what the block holds. Repointing those references\n * at another project is the business of {@link createInitialStorageFromParams}, on the way back\n * in, where the ids to point at are known.\n *\n * Every block declares the lambda, so every export produces params; a block with\n * nothing worth restoring returns `{}` rather than declining.\n *\n * @param storageJson - Storage as JSON string\n * @param deriveTemplateParams - The block's templateParams lambda\n * @returns DeriveResult holding the params exactly as the block projected them\n */\nexport function deriveTemplateParamsFromStorage<TP extends (data: unknown) => unknown>(\n storageJson: string,\n deriveTemplateParams: TP,\n): DeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n try {\n return { value: deriveTemplateParams(data) };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `templateParams() threw: ${errorMsg}` };\n }\n}\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n\n// =============================================================================\n// Internals\n// =============================================================================\n\n/** What a lambda building args, and the issues lambda checking them, made of a block's data. */\ntype ArgsWithIssues =\n | { type: \"threw\"; message: string }\n | { type: \"derived\"; args: unknown; issues: ArgsIssue[] };\n\nfunction deriveArgsWithIssues(data: unknown, derivation: ArgsDerivation): ArgsWithIssues {\n const { deriveArgs, argsIssues } = derivation;\n\n let args: unknown;\n try {\n args = deriveArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (argsIssues === undefined) return { type: \"derived\", args, issues: [] };\n return { type: \"derived\", args, issues: collectIssues(() => argsIssues({ args, data })) };\n}\n\nfunction derivePrerunArgsWithIssues(\n data: unknown,\n derivation: OwnPrerunArgsDerivation,\n): ArgsWithIssues {\n const { derivePrerunArgs, prerunArgsIssues } = derivation;\n\n let prerunArgs: unknown;\n try {\n prerunArgs = derivePrerunArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (prerunArgsIssues === undefined || prerunArgs === undefined) {\n return { type: \"derived\", args: prerunArgs, issues: [] };\n }\n return {\n type: \"derived\",\n args: prerunArgs,\n issues: collectIssues(() => prerunArgsIssues({ prerunArgs, data })),\n };\n}\n\n/**\n * Calls an issues lambda of the block. Its result is parsed rather than trusted: a block's types\n * do not hold at run time, and an entry that cannot be read must count as an error, not slip\n * past. A throw, or a result that cannot be read, is one error carrying its message.\n */\nfunction collectIssues(issuesOf: () => unknown): ArgsIssue[] {\n try {\n return parseArgsIssues(issuesOf());\n } catch (e) {\n return [{ severity: \"error\", message: messageOf(e) }];\n }\n}\n\nfunction errorMessages(issues: ArgsIssue[]): string[] {\n return issues.filter((issue) => issue.severity !== \"warning\").map((issue) => issue.message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAS,iBAAiB,YAA6C;CAErE,IAAI,eAAe,KAAA,KAAa,eAAe,MAE7C,OAAO;EAAE,SADOA,sBAAAA,mBAAmB,CAAC,CACrB;EAAG,MAAM,CAAC;CAAE;CAI7B,IAAI,SAAS;CACb,IAAI,OAAO,eAAe,UACxB,IAAI;EACF,SAAS,KAAK,MAAM,UAAU;CAChC,QAAQ;EAGN,OAAO;GAAE,SADOA,sBAAAA,mBAAmB,UACpB;GAAG,MAAM;EAAW;CACrC;CAIF,IAAIC,sBAAAA,eAAe,MAAM,GAAG;EAC1B,MAAM,UAAUC,sBAAAA,sBAAsB,MAAM;EAC5C,OAAO;GAAE;GAAS,MAAMC,sBAAAA,eAAe,OAAO;EAAE;CAClD;CAGA,IAAI,yBAAyB,MAAM,GAGjC,OAAO;EAAE,SADOH,sBAAAA,mBAAmB,MACpB;EAAG,MAAM;CAAO;CAKjC,OAAO;EAAE,SADOA,sBAAAA,mBAAmB,MACpB;EAAG,MAAM;CAAO;AACjC;;;;;;;;;AAUA,SAAgB,mBACd,oBACA,SAC+B;CAC/B,MAAM,EAAE,SAAS,mBAAmB,iBAAiB,kBAAkB;CAGvE,MAAM,iBAAiBI,sBAAAA,kBAAkB,gBAAgB,OAAO;CAEhE,QAAA,GAAOC,gCAAAA,cAAAA,CAAc,cAAc;AACrC;;;;;AAMA,SAAS,yBAAyB,MAA2C;CAC3E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;CACJ,IAAI;EACF,aAAa,iBAAiB,IAAI;CACpC,SAAS,GAAG;EACV,OAAO;GAAE,MAAM;GAAS,SAAS,UAAU,CAAC;EAAE;CAChD;CAEA,IAAI,qBAAqB,KAAA,KAAa,eAAe,KAAA,GACnD,OAAO;EAAE,MAAM;EAAW,MAAM;EAAY,QAAQ,CAAC;CAAE;CAEzD,OAAO;EACL,MAAM;EACN,MAAM;EACN,QAAQ,oBAAoB,iBAAiB;GAAE;GAAY;EAAK,CAAC,CAAC;CACpE;AACF;;;;;;AAOA,SAAS,cAAc,UAAsC;CAC3D,IAAI;EACF,QAAA,GAAOM,gCAAAA,gBAAAA,CAAgB,SAAS,CAAC;CACnC,SAAS,GAAG;EACV,OAAO,CAAC;GAAE,UAAU;GAAS,SAAS,UAAU,CAAC;EAAE,CAAC;CACtD;AACF;AAEA,SAAS,cAAc,QAA+B;CACpD,OAAO,OAAO,QAAQ,UAAU,MAAM,aAAa,SAAS,CAAC,CAAC,KAAK,UAAU,MAAM,OAAO;AAC5F"}
@@ -292,6 +292,51 @@ function createInitialStorageFromParams(paramsJson, blockIdsJson, hooks) {
292
292
  }
293
293
  }
294
294
  /**
295
+ * Puts params onto the block's live data with the block's own `applyParams`, the
296
+ * `__pl_storage_applyParams` callback.
297
+ *
298
+ * The params are checked as {@link createInitialStorageFromParams} checks them: the readable
299
+ * reference spelling is expanded, then the kind's parser runs and its output is what
300
+ * `applyParams` gets. They are live params, so no reference is relocated.
301
+ *
302
+ * The data is refused unless it is at the data model's current version: `applyParams` is written
303
+ * against that type, and migrating here would leave plugin transfers half done. Everything but the
304
+ * block's data — its version, plugins, registry — is kept as it is.
305
+ *
306
+ * @param storageJson - Current storage as JSON string
307
+ * @param paramsJson - The new params as JSON string, whole
308
+ * @param hooks - The block's `applyParams`, its data version, the kind's parser
309
+ * @returns The storage with the params applied, or why there is none
310
+ */
311
+ function applyParamsToStorage(storageJson, paramsJson, hooks) {
312
+ let params;
313
+ try {
314
+ params = JSON.parse(paramsJson);
315
+ } catch (e) {
316
+ return { error: `params are not valid JSON: ${messageOf(e)}` };
317
+ }
318
+ const { storage, data } = normalizeStorage(storageJson);
319
+ if (storage.__dataVersion !== hooks.dataVersion) return { error: `the block's data is at version ${storage.__dataVersion}, while applyParams() takes version ${hooks.dataVersion}: the data waits for a migration` };
320
+ try {
321
+ params = expandTemplateRefs(params);
322
+ } catch (e) {
323
+ return { error: `the params' references could not be read: ${messageOf(e)}` };
324
+ }
325
+ const checked = validateTemplateParams(params, hooks.parseInitializationParams);
326
+ if (checked.error !== void 0) return { error: checked.error };
327
+ let applied;
328
+ try {
329
+ applied = hooks.applyParams(data, checked.value);
330
+ } catch (e) {
331
+ return { error: `applyParams() threw on the given params: ${messageOf(e)}` };
332
+ }
333
+ return { storageJson: stringifyJson({
334
+ ...storage,
335
+ __dataVersion: applied.version,
336
+ __data: applied.data
337
+ }) };
338
+ }
339
+ /**
295
340
  * Derives args from storage using the block's args function, then finds the issues in them
296
341
  * with the block's `argsIssues()`.
297
342
  *
@@ -459,6 +504,6 @@ function collectIssues(issuesOf) {
459
504
  function errorMessages(issues) {
460
505
  return issues.filter((issue) => issue.severity !== "warning").map((issue) => issue.message);
461
506
  }
462
- export { BLOCK_STORAGE_KEY, applyStorageUpdate, createInitialStorage, createInitialStorageFromParams, deriveArgsFromStorage, derivePrerunArgsFromStorage, deriveTemplateParamsFromStorage, getStorageDebugView, migrateStorage, validateTemplateParams, validateTemplateParamsJson };
507
+ export { BLOCK_STORAGE_KEY, applyParamsToStorage, applyStorageUpdate, createInitialStorage, createInitialStorageFromParams, deriveArgsFromStorage, derivePrerunArgsFromStorage, deriveTemplateParamsFromStorage, getStorageDebugView, migrateStorage, validateTemplateParams, validateTemplateParamsJson };
463
508
 
464
509
  //# sourceMappingURL=block_storage_callbacks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"block_storage_callbacks.js","names":["obj"],"sources":["../src/block_storage_callbacks.ts"],"sourcesContent":["/**\n * BlockStorage Callback Implementations - wired to facade callbacks in BlockModelV3.done().\n *\n * Provides pure functions for storage operations (migration, initialization,\n * args derivation, updates, debug views). Each function takes its dependencies\n * explicitly as parameters.\n *\n * @module block_storage_callbacks\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n type PluginRegistry,\n type VersionedData,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n migrateBlockStorage,\n normalizeBlockStorage,\n updateStorageData,\n} from \"./block_storage\";\nimport type { PluginHandle } from \"./plugin_handle\";\n\nimport {\n stringifyJson,\n expandTemplateRefs,\n parseArgsIssues,\n relocateBlockIds,\n type ArgsIssue,\n type StringifiedJson,\n} from \"@milaboratories/pl-model-common\";\nimport type { DataVersioned, TransferRecord } from \"./block_migrations\";\nimport type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\n\n// =============================================================================\n// Hook interfaces for dependency injection\n// =============================================================================\n\n/** Dependencies for storage migration */\nexport interface MigrationHooks {\n migrateBlockData: (versioned: DataVersioned<unknown>) => DataVersioned<unknown> & {\n transfers: TransferRecord;\n };\n getPluginRegistry: () => PluginRegistry;\n migratePluginData: (\n handle: PluginHandle,\n versioned: DataVersioned<unknown>,\n ) => DataVersioned<unknown> | undefined;\n createPluginData: (\n handle: PluginHandle,\n transfer?: DataVersioned<unknown>,\n ) => DataVersioned<unknown>;\n}\n\n/** Dependencies for initial storage creation */\nexport interface InitialStorageHooks {\n getDefaultBlockData: () => DataVersioned<unknown>;\n getPluginRegistry: () => PluginRegistry;\n createPluginData: (handle: PluginHandle) => DataVersioned<unknown>;\n}\n\n/**\n * Result of storage normalization\n */\nexport interface NormalizeStorageResult {\n /** The normalized BlockStorage object */\n storage: BlockStorage;\n /** The extracted data (what developers see) */\n data: unknown;\n}\n\n/**\n * Normalizes raw storage data and extracts state.\n * Handles all formats:\n * - New BlockStorage format (has discriminator)\n * - Legacy V1/V2 format ({ args, uiState })\n * - Raw V3 state (any other format)\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns Object with normalized storage and extracted state\n */\nfunction normalizeStorage(rawStorage: unknown): NormalizeStorageResult {\n // Handle undefined/null\n if (rawStorage === undefined || rawStorage === null) {\n const storage = createBlockStorage({});\n return { storage, data: {} };\n }\n\n // Parse JSON string if needed\n let parsed = rawStorage;\n if (typeof rawStorage === \"string\") {\n try {\n parsed = JSON.parse(rawStorage);\n } catch {\n // If parsing fails, treat string as the data\n const storage = createBlockStorage(rawStorage);\n return { storage, data: rawStorage };\n }\n }\n\n // Check for BlockStorage format (has discriminator)\n if (isBlockStorage(parsed)) {\n const storage = normalizeBlockStorage(parsed);\n return { storage, data: getStorageData(storage) };\n }\n\n // Check for legacy V1/V2 format: { args, uiState }\n if (isLegacyModelV1ApiFormat(parsed)) {\n // For legacy format, the whole object IS the data\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n }\n\n // Raw V3 data - wrap it\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n}\n\n/**\n * Applies a state update to existing storage.\n * Used when setData is called from the frontend.\n *\n * @param currentStorageJson - Current storage as JSON string (must be defined)\n * @param payload - Update payload with operation type and value\n * @returns Updated storage as StringifiedJson<BlockStorage>\n */\nexport function applyStorageUpdate(\n currentStorageJson: string,\n payload: MutateStoragePayload,\n): StringifiedJson<BlockStorage> {\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n // Update data while preserving other storage fields (version, plugins)\n const updatedStorage = updateStorageData(currentStorage, payload);\n\n return stringifyJson(updatedStorage);\n}\n\n/**\n * Checks if data is in legacy Model API v1 format.\n * Legacy format has { args, uiState? } at top level without the BlockStorage discriminator.\n */\nfunction isLegacyModelV1ApiFormat(data: unknown): data is { args?: unknown } {\n if (data === null || typeof data !== \"object\") return false;\n if (isBlockStorage(data)) return false;\n\n const obj = data as Record<string, unknown>;\n return \"args\" in obj;\n}\n\n// =============================================================================\n// Facade Callback Implementations\n// =============================================================================\n\n/**\n * Gets storage debug view from raw storage data.\n * Returns structured debug info about the storage state.\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns JSON string with storage debug view\n */\nexport function getStorageDebugView(rawStorage: unknown): StringifiedJson<StorageDebugView> {\n const { storage } = normalizeStorage(rawStorage);\n const debugView: StorageDebugView = {\n dataVersion: storage.__dataVersion,\n data: storage.__data,\n };\n return stringifyJson(debugView);\n}\n\n// =============================================================================\n// Migration Support\n// =============================================================================\n\n/**\n * Result of storage migration.\n * Returned by __pl_storage_migrate callback.\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Runs storage migration using the provided hooks.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @param hooks - Migration dependencies (block/plugin data migration and creation functions)\n * @returns MigrationResult\n */\nexport function migrateStorage(\n currentStorageJson: string | undefined,\n hooks: MigrationHooks,\n): MigrationResult {\n // Normalize current storage\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n const newPluginRegistry = hooks.getPluginRegistry();\n\n // Perform atomic migration of block + all plugins\n const migrationResult = migrateBlockStorage(currentStorage, {\n migrateBlockData: hooks.migrateBlockData,\n migratePluginData: hooks.migratePluginData,\n newPluginRegistry,\n createPluginData: hooks.createPluginData,\n });\n\n if (!migrationResult.success) {\n return {\n error: `Migration failed at '${migrationResult.failedAt}': ${migrationResult.error}`,\n };\n }\n\n // Build info message\n const oldVersion = currentStorage.__dataVersion;\n const newVersion = migrationResult.storage.__dataVersion;\n const info =\n oldVersion === newVersion\n ? `No migration needed (${oldVersion})`\n : `Migrated ${oldVersion} -> ${newVersion}`;\n\n return {\n newStorageJson: stringifyJson(migrationResult.storage),\n info,\n };\n}\n\n// =============================================================================\n// Initial Storage Creation\n// =============================================================================\n\n/**\n * Creates complete initial storage (block data + all plugin data) atomically.\n *\n * @param hooks - Dependencies for creating initial block and plugin data\n * @returns Initial storage as branded JSON string\n * @throws If initialDataFn or createPluginData throws\n */\nexport function createInitialStorage(hooks: InitialStorageHooks): StringifiedJson<BlockStorage> {\n return assembleStorage(hooks.getDefaultBlockData(), hooks);\n}\n\n/**\n * Wraps freshly created block data and freshly created plugin data into storage.\n *\n * Shared by the two ways a block's first storage comes into being — from defaults\n * and from template params. Only the block's own data differs between them:\n * plugins have no params channel, so they are always created at their defaults.\n */\nfunction assembleStorage(\n blockData: DataVersioned<unknown>,\n hooks: Omit<InitialStorageHooks, \"getDefaultBlockData\">,\n): StringifiedJson<BlockStorage> {\n const pluginRegistry = hooks.getPluginRegistry();\n\n const plugins: Record<PluginHandle, VersionedData<unknown>> = {};\n for (const handle of Object.keys(pluginRegistry) as PluginHandle[]) {\n const initial = hooks.createPluginData(handle);\n plugins[handle] = { __dataVersion: initial.version, __data: initial.data };\n }\n\n const storage: BlockStorage = {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: blockData.version,\n __data: blockData.data,\n __pluginRegistry: pluginRegistry,\n __plugins: plugins,\n };\n return stringifyJson(storage);\n}\n\n/** Dependencies for creating storage from a template entry's params. */\nexport interface ParamsStorageHooks extends Omit<InitialStorageHooks, \"getDefaultBlockData\"> {\n /** The block's init factory, called with the entry's params. */\n getBlockDataFromParams: (params: unknown) => DataVersioned<unknown>;\n /**\n * The kind's runtime params check. Applied before the factory sees anything, and its\n * output is what the factory gets.\n */\n parseInitializationParams: (value: unknown) => unknown;\n}\n\n/** Result of checking params against their kind: the params to use, or why they lost. */\nexport type TemplateParamsValidationResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Check params against their kind's declared shape.\n *\n * The kind owns this rather than the block because the params contract belongs to the\n * kind: many block versions implement one kind, and a per-block check would let them\n * drift from each other and from the type.\n *\n * A parser rejects by throwing and accepts by returning the params to use, so its\n * output — not the input — is what flows onward. That is what lets a kind strip keys\n * it does not declare, which is the difference between a typo being ignored and a typo\n * being reported.\n *\n * Every kind declares a parser, so every set of params that reaches here is checked;\n * there is no pass-through path.\n *\n * @param value The params to check, references already in live form\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParams(\n value: unknown,\n parseInitializationParams: (value: unknown) => unknown,\n): TemplateParamsValidationResult {\n try {\n return { value: parseInitializationParams(value) };\n } catch (e) {\n // A rejection is an expected outcome for a hand-written file, so it is reported,\n // not thrown.\n return { error: `params do not match this block's kind: ${describeRejection(e)}` };\n }\n}\n\n/** One `{ path, message }` entry of a schema library's error. */\ntype IssueLike = { path?: unknown; message?: unknown };\n\n/**\n * Render whatever a parser threw as one readable line.\n *\n * An error carrying an `issues` array is unpacked rather than printed: that is the\n * shape zod (and several others) use, and its `message` is the whole issue list as\n * JSON — technically complete and unreadable in a dialog. Duck-typed on purpose, since\n * this package prescribes no schema library and takes no dependency on one; anything\n * else falls back to its own message.\n */\nfunction describeRejection(e: unknown): string {\n const issues = (e as { issues?: unknown }).issues;\n if (!Array.isArray(issues) || issues.length === 0) return messageOf(e);\n\n return issues\n .map((issue) => {\n const { path, message } = issue as IssueLike;\n const what = typeof message === \"string\" ? message : \"is invalid\";\n const where = Array.isArray(path) ? formatPath(path) : \"\";\n return where === \"\" ? what : `${where}: ${what}`;\n })\n .join(\"; \");\n}\n\n/** `[\"numbers\", 0]` → `numbers[0]` — how the params are written, not how they parse. */\nfunction formatPath(path: readonly unknown[]): string {\n return path.reduce<string>((acc, segment) => {\n if (typeof segment === \"number\") return `${acc}[${segment}]`;\n return acc === \"\" ? String(segment) : `${acc}.${String(segment)}`;\n }, \"\");\n}\n\n/**\n * Result of the `__pl_params_validate` callback.\n *\n * Carries no params back. The check is a pre-flight — its answer is \"may this entry be\n * applied\", and the params that actually reach the block are produced by\n * {@link createInitialStorageFromParams}, which parses again. One authoritative\n * producer, rather than two values that could differ.\n */\nexport type InitializationParamsValidateCallbackResult = { error: string } | { error?: undefined };\n\n/**\n * Check params that crossed into the model VM as text.\n *\n * The pre-flight entry point: a caller asks this before creating anything, once per\n * template entry, so params a kind rejects are reported while there is still no\n * project to half-build.\n *\n * The readable reference spelling is expanded here too, so what the kind checks is the shape it\n * declared. The ids it sees are the file's own — no block exists yet — which is why a kind must\n * not read meaning into a specific id.\n *\n * @param paramsJson The entry's params as JSON string\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParamsJson(\n paramsJson: string,\n parseInitializationParams: (value: unknown) => unknown,\n): InitializationParamsValidateCallbackResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Expanded before the kind sees anything, or a hand-written file would be rejected by every\n // kind that declares a reference: `{ block, name }` is not a `PlRef` and no contract accepts\n // one. Expansion needs nothing but the params, so this stays a two-argument check — the ids\n // are not known yet and are not needed to answer the question this asks.\n const result = validateTemplateParams(expandTemplateRefs(params), parseInitializationParams);\n if (result.error !== undefined) return { error: result.error };\n return {};\n}\n\nfunction messageOf(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Result of building initial storage from params.\n * Returned by the `__pl_storage_initialFromParams` callback.\n */\nexport type ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Creates complete initial storage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}: that projects storage\n * into params, this builds storage from them. The params are handed to the block's\n * init factory, whose output is versioned and wrapped exactly as\n * {@link createInitialStorage} wraps the defaults — so a block created from a\n * template is indistinguishable from one created in the UI and then edited.\n *\n * **This is where a template's references become the block's own**, and it is the only place in\n * a template's life where a reference is recognized at all. Params travel from the file\n * untouched — the engine carrying them neither marks a reference nor reads one, because\n * recognizing one means knowing the reference system, and that knowledge is here.\n *\n * Two things happen, in this order. The readable spelling a person may have written\n * (`{ block, name }`) is expanded into the `PlRef` it stands for. Then every reference naming\n * an entry that has a block is repointed at it: `blockIds` maps each template-local entry id to\n * the block id it was given, and an id it does not name is left alone, which is how a reference\n * to an entry created later ends up naming nothing rather than naming the wrong block.\n *\n * Relocation happens before the kind's parser and before the factory, so both see the ids the\n * block will actually hold. It is one step of this function rather than a callback of its own\n * precisely because nothing else wants its result: every VM call re-instantiates the runtime\n * and re-evaluates the whole model bundle, so a separate call would parse the block twice per\n * entry to produce a value only the next line reads.\n *\n * Params arrive as JSON text because this runs across the model-VM boundary, where\n * only strings pass. Anything the factory rejects is returned as an error rather\n * than thrown: applying a hand-written template is expected to surface bad params,\n * and the applier reports every entry's problem in one pass.\n *\n * @param paramsJson - The entry's params as JSON string, exactly as the file held them\n * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n * @param hooks - The block's init factory plus plugin creation\n * @returns The storage to write, or why the params could not produce any\n */\nexport function createInitialStorageFromParams(\n paramsJson: string,\n blockIdsJson: string,\n hooks: ParamsStorageHooks,\n): ParamsStorageResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Read separately from the params, and reported separately, because the two fail for\n // completely different reasons. Params are the file's and a bad one is the author's mistake;\n // this argument is the caller's, so the only way it arrives unreadable is a caller that does\n // not send it — a middle layer older than this block, which is a build to refresh rather than\n // anything to fix in the template. Folding both into one message sent the reader to the file.\n let blockIds: Map<string, string>;\n try {\n blockIds = new Map(Object.entries(JSON.parse(blockIdsJson) as Record<string, string>));\n } catch (e) {\n return {\n error:\n `this block was not told which blocks the template's references should point at ` +\n `(${messageOf(e)}). The application applying the template is older than the block; ` +\n `rebuild or update it.`,\n };\n }\n\n try {\n // Spelling first, ids second. Expansion turns `{ block, name }` into a `PlRef` naming an\n // ENTRY, which is exactly what relocation then repoints — so both spellings reach the\n // block through the same step and cannot diverge in how they behave.\n params = relocateBlockIds(expandTemplateRefs(params), blockIds);\n } catch (e) {\n return { error: `this entry's references could not be relocated: ${messageOf(e)}` };\n }\n\n // Checked here too, not only in the caller's pre-flight pass. The pre-flight is\n // about reporting every bad entry before anything is created; this is about the\n // factory never being handed a value the kind rejects, whichever path got here.\n const checked = validateTemplateParams(params, hooks.parseInitializationParams);\n if (checked.error !== undefined) return { error: checked.error };\n\n try {\n return { storageJson: assembleStorage(hooks.getBlockDataFromParams(checked.value), hooks) };\n } catch (e) {\n return { error: `init() threw on the given params: ${messageOf(e)}` };\n }\n}\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of a derivation that either produced a value or failed.\n * Returned by the __pl_initializationParams_derive callback.\n */\nexport type DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of args derivation from storage, returned by the __pl_args_derive callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is runnable args, `error` is no args.\n *\n * - `{ error }`: `args()` threw, so there are no args.\n * - `{ error, args, issues }`: args were built, but `argsIssues()` found errors in them, so the\n * block must not run. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args were built and nothing blocks the run; `issues` holds the warnings.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error: string; args: unknown; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/**\n * Result of prerun args derivation from storage, returned by the __pl_prerunArgs_derive\n * callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is args to stage, `error` skips staging.\n *\n * - `{ error }`: the lambda that builds the prerun args threw.\n * - `{ error, issues }`: prerun args were built, but the issues found in them include errors, so\n * the block is not staged. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args to stage; `issues` holds the warnings. A `value` of `undefined`\n * comes from a `prerunArgs()` that returned nothing, and skips staging.\n */\nexport type PrerunArgsDeriveResult =\n | { error: string }\n | { error: string; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/** The block's lambdas that turn its data into args and find what keeps those args from running. */\nexport interface ArgsDerivation {\n /** The block's `args()` lambda. */\n deriveArgs: (data: unknown) => unknown;\n /** The block's `argsIssues()` lambda; `undefined` when the block declares none. */\n argsIssues: ((input: { args: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** The block's own lambdas for staging: its `prerunArgs()` and the `prerunArgsIssues()` set after it. */\nexport interface OwnPrerunArgsDerivation {\n /** The block's `prerunArgs()` lambda. */\n derivePrerunArgs: (data: unknown) => unknown;\n /** The block's `prerunArgsIssues()` lambda; `undefined` when the block declares none. */\n prerunArgsIssues: ((input: { prerunArgs: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** {@link ArgsDerivation} plus the block's own lambdas for staging args. */\nexport interface PrerunArgsDerivation extends ArgsDerivation {\n /** The block's own staging lambdas; `undefined` when the block stages its args. */\n ownPrerunArgs: OwnPrerunArgsDerivation | undefined;\n}\n\n/**\n * Derives args from storage using the block's args function, then finds the issues in them\n * with the block's `argsIssues()`.\n *\n * A throw from `argsIssues()`, or a result that is not a list of issues, is one error carrying\n * the thrown or parser message, so a broken check keeps the block from running instead of\n * letting it run unchecked.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args and args issues lambdas\n * @returns ArgsDeriveResult with derived args and args issues, or error\n */\nexport function deriveArgsFromStorage(\n storageJson: string,\n derivation: ArgsDerivation,\n): ArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw: ${run.message}` };\n\n const { args, issues } = run;\n const errors = errorMessages(issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), args, issues };\n return { value: args, issues };\n}\n\n/**\n * Derives prerunArgs from storage.\n *\n * A block with its own `prerunArgs()` is staged with what it returns, unless its\n * `prerunArgsIssues()` finds errors in it; `argsIssues()` is not consulted then. A `prerunArgs()`\n * that returns `undefined` skips staging, and `prerunArgsIssues()` is not called for it.\n *\n * A block without its own `prerunArgs()` is staged with its args, unless `argsIssues()` finds\n * errors in them: args that may not run are not staged either.\n *\n * A throw from either issues lambda, or a result that is not a list of issues, is one error\n * carrying the thrown or parser message.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args, args issues and own staging lambdas\n * @returns PrerunArgsDeriveResult with derived prerunArgs and their issues, or error\n */\nexport function derivePrerunArgsFromStorage(\n storageJson: string,\n derivation: PrerunArgsDerivation,\n): PrerunArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n const { ownPrerunArgs } = derivation;\n\n if (ownPrerunArgs !== undefined) {\n const run = derivePrerunArgsWithIssues(data, ownPrerunArgs);\n if (run.type === \"threw\") return { error: `prerunArgs() threw: ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), issues: run.issues };\n return { value: run.args, issues: run.issues };\n }\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw (fallback): ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) {\n return {\n error: `argsIssues() found errors (fallback): ${errors.join(\"; \")}`,\n issues: run.issues,\n };\n }\n return { value: run.args, issues: run.issues };\n}\n\n// =============================================================================\n// Template Entry Derivation from Storage\n// =============================================================================\n\n/**\n * Derives this block's template-entry params from storage.\n *\n * The inverse of the data model's `init`: `init` turns `params` into data, this\n * turns data back into the params that would recreate it.\n *\n * The lambda returns ordinary live params — references as `PlRef`s, column identifiers as they\n * are stored — and that is exactly what gets written. Nothing is marked, normalized or\n * rewritten on the way out: a template holds what the block holds. Repointing those references\n * at another project is the business of {@link createInitialStorageFromParams}, on the way back\n * in, where the ids to point at are known.\n *\n * Every block declares the lambda, so every export produces params; a block with\n * nothing worth restoring returns `{}` rather than declining.\n *\n * @param storageJson - Storage as JSON string\n * @param deriveTemplateParams - The block's templateParams lambda\n * @returns DeriveResult holding the params exactly as the block projected them\n */\nexport function deriveTemplateParamsFromStorage<TP extends (data: unknown) => unknown>(\n storageJson: string,\n deriveTemplateParams: TP,\n): DeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n try {\n return { value: deriveTemplateParams(data) };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `templateParams() threw: ${errorMsg}` };\n }\n}\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n\n// =============================================================================\n// Internals\n// =============================================================================\n\n/** What a lambda building args, and the issues lambda checking them, made of a block's data. */\ntype ArgsWithIssues =\n | { type: \"threw\"; message: string }\n | { type: \"derived\"; args: unknown; issues: ArgsIssue[] };\n\nfunction deriveArgsWithIssues(data: unknown, derivation: ArgsDerivation): ArgsWithIssues {\n const { deriveArgs, argsIssues } = derivation;\n\n let args: unknown;\n try {\n args = deriveArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (argsIssues === undefined) return { type: \"derived\", args, issues: [] };\n return { type: \"derived\", args, issues: collectIssues(() => argsIssues({ args, data })) };\n}\n\nfunction derivePrerunArgsWithIssues(\n data: unknown,\n derivation: OwnPrerunArgsDerivation,\n): ArgsWithIssues {\n const { derivePrerunArgs, prerunArgsIssues } = derivation;\n\n let prerunArgs: unknown;\n try {\n prerunArgs = derivePrerunArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (prerunArgsIssues === undefined || prerunArgs === undefined) {\n return { type: \"derived\", args: prerunArgs, issues: [] };\n }\n return {\n type: \"derived\",\n args: prerunArgs,\n issues: collectIssues(() => prerunArgsIssues({ prerunArgs, data })),\n };\n}\n\n/**\n * Calls an issues lambda of the block. Its result is parsed rather than trusted: a block's types\n * do not hold at run time, and an entry that cannot be read must count as an error, not slip\n * past. A throw, or a result that cannot be read, is one error carrying its message.\n */\nfunction collectIssues(issuesOf: () => unknown): ArgsIssue[] {\n try {\n return parseArgsIssues(issuesOf());\n } catch (e) {\n return [{ severity: \"error\", message: messageOf(e) }];\n }\n}\n\nfunction errorMessages(issues: ArgsIssue[]): string[] {\n return issues.filter((issue) => issue.severity !== \"warning\").map((issue) => issue.message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAS,iBAAiB,YAA6C;CAErE,IAAI,eAAe,KAAA,KAAa,eAAe,MAE7C,OAAO;EAAE,SADO,mBAAmB,CAAC,CACrB;EAAG,MAAM,CAAC;CAAE;CAI7B,IAAI,SAAS;CACb,IAAI,OAAO,eAAe,UACxB,IAAI;EACF,SAAS,KAAK,MAAM,UAAU;CAChC,QAAQ;EAGN,OAAO;GAAE,SADO,mBAAmB,UACpB;GAAG,MAAM;EAAW;CACrC;CAIF,IAAI,eAAe,MAAM,GAAG;EAC1B,MAAM,UAAU,sBAAsB,MAAM;EAC5C,OAAO;GAAE;GAAS,MAAM,eAAe,OAAO;EAAE;CAClD;CAGA,IAAI,yBAAyB,MAAM,GAGjC,OAAO;EAAE,SADO,mBAAmB,MACpB;EAAG,MAAM;CAAO;CAKjC,OAAO;EAAE,SADO,mBAAmB,MACpB;EAAG,MAAM;CAAO;AACjC;;;;;;;;;AAUA,SAAgB,mBACd,oBACA,SAC+B;CAC/B,MAAM,EAAE,SAAS,mBAAmB,iBAAiB,kBAAkB;CAGvE,MAAM,iBAAiB,kBAAkB,gBAAgB,OAAO;CAEhE,OAAO,cAAc,cAAc;AACrC;;;;;AAMA,SAAS,yBAAyB,MAA2C;CAC3E,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU,OAAO;CACtD,IAAI,eAAe,IAAI,GAAG,OAAO;CAGjC,OAAO,UAAUA;AACnB;;;;;;;;AAaA,SAAgB,oBAAoB,YAAwD;CAC1F,MAAM,EAAE,YAAY,iBAAiB,UAAU;CAC/C,MAAM,YAA8B;EAClC,aAAa,QAAQ;EACrB,MAAM,QAAQ;CAChB;CACA,OAAO,cAAc,SAAS;AAChC;;;;;;;;;AAyBA,SAAgB,eACd,o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AAU,CAAC;EAAE;CAChD;CAEA,IAAI,qBAAqB,KAAA,KAAa,eAAe,KAAA,GACnD,OAAO;EAAE,MAAM;EAAW,MAAM;EAAY,QAAQ,CAAC;CAAE;CAEzD,OAAO;EACL,MAAM;EACN,MAAM;EACN,QAAQ,oBAAoB,iBAAiB;GAAE;GAAY;EAAK,CAAC,CAAC;CACpE;AACF;;;;;;AAOA,SAAS,cAAc,UAAsC;CAC3D,IAAI;EACF,OAAO,gBAAgB,SAAS,CAAC;CACnC,SAAS,GAAG;EACV,OAAO,CAAC;GAAE,UAAU;GAAS,SAAS,UAAU,CAAC;EAAE,CAAC;CACtD;AACF;AAEA,SAAS,cAAc,QAA+B;CACpD,OAAO,OAAO,QAAQ,UAAU,MAAM,aAAa,SAAS,CAAC,CAAC,KAAK,UAAU,MAAM,OAAO;AAC5F"}
1
+ {"version":3,"file":"block_storage_callbacks.js","names":["obj"],"sources":["../src/block_storage_callbacks.ts"],"sourcesContent":["/**\n * BlockStorage Callback Implementations - wired to facade callbacks in BlockModelV3.done().\n *\n * Provides pure functions for storage operations (migration, initialization,\n * args derivation, updates, debug views). Each function takes its dependencies\n * explicitly as parameters.\n *\n * @module block_storage_callbacks\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n type PluginRegistry,\n type VersionedData,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n migrateBlockStorage,\n normalizeBlockStorage,\n updateStorageData,\n} from \"./block_storage\";\nimport type { PluginHandle } from \"./plugin_handle\";\n\nimport {\n stringifyJson,\n expandTemplateRefs,\n parseArgsIssues,\n relocateBlockIds,\n type ArgsIssue,\n type StringifiedJson,\n} from \"@milaboratories/pl-model-common\";\nimport type { DataVersioned, TransferRecord } from \"./block_migrations\";\nimport type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\n\n// =============================================================================\n// Hook interfaces for dependency injection\n// =============================================================================\n\n/** Dependencies for storage migration */\nexport interface MigrationHooks {\n migrateBlockData: (versioned: DataVersioned<unknown>) => DataVersioned<unknown> & {\n transfers: TransferRecord;\n };\n getPluginRegistry: () => PluginRegistry;\n migratePluginData: (\n handle: PluginHandle,\n versioned: DataVersioned<unknown>,\n ) => DataVersioned<unknown> | undefined;\n createPluginData: (\n handle: PluginHandle,\n transfer?: DataVersioned<unknown>,\n ) => DataVersioned<unknown>;\n}\n\n/** Dependencies for initial storage creation */\nexport interface InitialStorageHooks {\n getDefaultBlockData: () => DataVersioned<unknown>;\n getPluginRegistry: () => PluginRegistry;\n createPluginData: (handle: PluginHandle) => DataVersioned<unknown>;\n}\n\n/**\n * Result of storage normalization\n */\nexport interface NormalizeStorageResult {\n /** The normalized BlockStorage object */\n storage: BlockStorage;\n /** The extracted data (what developers see) */\n data: unknown;\n}\n\n/**\n * Normalizes raw storage data and extracts state.\n * Handles all formats:\n * - New BlockStorage format (has discriminator)\n * - Legacy V1/V2 format ({ args, uiState })\n * - Raw V3 state (any other format)\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns Object with normalized storage and extracted state\n */\nfunction normalizeStorage(rawStorage: unknown): NormalizeStorageResult {\n // Handle undefined/null\n if (rawStorage === undefined || rawStorage === null) {\n const storage = createBlockStorage({});\n return { storage, data: {} };\n }\n\n // Parse JSON string if needed\n let parsed = rawStorage;\n if (typeof rawStorage === \"string\") {\n try {\n parsed = JSON.parse(rawStorage);\n } catch {\n // If parsing fails, treat string as the data\n const storage = createBlockStorage(rawStorage);\n return { storage, data: rawStorage };\n }\n }\n\n // Check for BlockStorage format (has discriminator)\n if (isBlockStorage(parsed)) {\n const storage = normalizeBlockStorage(parsed);\n return { storage, data: getStorageData(storage) };\n }\n\n // Check for legacy V1/V2 format: { args, uiState }\n if (isLegacyModelV1ApiFormat(parsed)) {\n // For legacy format, the whole object IS the data\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n }\n\n // Raw V3 data - wrap it\n const storage = createBlockStorage(parsed);\n return { storage, data: parsed };\n}\n\n/**\n * Applies a state update to existing storage.\n * Used when setData is called from the frontend.\n *\n * @param currentStorageJson - Current storage as JSON string (must be defined)\n * @param payload - Update payload with operation type and value\n * @returns Updated storage as StringifiedJson<BlockStorage>\n */\nexport function applyStorageUpdate(\n currentStorageJson: string,\n payload: MutateStoragePayload,\n): StringifiedJson<BlockStorage> {\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n // Update data while preserving other storage fields (version, plugins)\n const updatedStorage = updateStorageData(currentStorage, payload);\n\n return stringifyJson(updatedStorage);\n}\n\n/**\n * Checks if data is in legacy Model API v1 format.\n * Legacy format has { args, uiState? } at top level without the BlockStorage discriminator.\n */\nfunction isLegacyModelV1ApiFormat(data: unknown): data is { args?: unknown } {\n if (data === null || typeof data !== \"object\") return false;\n if (isBlockStorage(data)) return false;\n\n const obj = data as Record<string, unknown>;\n return \"args\" in obj;\n}\n\n// =============================================================================\n// Facade Callback Implementations\n// =============================================================================\n\n/**\n * Gets storage debug view from raw storage data.\n * Returns structured debug info about the storage state.\n *\n * @param rawStorage - Raw data from blockStorage field (may be JSON string or object)\n * @returns JSON string with storage debug view\n */\nexport function getStorageDebugView(rawStorage: unknown): StringifiedJson<StorageDebugView> {\n const { storage } = normalizeStorage(rawStorage);\n const debugView: StorageDebugView = {\n dataVersion: storage.__dataVersion,\n data: storage.__data,\n };\n return stringifyJson(debugView);\n}\n\n// =============================================================================\n// Migration Support\n// =============================================================================\n\n/**\n * Result of storage migration.\n * Returned by __pl_storage_migrate callback.\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Runs storage migration using the provided hooks.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @param hooks - Migration dependencies (block/plugin data migration and creation functions)\n * @returns MigrationResult\n */\nexport function migrateStorage(\n currentStorageJson: string | undefined,\n hooks: MigrationHooks,\n): MigrationResult {\n // Normalize current storage\n const { storage: currentStorage } = normalizeStorage(currentStorageJson);\n\n const newPluginRegistry = hooks.getPluginRegistry();\n\n // Perform atomic migration of block + all plugins\n const migrationResult = migrateBlockStorage(currentStorage, {\n migrateBlockData: hooks.migrateBlockData,\n migratePluginData: hooks.migratePluginData,\n newPluginRegistry,\n createPluginData: hooks.createPluginData,\n });\n\n if (!migrationResult.success) {\n return {\n error: `Migration failed at '${migrationResult.failedAt}': ${migrationResult.error}`,\n };\n }\n\n // Build info message\n const oldVersion = currentStorage.__dataVersion;\n const newVersion = migrationResult.storage.__dataVersion;\n const info =\n oldVersion === newVersion\n ? `No migration needed (${oldVersion})`\n : `Migrated ${oldVersion} -> ${newVersion}`;\n\n return {\n newStorageJson: stringifyJson(migrationResult.storage),\n info,\n };\n}\n\n// =============================================================================\n// Initial Storage Creation\n// =============================================================================\n\n/**\n * Creates complete initial storage (block data + all plugin data) atomically.\n *\n * @param hooks - Dependencies for creating initial block and plugin data\n * @returns Initial storage as branded JSON string\n * @throws If initialDataFn or createPluginData throws\n */\nexport function createInitialStorage(hooks: InitialStorageHooks): StringifiedJson<BlockStorage> {\n return assembleStorage(hooks.getDefaultBlockData(), hooks);\n}\n\n/**\n * Wraps freshly created block data and freshly created plugin data into storage.\n *\n * Shared by the two ways a block's first storage comes into being — from defaults\n * and from template params. Only the block's own data differs between them:\n * plugins have no params channel, so they are always created at their defaults.\n */\nfunction assembleStorage(\n blockData: DataVersioned<unknown>,\n hooks: Omit<InitialStorageHooks, \"getDefaultBlockData\">,\n): StringifiedJson<BlockStorage> {\n const pluginRegistry = hooks.getPluginRegistry();\n\n const plugins: Record<PluginHandle, VersionedData<unknown>> = {};\n for (const handle of Object.keys(pluginRegistry) as PluginHandle[]) {\n const initial = hooks.createPluginData(handle);\n plugins[handle] = { __dataVersion: initial.version, __data: initial.data };\n }\n\n const storage: BlockStorage = {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: blockData.version,\n __data: blockData.data,\n __pluginRegistry: pluginRegistry,\n __plugins: plugins,\n };\n return stringifyJson(storage);\n}\n\n/** Dependencies for creating storage from a template entry's params. */\nexport interface ParamsStorageHooks extends Omit<InitialStorageHooks, \"getDefaultBlockData\"> {\n /** The block's init factory, called with the entry's params. */\n getBlockDataFromParams: (params: unknown) => DataVersioned<unknown>;\n /**\n * The kind's runtime params check. Applied before the factory sees anything, and its\n * output is what the factory gets.\n */\n parseInitializationParams: (value: unknown) => unknown;\n}\n\n/** Result of checking params against their kind: the params to use, or why they lost. */\nexport type TemplateParamsValidationResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Check params against their kind's declared shape.\n *\n * The kind owns this rather than the block because the params contract belongs to the\n * kind: many block versions implement one kind, and a per-block check would let them\n * drift from each other and from the type.\n *\n * A parser rejects by throwing and accepts by returning the params to use, so its\n * output — not the input — is what flows onward. That is what lets a kind strip keys\n * it does not declare, which is the difference between a typo being ignored and a typo\n * being reported.\n *\n * Every kind declares a parser, so every set of params that reaches here is checked;\n * there is no pass-through path.\n *\n * @param value The params to check, references already in live form\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParams(\n value: unknown,\n parseInitializationParams: (value: unknown) => unknown,\n): TemplateParamsValidationResult {\n try {\n return { value: parseInitializationParams(value) };\n } catch (e) {\n // A rejection is an expected outcome for a hand-written file, so it is reported,\n // not thrown.\n return { error: `params do not match this block's kind: ${describeRejection(e)}` };\n }\n}\n\n/** One `{ path, message }` entry of a schema library's error. */\ntype IssueLike = { path?: unknown; message?: unknown };\n\n/**\n * Render whatever a parser threw as one readable line.\n *\n * An error carrying an `issues` array is unpacked rather than printed: that is the\n * shape zod (and several others) use, and its `message` is the whole issue list as\n * JSON — technically complete and unreadable in a dialog. Duck-typed on purpose, since\n * this package prescribes no schema library and takes no dependency on one; anything\n * else falls back to its own message.\n */\nfunction describeRejection(e: unknown): string {\n const issues = (e as { issues?: unknown }).issues;\n if (!Array.isArray(issues) || issues.length === 0) return messageOf(e);\n\n return issues\n .map((issue) => {\n const { path, message } = issue as IssueLike;\n const what = typeof message === \"string\" ? message : \"is invalid\";\n const where = Array.isArray(path) ? formatPath(path) : \"\";\n return where === \"\" ? what : `${where}: ${what}`;\n })\n .join(\"; \");\n}\n\n/** `[\"numbers\", 0]` → `numbers[0]` — how the params are written, not how they parse. */\nfunction formatPath(path: readonly unknown[]): string {\n return path.reduce<string>((acc, segment) => {\n if (typeof segment === \"number\") return `${acc}[${segment}]`;\n return acc === \"\" ? String(segment) : `${acc}.${String(segment)}`;\n }, \"\");\n}\n\n/**\n * Result of the `__pl_params_validate` callback.\n *\n * Carries no params back. The check is a pre-flight — its answer is \"may this entry be\n * applied\", and the params that actually reach the block are produced by\n * {@link createInitialStorageFromParams}, which parses again. One authoritative\n * producer, rather than two values that could differ.\n */\nexport type InitializationParamsValidateCallbackResult = { error: string } | { error?: undefined };\n\n/**\n * Check params that crossed into the model VM as text.\n *\n * The pre-flight entry point: a caller asks this before creating anything, once per\n * template entry, so params a kind rejects are reported while there is still no\n * project to half-build.\n *\n * The readable reference spelling is expanded here too, so what the kind checks is the shape it\n * declared. The ids it sees are the file's own — no block exists yet — which is why a kind must\n * not read meaning into a specific id.\n *\n * @param paramsJson The entry's params as JSON string\n * @param parseInitializationParams The kind's parser\n */\nexport function validateTemplateParamsJson(\n paramsJson: string,\n parseInitializationParams: (value: unknown) => unknown,\n): InitializationParamsValidateCallbackResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Expanded before the kind sees anything, or a hand-written file would be rejected by every\n // kind that declares a reference: `{ block, name }` is not a `PlRef` and no contract accepts\n // one. Expansion needs nothing but the params, so this stays a two-argument check — the ids\n // are not known yet and are not needed to answer the question this asks.\n const result = validateTemplateParams(expandTemplateRefs(params), parseInitializationParams);\n if (result.error !== undefined) return { error: result.error };\n return {};\n}\n\nfunction messageOf(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Result of building initial storage from params.\n * Returned by the `__pl_storage_initialFromParams` callback.\n */\nexport type ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Creates complete initial storage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}: that projects storage\n * into params, this builds storage from them. The params are handed to the block's\n * init factory, whose output is versioned and wrapped exactly as\n * {@link createInitialStorage} wraps the defaults — so a block created from a\n * template is indistinguishable from one created in the UI and then edited.\n *\n * **This is where a template's references become the block's own**, and it is the only place in\n * a template's life where a reference is recognized at all. Params travel from the file\n * untouched — the engine carrying them neither marks a reference nor reads one, because\n * recognizing one means knowing the reference system, and that knowledge is here.\n *\n * Two things happen, in this order. The readable spelling a person may have written\n * (`{ block, name }`) is expanded into the `PlRef` it stands for. Then every reference naming\n * an entry that has a block is repointed at it: `blockIds` maps each template-local entry id to\n * the block id it was given, and an id it does not name is left alone, which is how a reference\n * to an entry created later ends up naming nothing rather than naming the wrong block.\n *\n * Relocation happens before the kind's parser and before the factory, so both see the ids the\n * block will actually hold. It is one step of this function rather than a callback of its own\n * precisely because nothing else wants its result: every VM call re-instantiates the runtime\n * and re-evaluates the whole model bundle, so a separate call would parse the block twice per\n * entry to produce a value only the next line reads.\n *\n * Params arrive as JSON text because this runs across the model-VM boundary, where\n * only strings pass. Anything the factory rejects is returned as an error rather\n * than thrown: applying a hand-written template is expected to surface bad params,\n * and the applier reports every entry's problem in one pass.\n *\n * @param paramsJson - The entry's params as JSON string, exactly as the file held them\n * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n * @param hooks - The block's init factory plus plugin creation\n * @returns The storage to write, or why the params could not produce any\n */\nexport function createInitialStorageFromParams(\n paramsJson: string,\n blockIdsJson: string,\n hooks: ParamsStorageHooks,\n): ParamsStorageResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n // Read separately from the params, and reported separately, because the two fail for\n // completely different reasons. Params are the file's and a bad one is the author's mistake;\n // this argument is the caller's, so the only way it arrives unreadable is a caller that does\n // not send it — a middle layer older than this block, which is a build to refresh rather than\n // anything to fix in the template. Folding both into one message sent the reader to the file.\n let blockIds: Map<string, string>;\n try {\n blockIds = new Map(Object.entries(JSON.parse(blockIdsJson) as Record<string, string>));\n } catch (e) {\n return {\n error:\n `this block was not told which blocks the template's references should point at ` +\n `(${messageOf(e)}). The application applying the template is older than the block; ` +\n `rebuild or update it.`,\n };\n }\n\n try {\n // Spelling first, ids second. Expansion turns `{ block, name }` into a `PlRef` naming an\n // ENTRY, which is exactly what relocation then repoints — so both spellings reach the\n // block through the same step and cannot diverge in how they behave.\n params = relocateBlockIds(expandTemplateRefs(params), blockIds);\n } catch (e) {\n return { error: `this entry's references could not be relocated: ${messageOf(e)}` };\n }\n\n // Checked here too, not only in the caller's pre-flight pass. The pre-flight is\n // about reporting every bad entry before anything is created; this is about the\n // factory never being handed a value the kind rejects, whichever path got here.\n const checked = validateTemplateParams(params, hooks.parseInitializationParams);\n if (checked.error !== undefined) return { error: checked.error };\n\n try {\n return { storageJson: assembleStorage(hooks.getBlockDataFromParams(checked.value), hooks) };\n } catch (e) {\n return { error: `init() threw on the given params: ${messageOf(e)}` };\n }\n}\n\n// =============================================================================\n// Params onto Live Data\n// =============================================================================\n\n/** Dependencies for putting params onto a block's live data. */\nexport interface ApplyParamsHooks {\n /** The data model's current version: the one `applyParams` takes and returns. */\n dataVersion: string;\n /** The block's `applyParams`, given data at {@link ApplyParamsHooks.dataVersion}. */\n applyParams: (data: unknown, params: unknown) => DataVersioned<unknown>;\n /** The kind's runtime params check; its output is what `applyParams` gets. */\n parseInitializationParams: (value: unknown) => unknown;\n}\n\n/**\n * Puts params onto the block's live data with the block's own `applyParams`, the\n * `__pl_storage_applyParams` callback.\n *\n * The params are checked as {@link createInitialStorageFromParams} checks them: the readable\n * reference spelling is expanded, then the kind's parser runs and its output is what\n * `applyParams` gets. They are live params, so no reference is relocated.\n *\n * The data is refused unless it is at the data model's current version: `applyParams` is written\n * against that type, and migrating here would leave plugin transfers half done. Everything but the\n * block's data — its version, plugins, registry — is kept as it is.\n *\n * @param storageJson - Current storage as JSON string\n * @param paramsJson - The new params as JSON string, whole\n * @param hooks - The block's `applyParams`, its data version, the kind's parser\n * @returns The storage with the params applied, or why there is none\n */\nexport function applyParamsToStorage(\n storageJson: string,\n paramsJson: string,\n hooks: ApplyParamsHooks,\n): ParamsStorageResult {\n let params: unknown;\n try {\n params = JSON.parse(paramsJson);\n } catch (e) {\n return { error: `params are not valid JSON: ${messageOf(e)}` };\n }\n\n const { storage, data } = normalizeStorage(storageJson);\n if (storage.__dataVersion !== hooks.dataVersion)\n return {\n error:\n `the block's data is at version ${storage.__dataVersion}, while applyParams() ` +\n `takes version ${hooks.dataVersion}: the data waits for a migration`,\n };\n\n try {\n params = expandTemplateRefs(params);\n } catch (e) {\n return { error: `the params' references could not be read: ${messageOf(e)}` };\n }\n const checked = validateTemplateParams(params, hooks.parseInitializationParams);\n if (checked.error !== undefined) return { error: checked.error };\n\n let applied: DataVersioned<unknown>;\n try {\n applied = hooks.applyParams(data, checked.value);\n } catch (e) {\n return { error: `applyParams() threw on the given params: ${messageOf(e)}` };\n }\n return {\n storageJson: stringifyJson({\n ...storage,\n __dataVersion: applied.version,\n __data: applied.data,\n }),\n };\n}\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of a derivation that either produced a value or failed.\n * Returned by the __pl_initializationParams_derive callback.\n */\nexport type DeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of args derivation from storage, returned by the __pl_args_derive callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is runnable args, `error` is no args.\n *\n * - `{ error }`: `args()` threw, so there are no args.\n * - `{ error, args, issues }`: args were built, but `argsIssues()` found errors in them, so the\n * block must not run. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args were built and nothing blocks the run; `issues` holds the warnings.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error: string; args: unknown; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/**\n * Result of prerun args derivation from storage, returned by the __pl_prerunArgs_derive\n * callback.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is args to stage, `error` skips staging.\n *\n * - `{ error }`: the lambda that builds the prerun args threw.\n * - `{ error, issues }`: prerun args were built, but the issues found in them include errors, so\n * the block is not staged. `error` joins the error messages; `issues` lists every issue found.\n * - `{ value, issues }`: args to stage; `issues` holds the warnings. A `value` of `undefined`\n * comes from a `prerunArgs()` that returned nothing, and skips staging.\n */\nexport type PrerunArgsDeriveResult =\n | { error: string }\n | { error: string; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n/** The block's lambdas that turn its data into args and find what keeps those args from running. */\nexport interface ArgsDerivation {\n /** The block's `args()` lambda. */\n deriveArgs: (data: unknown) => unknown;\n /** The block's `argsIssues()` lambda; `undefined` when the block declares none. */\n argsIssues: ((input: { args: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** The block's own lambdas for staging: its `prerunArgs()` and the `prerunArgsIssues()` set after it. */\nexport interface OwnPrerunArgsDerivation {\n /** The block's `prerunArgs()` lambda. */\n derivePrerunArgs: (data: unknown) => unknown;\n /** The block's `prerunArgsIssues()` lambda; `undefined` when the block declares none. */\n prerunArgsIssues: ((input: { prerunArgs: unknown; data: unknown }) => ArgsIssue[]) | undefined;\n}\n\n/** {@link ArgsDerivation} plus the block's own lambdas for staging args. */\nexport interface PrerunArgsDerivation extends ArgsDerivation {\n /** The block's own staging lambdas; `undefined` when the block stages its args. */\n ownPrerunArgs: OwnPrerunArgsDerivation | undefined;\n}\n\n/**\n * Derives args from storage using the block's args function, then finds the issues in them\n * with the block's `argsIssues()`.\n *\n * A throw from `argsIssues()`, or a result that is not a list of issues, is one error carrying\n * the thrown or parser message, so a broken check keeps the block from running instead of\n * letting it run unchecked.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args and args issues lambdas\n * @returns ArgsDeriveResult with derived args and args issues, or error\n */\nexport function deriveArgsFromStorage(\n storageJson: string,\n derivation: ArgsDerivation,\n): ArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw: ${run.message}` };\n\n const { args, issues } = run;\n const errors = errorMessages(issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), args, issues };\n return { value: args, issues };\n}\n\n/**\n * Derives prerunArgs from storage.\n *\n * A block with its own `prerunArgs()` is staged with what it returns, unless its\n * `prerunArgsIssues()` finds errors in it; `argsIssues()` is not consulted then. A `prerunArgs()`\n * that returns `undefined` skips staging, and `prerunArgsIssues()` is not called for it.\n *\n * A block without its own `prerunArgs()` is staged with its args, unless `argsIssues()` finds\n * errors in them: args that may not run are not staged either.\n *\n * A throw from either issues lambda, or a result that is not a list of issues, is one error\n * carrying the thrown or parser message.\n *\n * @param storageJson - Storage as JSON string\n * @param derivation - The block's args, args issues and own staging lambdas\n * @returns PrerunArgsDeriveResult with derived prerunArgs and their issues, or error\n */\nexport function derivePrerunArgsFromStorage(\n storageJson: string,\n derivation: PrerunArgsDerivation,\n): PrerunArgsDeriveResult {\n const { data } = normalizeStorage(storageJson);\n const { ownPrerunArgs } = derivation;\n\n if (ownPrerunArgs !== undefined) {\n const run = derivePrerunArgsWithIssues(data, ownPrerunArgs);\n if (run.type === \"threw\") return { error: `prerunArgs() threw: ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) return { error: errors.join(\"; \"), issues: run.issues };\n return { value: run.args, issues: run.issues };\n }\n\n const run = deriveArgsWithIssues(data, derivation);\n if (run.type === \"threw\") return { error: `args() threw (fallback): ${run.message}` };\n\n const errors = errorMessages(run.issues);\n if (errors.length > 0) {\n return {\n error: `argsIssues() found errors (fallback): ${errors.join(\"; \")}`,\n issues: run.issues,\n };\n }\n return { value: run.args, issues: run.issues };\n}\n\n// =============================================================================\n// Template Entry Derivation from Storage\n// =============================================================================\n\n/**\n * Derives this block's template-entry params from storage.\n *\n * The inverse of the data model's `init`: `init` turns `params` into data, this\n * turns data back into the params that would recreate it.\n *\n * The lambda returns ordinary live params — references as `PlRef`s, column identifiers as they\n * are stored — and that is exactly what gets written. Nothing is marked, normalized or\n * rewritten on the way out: a template holds what the block holds. Repointing those references\n * at another project is the business of {@link createInitialStorageFromParams}, on the way back\n * in, where the ids to point at are known.\n *\n * Every block declares the lambda, so every export produces params; a block with\n * nothing worth restoring returns `{}` rather than declining.\n *\n * @param storageJson - Storage as JSON string\n * @param deriveTemplateParams - The block's templateParams lambda\n * @returns DeriveResult holding the params exactly as the block projected them\n */\nexport function deriveTemplateParamsFromStorage<TP extends (data: unknown) => unknown>(\n storageJson: string,\n deriveTemplateParams: TP,\n): DeriveResult {\n const { data } = normalizeStorage(storageJson);\n\n try {\n return { value: deriveTemplateParams(data) };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `templateParams() threw: ${errorMsg}` };\n }\n}\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n\n// =============================================================================\n// Internals\n// =============================================================================\n\n/** What a lambda building args, and the issues lambda checking them, made of a block's data. */\ntype ArgsWithIssues =\n | { type: \"threw\"; message: string }\n | { type: \"derived\"; args: unknown; issues: ArgsIssue[] };\n\nfunction deriveArgsWithIssues(data: unknown, derivation: ArgsDerivation): ArgsWithIssues {\n const { deriveArgs, argsIssues } = derivation;\n\n let args: unknown;\n try {\n args = deriveArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (argsIssues === undefined) return { type: \"derived\", args, issues: [] };\n return { type: \"derived\", args, issues: collectIssues(() => argsIssues({ args, data })) };\n}\n\nfunction derivePrerunArgsWithIssues(\n data: unknown,\n derivation: OwnPrerunArgsDerivation,\n): ArgsWithIssues {\n const { derivePrerunArgs, prerunArgsIssues } = derivation;\n\n let prerunArgs: unknown;\n try {\n prerunArgs = derivePrerunArgs(data);\n } catch (e) {\n return { type: \"threw\", message: messageOf(e) };\n }\n\n if (prerunArgsIssues === undefined || prerunArgs === undefined) {\n return { type: \"derived\", args: prerunArgs, issues: [] };\n }\n return {\n type: \"derived\",\n args: prerunArgs,\n issues: collectIssues(() => prerunArgsIssues({ prerunArgs, data })),\n };\n}\n\n/**\n * Calls an issues lambda of the block. Its result is parsed rather than trusted: a block's types\n * do not hold at run time, and an entry that cannot be read must count as an error, not slip\n * past. A throw, or a result that cannot be read, is one error carrying its message.\n */\nfunction collectIssues(issuesOf: () => unknown): ArgsIssue[] {\n try {\n return parseArgsIssues(issuesOf());\n } catch (e) {\n return [{ severity: \"error\", message: messageOf(e) }];\n }\n}\n\nfunction errorMessages(issues: ArgsIssue[]): string[] {\n return issues.filter((issue) => issue.severity !== \"warning\").map((issue) => issue.message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAS,iBAAiB,YAA6C;CAErE,IAAI,eAAe,KAAA,KAAa,eAAe,MAE7C,OAAO;EAAE,SADO,mBAAmB,CAAC,CACrB;EAAG,MAAM,CAAC;CAAE;CAI7B,IAAI,SAAS;CACb,IAAI,OAAO,eAAe,UACxB,IAAI;EACF,SAAS,KAAK,MAAM,UAAU;CAChC,QAAQ;EAGN,OAAO;GAAE,SADO,mBAAmB,UACpB;GAAG,MAAM;EAAW;CACrC;CAIF,IAAI,eAAe,MAAM,GAAG;EAC1B,MAAM,UAAU,sBAAsB,MAAM;EAC5C,OAAO;GAAE;GAAS,MAAM,eAAe,O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M;EAAW;EAAM,QAAQ,oBAAoB,WAAW;GAAE;GAAM;EAAK,CAAC,CAAC;CAAE;AAC1F;AAEA,SAAS,2BACP,MACA,YACgB;CAChB,MAAM,EAAE,kBAAkB,qBAAqB;CAE/C,IAAI;CACJ,IAAI;EACF,aAAa,iBAAiB,IAAI;CACpC,SAAS,GAAG;EACV,OAAO;GAAE,MAAM;GAAS,SAAS,UAAU,CAAC;EAAE;CAChD;CAEA,IAAI,qBAAqB,KAAA,KAAa,eAAe,KAAA,GACnD,OAAO;EAAE,MAAM;EAAW,MAAM;EAAY,QAAQ,CAAC;CAAE;CAEzD,OAAO;EACL,MAAM;EACN,MAAM;EACN,QAAQ,oBAAoB,iBAAiB;GAAE;GAAY;EAAK,CAAC,CAAC;CACpE;AACF;;;;;;AAOA,SAAS,cAAc,UAAsC;CAC3D,IAAI;EACF,OAAO,gBAAgB,SAAS,CAAC;CACnC,SAAS,GAAG;EACV,OAAO,CAAC;GAAE,UAAU;GAAS,SAAS,UAAU,CAAC;EAAE,CAAC;CACtD;AACF;AAEA,SAAS,cAAc,QAA+B;CACpD,OAAO,OAAO,QAAQ,UAAU,MAAM,aAAa,SAAS,CAAC,CAAC,KAAK,UAAU,MAAM,OAAO;AAC5F"}
@@ -23,27 +23,47 @@ const BlockStorageFacadeCallbacks = {
23
23
  StorageInitial: "__pl_storage_initial",
24
24
  InitializationParamsDerive: "__pl_initializationParams_derive",
25
25
  StorageInitialFromParams: "__pl_storage_initialFromParams",
26
- InitializationParamsValidate: "__pl_initializationParams_validate"
26
+ InitializationParamsValidate: "__pl_initializationParams_validate",
27
+ StorageApplyParams: "__pl_storage_applyParams"
27
28
  };
28
29
  /**
30
+ * Callbacks a block registers only when its model declares what they run. A block's config lists
31
+ * their handles only then, so whoever reads the config knows whether it may call them; the
32
+ * defaults filled in for a config that lists no callbacks leave them out.
33
+ */
34
+ const OptionalFacadeCallbacks = { StorageApplyParams: BlockStorageFacadeCallbacks.StorageApplyParams };
35
+ /**
29
36
  * Creates a map of lambda handles from a callbacks constant object.
30
37
  * Keys are the callback string values (e.g., '__pl_storage_applyUpdate').
31
38
  */
32
39
  function createFacadeHandles(callbacks) {
33
40
  return Object.fromEntries(Object.values(callbacks).map((handle) => [handle, require_internal.createRenderLambda({ handle })]));
34
41
  }
42
+ const { StorageApplyParams: _optional, ...requiredFacadeCallbacks } = BlockStorageFacadeCallbacks;
35
43
  /**
36
- * Lambda handles for facade callbacks.
44
+ * Lambda handles of the facade callbacks every block registers.
37
45
  * Used by the middle layer to invoke callbacks via executeSingleLambda().
38
46
  */
39
- const BlockStorageFacadeHandles = createFacadeHandles(BlockStorageFacadeCallbacks);
40
- /** Register all facade callbacks at once. Ensures all required callbacks are provided. */
47
+ const BlockStorageFacadeHandles = createFacadeHandles(requiredFacadeCallbacks);
48
+ /**
49
+ * Lambda handles of the facade callbacks a block registers only when its model declares what
50
+ * they run (see {@link BlockStorageFacadeCallbacks.StorageApplyParams}).
51
+ */
52
+ const BlockStorageFacadeOptionalHandles = createFacadeHandles(OptionalFacadeCallbacks);
53
+ /**
54
+ * Register all facade callbacks at once. The types ensure every required callback is provided;
55
+ * an optional one left undefined is not registered.
56
+ */
41
57
  function registerFacadeCallbacks(callbacks) {
42
- for (const key of Object.values(BlockStorageFacadeCallbacks)) require_internal.tryRegisterCallback(key, callbacks[key]);
58
+ for (const key of Object.values(BlockStorageFacadeCallbacks)) {
59
+ const callback = callbacks[key];
60
+ if (callback !== void 0) require_internal.tryRegisterCallback(key, callback);
61
+ }
43
62
  }
44
63
  exports.BLOCK_STORAGE_FACADE_VERSION = BLOCK_STORAGE_FACADE_VERSION;
45
64
  exports.BlockStorageFacadeCallbacks = BlockStorageFacadeCallbacks;
46
65
  exports.BlockStorageFacadeHandles = BlockStorageFacadeHandles;
66
+ exports.BlockStorageFacadeOptionalHandles = BlockStorageFacadeOptionalHandles;
47
67
  exports.registerFacadeCallbacks = registerFacadeCallbacks;
48
68
 
49
69
  //# sourceMappingURL=block_storage_facade.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"block_storage_facade.cjs","names":["createRenderLambda"],"sources":["../src/block_storage_facade.ts"],"sourcesContent":["/**\n * Block Storage Facade - Contract between bundled blocks and middle layer.\n *\n * ============================================================================\n * VERSIONING\n * ============================================================================\n *\n * Blocks declare their model API version via the `requiresModelAPIVersion` feature flag\n * (see BlockCodeKnownFeatureFlags). This determines how the middle layer manages block state:\n *\n * - Version 1: Legacy BlockModel - state is {args, uiState}, managed directly by middle layer\n * - Version 2: BlockModelV3 - uses blockStorage with VM-based callbacks (this facade)\n *\n * This facade (BlockStorageFacade) is used by blocks with `requiresModelAPIVersion: 2`.\n * The version number matches the model API version for clarity.\n *\n * ============================================================================\n * BACKWARD COMPATIBILITY WARNING\n * ============================================================================\n *\n * This file documents the FACADE between the SDK (bundled into blocks) and the\n * middle layer. Once a block is published, its SDK version is frozen. The middle\n * layer must support ALL previously released callback signatures indefinitely.\n *\n * RULES:\n * 1. NEVER change the signature of existing callbacks\n * 2. NEVER remove existing callbacks\n * 3. New callbacks CAN be added (old blocks won't register them, middle layer\n * should handle missing callbacks gracefully)\n * 4. Callback return types can be EXTENDED (add optional fields) but not changed\n * 5. Callback parameter types should remain compatible (middle layer may need\n * to handle both old and new formats)\n *\n * The facade consists of callbacks registered via `tryRegisterCallback()` with\n * the `__pl_` prefix. These are registered by the SDK when a block loads and\n * called by the middle layer to perform operations.\n *\n * ============================================================================\n * WHAT CAN BE CHANGED FREELY\n * ============================================================================\n *\n * - Middle layer code (lib/node/pl-middle-layer)\n * - SDK internal implementation (as long as callback contracts are preserved)\n * - SDK exports used ONLY by middle layer (not by blocks themselves)\n * - New SDK features that don't affect existing callbacks\n *\n * @module block_storage_facade\n */\n\nimport type { MutateStoragePayload } from \"./block_storage\";\nimport type { ConfigRenderLambda } from \"./bconfig\";\nimport { createRenderLambda, tryRegisterCallback } from \"./internal\";\nimport type { ArgsIssue, StringifiedJson } from \"@milaboratories/pl-model-common\";\n\n// =============================================================================\n// Facade Version\n// =============================================================================\n\n/**\n * The current facade version. This value is used for `requiresModelAPIVersion`\n * feature flag in BlockModelV3.\n */\nexport const BLOCK_STORAGE_FACADE_VERSION = 2;\n\n// =============================================================================\n// Facade Callback Names\n// =============================================================================\n\n/**\n * All facade callback names as constants.\n * These are the source of truth - the interface is derived from these.\n *\n * IMPORTANT: When adding a new callback:\n * 1. Add the constant here\n * 2. Add the callback signature to FacadeCallbackTypes below\n * 3. The BlockStorageFacade type will automatically include it\n */\nexport const BlockStorageFacadeCallbacks = {\n StorageApplyUpdate: \"__pl_storage_applyUpdate\",\n StorageDebugView: \"__pl_storage_debugView\",\n StorageMigrate: \"__pl_storage_migrate\",\n ArgsDerive: \"__pl_args_derive\",\n PrerunArgsDerive: \"__pl_prerunArgs_derive\",\n StorageInitial: \"__pl_storage_initial\",\n InitializationParamsDerive: \"__pl_initializationParams_derive\",\n StorageInitialFromParams: \"__pl_storage_initialFromParams\",\n InitializationParamsValidate: \"__pl_initializationParams_validate\",\n} as const;\n\n/**\n * Creates a map of lambda handles from a callbacks constant object.\n * Keys are the callback string values (e.g., '__pl_storage_applyUpdate').\n */\nfunction createFacadeHandles<T extends Record<string, string>>(\n callbacks: T,\n): { [K in T[keyof T]]: ConfigRenderLambda } {\n return Object.fromEntries(\n Object.values(callbacks).map((handle) => [handle, createRenderLambda({ handle })]),\n ) as { [K in T[keyof T]]: ConfigRenderLambda };\n}\n\n/**\n * Lambda handles for facade callbacks.\n * Used by the middle layer to invoke callbacks via executeSingleLambda().\n */\nexport const BlockStorageFacadeHandles = createFacadeHandles(BlockStorageFacadeCallbacks);\n\n// =============================================================================\n// Facade Interface (source of truth for callback signatures)\n// =============================================================================\n\n/**\n * The complete facade interface between bundled blocks (SDK) and middle layer.\n *\n * This interface defines ALL callbacks that a block registers. The middle layer\n * calls these callbacks to perform storage operations.\n *\n * ALL types are inlined to simplify versioning - when a callback changes,\n * the entire signature is visible in one place.\n *\n * BACKWARD COMPATIBILITY:\n * - This interface can only be EXTENDED, never shrunk\n * - Existing callback signatures MUST NOT change\n * - Middle layer should use Partial<BlockStorageFacade> when dealing with\n * blocks of unknown version (older blocks may not have all callbacks)\n *\n * Each callback is documented with:\n * - Purpose and when it's called\n * - Parameter descriptions\n * - Return value description\n */\nexport interface BlockStorageFacade {\n /**\n * Apply state update to storage.\n * Called when UI updates block state (setState) or plugin data.\n * @param currentStorageJson - Current storage as JSON string\n * @param payload - Update payload with operation type and value\n * @returns Updated storage as JSON string\n */\n [BlockStorageFacadeCallbacks.StorageApplyUpdate]: (\n currentStorageJson: StringifiedJson,\n payload: MutateStoragePayload,\n ) => StringifiedJson;\n\n /**\n * Get debug view of storage.\n * Called by developer tools to inspect storage state.\n * @param storageJson - Storage as JSON string (or undefined for new blocks)\n * @returns JSON string containing StorageDebugView\n */\n [BlockStorageFacadeCallbacks.StorageDebugView]: (\n storageJson: StringifiedJson | undefined,\n ) => StringifiedJson;\n\n /**\n * Run storage migration.\n * Called when block loads to migrate data to latest version.\n * @param currentStorageJson - Current storage as JSON string (or undefined for new blocks)\n * @returns Migration result - either error or success with new storage\n */\n [BlockStorageFacadeCallbacks.StorageMigrate]: (\n currentStorageJson: StringifiedJson | undefined,\n ) =>\n | { error: string }\n | {\n error?: undefined;\n newStorageJson: StringifiedJson;\n info: string;\n };\n\n /**\n * Derive args from storage.\n * Called to get block configuration args from storage, and whether the block may run them.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is runnable args, `error` is no args. A block built\n * with an SDK that predates args issues returns `{ error }` or `{ value }` with no `issues`.\n *\n * @param storageJson - Storage as JSON string\n * @returns One of:\n * - `{ error }`: `args()` threw, so there are no args;\n * - `{ error, args, issues }`: args were built, but the block's `argsIssues()` found errors in\n * them, so the block must not run; `error` joins the error messages, `issues` lists every\n * issue;\n * - `{ value, issues }`: args the block may run; `issues` holds the warnings.\n */\n [BlockStorageFacadeCallbacks.ArgsDerive]: (\n storageJson: StringifiedJson,\n ) =>\n | { error: string }\n | { error: string; args: unknown; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n /**\n * Derive prerunArgs from storage.\n * Called to get prerun args; falls back to args callback if not registered.\n *\n * A block with its own prerunArgs is staged with them unless its `prerunArgsIssues()` finds errors\n * in them. A block without its own prerunArgs is staged with its args unless its `argsIssues()`\n * finds errors in them.\n *\n * A middle layer that predates args issues reads only `error` and `value`: `value` is args to\n * stage, `error` skips staging. A block built with an SDK that predates args issues returns\n * `{ error }` or `{ value }` with no `issues`.\n *\n * @param storageJson - Storage as JSON string\n * @returns One of:\n * - `{ error }`: the lambda building the prerun args threw;\n * - `{ error, issues }`: prerun args were built, but errors were found in them, so the block\n * is not staged; `error` joins the error messages, `issues` lists every issue;\n * - `{ value, issues }`: args to stage, `undefined` to skip staging; `issues` holds the\n * warnings.\n */\n [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (\n storageJson: StringifiedJson,\n ) =>\n | { error: string }\n | { error: string; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n /**\n * Get initial storage JSON for new blocks.\n * Called when creating a new block to get complete initial storage.\n * @returns Initial storage as JSON string\n */\n [BlockStorageFacadeCallbacks.StorageInitial]: () => StringifiedJson;\n\n /**\n * Derive this block's template entry params from storage.\n * Called when exporting the project as a template.\n *\n * Every V3 block declares `.templateParams()` — the model does not build without\n * it — so every export produces params. A block whose state carries nothing worth\n * restoring returns `{}`, which is written out and used as-is by init.\n *\n * The returned params are written out exactly as they come back, references included: the\n * template engine carrying them recognizes nothing in there, and the block that receives\n * them on the way back in is what repoints them. The caller supplies everything else in the\n * entry — `id`, `kind` — so the lambda cannot set them.\n *\n * @param storageJson - Storage as JSON string\n * @returns Either an error, or the params to write\n */\n [BlockStorageFacadeCallbacks.InitializationParamsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\n\n /**\n * Get initial storage JSON for a block created from params.\n * Called when applying a template, once per entry that carries `params`.\n *\n * The mirror image of {@link BlockStorageFacadeCallbacks.InitializationParamsDerive}:\n * that one turns storage into params, this one turns params into storage. Every\n * applied entry comes through here, including one whose file omitted `params` —\n * an omitted key is read as `{}` and checked like any other value, so no entry\n * reaches a block without passing its kind's contract.\n * {@link BlockStorageFacadeCallbacks.StorageInitial} stays the UI-creation path,\n * where there are genuinely no params.\n *\n * Separate from `StorageInitial` rather than an optional argument to it,\n * deliberately: a block bundled with an older SDK does not register this\n * callback at all, so the caller sees it missing and can say so. Widening\n * `StorageInitial` would instead have that block silently ignore the params and\n * produce a default-initialized block that looks successfully applied.\n *\n * The params arrive as ordinary live params — references are `PlRef`s, already\n * pointing at the ids the target project just assigned. Resolution happens in\n * the engine, before this call, so a block's init factory never handles a\n * template-local reference.\n *\n * Errors are returned, not thrown: a factory rejecting params it cannot use is\n * an expected outcome for a hand-written template file, and every entry's\n * problem is reported together.\n *\n * **Also where the entry's references are pointed at this project.** Params reach here\n * exactly as the file held them: nothing between the block that exported them and this call\n * marks a reference, reads one, or rewrites one, because recognizing one means knowing the\n * reference system and this bundle is where that knowledge lives. `blockIdsJson` maps each\n * template-local entry id to the block id it was given, holding the entries created so far —\n * so an id it does not name is left alone, and a reference to an entry created later names\n * nothing rather than naming the wrong block.\n *\n * Relocating and initializing are one call rather than two because every call\n * re-instantiates the runtime and re-evaluates the whole model bundle: splitting them would\n * parse the block twice per entry to produce an intermediate only the second half reads.\n *\n * @param paramsJson - The entry's params as JSON string, as the file held them\n * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n * @returns Either an error, or the initial storage as JSON string\n */\n [BlockStorageFacadeCallbacks.StorageInitialFromParams]: (\n paramsJson: StringifiedJson,\n blockIdsJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; storageJson: StringifiedJson };\n\n /**\n * Check params against this block's kind, creating nothing.\n *\n * Called once per entry before a template is applied, so params a kind rejects are\n * reported against the entry that carries them while there is still no project — the\n * same reason references and ids are checked before construction starts. Applying\n * without this call is safe but worse: `StorageInitialFromParams` runs the same check\n * and refuses, by which point earlier entries have already been created.\n *\n * A pass carries nothing back but its own absence of error: every kind declares a\n * parser, so a pass means the params were checked against the contract, not merely\n * that they were valid JSON.\n *\n * Reference ids inside the params may be placeholders at this point: the check runs\n * before blocks exist, so what is verified is the shape of the params, not what they\n * point at.\n *\n * @param paramsJson The entry's params as JSON string\n * @returns Why the params were rejected, or nothing\n */\n [BlockStorageFacadeCallbacks.InitializationParamsValidate]: (\n paramsJson: StringifiedJson,\n ) => { error: string } | { error?: undefined };\n}\n\n/** Register all facade callbacks at once. Ensures all required callbacks are provided. */\nexport function registerFacadeCallbacks(callbacks: BlockStorageFacade): void {\n for (const key of Object.values(BlockStorageFacadeCallbacks)) {\n tryRegisterCallback(key, callbacks[key] as (...args: any[]) => any);\n }\n}\n"],"mappings":";;;;;;AA8DA,MAAa,+BAA+B;;;;;;;;;;AAe5C,MAAa,8BAA8B;CACzC,oBAAoB;CACpB,kBAAkB;CAClB,gBAAgB;CAChB,YAAY;CACZ,kBAAkB;CAClB,gBAAgB;CAChB,4BAA4B;CAC5B,0BAA0B;CAC1B,8BAA8B;AAChC;;;;;AAMA,SAAS,oBACP,WAC2C;CAC3C,OAAO,OAAO,YACZ,OAAO,OAAO,SAAS,CAAC,CAAC,KAAK,WAAW,CAAC,QAAQA,iBAAAA,mBAAmB,EAAE,OAAO,CAAC,CAAC,CAAC,CACnF;AACF;;;;;AAMA,MAAa,4BAA4B,oBAAoB,2BAA2B;;AAwNxF,SAAgB,wBAAwB,WAAqC;CAC3E,KAAK,MAAM,OAAO,OAAO,OAAO,2BAA2B,GACzD,iBAAA,oBAAoB,KAAK,UAAU,IAA+B;AAEtE"}
1
+ {"version":3,"file":"block_storage_facade.cjs","names":["createRenderLambda"],"sources":["../src/block_storage_facade.ts"],"sourcesContent":["/**\n * Block Storage Facade - Contract between bundled blocks and middle layer.\n *\n * ============================================================================\n * VERSIONING\n * ============================================================================\n *\n * Blocks declare their model API version via the `requiresModelAPIVersion` feature flag\n * (see BlockCodeKnownFeatureFlags). This determines how the middle layer manages block state:\n *\n * - Version 1: Legacy BlockModel - state is {args, uiState}, managed directly by middle layer\n * - Version 2: BlockModelV3 - uses blockStorage with VM-based callbacks (this facade)\n *\n * This facade (BlockStorageFacade) is used by blocks with `requiresModelAPIVersion: 2`.\n * The version number matches the model API version for clarity.\n *\n * ============================================================================\n * BACKWARD COMPATIBILITY WARNING\n * ============================================================================\n *\n * This file documents the FACADE between the SDK (bundled into blocks) and the\n * middle layer. Once a block is published, its SDK version is frozen. The middle\n * layer must support ALL previously released callback signatures indefinitely.\n *\n * RULES:\n * 1. NEVER change the signature of existing callbacks\n * 2. NEVER remove existing callbacks\n * 3. New callbacks CAN be added (old blocks won't register them, middle layer\n * should handle missing callbacks gracefully)\n * 4. Callback return types can be EXTENDED (add optional fields) but not changed\n * 5. Callback parameter types should remain compatible (middle layer may need\n * to handle both old and new formats)\n *\n * The facade consists of callbacks registered via `tryRegisterCallback()` with\n * the `__pl_` prefix. These are registered by the SDK when a block loads and\n * called by the middle layer to perform operations.\n *\n * ============================================================================\n * WHAT CAN BE CHANGED FREELY\n * ============================================================================\n *\n * - Middle layer code (lib/node/pl-middle-layer)\n * - SDK internal implementation (as long as callback contracts are preserved)\n * - SDK exports used ONLY by middle layer (not by blocks themselves)\n * - New SDK features that don't affect existing callbacks\n *\n * @module block_storage_facade\n */\n\nimport type { MutateStoragePayload } from \"./block_storage\";\nimport type { ConfigRenderLambda } from \"./bconfig\";\nimport { createRenderLambda, tryRegisterCallback } from \"./internal\";\nimport type { ArgsIssue, StringifiedJson } from \"@milaboratories/pl-model-common\";\n\n// =============================================================================\n// Facade Version\n// =============================================================================\n\n/**\n * The current facade version. This value is used for `requiresModelAPIVersion`\n * feature flag in BlockModelV3.\n */\nexport const BLOCK_STORAGE_FACADE_VERSION = 2;\n\n// =============================================================================\n// Facade Callback Names\n// =============================================================================\n\n/**\n * All facade callback names as constants.\n * These are the source of truth - the interface is derived from these.\n *\n * IMPORTANT: When adding a new callback:\n * 1. Add the constant here\n * 2. Add the callback signature to FacadeCallbackTypes below\n * 3. The BlockStorageFacade type will automatically include it\n */\nexport const BlockStorageFacadeCallbacks = {\n StorageApplyUpdate: \"__pl_storage_applyUpdate\",\n StorageDebugView: \"__pl_storage_debugView\",\n StorageMigrate: \"__pl_storage_migrate\",\n ArgsDerive: \"__pl_args_derive\",\n PrerunArgsDerive: \"__pl_prerunArgs_derive\",\n StorageInitial: \"__pl_storage_initial\",\n InitializationParamsDerive: \"__pl_initializationParams_derive\",\n StorageInitialFromParams: \"__pl_storage_initialFromParams\",\n InitializationParamsValidate: \"__pl_initializationParams_validate\",\n StorageApplyParams: \"__pl_storage_applyParams\",\n} as const;\n\n/**\n * Callbacks a block registers only when its model declares what they run. A block's config lists\n * their handles only then, so whoever reads the config knows whether it may call them; the\n * defaults filled in for a config that lists no callbacks leave them out.\n */\nconst OptionalFacadeCallbacks = {\n StorageApplyParams: BlockStorageFacadeCallbacks.StorageApplyParams,\n} as const;\n\n/**\n * Creates a map of lambda handles from a callbacks constant object.\n * Keys are the callback string values (e.g., '__pl_storage_applyUpdate').\n */\nfunction createFacadeHandles<T extends Record<string, string>>(\n callbacks: T,\n): { [K in T[keyof T]]: ConfigRenderLambda } {\n return Object.fromEntries(\n Object.values(callbacks).map((handle) => [handle, createRenderLambda({ handle })]),\n ) as { [K in T[keyof T]]: ConfigRenderLambda };\n}\n\nconst { StorageApplyParams: _optional, ...requiredFacadeCallbacks } = BlockStorageFacadeCallbacks;\n\n/**\n * Lambda handles of the facade callbacks every block registers.\n * Used by the middle layer to invoke callbacks via executeSingleLambda().\n */\nexport const BlockStorageFacadeHandles = createFacadeHandles(requiredFacadeCallbacks);\n\n/**\n * Lambda handles of the facade callbacks a block registers only when its model declares what\n * they run (see {@link BlockStorageFacadeCallbacks.StorageApplyParams}).\n */\nexport const BlockStorageFacadeOptionalHandles = createFacadeHandles(OptionalFacadeCallbacks);\n\n// =============================================================================\n// Facade Interface (source of truth for callback signatures)\n// =============================================================================\n\n/**\n * The complete facade interface between bundled blocks (SDK) and middle layer.\n *\n * This interface defines ALL callbacks that a block registers. The middle layer\n * calls these callbacks to perform storage operations.\n *\n * ALL types are inlined to simplify versioning - when a callback changes,\n * the entire signature is visible in one place.\n *\n * BACKWARD COMPATIBILITY:\n * - This interface can only be EXTENDED, never shrunk\n * - Existing callback signatures MUST NOT change\n * - Middle layer should use Partial<BlockStorageFacade> when dealing with\n * blocks of unknown version (older blocks may not have all callbacks)\n *\n * Each callback is documented with:\n * - Purpose and when it's called\n * - Parameter descriptions\n * - Return value description\n */\nexport interface BlockStorageFacade {\n /**\n * Apply state update to storage.\n * Called when UI updates block state (setState) or plugin data.\n * @param currentStorageJson - Current storage as JSON string\n * @param payload - Update payload with operation type and value\n * @returns Updated storage as JSON string\n */\n [BlockStorageFacadeCallbacks.StorageApplyUpdate]: (\n currentStorageJson: StringifiedJson,\n payload: MutateStoragePayload,\n ) => StringifiedJson;\n\n /**\n * Get debug view of storage.\n * Called by developer tools to inspect storage state.\n * @param storageJson - Storage as JSON string (or undefined for new blocks)\n * @returns JSON string containing StorageDebugView\n */\n [BlockStorageFacadeCallbacks.StorageDebugView]: (\n storageJson: StringifiedJson | undefined,\n ) => StringifiedJson;\n\n /**\n * Run storage migration.\n * Called when block loads to migrate data to latest version.\n * @param currentStorageJson - Current storage as JSON string (or undefined for new blocks)\n * @returns Migration result - either error or success with new storage\n */\n [BlockStorageFacadeCallbacks.StorageMigrate]: (\n currentStorageJson: StringifiedJson | undefined,\n ) =>\n | { error: string }\n | {\n error?: undefined;\n newStorageJson: StringifiedJson;\n info: string;\n };\n\n /**\n * Derive args from storage.\n * Called to get block configuration args from storage, and whether the block may run them.\n *\n * A middle layer that predates args issues reads only `error` and `value`, and each variant\n * means the same to it as before: `value` is runnable args, `error` is no args. A block built\n * with an SDK that predates args issues returns `{ error }` or `{ value }` with no `issues`.\n *\n * @param storageJson - Storage as JSON string\n * @returns One of:\n * - `{ error }`: `args()` threw, so there are no args;\n * - `{ error, args, issues }`: args were built, but the block's `argsIssues()` found errors in\n * them, so the block must not run; `error` joins the error messages, `issues` lists every\n * issue;\n * - `{ value, issues }`: args the block may run; `issues` holds the warnings.\n */\n [BlockStorageFacadeCallbacks.ArgsDerive]: (\n storageJson: StringifiedJson,\n ) =>\n | { error: string }\n | { error: string; args: unknown; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n /**\n * Derive prerunArgs from storage.\n * Called to get prerun args; falls back to args callback if not registered.\n *\n * A block with its own prerunArgs is staged with them unless its `prerunArgsIssues()` finds errors\n * in them. A block without its own prerunArgs is staged with its args unless its `argsIssues()`\n * finds errors in them.\n *\n * A middle layer that predates args issues reads only `error` and `value`: `value` is args to\n * stage, `error` skips staging. A block built with an SDK that predates args issues returns\n * `{ error }` or `{ value }` with no `issues`.\n *\n * @param storageJson - Storage as JSON string\n * @returns One of:\n * - `{ error }`: the lambda building the prerun args threw;\n * - `{ error, issues }`: prerun args were built, but errors were found in them, so the block\n * is not staged; `error` joins the error messages, `issues` lists every issue;\n * - `{ value, issues }`: args to stage, `undefined` to skip staging; `issues` holds the\n * warnings.\n */\n [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (\n storageJson: StringifiedJson,\n ) =>\n | { error: string }\n | { error: string; issues: ArgsIssue[] }\n | { error?: undefined; value: unknown; issues: ArgsIssue[] };\n\n /**\n * Get initial storage JSON for new blocks.\n * Called when creating a new block to get complete initial storage.\n * @returns Initial storage as JSON string\n */\n [BlockStorageFacadeCallbacks.StorageInitial]: () => StringifiedJson;\n\n /**\n * Derive this block's template entry params from storage.\n * Called when exporting the project as a template.\n *\n * Every V3 block declares `.templateParams()` — the model does not build without\n * it — so every export produces params. A block whose state carries nothing worth\n * restoring returns `{}`, which is written out and used as-is by init.\n *\n * The returned params are written out exactly as they come back, references included: the\n * template engine carrying them recognizes nothing in there, and the block that receives\n * them on the way back in is what repoints them. The caller supplies everything else in the\n * entry — `id`, `kind` — so the lambda cannot set them.\n *\n * @param storageJson - Storage as JSON string\n * @returns Either an error, or the params to write\n */\n [BlockStorageFacadeCallbacks.InitializationParamsDerive]: (\n storageJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; value: unknown };\n\n /**\n * Get initial storage JSON for a block created from params.\n * Called when applying a template, once per entry that carries `params`.\n *\n * The mirror image of {@link BlockStorageFacadeCallbacks.InitializationParamsDerive}:\n * that one turns storage into params, this one turns params into storage. Every\n * applied entry comes through here, including one whose file omitted `params` —\n * an omitted key is read as `{}` and checked like any other value, so no entry\n * reaches a block without passing its kind's contract.\n * {@link BlockStorageFacadeCallbacks.StorageInitial} stays the UI-creation path,\n * where there are genuinely no params.\n *\n * Separate from `StorageInitial` rather than an optional argument to it,\n * deliberately: a block bundled with an older SDK does not register this\n * callback at all, so the caller sees it missing and can say so. Widening\n * `StorageInitial` would instead have that block silently ignore the params and\n * produce a default-initialized block that looks successfully applied.\n *\n * The params arrive as ordinary live params — references are `PlRef`s, already\n * pointing at the ids the target project just assigned. Resolution happens in\n * the engine, before this call, so a block's init factory never handles a\n * template-local reference.\n *\n * Errors are returned, not thrown: a factory rejecting params it cannot use is\n * an expected outcome for a hand-written template file, and every entry's\n * problem is reported together.\n *\n * **Also where the entry's references are pointed at this project.** Params reach here\n * exactly as the file held them: nothing between the block that exported them and this call\n * marks a reference, reads one, or rewrites one, because recognizing one means knowing the\n * reference system and this bundle is where that knowledge lives. `blockIdsJson` maps each\n * template-local entry id to the block id it was given, holding the entries created so far —\n * so an id it does not name is left alone, and a reference to an entry created later names\n * nothing rather than naming the wrong block.\n *\n * Relocating and initializing are one call rather than two because every call\n * re-instantiates the runtime and re-evaluates the whole model bundle: splitting them would\n * parse the block twice per entry to produce an intermediate only the second half reads.\n *\n * @param paramsJson - The entry's params as JSON string, as the file held them\n * @param blockIdsJson - template-local entry id → assigned block id, as a JSON object\n * @returns Either an error, or the initial storage as JSON string\n */\n [BlockStorageFacadeCallbacks.StorageInitialFromParams]: (\n paramsJson: StringifiedJson,\n blockIdsJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; storageJson: StringifiedJson };\n\n /**\n * Check params against this block's kind, creating nothing.\n *\n * Called once per entry before a template is applied, so params a kind rejects are\n * reported against the entry that carries them while there is still no project — the\n * same reason references and ids are checked before construction starts. Applying\n * without this call is safe but worse: `StorageInitialFromParams` runs the same check\n * and refuses, by which point earlier entries have already been created.\n *\n * A pass carries nothing back but its own absence of error: every kind declares a\n * parser, so a pass means the params were checked against the contract, not merely\n * that they were valid JSON.\n *\n * Reference ids inside the params may be placeholders at this point: the check runs\n * before blocks exist, so what is verified is the shape of the params, not what they\n * point at.\n *\n * @param paramsJson The entry's params as JSON string\n * @returns Why the params were rejected, or nothing\n */\n [BlockStorageFacadeCallbacks.InitializationParamsValidate]: (\n paramsJson: StringifiedJson,\n ) => { error: string } | { error?: undefined };\n\n /**\n * Put params onto the block's live data with the block's own `applyParams`.\n *\n * Registered, and listed in the block's config, only when the block declares `applyParams`\n * (`BlockModelV3.applyParams`); a block without it, or bundled with an older SDK, has no such\n * callback, and the caller builds data from params with\n * {@link BlockStorageFacadeCallbacks.StorageInitialFromParams} instead.\n *\n * The params get what the from-params path gives them: the readable reference spelling is\n * expanded and the kind's parser checks them; its output is what `applyParams` gets. They are\n * live params, so nothing is relocated: references name blocks of this project.\n *\n * The data must be at the data model's current version, the one `applyParams` is written\n * against; data waiting for a migration is refused. Plugin data and everything else in the\n * storage stay as they are. Nothing is written: the caller decides what to do with the result.\n *\n * @param storageJson - Current storage as JSON string\n * @param paramsJson - The new params as JSON string, whole\n * @returns Either an error, or the storage with the params applied as JSON string\n */\n [BlockStorageFacadeCallbacks.StorageApplyParams]?: (\n storageJson: StringifiedJson,\n paramsJson: StringifiedJson,\n ) => { error: string } | { error?: undefined; storageJson: StringifiedJson };\n}\n\n/**\n * Register all facade callbacks at once. The types ensure every required callback is provided;\n * an optional one left undefined is not registered.\n */\nexport function registerFacadeCallbacks(callbacks: BlockStorageFacade): void {\n for (const key of Object.values(BlockStorageFacadeCallbacks)) {\n const callback = callbacks[key];\n if (callback !== undefined) tryRegisterCallback(key, callback as (...args: any[]) => any);\n }\n}\n"],"mappings":";;;;;;AA8DA,MAAa,+BAA+B;;;;;;;;;;AAe5C,MAAa,8BAA8B;CACzC,oBAAoB;CACpB,kBAAkB;CAClB,gBAAgB;CAChB,YAAY;CACZ,kBAAkB;CAClB,gBAAgB;CAChB,4BAA4B;CAC5B,0BAA0B;CAC1B,8BAA8B;CAC9B,oBAAoB;AACtB;;;;;;AAOA,MAAM,0BAA0B,EAC9B,oBAAoB,4BAA4B,mBAClD;;;;;AAMA,SAAS,oBACP,WAC2C;CAC3C,OAAO,OAAO,YACZ,OAAO,OAAO,SAAS,CAAC,CAAC,KAAK,WAAW,CAAC,QAAQA,iBAAAA,mBAAmB,EAAE,OAAO,CAAC,CAAC,CAAC,CACnF;AACF;AAEA,MAAM,EAAE,oBAAoB,WAAW,GAAG,4BAA4B;;;;;AAMtE,MAAa,4BAA4B,oBAAoB,uBAAuB;;;;;AAMpF,MAAa,oCAAoC,oBAAoB,uBAAuB;;;;;AAoP5F,SAAgB,wBAAwB,WAAqC;CAC3E,KAAK,MAAM,OAAO,OAAO,OAAO,2BAA2B,GAAG;EAC5D,MAAM,WAAW,UAAU;EAC3B,IAAI,aAAa,KAAA,GAAW,iBAAA,oBAAoB,KAAK,QAAmC;CAC1F;AACF"}