@platforma-sdk/model 1.52.3 → 1.53.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.
- package/dist/block_storage.cjs.map +1 -1
- package/dist/block_storage.d.ts +10 -0
- package/dist/block_storage.d.ts.map +1 -1
- package/dist/block_storage.js.map +1 -1
- package/dist/block_storage_vm.cjs +12 -15
- package/dist/block_storage_vm.cjs.map +1 -1
- package/dist/block_storage_vm.d.ts +1 -9
- package/dist/block_storage_vm.d.ts.map +1 -1
- package/dist/block_storage_vm.js +13 -16
- package/dist/block_storage_vm.js.map +1 -1
- package/dist/components/PlMultiSequenceAlignment.cjs.map +1 -1
- package/dist/components/PlMultiSequenceAlignment.d.ts +5 -3
- package/dist/components/PlMultiSequenceAlignment.d.ts.map +1 -1
- package/dist/components/PlMultiSequenceAlignment.js.map +1 -1
- package/dist/package.json.cjs +1 -1
- package/dist/package.json.js +1 -1
- package/package.json +8 -8
- package/src/block_storage.ts +11 -0
- package/src/block_storage_vm.ts +13 -24
- package/src/components/PlMultiSequenceAlignment.ts +12 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage.cjs","sources":["../src/block_storage.ts"],"sourcesContent":["/**\n * BlockStorage - Typed storage abstraction for block persistent data.\n *\n * This module provides:\n * - A typed structure for block storage with versioning and plugin support\n * - Utility functions for manipulating storage\n * - Handler interfaces for model-level customization\n *\n * @module block_storage\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Discriminator key for BlockStorage format detection.\n * This unique hash-based key identifies data as BlockStorage vs legacy formats.\n */\nexport const BLOCK_STORAGE_KEY = '__pl_a7f3e2b9__';\n\n/**\n * Current BlockStorage schema version.\n * Increment this when the storage structure itself changes (not block state migrations).\n */\nexport const BLOCK_STORAGE_SCHEMA_VERSION = 'v1';\n\n/**\n * Type for valid schema versions\n */\nexport type BlockStorageSchemaVersion = 'v1'; // Add 'v2', 'v3', etc. as schema evolves\n\n/**\n * Plugin key type - keys starting with `@plugin/` are reserved for plugin data\n */\nexport type PluginKey = `@plugin/${string}`;\n\n/**\n * Core BlockStorage type that holds:\n * - __pl_a7f3e2b9__: Schema version (discriminator key identifies BlockStorage format)\n * - __dataVersion: Version number for block data migrations\n * - __data: The block's user-facing data (state)\n * - @plugin/*: Optional plugin-specific data\n */\nexport type BlockStorage<TState = unknown> = {\n /** Schema version - the key itself is the discriminator */\n readonly [BLOCK_STORAGE_KEY]: BlockStorageSchemaVersion;\n /** Version of the block data, used for migrations */\n __dataVersion: number;\n /** The block's user-facing data (state) */\n __data: TState;\n} & {\n /** Plugin-specific data, keyed by `@plugin/<pluginName>` */\n [K in PluginKey]?: unknown;\n};\n\n/**\n * Type guard to check if a value is a valid BlockStorage object.\n * Checks for the discriminator key and valid schema version.\n */\nexport function isBlockStorage(value: unknown): value is BlockStorage {\n if (value === null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n const schemaVersion = obj[BLOCK_STORAGE_KEY];\n // Currently only 'v1' is valid, but this allows future versions\n return schemaVersion === 'v1'; // Add more versions as schema evolves\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Creates a BlockStorage with the given initial data\n *\n * @param initialData - The initial data value (defaults to empty object)\n * @param version - The initial data version (defaults to 1)\n * @returns A new BlockStorage instance with discriminator key\n */\nexport function createBlockStorage<TState = unknown>(\n initialData: TState = {} as TState,\n version: number = 1,\n): BlockStorage<TState> {\n return {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: version,\n __data: initialData,\n };\n}\n\n/**\n * Normalizes raw storage data to BlockStorage format.\n * If the input is already a BlockStorage, returns it as-is.\n * If the input is legacy format (raw state), wraps it in BlockStorage structure.\n *\n * @param raw - Raw storage data (may be legacy format or BlockStorage)\n * @returns Normalized BlockStorage\n */\nexport function normalizeBlockStorage<TState = unknown>(raw: unknown): BlockStorage<TState> {\n if (isBlockStorage(raw)) {\n return raw as BlockStorage<TState>;\n }\n // Legacy format: raw is the state directly\n return createBlockStorage(raw as TState, 1);\n}\n\n// =============================================================================\n// Data Access & Update Functions\n// =============================================================================\n\n/**\n * Gets the data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data value\n */\nexport function getStorageData<TState>(storage: BlockStorage<TState>): TState {\n return storage.__data;\n}\n\n/**\n * Derives data from raw block storage.\n * This function is meant to be called from sdk/ui-vue to extract\n * user-facing data from the raw storage returned by the middle layer.\n *\n * The middle layer returns raw storage (opaque to it), and the UI\n * uses this function to derive the actual data value.\n *\n * @param rawStorage - Raw storage data from middle layer (may be any format)\n * @returns The extracted data value, or undefined if storage is undefined/null\n */\nexport function deriveDataFromStorage<TData = unknown>(\n rawStorage: unknown,\n): TData {\n // Normalize to BlockStorage format (handles legacy formats too)\n const storage = normalizeBlockStorage<TData>(rawStorage);\n return getStorageData(storage);\n}\n\n/** Payload for storage mutation operations. SDK defines specific operations. */\nexport type MutateStoragePayload<T = unknown> = { operation: 'update-data'; value: T };\n\n/**\n * Updates the data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param payload - The update payload with operation and value\n * @returns A new BlockStorage with updated data\n */\nexport function updateStorageData<TValue = unknown>(\n storage: BlockStorage<TValue>,\n payload: MutateStoragePayload<TValue>,\n): BlockStorage<TValue> {\n switch (payload.operation) {\n case 'update-data':\n return { ...storage, __data: payload.value };\n default:\n throw new Error(`Unknown storage operation: ${(payload as { operation: string }).operation}`);\n }\n}\n\n/**\n * Gets the data version from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data version number\n */\nexport function getStorageDataVersion(storage: BlockStorage): number {\n return storage.__dataVersion;\n}\n\n/**\n * Updates the data version in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param version - The new version number\n * @returns A new BlockStorage with updated version\n */\nexport function updateStorageDataVersion<TState>(\n storage: BlockStorage<TState>,\n version: number,\n): BlockStorage<TState> {\n return { ...storage, __dataVersion: version };\n}\n\n// =============================================================================\n// Plugin Data Functions\n// =============================================================================\n\n/**\n * Gets plugin-specific data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns The plugin data or undefined if not set\n */\nexport function getPluginData<TData = unknown>(\n storage: BlockStorage,\n pluginName: string,\n): TData | undefined {\n const key: PluginKey = `@plugin/${pluginName}`;\n return storage[key] as TData | undefined;\n}\n\n/**\n * Sets plugin-specific data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @param data - The plugin data to store\n * @returns A new BlockStorage with updated plugin data\n */\nexport function setPluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n data: unknown,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n return { ...storage, [key]: data };\n}\n\n/**\n * Removes plugin-specific data from BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns A new BlockStorage with the plugin data removed\n */\nexport function removePluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n const { [key]: _, ...rest } = storage;\n return rest as BlockStorage<TState>;\n}\n\n/**\n * Gets all plugin names that have data stored\n *\n * @param storage - The BlockStorage instance\n * @returns Array of plugin names (without `@plugin/` prefix)\n */\nexport function getPluginNames(storage: BlockStorage): string[] {\n return Object.keys(storage)\n .filter((key): key is PluginKey => key.startsWith('@plugin/'))\n .map((key) => key.slice('@plugin/'.length));\n}\n\n// =============================================================================\n// Generic Storage Access\n// =============================================================================\n\n/**\n * Gets a value from BlockStorage by key\n *\n * @param storage - The BlockStorage instance\n * @param key - The key to retrieve\n * @returns The value at the given key\n */\nexport function getFromStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(storage: BlockStorage<TState>, key: K): BlockStorage<TState>[K] {\n return storage[key];\n}\n\n/**\n * Updates a value in BlockStorage by key (immutable)\n *\n * @param storage - The current BlockStorage\n * @param key - The key to update\n * @param value - The new value\n * @returns A new BlockStorage with the updated value\n */\nexport function updateStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(\n storage: BlockStorage<TState>,\n key: K,\n value: BlockStorage<TState>[K],\n): BlockStorage<TState> {\n return { ...storage, [key]: value };\n}\n\n// =============================================================================\n// Storage Handlers (for Phase 2 - Model-Level Customization)\n// =============================================================================\n\n/**\n * Interface for model-configurable storage operations.\n * These handlers allow block models to customize how storage is managed.\n */\nexport interface BlockStorageHandlers<TState = unknown> {\n /**\n * Called when setState is invoked - transforms the new state before storing.\n * Default behavior: replaces the state directly.\n *\n * @param currentStorage - The current BlockStorage\n * @param newState - The new state being set\n * @returns The updated BlockStorage\n */\n transformStateForStorage?: (\n currentStorage: BlockStorage<TState>,\n newState: TState,\n ) => BlockStorage<TState>;\n\n /**\n * Called when reading state for args derivation.\n * Default behavior: returns the state directly.\n *\n * @param storage - The current BlockStorage\n * @returns The state to use for args derivation\n */\n deriveStateForArgs?: (storage: BlockStorage<TState>) => TState;\n\n /**\n * Called during storage schema migration.\n * Default behavior: updates stateVersion only.\n *\n * @param oldStorage - The storage before migration\n * @param fromVersion - The version migrating from\n * @param toVersion - The version migrating to\n * @returns The migrated BlockStorage\n */\n migrateStorage?: (\n oldStorage: BlockStorage<TState>,\n fromVersion: number,\n toVersion: number,\n ) => BlockStorage<TState>;\n}\n\n/**\n * Default implementations of storage handlers\n */\nexport const defaultBlockStorageHandlers: Required<BlockStorageHandlers<unknown>> = {\n transformStateForStorage: <TState>(\n storage: BlockStorage<TState>,\n newState: TState,\n ): BlockStorage<TState> => updateStorageData(storage, { operation: 'update-data', value: newState }),\n\n deriveStateForArgs: <TState>(storage: BlockStorage<TState>): TState => getStorageData(storage),\n\n migrateStorage: <TState>(\n storage: BlockStorage<TState>,\n _fromVersion: number,\n toVersion: number,\n ): BlockStorage<TState> => updateStorageDataVersion(storage, toVersion),\n};\n\n/**\n * Merges custom handlers with defaults\n *\n * @param customHandlers - Custom handlers to merge\n * @returns Complete handlers with defaults for missing functions\n */\nexport function mergeBlockStorageHandlers<TState>(\n customHandlers?: BlockStorageHandlers<TState>,\n): Required<BlockStorageHandlers<TState>> {\n return {\n ...defaultBlockStorageHandlers,\n ...customHandlers,\n } as Required<BlockStorageHandlers<TState>>;\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;AASG;AAEH;AACA;AACA;AAEA;;;AAGG;AACI,MAAM,iBAAiB,GAAG;AAEjC;;;AAGG;AACI,MAAM,4BAA4B,GAAG;AA+B5C;;;AAGG;AACG,SAAU,cAAc,CAAC,KAAc,EAAA;AAC3C,IAAA,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;AAAE,QAAA,OAAO,KAAK;IAC7D,MAAM,GAAG,GAAG,KAAgC;AAC5C,IAAA,MAAM,aAAa,GAAG,GAAG,CAAC,iBAAiB,CAAC;;AAE5C,IAAA,OAAO,aAAa,KAAK,IAAI,CAAC;AAChC;AAEA;AACA;AACA;AAEA;;;;;;AAMG;SACa,kBAAkB,CAChC,cAAsB,EAAY,EAClC,UAAkB,CAAC,EAAA;IAEnB,OAAO;QACL,CAAC,iBAAiB,GAAG,4BAA4B;AACjD,QAAA,aAAa,EAAE,OAAO;AACtB,QAAA,MAAM,EAAE,WAAW;KACpB;AACH;AAEA;;;;;;;AAOG;AACG,SAAU,qBAAqB,CAAmB,GAAY,EAAA;AAClE,IAAA,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE;AACvB,QAAA,OAAO,GAA2B;IACpC;;AAEA,IAAA,OAAO,kBAAkB,CAAC,GAAa,EAAE,CAAC,CAAC;AAC7C;AAEA;AACA;AACA;AAEA;;;;;AAKG;AACG,SAAU,cAAc,CAAS,OAA6B,EAAA;IAClE,OAAO,OAAO,CAAC,MAAM;AACvB;AAEA;;;;;;;;;;AAUG;AACG,SAAU,qBAAqB,CACnC,UAAmB,EAAA;;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ockStorage - Typed storage abstraction for block persistent data.\n *\n * This module provides:\n * - A typed structure for block storage with versioning and plugin support\n * - Utility functions for manipulating storage\n * - Handler interfaces for model-level customization\n *\n * @module block_storage\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Discriminator key for BlockStorage format detection.\n * This unique hash-based key identifies data as BlockStorage vs legacy formats.\n */\nexport const BLOCK_STORAGE_KEY = '__pl_a7f3e2b9__';\n\n/**\n * Current BlockStorage schema version.\n * Increment this when the storage structure itself changes (not block state migrations).\n */\nexport const BLOCK_STORAGE_SCHEMA_VERSION = 'v1';\n\n/**\n * Type for valid schema versions\n */\nexport type BlockStorageSchemaVersion = 'v1'; // Add 'v2', 'v3', etc. as schema evolves\n\n/**\n * Plugin key type - keys starting with `@plugin/` are reserved for plugin data\n */\nexport type PluginKey = `@plugin/${string}`;\n\n/**\n * Core BlockStorage type that holds:\n * - __pl_a7f3e2b9__: Schema version (discriminator key identifies BlockStorage format)\n * - __dataVersion: Version number for block data migrations\n * - __data: The block's user-facing data (state)\n * - @plugin/*: Optional plugin-specific data\n */\nexport type BlockStorage<TState = unknown> = {\n /** Schema version - the key itself is the discriminator */\n readonly [BLOCK_STORAGE_KEY]: BlockStorageSchemaVersion;\n /** Version of the block data, used for migrations */\n __dataVersion: number;\n /** The block's user-facing data (state) */\n __data: TState;\n} & {\n /** Plugin-specific data, keyed by `@plugin/<pluginName>` */\n [K in PluginKey]?: unknown;\n};\n\n/**\n * Type guard to check if a value is a valid BlockStorage object.\n * Checks for the discriminator key and valid schema version.\n */\nexport function isBlockStorage(value: unknown): value is BlockStorage {\n if (value === null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n const schemaVersion = obj[BLOCK_STORAGE_KEY];\n // Currently only 'v1' is valid, but this allows future versions\n return schemaVersion === 'v1'; // Add more versions as schema evolves\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Creates a BlockStorage with the given initial data\n *\n * @param initialData - The initial data value (defaults to empty object)\n * @param version - The initial data version (defaults to 1)\n * @returns A new BlockStorage instance with discriminator key\n */\nexport function createBlockStorage<TState = unknown>(\n initialData: TState = {} as TState,\n version: number = 1,\n): BlockStorage<TState> {\n return {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: version,\n __data: initialData,\n };\n}\n\n/**\n * Normalizes raw storage data to BlockStorage format.\n * If the input is already a BlockStorage, returns it as-is.\n * If the input is legacy format (raw state), wraps it in BlockStorage structure.\n *\n * @param raw - Raw storage data (may be legacy format or BlockStorage)\n * @returns Normalized BlockStorage\n */\nexport function normalizeBlockStorage<TState = unknown>(raw: unknown): BlockStorage<TState> {\n if (isBlockStorage(raw)) {\n return raw as BlockStorage<TState>;\n }\n // Legacy format: raw is the state directly\n return createBlockStorage(raw as TState, 1);\n}\n\n// =============================================================================\n// Data Access & Update Functions\n// =============================================================================\n\n/**\n * Gets the data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data value\n */\nexport function getStorageData<TState>(storage: BlockStorage<TState>): TState {\n return storage.__data;\n}\n\n/**\n * Derives data from raw block storage.\n * This function is meant to be called from sdk/ui-vue to extract\n * user-facing data from the raw storage returned by the middle layer.\n *\n * The middle layer returns raw storage (opaque to it), and the UI\n * uses this function to derive the actual data value.\n *\n * @param rawStorage - Raw storage data from middle layer (may be any format)\n * @returns The extracted data value, or undefined if storage is undefined/null\n */\nexport function deriveDataFromStorage<TData = unknown>(\n rawStorage: unknown,\n): TData {\n // Normalize to BlockStorage format (handles legacy formats too)\n const storage = normalizeBlockStorage<TData>(rawStorage);\n return getStorageData(storage);\n}\n\n/** Payload for storage mutation operations. SDK defines specific operations. */\nexport type MutateStoragePayload<T = unknown> = { operation: 'update-data'; value: T };\n\n/**\n * Updates the data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param payload - The update payload with operation and value\n * @returns A new BlockStorage with updated data\n */\nexport function updateStorageData<TValue = unknown>(\n storage: BlockStorage<TValue>,\n payload: MutateStoragePayload<TValue>,\n): BlockStorage<TValue> {\n switch (payload.operation) {\n case 'update-data':\n return { ...storage, __data: payload.value };\n default:\n throw new Error(`Unknown storage operation: ${(payload as { operation: string }).operation}`);\n }\n}\n\n/**\n * Gets the data version from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data version number\n */\nexport function getStorageDataVersion(storage: BlockStorage): number {\n return storage.__dataVersion;\n}\n\n/**\n * Updates the data version in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param version - The new version number\n * @returns A new BlockStorage with updated version\n */\nexport function updateStorageDataVersion<TState>(\n storage: BlockStorage<TState>,\n version: number,\n): BlockStorage<TState> {\n return { ...storage, __dataVersion: version };\n}\n\n/**\n * Storage debug view returned by __pl_storage_debugView callback.\n * Used by developer tools to display block storage info.\n */\nexport interface StorageDebugView {\n /** Current data version (1-based, starts at 1) */\n dataVersion: number;\n /** Raw data payload stored in BlockStorage */\n data: unknown;\n}\n\n// =============================================================================\n// Plugin Data Functions\n// =============================================================================\n\n/**\n * Gets plugin-specific data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns The plugin data or undefined if not set\n */\nexport function getPluginData<TData = unknown>(\n storage: BlockStorage,\n pluginName: string,\n): TData | undefined {\n const key: PluginKey = `@plugin/${pluginName}`;\n return storage[key] as TData | undefined;\n}\n\n/**\n * Sets plugin-specific data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @param data - The plugin data to store\n * @returns A new BlockStorage with updated plugin data\n */\nexport function setPluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n data: unknown,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n return { ...storage, [key]: data };\n}\n\n/**\n * Removes plugin-specific data from BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns A new BlockStorage with the plugin data removed\n */\nexport function removePluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n const { [key]: _, ...rest } = storage;\n return rest as BlockStorage<TState>;\n}\n\n/**\n * Gets all plugin names that have data stored\n *\n * @param storage - The BlockStorage instance\n * @returns Array of plugin names (without `@plugin/` prefix)\n */\nexport function getPluginNames(storage: BlockStorage): string[] {\n return Object.keys(storage)\n .filter((key): key is PluginKey => key.startsWith('@plugin/'))\n .map((key) => key.slice('@plugin/'.length));\n}\n\n// =============================================================================\n// Generic Storage Access\n// =============================================================================\n\n/**\n * Gets a value from BlockStorage by key\n *\n * @param storage - The BlockStorage instance\n * @param key - The key to retrieve\n * @returns The value at the given key\n */\nexport function getFromStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(storage: BlockStorage<TState>, key: K): BlockStorage<TState>[K] {\n return storage[key];\n}\n\n/**\n * Updates a value in BlockStorage by key (immutable)\n *\n * @param storage - The current BlockStorage\n * @param key - The key to update\n * @param value - The new value\n * @returns A new BlockStorage with the updated value\n */\nexport function updateStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(\n storage: BlockStorage<TState>,\n key: K,\n value: BlockStorage<TState>[K],\n): BlockStorage<TState> {\n return { ...storage, [key]: value };\n}\n\n// =============================================================================\n// Storage Handlers (for Phase 2 - Model-Level Customization)\n// =============================================================================\n\n/**\n * Interface for model-configurable storage operations.\n * These handlers allow block models to customize how storage is managed.\n */\nexport interface BlockStorageHandlers<TState = unknown> {\n /**\n * Called when setState is invoked - transforms the new state before storing.\n * Default behavior: replaces the state directly.\n *\n * @param currentStorage - The current BlockStorage\n * @param newState - The new state being set\n * @returns The updated BlockStorage\n */\n transformStateForStorage?: (\n currentStorage: BlockStorage<TState>,\n newState: TState,\n ) => BlockStorage<TState>;\n\n /**\n * Called when reading state for args derivation.\n * Default behavior: returns the state directly.\n *\n * @param storage - The current BlockStorage\n * @returns The state to use for args derivation\n */\n deriveStateForArgs?: (storage: BlockStorage<TState>) => TState;\n\n /**\n * Called during storage schema migration.\n * Default behavior: updates stateVersion only.\n *\n * @param oldStorage - The storage before migration\n * @param fromVersion - The version migrating from\n * @param toVersion - The version migrating to\n * @returns The migrated BlockStorage\n */\n migrateStorage?: (\n oldStorage: BlockStorage<TState>,\n fromVersion: number,\n toVersion: number,\n ) => BlockStorage<TState>;\n}\n\n/**\n * Default implementations of storage handlers\n */\nexport const defaultBlockStorageHandlers: Required<BlockStorageHandlers<unknown>> = {\n transformStateForStorage: <TState>(\n storage: BlockStorage<TState>,\n newState: TState,\n ): BlockStorage<TState> => updateStorageData(storage, { operation: 'update-data', value: newState }),\n\n deriveStateForArgs: <TState>(storage: BlockStorage<TState>): TState => getStorageData(storage),\n\n migrateStorage: <TState>(\n storage: BlockStorage<TState>,\n _fromVersion: number,\n toVersion: number,\n ): BlockStorage<TState> => updateStorageDataVersion(storage, toVersion),\n};\n\n/**\n * Merges custom handlers with defaults\n *\n * @param customHandlers - Custom handlers to merge\n * @returns Complete handlers with defaults for missing functions\n */\nexport function mergeBlockStorageHandlers<TState>(\n customHandlers?: BlockStorageHandlers<TState>,\n): Required<BlockStorageHandlers<TState>> {\n return {\n ...defaultBlockStorageHandlers,\n ...customHandlers,\n } as Required<BlockStorageHandlers<TState>>;\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;AASG;AAEH;AACA;AACA;AAEA;;;AAGG;AACI,MAAM,iBAAiB,GAAG;AAEjC;;;AAGG;AACI,MAAM,4BAA4B,GAAG;AA+B5C;;;AAGG;AACG,SAAU,cAAc,CAAC,KAAc,EAAA;AAC3C,IAAA,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;AAAE,QAAA,OAAO,KAAK;IAC7D,MAAM,GAAG,GAAG,KAAgC;AAC5C,IAAA,MAAM,aAAa,GAAG,GAAG,CAAC,iBAAiB,CAAC;;AAE5C,IAAA,OAAO,a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AK,EAAE;AACrC;AAiDA;;AAEG;AACI,MAAM,2BAA2B,GAA4C;IAClF,wBAAwB,EAAE,CACxB,OAA6B,EAC7B,QAAgB,KACS,iBAAiB,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;IAEpG,kBAAkB,EAAE,CAAS,OAA6B,KAAa,cAAc,CAAC,OAAO,CAAC;AAE9F,IAAA,cAAc,EAAE,CACd,OAA6B,EAC7B,YAAoB,EACpB,SAAiB,KACQ,wBAAwB,CAAC,OAAO,EAAE,SAAS,CAAC;;AAGzE;;;;;AAKG;AACG,SAAU,yBAAyB,CACvC,cAA6C,EAAA;IAE7C,OAAO;AACL,QAAA,GAAG,2BAA2B;AAC9B,QAAA,GAAG,cAAc;KACwB;AAC7C;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/block_storage.d.ts
CHANGED
|
@@ -112,6 +112,16 @@ export declare function getStorageDataVersion(storage: BlockStorage): number;
|
|
|
112
112
|
* @returns A new BlockStorage with updated version
|
|
113
113
|
*/
|
|
114
114
|
export declare function updateStorageDataVersion<TState>(storage: BlockStorage<TState>, version: number): BlockStorage<TState>;
|
|
115
|
+
/**
|
|
116
|
+
* Storage debug view returned by __pl_storage_debugView callback.
|
|
117
|
+
* Used by developer tools to display block storage info.
|
|
118
|
+
*/
|
|
119
|
+
export interface StorageDebugView {
|
|
120
|
+
/** Current data version (1-based, starts at 1) */
|
|
121
|
+
dataVersion: number;
|
|
122
|
+
/** Raw data payload stored in BlockStorage */
|
|
123
|
+
data: unknown;
|
|
124
|
+
}
|
|
115
125
|
/**
|
|
116
126
|
* Gets plugin-specific data from BlockStorage
|
|
117
127
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage.d.ts","sourceRoot":"","sources":["../src/block_storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH;;;GAGG;AACH,eAAO,MAAM,iBAAiB,oBAAoB,CA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G;AACH,wBAAgB,aAAa,CAC3B,MAAM,EACN,CAAC,SAAS,MAAM,YAAY,CAAC,MAAM,CAAC,EAEpC,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,EAC7B,GAAG,EAAE,CAAC,EACN,KAAK,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAC7B,YAAY,CAAC,MAAM,CAAC,CAEtB;AAMD;;;GAGG;AACH,MAAM,WAAW,oBAAoB,CAAC,MAAM,GAAG,OAAO;IACpD;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,CACzB,cAAc,EAAE,YAAY,CAAC,MAAM,CAAC,EACpC,QAAQ,EAAE,MAAM,KACb,YAAY,CAAC,MAAM,CAAC,CAAC;IAE1B;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,MAAM,CAAC,KAAK,MAAM,CAAC;IAE/D;;;;;;;;OAQG;IACH,cAAc,CAAC,EAAE,CACf,UAAU,EAAE,YAAY,CAAC,MAAM,CAAC,EAChC,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,KACd,YAAY,CAAC,MAAM,CAAC,CAAC;CAC3B;AAED;;GAEG;AACH,eAAO,MAAM,2BAA2B,EAAE,QAAQ,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAa/E,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAC9C,cAAc,CAAC,EAAE,oBAAoB,CAAC,MAAM,CAAC,GAC5C,QAAQ,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC,CAKxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage.js","sources":["../src/block_storage.ts"],"sourcesContent":["/**\n * BlockStorage - Typed storage abstraction for block persistent data.\n *\n * This module provides:\n * - A typed structure for block storage with versioning and plugin support\n * - Utility functions for manipulating storage\n * - Handler interfaces for model-level customization\n *\n * @module block_storage\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Discriminator key for BlockStorage format detection.\n * This unique hash-based key identifies data as BlockStorage vs legacy formats.\n */\nexport const BLOCK_STORAGE_KEY = '__pl_a7f3e2b9__';\n\n/**\n * Current BlockStorage schema version.\n * Increment this when the storage structure itself changes (not block state migrations).\n */\nexport const BLOCK_STORAGE_SCHEMA_VERSION = 'v1';\n\n/**\n * Type for valid schema versions\n */\nexport type BlockStorageSchemaVersion = 'v1'; // Add 'v2', 'v3', etc. as schema evolves\n\n/**\n * Plugin key type - keys starting with `@plugin/` are reserved for plugin data\n */\nexport type PluginKey = `@plugin/${string}`;\n\n/**\n * Core BlockStorage type that holds:\n * - __pl_a7f3e2b9__: Schema version (discriminator key identifies BlockStorage format)\n * - __dataVersion: Version number for block data migrations\n * - __data: The block's user-facing data (state)\n * - @plugin/*: Optional plugin-specific data\n */\nexport type BlockStorage<TState = unknown> = {\n /** Schema version - the key itself is the discriminator */\n readonly [BLOCK_STORAGE_KEY]: BlockStorageSchemaVersion;\n /** Version of the block data, used for migrations */\n __dataVersion: number;\n /** The block's user-facing data (state) */\n __data: TState;\n} & {\n /** Plugin-specific data, keyed by `@plugin/<pluginName>` */\n [K in PluginKey]?: unknown;\n};\n\n/**\n * Type guard to check if a value is a valid BlockStorage object.\n * Checks for the discriminator key and valid schema version.\n */\nexport function isBlockStorage(value: unknown): value is BlockStorage {\n if (value === null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n const schemaVersion = obj[BLOCK_STORAGE_KEY];\n // Currently only 'v1' is valid, but this allows future versions\n return schemaVersion === 'v1'; // Add more versions as schema evolves\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Creates a BlockStorage with the given initial data\n *\n * @param initialData - The initial data value (defaults to empty object)\n * @param version - The initial data version (defaults to 1)\n * @returns A new BlockStorage instance with discriminator key\n */\nexport function createBlockStorage<TState = unknown>(\n initialData: TState = {} as TState,\n version: number = 1,\n): BlockStorage<TState> {\n return {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: version,\n __data: initialData,\n };\n}\n\n/**\n * Normalizes raw storage data to BlockStorage format.\n * If the input is already a BlockStorage, returns it as-is.\n * If the input is legacy format (raw state), wraps it in BlockStorage structure.\n *\n * @param raw - Raw storage data (may be legacy format or BlockStorage)\n * @returns Normalized BlockStorage\n */\nexport function normalizeBlockStorage<TState = unknown>(raw: unknown): BlockStorage<TState> {\n if (isBlockStorage(raw)) {\n return raw as BlockStorage<TState>;\n }\n // Legacy format: raw is the state directly\n return createBlockStorage(raw as TState, 1);\n}\n\n// =============================================================================\n// Data Access & Update Functions\n// =============================================================================\n\n/**\n * Gets the data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data value\n */\nexport function getStorageData<TState>(storage: BlockStorage<TState>): TState {\n return storage.__data;\n}\n\n/**\n * Derives data from raw block storage.\n * This function is meant to be called from sdk/ui-vue to extract\n * user-facing data from the raw storage returned by the middle layer.\n *\n * The middle layer returns raw storage (opaque to it), and the UI\n * uses this function to derive the actual data value.\n *\n * @param rawStorage - Raw storage data from middle layer (may be any format)\n * @returns The extracted data value, or undefined if storage is undefined/null\n */\nexport function deriveDataFromStorage<TData = unknown>(\n rawStorage: unknown,\n): TData {\n // Normalize to BlockStorage format (handles legacy formats too)\n const storage = normalizeBlockStorage<TData>(rawStorage);\n return getStorageData(storage);\n}\n\n/** Payload for storage mutation operations. SDK defines specific operations. */\nexport type MutateStoragePayload<T = unknown> = { operation: 'update-data'; value: T };\n\n/**\n * Updates the data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param payload - The update payload with operation and value\n * @returns A new BlockStorage with updated data\n */\nexport function updateStorageData<TValue = unknown>(\n storage: BlockStorage<TValue>,\n payload: MutateStoragePayload<TValue>,\n): BlockStorage<TValue> {\n switch (payload.operation) {\n case 'update-data':\n return { ...storage, __data: payload.value };\n default:\n throw new Error(`Unknown storage operation: ${(payload as { operation: string }).operation}`);\n }\n}\n\n/**\n * Gets the data version from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data version number\n */\nexport function getStorageDataVersion(storage: BlockStorage): number {\n return storage.__dataVersion;\n}\n\n/**\n * Updates the data version in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param version - The new version number\n * @returns A new BlockStorage with updated version\n */\nexport function updateStorageDataVersion<TState>(\n storage: BlockStorage<TState>,\n version: number,\n): BlockStorage<TState> {\n return { ...storage, __dataVersion: version };\n}\n\n// =============================================================================\n// Plugin Data Functions\n// =============================================================================\n\n/**\n * Gets plugin-specific data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns The plugin data or undefined if not set\n */\nexport function getPluginData<TData = unknown>(\n storage: BlockStorage,\n pluginName: string,\n): TData | undefined {\n const key: PluginKey = `@plugin/${pluginName}`;\n return storage[key] as TData | undefined;\n}\n\n/**\n * Sets plugin-specific data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @param data - The plugin data to store\n * @returns A new BlockStorage with updated plugin data\n */\nexport function setPluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n data: unknown,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n return { ...storage, [key]: data };\n}\n\n/**\n * Removes plugin-specific data from BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns A new BlockStorage with the plugin data removed\n */\nexport function removePluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n const { [key]: _, ...rest } = storage;\n return rest as BlockStorage<TState>;\n}\n\n/**\n * Gets all plugin names that have data stored\n *\n * @param storage - The BlockStorage instance\n * @returns Array of plugin names (without `@plugin/` prefix)\n */\nexport function getPluginNames(storage: BlockStorage): string[] {\n return Object.keys(storage)\n .filter((key): key is PluginKey => key.startsWith('@plugin/'))\n .map((key) => key.slice('@plugin/'.length));\n}\n\n// =============================================================================\n// Generic Storage Access\n// =============================================================================\n\n/**\n * Gets a value from BlockStorage by key\n *\n * @param storage - The BlockStorage instance\n * @param key - The key to retrieve\n * @returns The value at the given key\n */\nexport function getFromStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(storage: BlockStorage<TState>, key: K): BlockStorage<TState>[K] {\n return storage[key];\n}\n\n/**\n * Updates a value in BlockStorage by key (immutable)\n *\n * @param storage - The current BlockStorage\n * @param key - The key to update\n * @param value - The new value\n * @returns A new BlockStorage with the updated value\n */\nexport function updateStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(\n storage: BlockStorage<TState>,\n key: K,\n value: BlockStorage<TState>[K],\n): BlockStorage<TState> {\n return { ...storage, [key]: value };\n}\n\n// =============================================================================\n// Storage Handlers (for Phase 2 - Model-Level Customization)\n// =============================================================================\n\n/**\n * Interface for model-configurable storage operations.\n * These handlers allow block models to customize how storage is managed.\n */\nexport interface BlockStorageHandlers<TState = unknown> {\n /**\n * Called when setState is invoked - transforms the new state before storing.\n * Default behavior: replaces the state directly.\n *\n * @param currentStorage - The current BlockStorage\n * @param newState - The new state being set\n * @returns The updated BlockStorage\n */\n transformStateForStorage?: (\n currentStorage: BlockStorage<TState>,\n newState: TState,\n ) => BlockStorage<TState>;\n\n /**\n * Called when reading state for args derivation.\n * Default behavior: returns the state directly.\n *\n * @param storage - The current BlockStorage\n * @returns The state to use for args derivation\n */\n deriveStateForArgs?: (storage: BlockStorage<TState>) => TState;\n\n /**\n * Called during storage schema migration.\n * Default behavior: updates stateVersion only.\n *\n * @param oldStorage - The storage before migration\n * @param fromVersion - The version migrating from\n * @param toVersion - The version migrating to\n * @returns The migrated BlockStorage\n */\n migrateStorage?: (\n oldStorage: BlockStorage<TState>,\n fromVersion: number,\n toVersion: number,\n ) => BlockStorage<TState>;\n}\n\n/**\n * Default implementations of storage handlers\n */\nexport const defaultBlockStorageHandlers: Required<BlockStorageHandlers<unknown>> = {\n transformStateForStorage: <TState>(\n storage: BlockStorage<TState>,\n newState: TState,\n ): BlockStorage<TState> => updateStorageData(storage, { operation: 'update-data', value: newState }),\n\n deriveStateForArgs: <TState>(storage: BlockStorage<TState>): TState => getStorageData(storage),\n\n migrateStorage: <TState>(\n storage: BlockStorage<TState>,\n _fromVersion: number,\n toVersion: number,\n ): BlockStorage<TState> => updateStorageDataVersion(storage, toVersion),\n};\n\n/**\n * Merges custom handlers with defaults\n *\n * @param customHandlers - Custom handlers to merge\n * @returns Complete handlers with defaults for missing functions\n */\nexport function mergeBlockStorageHandlers<TState>(\n customHandlers?: BlockStorageHandlers<TState>,\n): Required<BlockStorageHandlers<TState>> {\n return {\n ...defaultBlockStorageHandlers,\n ...customHandlers,\n } as Required<BlockStorageHandlers<TState>>;\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;AASG;AAEH;AACA;AACA;AAEA;;;AAGG;AACI,MAAM,iBAAiB,GAAG;AAEjC;;;AAGG;AACI,MAAM,4BAA4B,GAAG;AA+B5C;;;AAGG;AACG,SAAU,cAAc,CAAC,KAAc,EAAA;AAC3C,IAAA,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;AAAE,QAAA,OAAO,KAAK;IAC7D,MAAM,GAAG,GAAG,KAAgC;AAC5C,IAAA,MAAM,aAAa,GAAG,GAAG,CAAC,iBAAiB,CAAC;;AAE5C,IAAA,OAAO,aAAa,KAAK,IAAI,CAAC;AAChC;AAEA;AACA;AACA;AAEA;;;;;;AAMG;SACa,kBAAkB,CAChC,cAAsB,EAAY,EAClC,UAAkB,CAAC,EAAA;IAEnB,OAAO;QACL,CAAC,iBAAiB,GAAG,4BAA4B;AACjD,QAAA,aAAa,EAAE,OAAO;AACtB,QAAA,MAAM,EAAE,WAAW;KACpB;AACH;AAEA;;;;;;;AAOG;AACG,SAAU,qBAAqB,CAAmB,GAAY,EA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OAA6B,EAC7B,YAAoB,EACpB,SAAiB,KACQ,wBAAwB,CAAC,OAAO,EAAE,SAAS,CAAC;;AAGzE;;;;;AAKG;AACG,SAAU,yBAAyB,CACvC,cAA6C,EAAA;IAE7C,OAAO;AACL,QAAA,GAAG,2BAA2B;AAC9B,QAAA,GAAG,cAAc;KACwB;AAC7C;;;;"}
|
|
1
|
+
{"version":3,"file":"block_storage.js","sources":["../src/block_storage.ts"],"sourcesContent":["/**\n * BlockStorage - Typed storage abstraction for block persistent data.\n *\n * This module provides:\n * - A typed structure for block storage with versioning and plugin support\n * - Utility functions for manipulating storage\n * - Handler interfaces for model-level customization\n *\n * @module block_storage\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Discriminator key for BlockStorage format detection.\n * This unique hash-based key identifies data as BlockStorage vs legacy formats.\n */\nexport const BLOCK_STORAGE_KEY = '__pl_a7f3e2b9__';\n\n/**\n * Current BlockStorage schema version.\n * Increment this when the storage structure itself changes (not block state migrations).\n */\nexport const BLOCK_STORAGE_SCHEMA_VERSION = 'v1';\n\n/**\n * Type for valid schema versions\n */\nexport type BlockStorageSchemaVersion = 'v1'; // Add 'v2', 'v3', etc. as schema evolves\n\n/**\n * Plugin key type - keys starting with `@plugin/` are reserved for plugin data\n */\nexport type PluginKey = `@plugin/${string}`;\n\n/**\n * Core BlockStorage type that holds:\n * - __pl_a7f3e2b9__: Schema version (discriminator key identifies BlockStorage format)\n * - __dataVersion: Version number for block data migrations\n * - __data: The block's user-facing data (state)\n * - @plugin/*: Optional plugin-specific data\n */\nexport type BlockStorage<TState = unknown> = {\n /** Schema version - the key itself is the discriminator */\n readonly [BLOCK_STORAGE_KEY]: BlockStorageSchemaVersion;\n /** Version of the block data, used for migrations */\n __dataVersion: number;\n /** The block's user-facing data (state) */\n __data: TState;\n} & {\n /** Plugin-specific data, keyed by `@plugin/<pluginName>` */\n [K in PluginKey]?: unknown;\n};\n\n/**\n * Type guard to check if a value is a valid BlockStorage object.\n * Checks for the discriminator key and valid schema version.\n */\nexport function isBlockStorage(value: unknown): value is BlockStorage {\n if (value === null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n const schemaVersion = obj[BLOCK_STORAGE_KEY];\n // Currently only 'v1' is valid, but this allows future versions\n return schemaVersion === 'v1'; // Add more versions as schema evolves\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Creates a BlockStorage with the given initial data\n *\n * @param initialData - The initial data value (defaults to empty object)\n * @param version - The initial data version (defaults to 1)\n * @returns A new BlockStorage instance with discriminator key\n */\nexport function createBlockStorage<TState = unknown>(\n initialData: TState = {} as TState,\n version: number = 1,\n): BlockStorage<TState> {\n return {\n [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,\n __dataVersion: version,\n __data: initialData,\n };\n}\n\n/**\n * Normalizes raw storage data to BlockStorage format.\n * If the input is already a BlockStorage, returns it as-is.\n * If the input is legacy format (raw state), wraps it in BlockStorage structure.\n *\n * @param raw - Raw storage data (may be legacy format or BlockStorage)\n * @returns Normalized BlockStorage\n */\nexport function normalizeBlockStorage<TState = unknown>(raw: unknown): BlockStorage<TState> {\n if (isBlockStorage(raw)) {\n return raw as BlockStorage<TState>;\n }\n // Legacy format: raw is the state directly\n return createBlockStorage(raw as TState, 1);\n}\n\n// =============================================================================\n// Data Access & Update Functions\n// =============================================================================\n\n/**\n * Gets the data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data value\n */\nexport function getStorageData<TState>(storage: BlockStorage<TState>): TState {\n return storage.__data;\n}\n\n/**\n * Derives data from raw block storage.\n * This function is meant to be called from sdk/ui-vue to extract\n * user-facing data from the raw storage returned by the middle layer.\n *\n * The middle layer returns raw storage (opaque to it), and the UI\n * uses this function to derive the actual data value.\n *\n * @param rawStorage - Raw storage data from middle layer (may be any format)\n * @returns The extracted data value, or undefined if storage is undefined/null\n */\nexport function deriveDataFromStorage<TData = unknown>(\n rawStorage: unknown,\n): TData {\n // Normalize to BlockStorage format (handles legacy formats too)\n const storage = normalizeBlockStorage<TData>(rawStorage);\n return getStorageData(storage);\n}\n\n/** Payload for storage mutation operations. SDK defines specific operations. */\nexport type MutateStoragePayload<T = unknown> = { operation: 'update-data'; value: T };\n\n/**\n * Updates the data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param payload - The update payload with operation and value\n * @returns A new BlockStorage with updated data\n */\nexport function updateStorageData<TValue = unknown>(\n storage: BlockStorage<TValue>,\n payload: MutateStoragePayload<TValue>,\n): BlockStorage<TValue> {\n switch (payload.operation) {\n case 'update-data':\n return { ...storage, __data: payload.value };\n default:\n throw new Error(`Unknown storage operation: ${(payload as { operation: string }).operation}`);\n }\n}\n\n/**\n * Gets the data version from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @returns The data version number\n */\nexport function getStorageDataVersion(storage: BlockStorage): number {\n return storage.__dataVersion;\n}\n\n/**\n * Updates the data version in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param version - The new version number\n * @returns A new BlockStorage with updated version\n */\nexport function updateStorageDataVersion<TState>(\n storage: BlockStorage<TState>,\n version: number,\n): BlockStorage<TState> {\n return { ...storage, __dataVersion: version };\n}\n\n/**\n * Storage debug view returned by __pl_storage_debugView callback.\n * Used by developer tools to display block storage info.\n */\nexport interface StorageDebugView {\n /** Current data version (1-based, starts at 1) */\n dataVersion: number;\n /** Raw data payload stored in BlockStorage */\n data: unknown;\n}\n\n// =============================================================================\n// Plugin Data Functions\n// =============================================================================\n\n/**\n * Gets plugin-specific data from BlockStorage\n *\n * @param storage - The BlockStorage instance\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns The plugin data or undefined if not set\n */\nexport function getPluginData<TData = unknown>(\n storage: BlockStorage,\n pluginName: string,\n): TData | undefined {\n const key: PluginKey = `@plugin/${pluginName}`;\n return storage[key] as TData | undefined;\n}\n\n/**\n * Sets plugin-specific data in BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @param data - The plugin data to store\n * @returns A new BlockStorage with updated plugin data\n */\nexport function setPluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n data: unknown,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n return { ...storage, [key]: data };\n}\n\n/**\n * Removes plugin-specific data from BlockStorage (immutable)\n *\n * @param storage - The current BlockStorage\n * @param pluginName - The plugin name (without `@plugin/` prefix)\n * @returns A new BlockStorage with the plugin data removed\n */\nexport function removePluginData<TState>(\n storage: BlockStorage<TState>,\n pluginName: string,\n): BlockStorage<TState> {\n const key: PluginKey = `@plugin/${pluginName}`;\n const { [key]: _, ...rest } = storage;\n return rest as BlockStorage<TState>;\n}\n\n/**\n * Gets all plugin names that have data stored\n *\n * @param storage - The BlockStorage instance\n * @returns Array of plugin names (without `@plugin/` prefix)\n */\nexport function getPluginNames(storage: BlockStorage): string[] {\n return Object.keys(storage)\n .filter((key): key is PluginKey => key.startsWith('@plugin/'))\n .map((key) => key.slice('@plugin/'.length));\n}\n\n// =============================================================================\n// Generic Storage Access\n// =============================================================================\n\n/**\n * Gets a value from BlockStorage by key\n *\n * @param storage - The BlockStorage instance\n * @param key - The key to retrieve\n * @returns The value at the given key\n */\nexport function getFromStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(storage: BlockStorage<TState>, key: K): BlockStorage<TState>[K] {\n return storage[key];\n}\n\n/**\n * Updates a value in BlockStorage by key (immutable)\n *\n * @param storage - The current BlockStorage\n * @param key - The key to update\n * @param value - The new value\n * @returns A new BlockStorage with the updated value\n */\nexport function updateStorage<\n TState,\n K extends keyof BlockStorage<TState>,\n>(\n storage: BlockStorage<TState>,\n key: K,\n value: BlockStorage<TState>[K],\n): BlockStorage<TState> {\n return { ...storage, [key]: value };\n}\n\n// =============================================================================\n// Storage Handlers (for Phase 2 - Model-Level Customization)\n// =============================================================================\n\n/**\n * Interface for model-configurable storage operations.\n * These handlers allow block models to customize how storage is managed.\n */\nexport interface BlockStorageHandlers<TState = unknown> {\n /**\n * Called when setState is invoked - transforms the new state before storing.\n * Default behavior: replaces the state directly.\n *\n * @param currentStorage - The current BlockStorage\n * @param newState - The new state being set\n * @returns The updated BlockStorage\n */\n transformStateForStorage?: (\n currentStorage: BlockStorage<TState>,\n newState: TState,\n ) => BlockStorage<TState>;\n\n /**\n * Called when reading state for args derivation.\n * Default behavior: returns the state directly.\n *\n * @param storage - The current BlockStorage\n * @returns The state to use for args derivation\n */\n deriveStateForArgs?: (storage: BlockStorage<TState>) => TState;\n\n /**\n * Called during storage schema migration.\n * Default behavior: updates stateVersion only.\n *\n * @param oldStorage - The storage before migration\n * @param fromVersion - The version migrating from\n * @param toVersion - The version migrating to\n * @returns The migrated BlockStorage\n */\n migrateStorage?: (\n oldStorage: BlockStorage<TState>,\n fromVersion: number,\n toVersion: number,\n ) => BlockStorage<TState>;\n}\n\n/**\n * Default implementations of storage handlers\n */\nexport const defaultBlockStorageHandlers: Required<BlockStorageHandlers<unknown>> = {\n transformStateForStorage: <TState>(\n storage: BlockStorage<TState>,\n newState: TState,\n ): BlockStorage<TState> => updateStorageData(storage, { operation: 'update-data', value: newState }),\n\n deriveStateForArgs: <TState>(storage: BlockStorage<TState>): TState => getStorageData(storage),\n\n migrateStorage: <TState>(\n storage: BlockStorage<TState>,\n _fromVersion: number,\n toVersion: number,\n ): BlockStorage<TState> => updateStorageDataVersion(storage, toVersion),\n};\n\n/**\n * Merges custom handlers with defaults\n *\n * @param customHandlers - Custom handlers to merge\n * @returns Complete handlers with defaults for missing functions\n */\nexport function mergeBlockStorageHandlers<TState>(\n customHandlers?: BlockStorageHandlers<TState>,\n): Required<BlockStorageHandlers<TState>> {\n return {\n ...defaultBlockStorageHandlers,\n ...customHandlers,\n } as Required<BlockStorageHandlers<TState>>;\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;AASG;AAEH;AACA;AACA;AAEA;;;AAGG;AACI,MAAM,iBAAiB,GAAG;AAEjC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,MAAM,CAAC,CAAC;AAC/C;AAEA;AACA;AACA;AAEA;;;;;;AAMG;AACG,SAAU,cAAc,CAG5B,OAA6B,EAAE,GAAM,EAAA;AACrC,IAAA,OAAO,OAAO,CAAC,GAAG,CAAC;AACrB;AAEA;;;;;;;AAOG;SACa,aAAa,CAI3B,OAA6B,EAC7B,GAAM,EACN,KAA8B,EAAA;IAE9B,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC,GAAG,GAAG,KAAK,EAAE;AACrC;AAiDA;;AAEG;AACI,MAAM,2BAA2B,GAA4C;IAClF,wBAAwB,EAAE,CACxB,OAA6B,EAC7B,QAAgB,KACS,iBAAiB,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;IAEpG,kBAAkB,EAAE,CAAS,OAA6B,KAAa,cAAc,CAAC,OAAO,CAAC;AAE9F,IAAA,cAAc,EAAE,CACd,OAA6B,EAC7B,YAAoB,EACpB,SAAiB,KACQ,wBAAwB,CAAC,OAAO,EAAE,SAAS,CAAC;;AAGzE;;;;;AAKG;AACG,SAAU,yBAAyB,CACvC,cAA6C,EAAA;IAE7C,OAAO;AACL,QAAA,GAAG,2BAA2B;AAC9B,QAAA,GAAG,cAAc;KACwB;AAC7C;;;;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var block_storage = require('./block_storage.cjs');
|
|
4
|
+
var plModelCommon = require('@milaboratories/pl-model-common');
|
|
4
5
|
var internal = require('./internal.cjs');
|
|
5
6
|
|
|
6
7
|
/**
|
|
@@ -11,9 +12,8 @@ var internal = require('./internal.cjs');
|
|
|
11
12
|
* directly - they only see `state`.
|
|
12
13
|
*
|
|
13
14
|
* Registered callbacks (all prefixed with `__pl_` for internal SDK use):
|
|
14
|
-
* - `__pl_storage_normalize`: (rawStorage) => { storage, data }
|
|
15
15
|
* - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson
|
|
16
|
-
* - `
|
|
16
|
+
* - `__pl_storage_debugView`: (rawStorage) => JSON string with storage debug view
|
|
17
17
|
* - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult
|
|
18
18
|
* - `__pl_args_derive`: (storageJson) => ArgsDeriveResult
|
|
19
19
|
* - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult
|
|
@@ -97,31 +97,28 @@ function isLegacyModelV1ApiFormat(data) {
|
|
|
97
97
|
// =============================================================================
|
|
98
98
|
// Auto-register internal callbacks when module is loaded in VM
|
|
99
99
|
// =============================================================================
|
|
100
|
-
// Register normalize callback
|
|
101
|
-
internal.tryRegisterCallback('__pl_storage_normalize', (rawStorage) => {
|
|
102
|
-
return normalizeStorage(rawStorage);
|
|
103
|
-
});
|
|
104
100
|
// Register apply update callback (requires existing storage)
|
|
105
101
|
internal.tryRegisterCallback('__pl_storage_applyUpdate', (currentStorageJson, payload) => {
|
|
106
102
|
return applyStorageUpdate(currentStorageJson, payload);
|
|
107
103
|
});
|
|
108
104
|
/**
|
|
109
|
-
* Gets storage
|
|
110
|
-
* Returns structured info about the storage state.
|
|
105
|
+
* Gets storage debug view from raw storage data.
|
|
106
|
+
* Returns structured debug info about the storage state.
|
|
111
107
|
*
|
|
112
108
|
* @param rawStorage - Raw data from blockStorage field (may be JSON string or object)
|
|
113
|
-
* @returns JSON string with storage
|
|
109
|
+
* @returns JSON string with storage debug view
|
|
114
110
|
*/
|
|
115
|
-
function
|
|
111
|
+
function getStorageDebugView(rawStorage) {
|
|
116
112
|
const { storage } = normalizeStorage(rawStorage);
|
|
117
|
-
const
|
|
113
|
+
const debugView = {
|
|
118
114
|
dataVersion: storage.__dataVersion,
|
|
115
|
+
data: storage.__data,
|
|
119
116
|
};
|
|
120
|
-
return
|
|
117
|
+
return plModelCommon.stringifyJson(debugView);
|
|
121
118
|
}
|
|
122
|
-
// Register
|
|
123
|
-
internal.tryRegisterCallback('
|
|
124
|
-
return
|
|
119
|
+
// Register debug view callback
|
|
120
|
+
internal.tryRegisterCallback('__pl_storage_debugView', (rawStorage) => {
|
|
121
|
+
return getStorageDebugView(rawStorage);
|
|
125
122
|
});
|
|
126
123
|
/**
|
|
127
124
|
* Runs storage migration using the DataModel's upgrade callback.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage_vm.cjs","sources":["../src/block_storage_vm.ts"],"sourcesContent":["/**\n * BlockStorage VM Integration - Internal module for VM-based storage operations.\n *\n * This module auto-registers internal callbacks that the middle layer can invoke\n * to perform storage transformations. Block developers never interact with these\n * directly - they only see `state`.\n *\n * Registered callbacks (all prefixed with `__pl_` for internal SDK use):\n * - `__pl_storage_normalize`: (rawStorage) => { storage, data }\n * - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson\n * - `__pl_storage_getInfo`: (rawStorage) => JSON string with storage info\n * - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult\n * - `__pl_args_derive`: (storageJson) => ArgsDeriveResult\n * - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult\n *\n * Callbacks registered by DataModel.registerCallbacks():\n * - `__pl_data_initial`: () => initial data\n * - `__pl_data_upgrade`: (versioned) => UpgradeResult\n * - `__pl_storage_initial`: () => initial BlockStorage as JSON string\n *\n * @module block_storage_vm\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n updateStorageData,\n} from './block_storage';\nimport { tryGetCfgRenderCtx, tryRegisterCallback } from './internal';\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 return { storage: parsed, data: getStorageData(parsed) };\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 newData - New data from application\n * @returns Updated storage as JSON string\n */\nfunction applyStorageUpdate(currentStorageJson: string, payload: MutateStoragePayload): string {\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 JSON.stringify(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// Auto-register internal callbacks when module is loaded in VM\n// =============================================================================\n\n// Register normalize callback\ntryRegisterCallback('__pl_storage_normalize', (rawStorage: unknown) => {\n return normalizeStorage(rawStorage);\n});\n\n// Register apply update callback (requires existing storage)\ntryRegisterCallback('__pl_storage_applyUpdate', (currentStorageJson: string, payload: MutateStoragePayload) => {\n return applyStorageUpdate(currentStorageJson, payload);\n});\n\n/**\n * Storage info result returned by __pl_storage_getInfo callback.\n */\nexport interface StorageInfo {\n /** Current data version (1-based, starts at 1) */\n dataVersion: number;\n}\n\n/**\n * Gets storage info from raw storage data.\n * Returns structured 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 info\n */\nfunction getStorageInfo(rawStorage: unknown): string {\n const { storage } = normalizeStorage(rawStorage);\n const info: StorageInfo = {\n dataVersion: storage.__dataVersion,\n };\n return JSON.stringify(info);\n}\n\n// Register get info callback\ntryRegisterCallback('__pl_storage_getInfo', (rawStorage: unknown) => {\n return getStorageInfo(rawStorage);\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: string, info: string, warn?: string } - migration succeeded or reset to initial\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: string; info: string; warn?: string };\n\n/** Result from Migrator.upgrade() */\ninterface UpgradeResult {\n version: number;\n data: unknown;\n warning?: string;\n}\n\n/**\n * Runs storage migration using the DataModel's upgrade callback.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * Uses the '__pl_data_upgrade' callback registered by DataModel.registerCallbacks() which:\n * - Handles all migration logic internally\n * - Returns { version, data, warning? } - warning present if reset to initial data\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @returns MigrationResult\n */\nfunction migrateStorage(currentStorageJson: string | undefined): MigrationResult {\n // Get the callback registry context\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Normalize storage to get current data and version\n const { storage: currentStorage, data: currentData } = normalizeStorage(currentStorageJson);\n const currentVersion = currentStorage.__dataVersion;\n\n // Helper to create storage with given data and version\n const createStorageJson = (data: unknown, version: number): string => {\n return JSON.stringify({\n ...currentStorage,\n __dataVersion: version,\n __data: data,\n });\n };\n\n // Get the upgrade callback (registered by DataModel.registerCallbacks())\n const upgradeCallback = ctx.callbackRegistry['__pl_data_upgrade'] as ((v: { version: number; data: unknown }) => UpgradeResult) | undefined;\n if (typeof upgradeCallback !== 'function') {\n return { error: '__pl_data_upgrade callback not found (DataModel not registered)' };\n }\n\n // Call the migrator's upgrade function\n let result: UpgradeResult;\n try {\n result = upgradeCallback({ version: currentVersion, data: currentData });\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `upgrade() threw: ${errorMsg}` };\n }\n\n // Build info message\n const info = result.version === currentVersion\n ? `No migration needed (v${currentVersion})`\n : result.warning\n ? `Reset to initial data (v${result.version})`\n : `Migrated v${currentVersion}→v${result.version}`;\n\n return {\n newStorageJson: createStorageJson(result.data, result.version),\n info,\n warn: result.warning,\n };\n}\n\n// Register migrate callback\ntryRegisterCallback('__pl_storage_migrate', (currentStorageJson: string | undefined) => {\n return migrateStorage(currentStorageJson);\n});\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive callbacks.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Derives args from storage using the registered 'args' callback.\n * This extracts data from storage and passes it to the block's args() function.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived args or error\n */\nfunction deriveArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Get the args callback (registered by BlockModelV3.args())\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found' };\n }\n\n // Call the args callback with extracted data\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw: ${errorMsg}` };\n }\n}\n\n// Register args derivation callback\ntryRegisterCallback('__pl_args_derive', (storageJson: string) => {\n return deriveArgsFromStorage(storageJson);\n});\n\n/**\n * Derives prerunArgs from storage using the registered 'prerunArgs' callback.\n * Falls back to 'args' callback if 'prerunArgs' is not defined.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived prerunArgs or error\n */\nfunction derivePrerunArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Try prerunArgs callback first\n const prerunArgsCallback = ctx.callbackRegistry['prerunArgs'] as ((data: unknown) => unknown) | undefined;\n if (typeof prerunArgsCallback === 'function') {\n try {\n const result = prerunArgsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `prerunArgs() threw: ${errorMsg}` };\n }\n }\n\n // Fall back to args callback\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found (fallback from missing prerunArgs)' };\n }\n\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw (fallback): ${errorMsg}` };\n }\n}\n\n// Register prerunArgs derivation callback\ntryRegisterCallback('__pl_prerunArgs_derive', (storageJson: string) => {\n return derivePrerunArgsFromStorage(storageJson);\n});\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n"],"names":["createBlockStorage","isBlockStorage","getStorageData","updateStorageData","tryRegisterCallback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CAAC;AACjD,CAAC,CAAC;;;;;"}
|
|
1
|
+
{"version":3,"file":"block_storage_vm.cjs","sources":["../src/block_storage_vm.ts"],"sourcesContent":["/**\n * BlockStorage VM Integration - Internal module for VM-based storage operations.\n *\n * This module auto-registers internal callbacks that the middle layer can invoke\n * to perform storage transformations. Block developers never interact with these\n * directly - they only see `state`.\n *\n * Registered callbacks (all prefixed with `__pl_` for internal SDK use):\n * - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson\n * - `__pl_storage_debugView`: (rawStorage) => JSON string with storage debug view\n * - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult\n * - `__pl_args_derive`: (storageJson) => ArgsDeriveResult\n * - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult\n *\n * Callbacks registered by DataModel.registerCallbacks():\n * - `__pl_data_initial`: () => initial data\n * - `__pl_data_upgrade`: (versioned) => UpgradeResult\n * - `__pl_storage_initial`: () => initial BlockStorage as JSON string\n *\n * @module block_storage_vm\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n type StorageDebugView,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n updateStorageData,\n} from './block_storage';\nimport { stringifyJson, type StringifiedJson } from '@milaboratories/pl-model-common';\nimport { tryGetCfgRenderCtx, tryRegisterCallback } from './internal';\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 return { storage: parsed, data: getStorageData(parsed) };\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 newData - New data from application\n * @returns Updated storage as JSON string\n */\nfunction applyStorageUpdate(currentStorageJson: string, payload: MutateStoragePayload): string {\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 JSON.stringify(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// Auto-register internal callbacks when module is loaded in VM\n// =============================================================================\n\n// Register apply update callback (requires existing storage)\ntryRegisterCallback('__pl_storage_applyUpdate', (currentStorageJson: string, payload: MutateStoragePayload) => {\n return applyStorageUpdate(currentStorageJson, payload);\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 */\nfunction 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// Register debug view callback\ntryRegisterCallback('__pl_storage_debugView', (rawStorage: unknown) => {\n return getStorageDebugView(rawStorage);\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: string, info: string, warn?: string } - migration succeeded or reset to initial\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: string; info: string; warn?: string };\n\n/** Result from Migrator.upgrade() */\ninterface UpgradeResult {\n version: number;\n data: unknown;\n warning?: string;\n}\n\n/**\n * Runs storage migration using the DataModel's upgrade callback.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * Uses the '__pl_data_upgrade' callback registered by DataModel.registerCallbacks() which:\n * - Handles all migration logic internally\n * - Returns { version, data, warning? } - warning present if reset to initial data\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @returns MigrationResult\n */\nfunction migrateStorage(currentStorageJson: string | undefined): MigrationResult {\n // Get the callback registry context\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Normalize storage to get current data and version\n const { storage: currentStorage, data: currentData } = normalizeStorage(currentStorageJson);\n const currentVersion = currentStorage.__dataVersion;\n\n // Helper to create storage with given data and version\n const createStorageJson = (data: unknown, version: number): string => {\n return JSON.stringify({\n ...currentStorage,\n __dataVersion: version,\n __data: data,\n });\n };\n\n // Get the upgrade callback (registered by DataModel.registerCallbacks())\n const upgradeCallback = ctx.callbackRegistry['__pl_data_upgrade'] as ((v: { version: number; data: unknown }) => UpgradeResult) | undefined;\n if (typeof upgradeCallback !== 'function') {\n return { error: '__pl_data_upgrade callback not found (DataModel not registered)' };\n }\n\n // Call the migrator's upgrade function\n let result: UpgradeResult;\n try {\n result = upgradeCallback({ version: currentVersion, data: currentData });\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `upgrade() threw: ${errorMsg}` };\n }\n\n // Build info message\n const info = result.version === currentVersion\n ? `No migration needed (v${currentVersion})`\n : result.warning\n ? `Reset to initial data (v${result.version})`\n : `Migrated v${currentVersion}→v${result.version}`;\n\n return {\n newStorageJson: createStorageJson(result.data, result.version),\n info,\n warn: result.warning,\n };\n}\n\n// Register migrate callback\ntryRegisterCallback('__pl_storage_migrate', (currentStorageJson: string | undefined) => {\n return migrateStorage(currentStorageJson);\n});\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive callbacks.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Derives args from storage using the registered 'args' callback.\n * This extracts data from storage and passes it to the block's args() function.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived args or error\n */\nfunction deriveArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Get the args callback (registered by BlockModelV3.args())\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found' };\n }\n\n // Call the args callback with extracted data\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw: ${errorMsg}` };\n }\n}\n\n// Register args derivation callback\ntryRegisterCallback('__pl_args_derive', (storageJson: string) => {\n return deriveArgsFromStorage(storageJson);\n});\n\n/**\n * Derives prerunArgs from storage using the registered 'prerunArgs' callback.\n * Falls back to 'args' callback if 'prerunArgs' is not defined.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived prerunArgs or error\n */\nfunction derivePrerunArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Try prerunArgs callback first\n const prerunArgsCallback = ctx.callbackRegistry['prerunArgs'] as ((data: unknown) => unknown) | undefined;\n if (typeof prerunArgsCallback === 'function') {\n try {\n const result = prerunArgsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `prerunArgs() threw: ${errorMsg}` };\n }\n }\n\n // Fall back to args callback\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found (fallback from missing prerunArgs)' };\n }\n\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw (fallback): ${errorMsg}` };\n }\n}\n\n// Register prerunArgs derivation callback\ntryRegisterCallback('__pl_prerunArgs_derive', (storageJson: string) => {\n return derivePrerunArgsFromStorage(storageJson);\n});\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n"],"names":["createBlockStorage","isBlockStorage","getStorageData","updateStorageData","tryRegisterCallback","stringifyJson","tryGetCfgRenderCtx"],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;AAqBG;AA0BH;;;;;;;;;AASG;AACH,SAAS,gBAAgB,CAAC,UAAmB,EAAA;;IAE3C,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,IAAI,EAAE;AACnD,QAAA,MAAM,OAAO,GAAGA,gCAAkB,CAAC,EAAE,CAAC;AACtC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AAC,IAAI,CAAC;AACvC,YAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE;QAC1B;QAAE,OAAO,CAAC,EAAE;AACV,YAAA,MAAM,QAAQ,GAAG,CAAC,YAAY,KAAK,GAAG,CAAC,CAAC,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC;AAC3D,YAAA,OAAO,EAAE,KAAK,EAAE,uBAAuB,QAAQ,CAAA,CAAE,EAAE;QACrD;IACF;;IAGA,MAAM,YAAY,GAAG,GAAG,CAAC,gBAAgB,CAAC,MAAM,CAA6C;AAC7F,IAAA,IAAI,OAAO,YAAY,KAAK,UAAU,EAAE;AACtC,QAAA,OAAO,EAAE,KAAK,EAAE,4DAA4D,EAAE;IAChF;AAEA,IAAA,IAAI;AACF,QAAA,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC;AACjC,QAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE;IAC1B;IAAE,OAAO,CAAC,EAAE;AACV,QAAA,MAAM,QAAQ,GAAG,CAAC,YAAY,KAAK,GAAG,CAAC,CAAC,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC;AAC3D,QAAA,OAAO,EAAE,KAAK,EAAE,4BAA4B,QAAQ,CAAA,CAAE,EAAE;IAC1D;AACF;AAEA;AACAF,4BAAmB,CAAC,wBAAwB,EAAE,CAAC,WAAmB,KAAI;AACpE,IAAA,OAAO,2BAA2B,CAAC,WAAW,CAAC;AACjD,CAAC,CAAC;;;;;"}
|
|
@@ -6,9 +6,8 @@
|
|
|
6
6
|
* directly - they only see `state`.
|
|
7
7
|
*
|
|
8
8
|
* Registered callbacks (all prefixed with `__pl_` for internal SDK use):
|
|
9
|
-
* - `__pl_storage_normalize`: (rawStorage) => { storage, data }
|
|
10
9
|
* - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson
|
|
11
|
-
* - `
|
|
10
|
+
* - `__pl_storage_debugView`: (rawStorage) => JSON string with storage debug view
|
|
12
11
|
* - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult
|
|
13
12
|
* - `__pl_args_derive`: (storageJson) => ArgsDeriveResult
|
|
14
13
|
* - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult
|
|
@@ -31,13 +30,6 @@ export interface NormalizeStorageResult {
|
|
|
31
30
|
/** The extracted data (what developers see) */
|
|
32
31
|
data: unknown;
|
|
33
32
|
}
|
|
34
|
-
/**
|
|
35
|
-
* Storage info result returned by __pl_storage_getInfo callback.
|
|
36
|
-
*/
|
|
37
|
-
export interface StorageInfo {
|
|
38
|
-
/** Current data version (1-based, starts at 1) */
|
|
39
|
-
dataVersion: number;
|
|
40
|
-
}
|
|
41
33
|
/**
|
|
42
34
|
* Result of storage migration.
|
|
43
35
|
* Returned by __pl_storage_migrate callback.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage_vm.d.ts","sourceRoot":"","sources":["../src/block_storage_vm.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"block_storage_vm.d.ts","sourceRoot":"","sources":["../src/block_storage_vm.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC5B,KAAK,YAAY,EAOlB,MAAM,iBAAiB,CAAC;AAIzB;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,yCAAyC;IACzC,OAAO,EAAE,YAAY,CAAC;IACtB,+CAA+C;IAC/C,IAAI,EAAE,OAAO,CAAC;CACf;AA+GD;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GACvB;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GACjB;IAAE,KAAK,CAAC,EAAE,SAAS,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AA8E/E;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GACjB;IAAE,KAAK,CAAC,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAwF1C,OAAO,EAAE,iBAAiB,EAAE,4BAA4B,EAAE,CAAC"}
|
package/dist/block_storage_vm.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { createBlockStorage, isBlockStorage, getStorageData
|
|
1
|
+
import { updateStorageData, createBlockStorage, isBlockStorage, getStorageData } from './block_storage.js';
|
|
2
2
|
export { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION } from './block_storage.js';
|
|
3
|
+
import { stringifyJson } from '@milaboratories/pl-model-common';
|
|
3
4
|
import { tryRegisterCallback, tryGetCfgRenderCtx } from './internal.js';
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -10,9 +11,8 @@ import { tryRegisterCallback, tryGetCfgRenderCtx } from './internal.js';
|
|
|
10
11
|
* directly - they only see `state`.
|
|
11
12
|
*
|
|
12
13
|
* Registered callbacks (all prefixed with `__pl_` for internal SDK use):
|
|
13
|
-
* - `__pl_storage_normalize`: (rawStorage) => { storage, data }
|
|
14
14
|
* - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson
|
|
15
|
-
* - `
|
|
15
|
+
* - `__pl_storage_debugView`: (rawStorage) => JSON string with storage debug view
|
|
16
16
|
* - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult
|
|
17
17
|
* - `__pl_args_derive`: (storageJson) => ArgsDeriveResult
|
|
18
18
|
* - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult
|
|
@@ -96,31 +96,28 @@ function isLegacyModelV1ApiFormat(data) {
|
|
|
96
96
|
// =============================================================================
|
|
97
97
|
// Auto-register internal callbacks when module is loaded in VM
|
|
98
98
|
// =============================================================================
|
|
99
|
-
// Register normalize callback
|
|
100
|
-
tryRegisterCallback('__pl_storage_normalize', (rawStorage) => {
|
|
101
|
-
return normalizeStorage(rawStorage);
|
|
102
|
-
});
|
|
103
99
|
// Register apply update callback (requires existing storage)
|
|
104
100
|
tryRegisterCallback('__pl_storage_applyUpdate', (currentStorageJson, payload) => {
|
|
105
101
|
return applyStorageUpdate(currentStorageJson, payload);
|
|
106
102
|
});
|
|
107
103
|
/**
|
|
108
|
-
* Gets storage
|
|
109
|
-
* Returns structured info about the storage state.
|
|
104
|
+
* Gets storage debug view from raw storage data.
|
|
105
|
+
* Returns structured debug info about the storage state.
|
|
110
106
|
*
|
|
111
107
|
* @param rawStorage - Raw data from blockStorage field (may be JSON string or object)
|
|
112
|
-
* @returns JSON string with storage
|
|
108
|
+
* @returns JSON string with storage debug view
|
|
113
109
|
*/
|
|
114
|
-
function
|
|
110
|
+
function getStorageDebugView(rawStorage) {
|
|
115
111
|
const { storage } = normalizeStorage(rawStorage);
|
|
116
|
-
const
|
|
112
|
+
const debugView = {
|
|
117
113
|
dataVersion: storage.__dataVersion,
|
|
114
|
+
data: storage.__data,
|
|
118
115
|
};
|
|
119
|
-
return
|
|
116
|
+
return stringifyJson(debugView);
|
|
120
117
|
}
|
|
121
|
-
// Register
|
|
122
|
-
tryRegisterCallback('
|
|
123
|
-
return
|
|
118
|
+
// Register debug view callback
|
|
119
|
+
tryRegisterCallback('__pl_storage_debugView', (rawStorage) => {
|
|
120
|
+
return getStorageDebugView(rawStorage);
|
|
124
121
|
});
|
|
125
122
|
/**
|
|
126
123
|
* Runs storage migration using the DataModel's upgrade callback.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_storage_vm.js","sources":["../src/block_storage_vm.ts"],"sourcesContent":["/**\n * BlockStorage VM Integration - Internal module for VM-based storage operations.\n *\n * This module auto-registers internal callbacks that the middle layer can invoke\n * to perform storage transformations. Block developers never interact with these\n * directly - they only see `state`.\n *\n * Registered callbacks (all prefixed with `__pl_` for internal SDK use):\n * - `__pl_storage_normalize`: (rawStorage) => { storage, data }\n * - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson\n * - `__pl_storage_getInfo`: (rawStorage) => JSON string with storage info\n * - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult\n * - `__pl_args_derive`: (storageJson) => ArgsDeriveResult\n * - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult\n *\n * Callbacks registered by DataModel.registerCallbacks():\n * - `__pl_data_initial`: () => initial data\n * - `__pl_data_upgrade`: (versioned) => UpgradeResult\n * - `__pl_storage_initial`: () => initial BlockStorage as JSON string\n *\n * @module block_storage_vm\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n updateStorageData,\n} from './block_storage';\nimport { tryGetCfgRenderCtx, tryRegisterCallback } from './internal';\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 return { storage: parsed, data: getStorageData(parsed) };\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 newData - New data from application\n * @returns Updated storage as JSON string\n */\nfunction applyStorageUpdate(currentStorageJson: string, payload: MutateStoragePayload): string {\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 JSON.stringify(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// Auto-register internal callbacks when module is loaded in VM\n// =============================================================================\n\n// Register normalize callback\ntryRegisterCallback('__pl_storage_normalize', (rawStorage: unknown) => {\n return normalizeStorage(rawStorage);\n});\n\n// Register apply update callback (requires existing storage)\ntryRegisterCallback('__pl_storage_applyUpdate', (currentStorageJson: string, payload: MutateStoragePayload) => {\n return applyStorageUpdate(currentStorageJson, payload);\n});\n\n/**\n * Storage info result returned by __pl_storage_getInfo callback.\n */\nexport interface StorageInfo {\n /** Current data version (1-based, starts at 1) */\n dataVersion: number;\n}\n\n/**\n * Gets storage info from raw storage data.\n * Returns structured 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 info\n */\nfunction getStorageInfo(rawStorage: unknown): string {\n const { storage } = normalizeStorage(rawStorage);\n const info: StorageInfo = {\n dataVersion: storage.__dataVersion,\n };\n return JSON.stringify(info);\n}\n\n// Register get info callback\ntryRegisterCallback('__pl_storage_getInfo', (rawStorage: unknown) => {\n return getStorageInfo(rawStorage);\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: string, info: string, warn?: string } - migration succeeded or reset to initial\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: string; info: string; warn?: string };\n\n/** Result from Migrator.upgrade() */\ninterface UpgradeResult {\n version: number;\n data: unknown;\n warning?: string;\n}\n\n/**\n * Runs storage migration using the DataModel's upgrade callback.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * Uses the '__pl_data_upgrade' callback registered by DataModel.registerCallbacks() which:\n * - Handles all migration logic internally\n * - Returns { version, data, warning? } - warning present if reset to initial data\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @returns MigrationResult\n */\nfunction migrateStorage(currentStorageJson: string | undefined): MigrationResult {\n // Get the callback registry context\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Normalize storage to get current data and version\n const { storage: currentStorage, data: currentData } = normalizeStorage(currentStorageJson);\n const currentVersion = currentStorage.__dataVersion;\n\n // Helper to create storage with given data and version\n const createStorageJson = (data: unknown, version: number): string => {\n return JSON.stringify({\n ...currentStorage,\n __dataVersion: version,\n __data: data,\n });\n };\n\n // Get the upgrade callback (registered by DataModel.registerCallbacks())\n const upgradeCallback = ctx.callbackRegistry['__pl_data_upgrade'] as ((v: { version: number; data: unknown }) => UpgradeResult) | undefined;\n if (typeof upgradeCallback !== 'function') {\n return { error: '__pl_data_upgrade callback not found (DataModel not registered)' };\n }\n\n // Call the migrator's upgrade function\n let result: UpgradeResult;\n try {\n result = upgradeCallback({ version: currentVersion, data: currentData });\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `upgrade() threw: ${errorMsg}` };\n }\n\n // Build info message\n const info = result.version === currentVersion\n ? `No migration needed (v${currentVersion})`\n : result.warning\n ? `Reset to initial data (v${result.version})`\n : `Migrated v${currentVersion}→v${result.version}`;\n\n return {\n newStorageJson: createStorageJson(result.data, result.version),\n info,\n warn: result.warning,\n };\n}\n\n// Register migrate callback\ntryRegisterCallback('__pl_storage_migrate', (currentStorageJson: string | undefined) => {\n return migrateStorage(currentStorageJson);\n});\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive callbacks.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Derives args from storage using the registered 'args' callback.\n * This extracts data from storage and passes it to the block's args() function.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived args or error\n */\nfunction deriveArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Get the args callback (registered by BlockModelV3.args())\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found' };\n }\n\n // Call the args callback with extracted data\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw: ${errorMsg}` };\n }\n}\n\n// Register args derivation callback\ntryRegisterCallback('__pl_args_derive', (storageJson: string) => {\n return deriveArgsFromStorage(storageJson);\n});\n\n/**\n * Derives prerunArgs from storage using the registered 'prerunArgs' callback.\n * Falls back to 'args' callback if 'prerunArgs' is not defined.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived prerunArgs or error\n */\nfunction derivePrerunArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Try prerunArgs callback first\n const prerunArgsCallback = ctx.callbackRegistry['prerunArgs'] as ((data: unknown) => unknown) | undefined;\n if (typeof prerunArgsCallback === 'function') {\n try {\n const result = prerunArgsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `prerunArgs() threw: ${errorMsg}` };\n }\n }\n\n // Fall back to args callback\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found (fallback from missing prerunArgs)' };\n }\n\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw (fallback): ${errorMsg}` };\n }\n}\n\n// Register prerunArgs derivation callback\ntryRegisterCallback('__pl_prerunArgs_derive', (storageJson: string) => {\n return derivePrerunArgsFromStorage(storageJson);\n});\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n"],"names":[],"mappings":";;;;AAAA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AAwBH;;;;;;;;;AASG;AACH,SAAS,gBAAgB,CAAC,UAAmB,EAAA;;IAE3C,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,IAAI,EAAE;AACnD,QAAA,MAAM,OAAO,GAAG,kBAAkB,CAAC,EAAE,CAAC;AACtC,QAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;IAC9B;;IAGA,IAAI,MAAM,GAAG,UAAU;AACvB,IAAA,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;AAClC,QAAA,IAAI;AACF,YAAA,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;QACjC;AAAE,QAAA,MAAM;;AAEN,YAAA,MAAM,OAAO,GAAG,kBAAk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OAAO,EAAE,KAAK,EAAE,uBAAuB,QAAQ,CAAA,CAAE,EAAE;QACrD;IACF;;IAGA,MAAM,YAAY,GAAG,GAAG,CAAC,gBAAgB,CAAC,MAAM,CAA6C;AAC7F,IAAA,IAAI,OAAO,YAAY,KAAK,UAAU,EAAE;AACtC,QAAA,OAAO,EAAE,KAAK,EAAE,4DAA4D,EAAE;IAChF;AAEA,IAAA,IAAI;AACF,QAAA,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC;AACjC,QAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE;IAC1B;IAAE,OAAO,CAAC,EAAE;AACV,QAAA,MAAM,QAAQ,GAAG,CAAC,YAAY,KAAK,GAAG,CAAC,CAAC,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC;AAC3D,QAAA,OAAO,EAAE,KAAK,EAAE,4BAA4B,QAAQ,CAAA,CAAE,EAAE;IAC1D;AACF;AAEA;AACA,mBAAmB,CAAC,wBAAwB,EAAE,CAAC,WAAmB,KAAI;AACpE,IAAA,OAAO,2BAA2B,CAAC,WAAW,CAAC;AACjD,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"block_storage_vm.js","sources":["../src/block_storage_vm.ts"],"sourcesContent":["/**\n * BlockStorage VM Integration - Internal module for VM-based storage operations.\n *\n * This module auto-registers internal callbacks that the middle layer can invoke\n * to perform storage transformations. Block developers never interact with these\n * directly - they only see `state`.\n *\n * Registered callbacks (all prefixed with `__pl_` for internal SDK use):\n * - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson\n * - `__pl_storage_debugView`: (rawStorage) => JSON string with storage debug view\n * - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult\n * - `__pl_args_derive`: (storageJson) => ArgsDeriveResult\n * - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult\n *\n * Callbacks registered by DataModel.registerCallbacks():\n * - `__pl_data_initial`: () => initial data\n * - `__pl_data_upgrade`: (versioned) => UpgradeResult\n * - `__pl_storage_initial`: () => initial BlockStorage as JSON string\n *\n * @module block_storage_vm\n * @internal\n */\n\nimport {\n BLOCK_STORAGE_KEY,\n BLOCK_STORAGE_SCHEMA_VERSION,\n type BlockStorage,\n type MutateStoragePayload,\n type StorageDebugView,\n createBlockStorage,\n getStorageData,\n isBlockStorage,\n updateStorageData,\n} from './block_storage';\nimport { stringifyJson, type StringifiedJson } from '@milaboratories/pl-model-common';\nimport { tryGetCfgRenderCtx, tryRegisterCallback } from './internal';\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 return { storage: parsed, data: getStorageData(parsed) };\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 newData - New data from application\n * @returns Updated storage as JSON string\n */\nfunction applyStorageUpdate(currentStorageJson: string, payload: MutateStoragePayload): string {\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 JSON.stringify(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// Auto-register internal callbacks when module is loaded in VM\n// =============================================================================\n\n// Register apply update callback (requires existing storage)\ntryRegisterCallback('__pl_storage_applyUpdate', (currentStorageJson: string, payload: MutateStoragePayload) => {\n return applyStorageUpdate(currentStorageJson, payload);\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 */\nfunction 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// Register debug view callback\ntryRegisterCallback('__pl_storage_debugView', (rawStorage: unknown) => {\n return getStorageDebugView(rawStorage);\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: string, info: string, warn?: string } - migration succeeded or reset to initial\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: string; info: string; warn?: string };\n\n/** Result from Migrator.upgrade() */\ninterface UpgradeResult {\n version: number;\n data: unknown;\n warning?: string;\n}\n\n/**\n * Runs storage migration using the DataModel's upgrade callback.\n * This is the main entry point for the middle layer to trigger migrations.\n *\n * Uses the '__pl_data_upgrade' callback registered by DataModel.registerCallbacks() which:\n * - Handles all migration logic internally\n * - Returns { version, data, warning? } - warning present if reset to initial data\n *\n * @param currentStorageJson - Current storage as JSON string (or undefined)\n * @returns MigrationResult\n */\nfunction migrateStorage(currentStorageJson: string | undefined): MigrationResult {\n // Get the callback registry context\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Normalize storage to get current data and version\n const { storage: currentStorage, data: currentData } = normalizeStorage(currentStorageJson);\n const currentVersion = currentStorage.__dataVersion;\n\n // Helper to create storage with given data and version\n const createStorageJson = (data: unknown, version: number): string => {\n return JSON.stringify({\n ...currentStorage,\n __dataVersion: version,\n __data: data,\n });\n };\n\n // Get the upgrade callback (registered by DataModel.registerCallbacks())\n const upgradeCallback = ctx.callbackRegistry['__pl_data_upgrade'] as ((v: { version: number; data: unknown }) => UpgradeResult) | undefined;\n if (typeof upgradeCallback !== 'function') {\n return { error: '__pl_data_upgrade callback not found (DataModel not registered)' };\n }\n\n // Call the migrator's upgrade function\n let result: UpgradeResult;\n try {\n result = upgradeCallback({ version: currentVersion, data: currentData });\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `upgrade() threw: ${errorMsg}` };\n }\n\n // Build info message\n const info = result.version === currentVersion\n ? `No migration needed (v${currentVersion})`\n : result.warning\n ? `Reset to initial data (v${result.version})`\n : `Migrated v${currentVersion}→v${result.version}`;\n\n return {\n newStorageJson: createStorageJson(result.data, result.version),\n info,\n warn: result.warning,\n };\n}\n\n// Register migrate callback\ntryRegisterCallback('__pl_storage_migrate', (currentStorageJson: string | undefined) => {\n return migrateStorage(currentStorageJson);\n});\n\n// =============================================================================\n// Args Derivation from Storage\n// =============================================================================\n\n/**\n * Result of args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive callbacks.\n */\nexport type ArgsDeriveResult =\n | { error: string }\n | { error?: undefined; value: unknown };\n\n/**\n * Derives args from storage using the registered 'args' callback.\n * This extracts data from storage and passes it to the block's args() function.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived args or error\n */\nfunction deriveArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Get the args callback (registered by BlockModelV3.args())\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found' };\n }\n\n // Call the args callback with extracted data\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw: ${errorMsg}` };\n }\n}\n\n// Register args derivation callback\ntryRegisterCallback('__pl_args_derive', (storageJson: string) => {\n return deriveArgsFromStorage(storageJson);\n});\n\n/**\n * Derives prerunArgs from storage using the registered 'prerunArgs' callback.\n * Falls back to 'args' callback if 'prerunArgs' is not defined.\n *\n * @param storageJson - Storage as JSON string\n * @returns ArgsDeriveResult with derived prerunArgs or error\n */\nfunction derivePrerunArgsFromStorage(storageJson: string): ArgsDeriveResult {\n const ctx = tryGetCfgRenderCtx();\n if (ctx === undefined) {\n return { error: 'Not in config rendering context' };\n }\n\n // Extract data from storage\n const { data } = normalizeStorage(storageJson);\n\n // Try prerunArgs callback first\n const prerunArgsCallback = ctx.callbackRegistry['prerunArgs'] as ((data: unknown) => unknown) | undefined;\n if (typeof prerunArgsCallback === 'function') {\n try {\n const result = prerunArgsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `prerunArgs() threw: ${errorMsg}` };\n }\n }\n\n // Fall back to args callback\n const argsCallback = ctx.callbackRegistry['args'] as ((data: unknown) => unknown) | undefined;\n if (typeof argsCallback !== 'function') {\n return { error: 'args callback not found (fallback from missing prerunArgs)' };\n }\n\n try {\n const result = argsCallback(data);\n return { value: result };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n return { error: `args() threw (fallback): ${errorMsg}` };\n }\n}\n\n// Register prerunArgs derivation callback\ntryRegisterCallback('__pl_prerunArgs_derive', (storageJson: string) => {\n return derivePrerunArgsFromStorage(storageJson);\n});\n\n// Export discriminator key and schema version for external checks\nexport { BLOCK_STORAGE_KEY, BLOCK_STORAGE_SCHEMA_VERSION };\n"],"names":[],"mappings":";;;;;AAAA;;;;;;;;;;;;;;;;;;;;;AAqBG;AA0BH;;;;;;;;;AASG;AACH,SAAS,gBAAgB,CAAC,UAAmB,EAAA;;IAE3C,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,IAAI,EAAE;AACnD,QAAA,MAAM,OAAO,GAAG,kBAAkB,CAAC,EAAE,CAAC;AACtC,QAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;IAC9B;;IAGA,IAAI,MAAM,GAAG,UAAU;AACvB,IAAA,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;AAClC,QAAA,IAAI;AACF,YAAA,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;QACjC;AAAE,QAAA,MAAM;;AAEN,YAAA,MAAM,OAAO,GAAG,kBAAkB,CAAC,UAAU,CAAC;AAC9C,YAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE;QACtC;IACF;;AAGA,IAAA,IAAI,cAAc,CAAC,MAAM,CAAC,EAAE;AAC1B,QAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,CAAC,MAAM,CAAC,EAAE;IAC1D;;AAGA,IAAA,IAAI,wBAAwB,CAAC,MAAM,CAAC,EAAE;;AAEpC,QAAA,MAAM,OAAO,GAAG,kBAAkB,CAAC,MAAM,CAAC;AAC1C,QA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C,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC;AAC3D,QAAA,OAAO,EAAE,KAAK,EAAE,4BAA4B,QAAQ,CAAA,CAAE,EAAE;IAC1D;AACF;AAEA;AACA,mBAAmB,CAAC,wBAAwB,EAAE,CAAC,WAAmB,KAAI;AACpE,IAAA,OAAO,2BAA2B,CAAC,WAAW,CAAC;AACjD,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlMultiSequenceAlignment.cjs","sources":["../../src/components/PlMultiSequenceAlignment.ts"],"sourcesContent":["import {\n
|
|
1
|
+
{"version":3,"file":"PlMultiSequenceAlignment.cjs","sources":["../../src/components/PlMultiSequenceAlignment.ts"],"sourcesContent":["import type {\n PColumn,\n PColumnIdAndSpec,\n PColumnKey,\n PColumnValues,\n PObjectId,\n PTableColumnId,\n} from '@milaboratories/pl-model-common';\nimport {\n Annotation,\n isPTableAbsent,\n PColumnName,\n stringifyJson,\n uniquePlId,\n ValueType,\n} from '@milaboratories/pl-model-common';\nimport type { PlSelectionModel } from './PlSelectionModel';\n\nexport type PColumnPredicate = (column: PColumnIdAndSpec) =>\n | boolean\n | { default: boolean };\n\nexport interface PlMultiSequenceAlignmentSettings {\n sequenceColumnIds?: PObjectId[];\n labelColumnIds?: PTableColumnId[];\n colorScheme: PlMultiSequenceAlignmentColorSchemeOption;\n widgets: PlMultiSequenceAlignmentWidget[];\n alignmentParams: {\n gpo: number;\n gpe: number;\n tgpe: number;\n };\n}\n\nexport type PlMultiSequenceAlignmentWidget =\n | 'consensus'\n | 'seqLogo'\n | 'tree'\n | 'legend';\n\nexport interface PlMultiSequenceAlignmentModel\n extends Partial<PlMultiSequenceAlignmentSettings> {\n version?: number;\n}\n\nexport type PlMultiSequenceAlignmentColorSchemeOption =\n | { type: 'no-color' }\n | { type: 'chemical-properties' }\n | { type: 'markup'; columnIds: PObjectId[] };\n\nexport function createRowSelectionColumn({\n selection,\n columnId = uniquePlId() as string as PObjectId,\n label = 'Selection marker',\n domain,\n}: {\n selection: PlSelectionModel | undefined;\n columnId?: PObjectId;\n label?: string;\n domain?: Record<string, string>;\n}): PColumn<PColumnValues> | undefined {\n if (!selection?.axesSpec.length) {\n return;\n }\n const data: PColumnValues = selection.selectedKeys\n .filter((r): r is PColumnKey => r.every((v) => !isPTableAbsent(v)))\n .map((r) => ({ key: r, val: 1 }));\n if (!data.length) {\n return;\n }\n return {\n id: columnId,\n spec: {\n kind: 'PColumn',\n valueType: ValueType.Int,\n name: PColumnName.Table.RowSelection,\n axesSpec: selection.axesSpec,\n ...(domain && Object.keys(domain).length && { domain }),\n annotations: {\n [Annotation.Label]: label,\n [Annotation.DiscreteValues]: stringifyJson([1]),\n } satisfies Annotation,\n },\n data,\n };\n}\n"],"names":["uniquePlId","isPTableAbsent","ValueType","PColumnName","Annotation","stringifyJson"],"mappings":";;;;SAkDgB,wBAAwB,CAAC,EACvC,SAAS,EACT,QAAQ,GAAGA,wBAAU,EAAyB,EAC9C,KAAK,GAAG,kBAAkB,EAC1B,MAAM,GAMP,EAAA;AACC,IAAA,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,EAAE;QAC/B;IACF;AACA,IAAA,MAAM,IAAI,GAAkB,SAAS,CAAC;SACnC,MAAM,CAAC,CAAC,CAAC,KAAsB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAACC,4BAAc,CAAC,CAAC,CAAC,CAAC;AACjE,SAAA,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;AACnC,IAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;QAChB;IACF;IACA,OAAO;AACL,QAAA,EAAE,EAAE,QAAQ;AACZ,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,SAAS;YACf,SAAS,EAAEC,uBAAS,CAAC,GAAG;AACxB,YAAA,IAAI,EAAEC,yBAAW,CAAC,KAAK,CAAC,YAAY;YACpC,QAAQ,EAAE,SAAS,CAAC,QAAQ;AAC5B,YAAA,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,IAAI,EAAE,MAAM,EAAE,CAAC;AACvD,YAAA,WAAW,EAAE;AACX,gBAAA,CAACC,wBAAU,CAAC,KAAK,GAAG,KAAK;gBACzB,CAACA,wBAAU,CAAC,cAAc,GAAGC,2BAAa,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3B,aAAA;AACvB,SAAA;QACD,IAAI;KACL;AACH;;;;"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
export type PColumnPredicate = (column: PColumnIdAndSpec) => boolean
|
|
1
|
+
import type { PColumn, PColumnIdAndSpec, PColumnValues, PObjectId, PTableColumnId } from '@milaboratories/pl-model-common';
|
|
2
|
+
import type { PlSelectionModel } from './PlSelectionModel';
|
|
3
|
+
export type PColumnPredicate = (column: PColumnIdAndSpec) => boolean | {
|
|
4
|
+
default: boolean;
|
|
5
|
+
};
|
|
4
6
|
export interface PlMultiSequenceAlignmentSettings {
|
|
5
7
|
sequenceColumnIds?: PObjectId[];
|
|
6
8
|
labelColumnIds?: PTableColumnId[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlMultiSequenceAlignment.d.ts","sourceRoot":"","sources":["../../src/components/PlMultiSequenceAlignment.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"PlMultiSequenceAlignment.d.ts","sourceRoot":"","sources":["../../src/components/PlMultiSequenceAlignment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EACP,gBAAgB,EAEhB,aAAa,EACb,SAAS,EACT,cAAc,EACf,MAAM,iCAAiC,CAAC;AASzC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,MAAM,MAAM,gBAAgB,GAAG,CA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version":3,"file":"PlMultiSequenceAlignment.js","sources":["../../src/components/PlMultiSequenceAlignment.ts"],"sourcesContent":["import type {\n PColumn,\n PColumnIdAndSpec,\n PColumnKey,\n PColumnValues,\n PObjectId,\n PTableColumnId,\n} from '@milaboratories/pl-model-common';\nimport {\n Annotation,\n isPTableAbsent,\n PColumnName,\n stringifyJson,\n uniquePlId,\n ValueType,\n} from '@milaboratories/pl-model-common';\nimport type { PlSelectionModel } from './PlSelectionModel';\n\nexport type PColumnPredicate = (column: PColumnIdAndSpec) =>\n | boolean\n | { default: boolean };\n\nexport interface PlMultiSequenceAlignmentSettings {\n sequenceColumnIds?: PObjectId[];\n labelColumnIds?: PTableColumnId[];\n colorScheme: PlMultiSequenceAlignmentColorSchemeOption;\n widgets: PlMultiSequenceAlignmentWidget[];\n alignmentParams: {\n gpo: number;\n gpe: number;\n tgpe: number;\n };\n}\n\nexport type PlMultiSequenceAlignmentWidget =\n | 'consensus'\n | 'seqLogo'\n | 'tree'\n | 'legend';\n\nexport interface PlMultiSequenceAlignmentModel\n extends Partial<PlMultiSequenceAlignmentSettings> {\n version?: number;\n}\n\nexport type PlMultiSequenceAlignmentColorSchemeOption =\n | { type: 'no-color' }\n | { type: 'chemical-properties' }\n | { type: 'markup'; columnIds: PObjectId[] };\n\nexport function createRowSelectionColumn({\n selection,\n columnId = uniquePlId() as string as PObjectId,\n label = 'Selection marker',\n domain,\n}: {\n selection: PlSelectionModel | undefined;\n columnId?: PObjectId;\n label?: string;\n domain?: Record<string, string>;\n}): PColumn<PColumnValues> | undefined {\n if (!selection?.axesSpec.length) {\n return;\n }\n const data: PColumnValues = selection.selectedKeys\n .filter((r): r is PColumnKey => r.every((v) => !isPTableAbsent(v)))\n .map((r) => ({ key: r, val: 1 }));\n if (!data.length) {\n return;\n }\n return {\n id: columnId,\n spec: {\n kind: 'PColumn',\n valueType: ValueType.Int,\n name: PColumnName.Table.RowSelection,\n axesSpec: selection.axesSpec,\n ...(domain && Object.keys(domain).length && { domain }),\n annotations: {\n [Annotation.Label]: label,\n [Annotation.DiscreteValues]: stringifyJson([1]),\n } satisfies Annotation,\n },\n data,\n };\n}\n"],"names":[],"mappings":";;SAkDgB,wBAAwB,CAAC,EACvC,SAAS,EACT,QAAQ,GAAG,UAAU,EAAyB,EAC9C,KAAK,GAAG,kBAAkB,EAC1B,MAAM,GAMP,EAAA;AACC,IAAA,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,EAAE;QAC/B;IACF;AACA,IAAA,MAAM,IAAI,GAAkB,SAAS,CAAC;SACnC,MAAM,CAAC,CAAC,CAAC,KAAsB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;AACjE,SAAA,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;AACnC,IAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;QAChB;IACF;IACA,OAAO;AACL,QAAA,EAAE,EAAE,QAAQ;AACZ,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,SAAS;YACf,SAAS,EAAE,SAAS,CAAC,GAAG;AACxB,YAAA,IAAI,EAAE,WAAW,CAAC,KAAK,CAAC,YAAY;YACpC,QAAQ,EAAE,SAAS,CAAC,QAAQ;AAC5B,YAAA,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,IAAI,EAAE,MAAM,EAAE,CAAC;AACvD,YAAA,WAAW,EAAE;AACX,gBAAA,CAAC,UAAU,CAAC,KAAK,GAAG,KAAK;gBACzB,CAAC,UAAU,CAAC,cAAc,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3B,aAAA;AACvB,SAAA;QACD,IAAI;KACL;AACH;;;;"}
|
package/dist/package.json.cjs
CHANGED
package/dist/package.json.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@platforma-sdk/model",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.53.0",
|
|
4
4
|
"description": "Platforma.bio SDK / Block Model",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -23,20 +23,20 @@
|
|
|
23
23
|
"canonicalize": "~2.1.0",
|
|
24
24
|
"es-toolkit": "^1.39.10",
|
|
25
25
|
"zod": "~3.23.8",
|
|
26
|
-
"@milaboratories/
|
|
27
|
-
"@milaboratories/pl-
|
|
28
|
-
"@milaboratories/
|
|
26
|
+
"@milaboratories/ptabler-expression-js": "1.1.11",
|
|
27
|
+
"@milaboratories/pl-model-common": "1.24.1",
|
|
28
|
+
"@milaboratories/pl-error-like": "1.12.5"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"typescript": "~5.6.3",
|
|
32
32
|
"vitest": "^4.0.16",
|
|
33
33
|
"@vitest/coverage-istanbul": "^4.0.16",
|
|
34
34
|
"fast-json-patch": "^3.1.1",
|
|
35
|
-
"@milaboratories/build-configs": "1.
|
|
36
|
-
"@milaboratories/ts-builder": "1.2.2",
|
|
35
|
+
"@milaboratories/build-configs": "1.4.0",
|
|
37
36
|
"@milaboratories/eslint-config": "1.0.5",
|
|
38
|
-
"@milaboratories/
|
|
39
|
-
"@milaboratories/
|
|
37
|
+
"@milaboratories/helpers": "1.13.0",
|
|
38
|
+
"@milaboratories/ts-builder": "1.2.4",
|
|
39
|
+
"@milaboratories/ts-configs": "1.2.0"
|
|
40
40
|
},
|
|
41
41
|
"scripts": {
|
|
42
42
|
"type-check": "ts-builder types --target node",
|
package/src/block_storage.ts
CHANGED
|
@@ -183,6 +183,17 @@ export function updateStorageDataVersion<TState>(
|
|
|
183
183
|
return { ...storage, __dataVersion: version };
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
+
/**
|
|
187
|
+
* Storage debug view returned by __pl_storage_debugView callback.
|
|
188
|
+
* Used by developer tools to display block storage info.
|
|
189
|
+
*/
|
|
190
|
+
export interface StorageDebugView {
|
|
191
|
+
/** Current data version (1-based, starts at 1) */
|
|
192
|
+
dataVersion: number;
|
|
193
|
+
/** Raw data payload stored in BlockStorage */
|
|
194
|
+
data: unknown;
|
|
195
|
+
}
|
|
196
|
+
|
|
186
197
|
// =============================================================================
|
|
187
198
|
// Plugin Data Functions
|
|
188
199
|
// =============================================================================
|
package/src/block_storage_vm.ts
CHANGED
|
@@ -6,9 +6,8 @@
|
|
|
6
6
|
* directly - they only see `state`.
|
|
7
7
|
*
|
|
8
8
|
* Registered callbacks (all prefixed with `__pl_` for internal SDK use):
|
|
9
|
-
* - `__pl_storage_normalize`: (rawStorage) => { storage, data }
|
|
10
9
|
* - `__pl_storage_applyUpdate`: (currentStorageJson, payload) => updatedStorageJson
|
|
11
|
-
* - `
|
|
10
|
+
* - `__pl_storage_debugView`: (rawStorage) => JSON string with storage debug view
|
|
12
11
|
* - `__pl_storage_migrate`: (currentStorageJson) => MigrationResult
|
|
13
12
|
* - `__pl_args_derive`: (storageJson) => ArgsDeriveResult
|
|
14
13
|
* - `__pl_prerunArgs_derive`: (storageJson) => ArgsDeriveResult
|
|
@@ -27,11 +26,13 @@ import {
|
|
|
27
26
|
BLOCK_STORAGE_SCHEMA_VERSION,
|
|
28
27
|
type BlockStorage,
|
|
29
28
|
type MutateStoragePayload,
|
|
29
|
+
type StorageDebugView,
|
|
30
30
|
createBlockStorage,
|
|
31
31
|
getStorageData,
|
|
32
32
|
isBlockStorage,
|
|
33
33
|
updateStorageData,
|
|
34
34
|
} from './block_storage';
|
|
35
|
+
import { stringifyJson, type StringifiedJson } from '@milaboratories/pl-model-common';
|
|
35
36
|
import { tryGetCfgRenderCtx, tryRegisterCallback } from './internal';
|
|
36
37
|
|
|
37
38
|
/**
|
|
@@ -123,42 +124,30 @@ function isLegacyModelV1ApiFormat(data: unknown): data is { args?: unknown } {
|
|
|
123
124
|
// Auto-register internal callbacks when module is loaded in VM
|
|
124
125
|
// =============================================================================
|
|
125
126
|
|
|
126
|
-
// Register normalize callback
|
|
127
|
-
tryRegisterCallback('__pl_storage_normalize', (rawStorage: unknown) => {
|
|
128
|
-
return normalizeStorage(rawStorage);
|
|
129
|
-
});
|
|
130
|
-
|
|
131
127
|
// Register apply update callback (requires existing storage)
|
|
132
128
|
tryRegisterCallback('__pl_storage_applyUpdate', (currentStorageJson: string, payload: MutateStoragePayload) => {
|
|
133
129
|
return applyStorageUpdate(currentStorageJson, payload);
|
|
134
130
|
});
|
|
135
131
|
|
|
136
132
|
/**
|
|
137
|
-
*
|
|
138
|
-
|
|
139
|
-
export interface StorageInfo {
|
|
140
|
-
/** Current data version (1-based, starts at 1) */
|
|
141
|
-
dataVersion: number;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/**
|
|
145
|
-
* Gets storage info from raw storage data.
|
|
146
|
-
* Returns structured info about the storage state.
|
|
133
|
+
* Gets storage debug view from raw storage data.
|
|
134
|
+
* Returns structured debug info about the storage state.
|
|
147
135
|
*
|
|
148
136
|
* @param rawStorage - Raw data from blockStorage field (may be JSON string or object)
|
|
149
|
-
* @returns JSON string with storage
|
|
137
|
+
* @returns JSON string with storage debug view
|
|
150
138
|
*/
|
|
151
|
-
function
|
|
139
|
+
function getStorageDebugView(rawStorage: unknown): StringifiedJson<StorageDebugView> {
|
|
152
140
|
const { storage } = normalizeStorage(rawStorage);
|
|
153
|
-
const
|
|
141
|
+
const debugView: StorageDebugView = {
|
|
154
142
|
dataVersion: storage.__dataVersion,
|
|
143
|
+
data: storage.__data,
|
|
155
144
|
};
|
|
156
|
-
return
|
|
145
|
+
return stringifyJson(debugView);
|
|
157
146
|
}
|
|
158
147
|
|
|
159
|
-
// Register
|
|
160
|
-
tryRegisterCallback('
|
|
161
|
-
return
|
|
148
|
+
// Register debug view callback
|
|
149
|
+
tryRegisterCallback('__pl_storage_debugView', (rawStorage: unknown) => {
|
|
150
|
+
return getStorageDebugView(rawStorage);
|
|
162
151
|
});
|
|
163
152
|
|
|
164
153
|
// =============================================================================
|
|
@@ -1,20 +1,24 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
PColumn,
|
|
3
|
+
PColumnIdAndSpec,
|
|
4
|
+
PColumnKey,
|
|
5
|
+
PColumnValues,
|
|
6
|
+
PObjectId,
|
|
7
|
+
PTableColumnId,
|
|
8
|
+
} from '@milaboratories/pl-model-common';
|
|
1
9
|
import {
|
|
2
10
|
Annotation,
|
|
3
11
|
isPTableAbsent,
|
|
4
|
-
type PColumn,
|
|
5
|
-
type PColumnIdAndSpec,
|
|
6
|
-
type PColumnKey,
|
|
7
12
|
PColumnName,
|
|
8
|
-
type PColumnValues,
|
|
9
|
-
type PObjectId,
|
|
10
|
-
type PTableColumnId,
|
|
11
13
|
stringifyJson,
|
|
12
14
|
uniquePlId,
|
|
13
15
|
ValueType,
|
|
14
16
|
} from '@milaboratories/pl-model-common';
|
|
15
|
-
import {
|
|
17
|
+
import type { PlSelectionModel } from './PlSelectionModel';
|
|
16
18
|
|
|
17
|
-
export type PColumnPredicate = (column: PColumnIdAndSpec) =>
|
|
19
|
+
export type PColumnPredicate = (column: PColumnIdAndSpec) =>
|
|
20
|
+
| boolean
|
|
21
|
+
| { default: boolean };
|
|
18
22
|
|
|
19
23
|
export interface PlMultiSequenceAlignmentSettings {
|
|
20
24
|
sequenceColumnIds?: PObjectId[];
|