@milaboratories/milaboratories.pool-explorer.model 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
1
   WARN  Issue while reading "/home/runner/_work/platforma/platforma/.npmrc". Failed to replace env in config: ${NPMJS_TOKEN}
2
2
 
3
- > @milaboratories/milaboratories.pool-explorer.model@1.1.3 build /home/runner/_work/platforma/platforma/etc/blocks/pool-explorer/model
3
+ > @milaboratories/milaboratories.pool-explorer.model@1.1.5 build /home/runner/_work/platforma/platforma/etc/blocks/pool-explorer/model
4
4
  > ts-builder build --target block-model && block-tools build-model
5
5
 
6
6
  Building block-model project...
7
7
  ↳ rollup -c /configs/rollup.block-model.config.js
8
8
  
9
9
  ./src/index.ts → dist, dist...
10
- created dist, dist in 2.3s
10
+ created dist, dist in 1.7s
11
11
  
12
12
  ./src/index.ts → dist...
13
13
  (!) Circular dependency
14
14
  ../../../../sdk/model/dist/components/PFrameForGraphs.js -> ../../../../sdk/model/dist/pframe_utils/columns.js -> ../../../../sdk/model/dist/components/PFrameForGraphs.js
15
- created dist in 3.6s
15
+ created dist in 3.4s
16
16
  Build completed successfully
@@ -1,5 +1,5 @@
1
1
   WARN  Issue while reading "/home/runner/_work/platforma/platforma/.npmrc". Failed to replace env in config: ${NPMJS_TOKEN}
2
2
 
3
- > @milaboratories/milaboratories.pool-explorer.model@1.1.3 lint /home/runner/_work/platforma/platforma/etc/blocks/pool-explorer/model
3
+ > @milaboratories/milaboratories.pool-explorer.model@1.1.5 lint /home/runner/_work/platforma/platforma/etc/blocks/pool-explorer/model
4
4
  > eslint .
5
5
 
@@ -1,6 +1,6 @@
1
1
   WARN  Issue while reading "/home/runner/_work/platforma/platforma/.npmrc". Failed to replace env in config: ${NPMJS_TOKEN}
2
2
 
3
- > @milaboratories/milaboratories.pool-explorer.model@1.1.3 type-check /home/runner/_work/platforma/platforma/etc/blocks/pool-explorer/model
3
+ > @milaboratories/milaboratories.pool-explorer.model@1.1.5 type-check /home/runner/_work/platforma/platforma/etc/blocks/pool-explorer/model
4
4
  > ts-builder types --target block-model
5
5
 
6
6
  ↳ tsc --noEmit --project ./tsconfig.json --customConditions ,
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @milaboratories/milaboratories.pool-explorer.model
2
2
 
3
+ ## 1.1.5
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [57799dd]
8
+ - @platforma-sdk/model@1.53.2
9
+
10
+ ## 1.1.4
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [a748b92]
15
+ - @platforma-sdk/model@1.53.1
16
+
3
17
  ## 1.1.3
4
18
 
5
19
  ### Patch Changes
package/dist/bundle.js CHANGED
@@ -27,6 +27,11 @@
27
27
  * Increment this when the storage structure itself changes (not block state migrations).
28
28
  */
29
29
  const BLOCK_STORAGE_SCHEMA_VERSION = 'v1';
30
+ /**
31
+ * Default data version for new blocks without migrations.
32
+ * Unique identifier ensures blocks are created via DataModel API.
33
+ */
34
+ const DATA_MODEL_DEFAULT_VERSION = '__pl_v1_d4e8f2a1__';
30
35
  /**
31
36
  * Type guard to check if a value is a valid BlockStorage object.
32
37
  * Checks for the discriminator key and valid schema version.
@@ -46,16 +51,38 @@
46
51
  * Creates a BlockStorage with the given initial data
47
52
  *
48
53
  * @param initialData - The initial data value (defaults to empty object)
49
- * @param version - The initial data version (defaults to 1)
54
+ * @param version - The initial data version key (defaults to DATA_MODEL_DEFAULT_VERSION)
50
55
  * @returns A new BlockStorage instance with discriminator key
51
56
  */
52
- function createBlockStorage(initialData = {}, version = 1) {
57
+ function createBlockStorage(initialData = {}, version = DATA_MODEL_DEFAULT_VERSION) {
53
58
  return {
54
59
  [BLOCK_STORAGE_KEY]: BLOCK_STORAGE_SCHEMA_VERSION,
55
60
  __dataVersion: version,
56
61
  __data: initialData,
57
62
  };
58
63
  }
64
+ /**
65
+ * Normalizes raw storage data to BlockStorage format.
66
+ * If the input is already a BlockStorage, returns it as-is.
67
+ * If the input is legacy format (raw state), wraps it in BlockStorage structure.
68
+ *
69
+ * @param raw - Raw storage data (may be legacy format or BlockStorage)
70
+ * @returns Normalized BlockStorage
71
+ */
72
+ function normalizeBlockStorage(raw) {
73
+ if (isBlockStorage(raw)) {
74
+ const storage = raw;
75
+ return {
76
+ ...storage,
77
+ // Fix for early released version where __dataVersion was a number
78
+ __dataVersion: typeof storage.__dataVersion === 'number'
79
+ ? DATA_MODEL_DEFAULT_VERSION
80
+ : storage.__dataVersion,
81
+ };
82
+ }
83
+ // Legacy format: raw is the state directly
84
+ return createBlockStorage(raw);
85
+ }
59
86
  // =============================================================================
60
87
  // Data Access & Update Functions
61
88
  // =============================================================================
@@ -7502,7 +7529,7 @@
7502
7529
  }
7503
7530
  }
7504
7531
 
7505
- var version = "1.53.0";
7532
+ var version = "1.53.2";
7506
7533
 
7507
7534
  const PlatformaSDKVersion = version;
7508
7535
 
@@ -7534,7 +7561,7 @@
7534
7561
  *
7535
7562
  * Callbacks registered by DataModel.registerCallbacks():
7536
7563
  * - `__pl_data_initial`: () => initial data
7537
- * - `__pl_data_upgrade`: (versioned) => UpgradeResult
7564
+ * - `__pl_data_upgrade`: (versioned) => DataMigrationResult
7538
7565
  * - `__pl_storage_initial`: () => initial BlockStorage as JSON string
7539
7566
  *
7540
7567
  * @module block_storage_vm
@@ -7570,7 +7597,8 @@
7570
7597
  }
7571
7598
  // Check for BlockStorage format (has discriminator)
7572
7599
  if (isBlockStorage(parsed)) {
7573
- return { storage: parsed, data: getStorageData(parsed) };
7600
+ const storage = normalizeBlockStorage(parsed);
7601
+ return { storage, data: getStorageData(storage) };
7574
7602
  }
7575
7603
  // Check for legacy V1/V2 format: { args, uiState }
7576
7604
  if (isLegacyModelV1ApiFormat(parsed)) {
@@ -7635,7 +7663,7 @@
7635
7663
  return getStorageDebugView(rawStorage);
7636
7664
  });
7637
7665
  /**
7638
- * Runs storage migration using the DataModel's upgrade callback.
7666
+ * Runs storage migration using the DataModel's migrate callback.
7639
7667
  * This is the main entry point for the middle layer to trigger migrations.
7640
7668
  *
7641
7669
  * Uses the '__pl_data_upgrade' callback registered by DataModel.registerCallbacks() which:
@@ -7662,26 +7690,26 @@
7662
7690
  __data: data,
7663
7691
  });
7664
7692
  };
7665
- // Get the upgrade callback (registered by DataModel.registerCallbacks())
7666
- const upgradeCallback = ctx.callbackRegistry['__pl_data_upgrade'];
7667
- if (typeof upgradeCallback !== 'function') {
7693
+ // Get the migrate callback (registered by DataModel.registerCallbacks())
7694
+ const migrateCallback = ctx.callbackRegistry['__pl_data_upgrade'];
7695
+ if (typeof migrateCallback !== 'function') {
7668
7696
  return { error: '__pl_data_upgrade callback not found (DataModel not registered)' };
7669
7697
  }
7670
- // Call the migrator's upgrade function
7698
+ // Call the migrator's migrate function
7671
7699
  let result;
7672
7700
  try {
7673
- result = upgradeCallback({ version: currentVersion, data: currentData });
7701
+ result = migrateCallback({ version: currentVersion, data: currentData });
7674
7702
  }
7675
7703
  catch (e) {
7676
7704
  const errorMsg = e instanceof Error ? e.message : String(e);
7677
- return { error: `upgrade() threw: ${errorMsg}` };
7705
+ return { error: `migrate() threw: ${errorMsg}` };
7678
7706
  }
7679
7707
  // Build info message
7680
7708
  const info = result.version === currentVersion
7681
- ? `No migration needed (v${currentVersion})`
7709
+ ? `No migration needed (${currentVersion})`
7682
7710
  : result.warning
7683
- ? `Reset to initial data (v${result.version})`
7684
- : `Migrated v${currentVersion}→v${result.version}`;
7711
+ ? `Reset to initial data (${result.version})`
7712
+ : `Migrated ${currentVersion}→${result.version}`;
7685
7713
  return {
7686
7714
  newStorageJson: createStorageJson(result.data, result.version),
7687
7715
  info,
@@ -7978,112 +8006,193 @@
7978
8006
  }
7979
8007
  }
7980
8008
 
7981
- /** Internal builder for chaining migrations */
7982
- class DataModelBuilder {
7983
- migrationSteps;
7984
- constructor(steps = []) {
7985
- this.migrationSteps = steps;
7986
- }
7987
- /** Start a migration chain from an initial type */
7988
- static from() {
7989
- return new DataModelBuilder();
7990
- }
7991
- /** Add a migration step */
7992
- migrate(fn) {
7993
- return new DataModelBuilder([...this.migrationSteps, fn]);
7994
- }
7995
- /** Finalize with initial data, creating the DataModel */
7996
- create(initialData, ..._) {
7997
- return DataModel._fromBuilder(this.migrationSteps, initialData);
8009
+ /** Create a DataVersioned wrapper with correct shape */
8010
+ function makeDataVersioned(version, data) {
8011
+ return { version, data };
8012
+ }
8013
+ /** Thrown by recover() to signal unrecoverable data. */
8014
+ class DataUnrecoverableError extends Error {
8015
+ name = 'DataUnrecoverableError';
8016
+ constructor(dataVersion) {
8017
+ super(`Unknown version '${dataVersion}'`);
7998
8018
  }
7999
8019
  }
8020
+ function isDataUnrecoverableError(error) {
8021
+ return error instanceof Error && error.name === 'DataUnrecoverableError';
8022
+ }
8023
+ /**
8024
+ * Default recover function for unknown versions.
8025
+ * Use as fallback at the end of custom recover functions.
8026
+ *
8027
+ * @example
8028
+ * .recover((version, data) => {
8029
+ * if (version === 'legacy') {
8030
+ * return transformLegacyData(data);
8031
+ * }
8032
+ * return defaultRecover(version, data);
8033
+ * })
8034
+ */
8035
+ const defaultRecover = (version, _data) => {
8036
+ throw new DataUnrecoverableError(version);
8037
+ };
8038
+ /** Symbol for internal builder creation method */
8039
+ const FROM_BUILDER = Symbol('fromBuilder');
8000
8040
  /**
8001
8041
  * DataModel defines the block's data structure, initial values, and migrations.
8002
8042
  * Used by BlockModelV3 to manage data state.
8003
8043
  *
8044
+ * Two ways to create a DataModel:
8045
+ *
8046
+ * 1. **Simple (no migrations)** - Use `DataModel.create()`:
8004
8047
  * @example
8005
- * // Simple data model (no migrations)
8006
8048
  * const dataModel = DataModel.create<BlockData>(() => ({
8007
8049
  * numbers: [],
8008
8050
  * labels: [],
8009
8051
  * }));
8010
8052
  *
8011
- * // Data model with migrations
8012
- * const dataModel = DataModel
8013
- * .from<V1>()
8014
- * .migrate((data) => ({ ...data, labels: [] })) // v1 → v2
8015
- * .migrate((data) => ({ ...data, description: '' })) // v2 → v3
8016
- * .create<BlockData>(() => ({ numbers: [], labels: [], description: '' }));
8053
+ * 2. **With migrations** - Use `new DataModelBuilder<VersionedData>()`:
8054
+ * @example
8055
+ * const Version = defineDataVersions({
8056
+ * V1: 'v1',
8057
+ * V2: 'v2',
8058
+ * V3: 'v3',
8059
+ * });
8060
+ *
8061
+ * type VersionedData = {
8062
+ * [Version.V1]: { numbers: number[] };
8063
+ * [Version.V2]: { numbers: number[]; labels: string[] };
8064
+ * [Version.V3]: { numbers: number[]; labels: string[]; description: string };
8065
+ * };
8066
+ *
8067
+ * const dataModel = new DataModelBuilder<VersionedData>()
8068
+ * .from(Version.V1)
8069
+ * .migrate(Version.V2, (data) => ({ ...data, labels: [] }))
8070
+ * .migrate(Version.V3, (data) => ({ ...data, description: '' }))
8071
+ * .recover((version, data) => {
8072
+ * if (version === 'legacy' && typeof data === 'object' && data !== null && 'numbers' in data) {
8073
+ * return { numbers: (data as { numbers: number[] }).numbers, labels: [], description: '' };
8074
+ * }
8075
+ * return defaultRecover(version, data);
8076
+ * })
8077
+ * .init(() => ({ numbers: [], labels: [], description: '' }));
8017
8078
  */
8018
8079
  class DataModel {
8080
+ versionChain;
8019
8081
  steps;
8020
- _initialData;
8021
- constructor(steps, initialData) {
8082
+ initialDataFn;
8083
+ recoverFn;
8084
+ constructor({ versionChain, steps, initialDataFn, recoverFn = defaultRecover, }) {
8085
+ if (versionChain.length === 0) {
8086
+ throw new Error('DataModel requires at least one version key');
8087
+ }
8088
+ this.versionChain = versionChain;
8022
8089
  this.steps = steps;
8023
- this._initialData = initialData;
8024
- }
8025
- /** Start a migration chain from an initial type */
8026
- static from() {
8027
- return DataModelBuilder.from();
8090
+ this.initialDataFn = initialDataFn;
8091
+ this.recoverFn = recoverFn;
8028
8092
  }
8029
- /** Create a data model with just initial data (no migrations) */
8030
- static create(initialData) {
8031
- return new DataModel([], initialData);
8093
+ /**
8094
+ * Create a DataModel with just initial data (no migrations).
8095
+ *
8096
+ * Use this for simple blocks that don't need version migrations.
8097
+ * The version will be set to an internal default value.
8098
+ *
8099
+ * @typeParam S - The state type
8100
+ * @param initialData - Factory function returning initial state
8101
+ * @param version - Optional custom version key (defaults to internal version)
8102
+ * @returns Finalized DataModel instance
8103
+ *
8104
+ * @example
8105
+ * const dataModel = DataModel.create<BlockData>(() => ({
8106
+ * numbers: [],
8107
+ * labels: [],
8108
+ * }));
8109
+ */
8110
+ static create(initialData, version = DATA_MODEL_DEFAULT_VERSION) {
8111
+ return new DataModel({
8112
+ versionChain: [version],
8113
+ steps: [],
8114
+ initialDataFn: initialData,
8115
+ });
8032
8116
  }
8033
- /** Create from builder (internal use) */
8034
- static _fromBuilder(steps, initialData) {
8035
- return new DataModel(steps, initialData);
8117
+ /**
8118
+ * Internal method for creating DataModel from builder.
8119
+ * Uses Symbol key to prevent external access.
8120
+ * @internal
8121
+ */
8122
+ static [FROM_BUILDER](state) {
8123
+ return new DataModel(state);
8036
8124
  }
8037
8125
  /**
8038
- * Latest version number.
8039
- * Version 1 = initial state, each migration adds 1.
8126
+ * The latest (current) version key in the migration chain.
8040
8127
  */
8041
8128
  get version() {
8042
- return this.steps.length + 1;
8129
+ return this.versionChain[this.versionChain.length - 1];
8043
8130
  }
8044
- /** Number of migration steps */
8131
+ /**
8132
+ * Number of migration steps defined.
8133
+ */
8045
8134
  get migrationCount() {
8046
8135
  return this.steps.length;
8047
8136
  }
8048
- /** Get initial data */
8137
+ /**
8138
+ * Get a fresh copy of the initial data.
8139
+ */
8049
8140
  initialData() {
8050
- return this._initialData();
8141
+ return this.initialDataFn();
8051
8142
  }
8052
- /** Get default data wrapped with current version */
8143
+ /**
8144
+ * Get initial data wrapped with current version.
8145
+ * Used when creating new blocks or resetting to defaults.
8146
+ */
8053
8147
  getDefaultData() {
8054
- return { version: this.version, data: this._initialData() };
8148
+ return makeDataVersioned(this.version, this.initialDataFn());
8149
+ }
8150
+ recoverFrom(data, version) {
8151
+ try {
8152
+ return { version: this.version, data: this.recoverFn(version, data) };
8153
+ }
8154
+ catch (error) {
8155
+ if (isDataUnrecoverableError(error)) {
8156
+ return { ...this.getDefaultData(), warning: error.message };
8157
+ }
8158
+ const errorMessage = error instanceof Error ? error.message : String(error);
8159
+ return {
8160
+ ...this.getDefaultData(),
8161
+ warning: `Recover failed for version '${version}': ${errorMessage}`,
8162
+ };
8163
+ }
8055
8164
  }
8056
8165
  /**
8057
- * Upgrade versioned data from any version to the latest.
8058
- * Applies only the migrations needed (skips already-applied ones).
8059
- * If a migration fails, returns default data with a warning.
8166
+ * Migrate versioned data from any version to the latest.
8167
+ *
8168
+ * - If data is already at latest version, returns as-is
8169
+ * - If version is in chain, applies needed migrations
8170
+ * - If version is unknown, calls recover function
8171
+ * - If migration/recovery fails, returns default data with warning
8172
+ *
8173
+ * @param versioned - Data with version tag
8174
+ * @returns Migration result with data at latest version
8060
8175
  */
8061
- upgrade(versioned) {
8176
+ migrate(versioned) {
8062
8177
  const { version: fromVersion, data } = versioned;
8063
- if (fromVersion > this.version) {
8064
- throw new Error(`Cannot downgrade from version ${fromVersion} to ${this.version}`);
8065
- }
8066
8178
  if (fromVersion === this.version) {
8067
8179
  return { version: this.version, data: data };
8068
8180
  }
8069
- // Apply migrations starting from (fromVersion - 1) index
8070
- // Version 1 -> no migrations applied yet -> start at index 0
8071
- // Version 2 -> migration[0] already applied -> start at index 1
8072
- const startIndex = fromVersion - 1;
8073
- const migrationsToApply = this.steps.slice(startIndex);
8181
+ const startIndex = this.versionChain.indexOf(fromVersion);
8182
+ if (startIndex < 0) {
8183
+ return this.recoverFrom(data, fromVersion);
8184
+ }
8074
8185
  let currentData = data;
8075
- for (let i = 0; i < migrationsToApply.length; i++) {
8076
- const stepIndex = startIndex + i;
8077
- const fromVer = stepIndex + 1;
8078
- const toVer = stepIndex + 2;
8186
+ for (let i = startIndex; i < this.steps.length; i++) {
8187
+ const step = this.steps[i];
8079
8188
  try {
8080
- currentData = migrationsToApply[i](currentData);
8189
+ currentData = step.migrate(currentData);
8081
8190
  }
8082
8191
  catch (error) {
8083
8192
  const errorMessage = error instanceof Error ? error.message : String(error);
8084
8193
  return {
8085
8194
  ...this.getDefaultData(),
8086
- warning: `Migration v${fromVer}→v${toVer} failed: ${errorMessage}`,
8195
+ warning: `Migration ${step.fromVersion}→${step.toVersion} failed: ${errorMessage}`,
8087
8196
  };
8088
8197
  }
8089
8198
  }
@@ -8093,14 +8202,11 @@
8093
8202
  * Register callbacks for use in the VM.
8094
8203
  * Called by BlockModelV3.create() to set up internal callbacks.
8095
8204
  *
8096
- * All callbacks are prefixed with `__pl_` to indicate internal SDK use:
8097
- * - `__pl_data_initial`: returns initial data for new blocks
8098
- * - `__pl_data_upgrade`: upgrades versioned data from any version to latest
8099
- * - `__pl_storage_initial`: returns initial BlockStorage as JSON string
8205
+ * @internal
8100
8206
  */
8101
8207
  registerCallbacks() {
8102
- tryRegisterCallback('__pl_data_initial', () => this._initialData());
8103
- tryRegisterCallback('__pl_data_upgrade', (versioned) => this.upgrade(versioned));
8208
+ tryRegisterCallback('__pl_data_initial', () => this.initialDataFn());
8209
+ tryRegisterCallback('__pl_data_upgrade', (versioned) => this.migrate(versioned));
8104
8210
  tryRegisterCallback('__pl_storage_initial', () => {
8105
8211
  const { version, data } = this.getDefaultData();
8106
8212
  const storage = createBlockStorage(data, version);