File size: 13,661 Bytes
6a49f21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/**
 * Application class - clean wrapper around plugin endpoint invocation and bootstrapping
 * @import { ApplicationState } from '../state.js'
 * @import PluginManager from '../modules/plugin-manager.js'
 * @import StateManager from '../modules/state-manager.js'
 * @import { InvokeOptions, InvocationResult } from '../modules/plugin-manager.js'
 */

import { PluginContext } from './plugin-context.js';
import ep from '../extension-points.js';

/**
 * Application class that provides a clean API for plugin management and bootstrapping
 */
export class Application {
  /**
   * @param {PluginManager} pluginManager 
   * @param {StateManager} stateManager 
   */
  constructor(pluginManager, stateManager) {
    this.#currentState = null;
    this.#pluginManager = pluginManager;
    this.#stateManager = stateManager;
    this.#pluginContext = new PluginContext(this);
    
    // Set up shutdown handler
    window.addEventListener('beforeunload', () => {
      this.shutdown().catch(() => {});
    });
  }

  /** 
   * simple flag for controlling debug messages
   */
  debug = false;

  /** @type {ApplicationState|null} */
  #currentState;

  /** @type {PluginManager} */
  #pluginManager;

  /** @type {StateManager} */
  #stateManager;

  /** @type {PluginContext} */
  #pluginContext;

  /** @type {boolean} */
  #isUpdatingState = false;

  /**
   * State changes explicitly scheduled via scheduleStateChange() to run after the
   * current propagation cycle completes. Each entry is { changes, resolve, reject }.
   * @type {Array<{changes: Partial<ApplicationState>, resolve: (s: ApplicationState)=>void, reject: (e: Error)=>void}>}
   */
  #scheduledStateChanges = [];

  //
  // Application bootstrapping methods
  //

  /**
   * Initialize application state with final composed state and configure bootstrapping
   * @param {ApplicationState} finalState - The final composed initial state
   * @param {object} options - Configuration options
   * @param {string[]} [options.persistedStateVars] - State variable names to persist in sessionStorage
   * @param {boolean} [options.enableStatePreservation=true] - Whether to enable automatic state preservation
   * @returns {ApplicationState} The initialized state
   */
  initializeState(finalState, options = {}) {
    const {
      persistedStateVars = [],
      enableStatePreservation = true
    } = options;

    // Update current state
    this.#currentState = finalState;

    // Enable automatic state preservation if requested
    if (enableStatePreservation) {
      // Always include sessionId in persisted vars
      const allPersistedVars = [...persistedStateVars, 'sessionId'];
      this.#stateManager.preserveState(true, allPersistedVars);
    }

    return this.#currentState;
  }

  /**
   * Get the current state
   * @returns {ApplicationState}
   */
  getCurrentState() {
    if (!this.#currentState) {
      throw new Error("State has not been initialized yet")
    }
    return this.#currentState;
  }

  //
  // Plugin lifecycle management
  //

  /**
   * Register plugins with the plugin manager
   * Supports plugin objects, Plugin class instances, and Plugin classes.
   * @param {Array} plugins - Array of plugin objects, Plugin instances, or Plugin classes
   */
  registerPlugins(plugins) {
    // Convert classes to instances, leave everything else as-is
    const processedPlugins = plugins.map(plugin => {
      // Check if it's a Plugin class (constructor function)
      if (typeof plugin === 'function' && plugin.prototype && plugin.prototype.constructor === plugin) {
        this.debug && console.log(`Creating Plugin singleton instance from class '${plugin.name}' with context`);
        return plugin.createInstance(this.#pluginContext);
      }
      return plugin;
    });

    // Register plugins - PluginManager handles Plugin instance conversion
    for (const plugin of processedPlugins) {
      const pluginName = plugin.name || plugin.constructor?.name || 'unknown';
      const deps = plugin.deps || [];
      this.debug && console.log(`Registering plugin '${pluginName}' with deps: [${deps.join(', ') || 'none'}]`);
      this.#pluginManager.register(plugin);
    }
  }

  /**
   * Install all registered plugins with provided state
   * @param {ApplicationState} state - The state to pass to plugin install methods
   * @returns {Promise<Array>}
   */
  async installPlugins(state) {
    const results = await this.#pluginManager.invoke(ep.install, state, { mode: 'sequential', result: 'full' });
    return results;
  }

  /**
   * Start all plugins after installation
   * @returns {Promise<Array>}
   */
  async start() {
    const results = await this.#pluginManager.invoke(ep.start, [], { mode: 'sequential', result: 'full' });
    return results;
  }

  /**
   * Shutdown all plugins (called on beforeunload)
   * @returns {Promise<Array>}
   */
  async shutdown() {
    try {
      const results = await this.#pluginManager.invoke(ep.shutdown, [], { mode: 'sequential', result: 'full' });
      return results;
    } catch (error) {
      console.warn('Error during plugin shutdown:', error);
      return [];
    }
  }

  //
  // State management orchestration
  //

  /**
   * Update application state and notify plugins
   * @param {Partial<ApplicationState>} changes - Changes to apply  
   * @returns {Promise<ApplicationState>} New state after plugin notification
   */
  async updateState(changes = {}) {
    // Prevent accidental re-entrant state changes during plugin notification.
    // If you need to dispatch after async work triggered by onStateUpdate, use scheduleStateChange().
    if (this.#isUpdatingState) {
      throw new Error('State changes are not allowed during state update propagation. Plugin state.update endpoints must be reactive observers only, not state mutators. Use scheduleStateChange() to dispatch after async work.');
    }

    // Use current state as base for changes
    const currentState = this.#currentState;
    if (!currentState) {
      throw new Error('Application state not initialized. Call initializeState() first.');
    }

    const { newState, changedKeys } = this.#stateManager.applyStateChanges(currentState, changes);
    
    // Skip plugin notification if no actual changes (only legacy system)
    if (changedKeys.length === 0) {
      this.#isUpdatingState = true;
      try {
        const results = await this.#pluginManager.invoke(ep.state.update, currentState, { result: 'full' });
        this.#checkForStateChangeErrors(results);
      } finally {
        this.#isUpdatingState = false;
      }
      return currentState;
    }
    
    // Set lock to prevent nested state changes
    this.#isUpdatingState = true;
    
    try {
      // Invoke all state update endpoints by convention:
      
      // 1. Legacy system: state.update with full state
      const legacyResults = await this.#pluginManager.invoke(ep.state.update, newState, { result: 'full' });
      this.#checkForStateChangeErrors(legacyResults);
      
      // 2. New system: updateInternalState with full state (silent)
      const internalResults = await this.#pluginManager.invoke(ep.state.updateInternal, newState, { result: 'full' });
      this.#checkForStateChangeErrors(internalResults);
      
      // 3. New system: onStateUpdate with changed keys (catch-all)
      const changeResults = await this.#pluginManager.invoke(ep.state.onStateUpdate, [changedKeys, newState], { result: 'full' });
      this.#checkForStateChangeErrors(changeResults);

      // 4. Per-key dispatch: state.<key>(newVal, prevVal, state) for object plugins
      //    and onStateUpdate.<key>(newVal, prevVal) for class plugins (on<Key>Change methods)
      for (const key of changedKeys) {
        const newVal = newState[key];
        const prevVal = this.#stateManager.getPreviousStateValue(newState, key);
        const perKeyArgs = [newVal, prevVal, newState];
        const perKeyResults1 = await this.#pluginManager.invoke(`state.${key}`, perKeyArgs, { mode: 'sequential', result: 'full' });
        this.#checkForStateChangeErrors(perKeyResults1);
        const perKeyResults2 = await this.#pluginManager.invoke(`onStateUpdate.${key}`, [newVal, prevVal], { mode: 'sequential', result: 'full' });
        this.#checkForStateChangeErrors(perKeyResults2);
      }

      // Update current state after successful plugin notification
      this.#currentState = newState;
      
      return newState;
    } finally {
      this.#isUpdatingState = false;
      this.#flushScheduledStateChanges();
    }
  }

  /**
   * Schedule a state change to run after the current propagation cycle completes.
   *
   * Use this only when a plugin needs to dispatch state changes as a result of async
   * work that was triggered by onStateUpdate (e.g. an API call whose result affects
   * state). Do NOT use it to work around the observer-only rule for synchronous work —
   * synchronous onStateUpdate handlers must remain pure observers.
   *
   * @param {Partial<ApplicationState>} changes
   * @returns {Promise<ApplicationState>}
   */
  scheduleStateChange(changes) {
    if (!this.#isUpdatingState) {
      return this.updateState(changes);
    }
    return new Promise((resolve, reject) => {
      this.#scheduledStateChanges.push({ changes, resolve, reject });
    });
  }

  /**
   * Flush state changes that were explicitly scheduled via scheduleStateChange().
   * Merges all pending changes into one update to avoid chained re-renders.
   */
  #flushScheduledStateChanges() {
    if (this.#scheduledStateChanges.length === 0) return;
    const pending = this.#scheduledStateChanges.splice(0);
    const merged = Object.assign({}, ...pending.map(p => p.changes));
    this.updateState(merged)
      .then(state => pending.forEach(p => p.resolve(state)))
      .catch(err => pending.forEach(p => p.reject(err)));
  }

  /**
   * Update extension properties in state and notify plugins
   * @param {Object} extChanges - Extension properties to update
   * @returns {Promise<ApplicationState>} New state after plugin notification
   */
  async updateStateExt(extChanges = {}) {
    if (this.#isUpdatingState) {
      throw new Error('State changes are not allowed during state update propagation. Use scheduleStateChange() to dispatch after async work.');
    }

    // Use current state as base for changes
    const currentState = this.#currentState;
    if (!currentState) {
      throw new Error('Application state not initialized. Call initializeState() first.');
    }

    const { newState, changedKeys } = this.#stateManager.applyExtensionChanges(currentState, extChanges);
    
    if (changedKeys.length === 0) {
      this.#isUpdatingState = true;
      try {
        const results = await this.#pluginManager.invoke(ep.state.update, currentState, { result: 'full' });
        this.#checkForStateChangeErrors(results);
      } finally {
        this.#isUpdatingState = false;
        this.#flushScheduledStateChanges();
      }
      return currentState;
    }

    this.#isUpdatingState = true;
    try {
      const results = await this.#pluginManager.invoke(ep.state.update, newState, { result: 'full' });
      this.#checkForStateChangeErrors(results);

      // Update current state after successful plugin notification
      this.#currentState = newState;

      return newState;
    } finally {
      this.#isUpdatingState = false;
      this.#flushScheduledStateChanges();
    }
  }

  /**
   * Check plugin invocation results for errors and rethrow them.
   * @param {Array} results - Results from plugin manager invoke
   */
  #checkForStateChangeErrors(results) {
    for (const result of results) {
      if (result.status === 'rejected' && result.reason?.message?.includes('State changes are not allowed during state update propagation')) {
        throw result.reason;
      }
    }
  }

  /**
   * Get state manager for direct access to state utilities
   * @returns {StateManager}
   */
  getStateManager() {
    return this.#stateManager;
  }

  /**
   * Get plugin context for plugin instantiation
   * @returns {PluginContext}
   */
  getPluginContext() {
    return this.#pluginContext;
  }

  //
  // Convenience methods for common plugin operations
  //

  /**
   * Invoke an endpoint on all plugins that implement it, in dependency order.
   * By default, throws on the first error encountered, and returns the value of the 
   * first fulfilled promise (or synchronous function). For other options, see {InvokeOptions}
   * 
   * @param {string} endpoint - Endpoint to invoke
   * @param {*|Array} [args] - Arguments to pass to endpoint functions. If array, spread as parameters; if not array, pass as single parameter
   * @param {InvokeOptions} [options] - Optional configuration for this invocation. 
   * @returns {Promise<InvocationResult[] | any[] | any>} Result formatted depending on options.result
   */
  async invokePluginEndpoint(endpoint, args = [], options = {throws:true, result:'first'}) {
    const result = await this.#pluginManager.invoke(endpoint, args, options);
    return result
  }

  /**
   * Get the plugin manager for direct access (use with caution)
   * @returns {PluginManager}
   */
  getPluginManager() {
    return this.#pluginManager;
  }

  /**
   * Get the public API of a registered plugin by name.
   * For class-based plugins returns the Plugin instance; for object plugins returns the
   * `api` field (or the plugin descriptor as fallback).
   * @param {string} name - Plugin name
   * @returns {any} The plugin's public API
   */
  getDependency(name) {
    return this.#pluginManager.getDependency(name);
  }
}

export default Application;