@asyra/feature-system 0.6.0 → 0.6.1

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,23 +1,10 @@
1
1
  import { SessionCancelPolicies, measureBrowserDragAsyncPhase } from '@asyra/utils';
2
2
  import { FeatureRegistry } from './feature-registry.js';
3
- import { SessionManager } from './session-manager.js';
4
- import executionRegistry from './execution-registry.js';
5
- import { FeatureRuntimeClosedError, interactionQueue } from './interaction-queue.js';
6
- import { featureTaskRegistry } from './feature-task-registry.js';
7
- const featureRegistry = new FeatureRegistry();
8
- let sessionManager = new SessionManager();
9
- let runtimeState = 'open';
10
- let runtimeIdentity = Symbol('feature-runtime');
11
- let disposal = null;
12
- const assertRuntimeOpen = () => {
13
- if (runtimeState !== 'open') {
14
- throw new FeatureRuntimeClosedError();
15
- }
16
- };
17
- let corePackages = {};
18
- let isPackagesSet = false;
19
- const eventBindings = new Map();
20
- const pendingRegistrations = [];
3
+ import { subscribeToEventBatches } from '@asyra/reactive-events';
4
+ import { SessionManager, SessionRuntime, sharedSessions } from './session-manager.js';
5
+ import sharedExecution, { ExecutionRegistryClass } from './execution-registry.js';
6
+ import { FeatureRuntimeClosedError, InteractionQueue } from './interaction-queue.js';
7
+ import { featureTaskRegistry as sharedTasks, FeatureTaskRegistry } from './feature-task-registry.js';
21
8
  export class FeatureUnregisterError extends Error {
22
9
  constructor(featureName) {
23
10
  super(`Feature "${featureName}" cannot be unregistered while active`);
@@ -26,350 +13,382 @@ export class FeatureUnregisterError extends Error {
26
13
  this.featureName = featureName;
27
14
  }
28
15
  }
29
- const removeEventBinding = (eventName) => {
30
- const binding = eventBindings.get(eventName);
31
- if (!binding) {
32
- return;
33
- }
34
- eventBindings.delete(eventName);
35
- binding.cleanupRequested = true;
36
- if (binding.inputSystem && binding.inputCallback) {
37
- binding.inputSystem.off(eventName, binding.inputCallback);
38
- }
39
- binding.subscription?.unsubscribe();
40
- };
41
- const cleanupUnusedEventBindings = () => {
42
- for (const [eventName, binding] of eventBindings) {
43
- const inUse = binding.participantType === 'session'
44
- ? sessionManager.hasSessionHandlers(binding.sessionName)
45
- : executionRegistry.hasHandlers(eventName);
46
- if (!inUse) {
47
- removeEventBinding(eventName);
16
+ export function createFeatureSystem(owner) {
17
+ return composeFeatureSystem(new SessionRuntime(new InteractionQueue(), owner), new ExecutionRegistryClass(owner), new FeatureTaskRegistry());
18
+ }
19
+ function composeFeatureSystem(sessions, executionRegistry, featureTaskRegistry) {
20
+ const interactionQueue = sessions.queue;
21
+ const featureRegistry = new FeatureRegistry();
22
+ let sessionManager = new SessionManager(sessions);
23
+ let runtimeState = 'open';
24
+ let runtimeIdentity = Symbol('feature-runtime');
25
+ let disposal = null;
26
+ const assertRuntimeOpen = () => {
27
+ if (runtimeState !== 'open') {
28
+ throw new FeatureRuntimeClosedError();
48
29
  }
49
- }
50
- };
51
- const createInputSnapshot = (systemContext, raw) => {
52
- const snapshot = systemContext.getSystemContextSnapshot?.() ?? raw;
53
- return {
54
- ...snapshot,
55
- ...(raw.detail ? { detail: raw.detail } : {})
56
30
  };
57
- };
58
- const registerSessionEventBinding = (eventName, sessionName, inputSystem, systemContext) => {
59
- if (eventBindings.has(eventName)) {
60
- return;
61
- }
62
- const manager = sessionManager;
63
- const inputCallback = async (raw) => {
64
- let phase = 'end';
65
- if (eventName.endsWith('.update')) {
66
- phase = 'update';
31
+ let corePackages = {};
32
+ let isPackagesSet = false;
33
+ const eventBindings = new Map();
34
+ const pendingRegistrations = [];
35
+ const removeEventBinding = (eventName) => {
36
+ const binding = eventBindings.get(eventName);
37
+ if (!binding) {
38
+ return;
67
39
  }
68
- if (eventName.endsWith('.start')) {
69
- phase = 'start';
40
+ eventBindings.delete(eventName);
41
+ binding.cleanupRequested = true;
42
+ if (binding.inputSystem && binding.inputCallback) {
43
+ binding.inputSystem.off(eventName, binding.inputCallback);
70
44
  }
71
- await measureBrowserDragAsyncPhase(`feature:event:${eventName}`, () => manager.handleSessionInput(sessionName, phase, () => createInputSnapshot(systemContext, raw), eventName));
45
+ binding.subscription?.unsubscribe();
72
46
  };
73
- inputSystem.on(eventName, inputCallback);
74
- eventBindings.set(eventName, {
75
- eventName,
76
- participantType: 'session',
77
- sessionName,
78
- inputSystem,
79
- inputCallback,
80
- cleanupRequested: false
81
- });
82
- };
83
- const registerExecutionEventBinding = (eventName, inputSystem, systemContext) => {
84
- if (eventBindings.has(eventName)) {
85
- return;
86
- }
87
- if (eventName.startsWith('render.')) {
47
+ const cleanupUnusedEventBindings = () => {
48
+ for (const [eventName, binding] of eventBindings) {
49
+ const inUse = binding.participantType === 'session'
50
+ ? sessionManager.hasSessionHandlers(binding.sessionName)
51
+ : executionRegistry.hasHandlers(eventName);
52
+ if (!inUse) {
53
+ removeEventBinding(eventName);
54
+ }
55
+ }
56
+ };
57
+ const createInputSnapshot = (systemContext, raw) => {
58
+ const snapshot = systemContext.getSystemContextSnapshot?.() ?? raw;
59
+ return {
60
+ ...snapshot,
61
+ ...(raw.detail ? { detail: raw.detail } : {})
62
+ };
63
+ };
64
+ const registerSessionEventBinding = (eventName, sessionName, inputSystem, systemContext) => {
65
+ if (eventBindings.has(eventName)) {
66
+ return;
67
+ }
68
+ const manager = sessionManager;
69
+ const inputCallback = async (raw) => {
70
+ let phase = 'end';
71
+ if (eventName.endsWith('.update')) {
72
+ phase = 'update';
73
+ }
74
+ if (eventName.endsWith('.start')) {
75
+ phase = 'start';
76
+ }
77
+ await measureBrowserDragAsyncPhase(`feature:event:${eventName}`, () => manager.handleSessionInput(sessionName, phase, () => createInputSnapshot(systemContext, raw), eventName));
78
+ };
79
+ inputSystem.on(eventName, inputCallback);
80
+ eventBindings.set(eventName, {
81
+ eventName,
82
+ participantType: 'session',
83
+ sessionName,
84
+ inputSystem,
85
+ inputCallback,
86
+ cleanupRequested: false
87
+ });
88
+ };
89
+ const registerExecutionEventBinding = (eventName, inputSystem, systemContext) => {
90
+ if (eventBindings.has(eventName)) {
91
+ return;
92
+ }
93
+ if (eventName.startsWith('render.')) {
94
+ const binding = {
95
+ eventName,
96
+ participantType: 'execution',
97
+ cleanupRequested: false
98
+ };
99
+ eventBindings.set(eventName, binding);
100
+ binding.subscription = subscribeToEventBatches((events) => {
101
+ for (const raw of events) {
102
+ if (binding.cleanupRequested || raw.type !== eventName) {
103
+ continue;
104
+ }
105
+ const owner = 'interactionOwner' in raw ? raw.interactionOwner : undefined;
106
+ if (owner !== corePackages.render?.interactionOwner) {
107
+ continue;
108
+ }
109
+ const payload = 'payload' in raw ? raw.payload : undefined;
110
+ const snapshot = systemContext.getSystemContextSnapshot?.() ?? raw;
111
+ const mergedSnapshot = {
112
+ ...snapshot,
113
+ detail: ('detail' in raw ? raw.detail : undefined) ?? payload,
114
+ payload
115
+ };
116
+ void interactionQueue
117
+ .run(() => executionRegistry.execute(eventName, mergedSnapshot))
118
+ .catch(console.error);
119
+ }
120
+ });
121
+ return;
122
+ }
123
+ const manager = sessionManager;
88
124
  const binding = {
89
125
  eventName,
90
126
  participantType: 'execution',
127
+ inputSystem,
91
128
  cleanupRequested: false
92
129
  };
93
- eventBindings.set(eventName, binding);
94
- import('@asyra/reactive-events')
95
- .then((module) => {
96
- const subscription = module
97
- .getEventBus()
98
- .subscribe((raw) => {
99
- if (binding.cleanupRequested || raw.type !== eventName) {
100
- return;
130
+ const inputCallback = async (raw) => {
131
+ const run = executionRegistry.getHandlers(eventName)[0]?.executionMode ===
132
+ 'immediate'
133
+ ? manager.runImmediatelyAfterCancellingActiveSessions.bind(manager)
134
+ : manager.runAfterCancellingActiveSessions.bind(manager);
135
+ await run(() => {
136
+ if (binding.cleanupRequested) {
137
+ throw new FeatureRuntimeClosedError();
101
138
  }
102
- const snapshot = systemContext.getSystemContextSnapshot?.() ?? raw;
103
- const mergedSnapshot = {
104
- ...snapshot,
105
- detail: raw.detail ?? raw.payload,
106
- payload: raw.payload
107
- };
108
- void interactionQueue
109
- .run(() => executionRegistry.execute(eventName, mergedSnapshot))
110
- .catch(console.error);
111
- });
112
- if (binding.cleanupRequested) {
113
- subscription.unsubscribe();
114
- return;
115
- }
116
- binding.subscription = subscription;
117
- })
118
- .catch(console.error);
119
- return;
120
- }
121
- const manager = sessionManager;
122
- const binding = {
123
- eventName,
124
- participantType: 'execution',
125
- inputSystem,
126
- cleanupRequested: false
139
+ return createInputSnapshot(systemContext, raw);
140
+ }, (mergedSnapshot) => binding.cleanupRequested
141
+ ? undefined
142
+ : executionRegistry.execute(eventName, mergedSnapshot), eventName);
143
+ };
144
+ binding.inputCallback = inputCallback;
145
+ inputSystem.on(eventName, inputCallback);
146
+ eventBindings.set(eventName, binding);
127
147
  };
128
- const inputCallback = async (raw) => {
129
- const run = executionRegistry.getHandlers(eventName)[0]?.executionMode === 'immediate'
130
- ? manager.runImmediatelyAfterCancellingActiveSessions.bind(manager)
131
- : manager.runAfterCancellingActiveSessions.bind(manager);
132
- await run(() => {
133
- if (binding.cleanupRequested) {
134
- throw new FeatureRuntimeClosedError();
148
+ function registerFeatureHandlers(name, keyConfig, definition) {
149
+ const hasSession = !!definition.session;
150
+ const hasExecution = !!definition.execution;
151
+ const { priority = 0, exclusive = true, cancelPolicy = SessionCancelPolicies.COMMIT_CURRENT } = definition;
152
+ if (!keyConfig) {
153
+ return;
154
+ }
155
+ let eventsToRegister = [];
156
+ if (hasSession) {
157
+ const baseEvent = keyConfig;
158
+ eventsToRegister = [
159
+ `${baseEvent}.start`,
160
+ `${baseEvent}.update`,
161
+ `${baseEvent}.end`
162
+ ];
163
+ }
164
+ else if (hasExecution) {
165
+ eventsToRegister = [keyConfig];
166
+ }
167
+ else {
168
+ eventsToRegister = [keyConfig];
169
+ }
170
+ if (hasSession && definition.session) {
171
+ sessionManager.registerSession(keyConfig, name, priority, exclusive, cancelPolicy, {
172
+ ...definition.session,
173
+ onStart: (snapshot) => featureRegistry.isInteractionEnabled(name)
174
+ ? (definition.session?.onStart?.(snapshot) ?? null)
175
+ : null
176
+ });
177
+ }
178
+ if (hasExecution && definition.execution) {
179
+ const execute = definition.execution;
180
+ for (const eventName of eventsToRegister) {
181
+ executionRegistry.register(eventName, name, { priority, exclusive, executionMode: definition.executionMode }, (snapshot) => featureRegistry.isInteractionEnabled(name)
182
+ ? execute(snapshot)
183
+ : null);
135
184
  }
136
- return createInputSnapshot(systemContext, raw);
137
- }, (mergedSnapshot) => binding.cleanupRequested
138
- ? undefined
139
- : executionRegistry.execute(eventName, mergedSnapshot), eventName);
140
- };
141
- binding.inputCallback = inputCallback;
142
- inputSystem.on(eventName, inputCallback);
143
- eventBindings.set(eventName, binding);
144
- };
145
- function registerFeatureHandlers(name, keyConfig, definition) {
146
- const hasSession = !!definition.session;
147
- const hasExecution = !!definition.execution;
148
- const { priority = 0, exclusive = true, cancelPolicy = SessionCancelPolicies.COMMIT_CURRENT } = definition;
149
- if (!keyConfig) {
150
- return;
151
- }
152
- let eventsToRegister = [];
153
- if (hasSession) {
154
- const baseEvent = keyConfig;
155
- eventsToRegister = [
156
- `${baseEvent}.start`,
157
- `${baseEvent}.update`,
158
- `${baseEvent}.end`
159
- ];
160
- }
161
- else if (hasExecution) {
162
- eventsToRegister = [keyConfig];
163
- }
164
- else {
165
- eventsToRegister = [keyConfig];
166
- }
167
- if (hasSession && definition.session) {
168
- sessionManager.registerSession(keyConfig, name, priority, exclusive, cancelPolicy, {
169
- ...definition.session,
170
- onStart: (snapshot) => featureRegistry.isInteractionEnabled(name)
171
- ? (definition.session?.onStart?.(snapshot) ?? null)
172
- : null
173
- });
174
- }
175
- if (hasExecution && definition.execution) {
176
- const execute = definition.execution;
177
- for (const eventName of eventsToRegister) {
178
- executionRegistry.register(eventName, name, { priority, exclusive, executionMode: definition.executionMode }, (snapshot) => featureRegistry.isInteractionEnabled(name) ? execute(snapshot) : null);
179
185
  }
180
- }
181
- const { inputSystem, systemContext } = corePackages;
182
- if (inputSystem && systemContext) {
183
- for (const event of eventsToRegister) {
184
- if (hasSession) {
185
- if (event.startsWith('render.')) {
186
- continue;
186
+ const { inputSystem, systemContext } = corePackages;
187
+ if (inputSystem && systemContext) {
188
+ for (const event of eventsToRegister) {
189
+ if (hasSession) {
190
+ if (event.startsWith('render.')) {
191
+ continue;
192
+ }
193
+ registerSessionEventBinding(event, keyConfig, inputSystem, systemContext);
194
+ }
195
+ else if (hasExecution) {
196
+ registerExecutionEventBinding(event, inputSystem, systemContext);
187
197
  }
188
- registerSessionEventBinding(event, keyConfig, inputSystem, systemContext);
189
- }
190
- else if (hasExecution) {
191
- registerExecutionEventBinding(event, inputSystem, systemContext);
192
198
  }
193
199
  }
194
200
  }
195
- }
196
- export function defineFeature(name, keyConfig, definition) {
197
- assertRuntimeOpen();
198
- const identity = runtimeIdentity;
199
- if (definition.session &&
200
- definition.cancelPolicy === SessionCancelPolicies.FEATURE_DEFINED &&
201
- !definition.session.onCancel) {
202
- throw new Error(`Feature ${name} uses feature-defined cancelPolicy without onCancel`);
203
- }
204
- if (definition.executionMode === 'immediate' &&
205
- (!definition.execution ||
206
- definition.session ||
207
- !keyConfig ||
208
- keyConfig.startsWith('render.'))) {
209
- throw new Error('Immediate execution requires a one-shot input Feature');
210
- }
211
- if (definition.execution && keyConfig) {
212
- const mode = definition.executionMode ?? 'queued';
213
- const conflicts = executionRegistry
214
- .getHandlers(keyConfig)
215
- .some((entry) => entry.executionMode !== mode) ||
216
- pendingRegistrations.some((entry) => entry.keyConfig === keyConfig &&
217
- entry.definition.execution &&
218
- (entry.definition.executionMode ?? 'queued') !== mode);
219
- if (conflicts) {
220
- throw new Error(`Execution event ${keyConfig} cannot mix execution modes`);
201
+ function defineFeature(name, keyConfig, definition) {
202
+ assertRuntimeOpen();
203
+ const identity = runtimeIdentity;
204
+ if (definition.session &&
205
+ definition.cancelPolicy === SessionCancelPolicies.FEATURE_DEFINED &&
206
+ !definition.session.onCancel) {
207
+ throw new Error(`Feature ${name} uses feature-defined cancelPolicy without onCancel`);
221
208
  }
222
- }
223
- const api = featureRegistry.register(name, definition);
224
- if (definition.task) {
225
- featureTaskRegistry.register(name, {
226
- priority: definition.priority ?? 0,
227
- exclusive: definition.exclusive ?? true,
228
- handler: definition.task
229
- });
230
- }
231
- const hasSession = !!definition.session;
232
- const hasExecution = !!definition.execution;
233
- if ((hasSession || hasExecution) && keyConfig !== undefined) {
234
- if (isPackagesSet) {
235
- registerFeatureHandlers(name, keyConfig, definition);
209
+ if (definition.executionMode === 'immediate' &&
210
+ (!definition.execution ||
211
+ definition.session ||
212
+ !keyConfig ||
213
+ keyConfig.startsWith('render.'))) {
214
+ throw new Error('Immediate execution requires a one-shot input Feature');
236
215
  }
237
- else {
238
- pendingRegistrations.push({
239
- featureName: name,
240
- keyConfig,
241
- definition: definition
216
+ if (definition.execution && keyConfig) {
217
+ const mode = definition.executionMode ?? 'queued';
218
+ const conflicts = executionRegistry
219
+ .getHandlers(keyConfig)
220
+ .some((entry) => entry.executionMode !== mode) ||
221
+ pendingRegistrations.some((entry) => entry.keyConfig === keyConfig &&
222
+ entry.definition.execution &&
223
+ (entry.definition.executionMode ?? 'queued') !== mode);
224
+ if (conflicts) {
225
+ throw new Error(`Execution event ${keyConfig} cannot mix execution modes`);
226
+ }
227
+ }
228
+ const api = featureRegistry.register(name, definition);
229
+ if (definition.task) {
230
+ featureTaskRegistry.register(name, {
231
+ priority: definition.priority ?? 0,
232
+ exclusive: definition.exclusive ?? true,
233
+ handler: definition.task
242
234
  });
243
235
  }
236
+ const hasSession = !!definition.session;
237
+ const hasExecution = !!definition.execution;
238
+ if ((hasSession || hasExecution) && keyConfig !== undefined) {
239
+ if (isPackagesSet) {
240
+ registerFeatureHandlers(name, keyConfig, definition);
241
+ }
242
+ else {
243
+ pendingRegistrations.push({
244
+ featureName: name,
245
+ keyConfig,
246
+ definition: definition
247
+ });
248
+ }
249
+ }
250
+ return {
251
+ api,
252
+ dispose: () => identity === runtimeIdentity && unregisterFeature(name)
253
+ };
244
254
  }
245
- return {
246
- api,
247
- dispose: () => identity === runtimeIdentity && unregisterFeature(name)
248
- };
249
- }
250
- export function setCorePackages(packages) {
251
- assertRuntimeOpen();
252
- corePackages = packages;
253
- isPackagesSet = true;
254
- for (const registration of pendingRegistrations) {
255
- try {
256
- registerFeatureHandlers(registration.featureName, registration.keyConfig, registration.definition);
255
+ function setCorePackages(packages) {
256
+ assertRuntimeOpen();
257
+ corePackages = packages;
258
+ isPackagesSet = true;
259
+ for (const registration of pendingRegistrations) {
260
+ try {
261
+ registerFeatureHandlers(registration.featureName, registration.keyConfig, registration.definition);
262
+ }
263
+ catch (error) {
264
+ console.error(`[defineFeature] Failed to register "${registration.featureName}":`, error);
265
+ }
257
266
  }
258
- catch (error) {
259
- console.error(`[defineFeature] Failed to register "${registration.featureName}":`, error);
267
+ pendingRegistrations.length = 0;
268
+ }
269
+ function getFeature(featureName) {
270
+ if (!featureRegistry.has(featureName)) {
271
+ throw new Error(`Feature "${featureName}" not found`);
260
272
  }
273
+ return featureRegistry.getAPI(featureName);
261
274
  }
262
- pendingRegistrations.length = 0;
263
- }
264
- export function getFeature(featureName) {
265
- if (!featureRegistry.has(featureName)) {
266
- throw new Error(`Feature "${featureName}" not found`);
275
+ function unregisterFeature(featureName) {
276
+ if (!featureRegistry.has(featureName)) {
277
+ return false;
278
+ }
279
+ if (executionRegistry.isFeatureActive(featureName) ||
280
+ sessionManager.isFeatureActive(featureName) ||
281
+ featureTaskRegistry.isActive(featureName)) {
282
+ throw new FeatureUnregisterError(featureName);
283
+ }
284
+ for (let index = pendingRegistrations.length - 1; index >= 0; index -= 1) {
285
+ if (pendingRegistrations[index].featureName === featureName) {
286
+ pendingRegistrations.splice(index, 1);
287
+ }
288
+ }
289
+ executionRegistry.unregisterFeature(featureName);
290
+ sessionManager.unregisterFeature(featureName);
291
+ featureTaskRegistry.unregister(featureName);
292
+ const removed = featureRegistry.unregister(featureName);
293
+ cleanupUnusedEventBindings();
294
+ return removed;
267
295
  }
268
- return featureRegistry.getAPI(featureName);
269
- }
270
- export function unregisterFeature(featureName) {
271
- if (!featureRegistry.has(featureName)) {
272
- return false;
296
+ function getFeatureRegistry() {
297
+ return featureRegistry;
273
298
  }
274
- if (executionRegistry.isFeatureActive(featureName) ||
275
- sessionManager.isFeatureActive(featureName) ||
276
- featureTaskRegistry.isActive(featureName)) {
277
- throw new FeatureUnregisterError(featureName);
299
+ function getSessionManager() {
300
+ return sessionManager;
278
301
  }
279
- for (let index = pendingRegistrations.length - 1; index >= 0; index -= 1) {
280
- if (pendingRegistrations[index].featureName === featureName) {
281
- pendingRegistrations.splice(index, 1);
302
+ function invokeFeatureTask(featureName, input, options) {
303
+ if (runtimeState !== 'open') {
304
+ return Promise.reject(new FeatureRuntimeClosedError());
282
305
  }
306
+ return featureTaskRegistry.invoke(featureName, input, options);
283
307
  }
284
- executionRegistry.unregisterFeature(featureName);
285
- sessionManager.unregisterFeature(featureName);
286
- featureTaskRegistry.unregister(featureName);
287
- const removed = featureRegistry.unregister(featureName);
288
- cleanupUnusedEventBindings();
289
- return removed;
290
- }
291
- export function getFeatureRegistry() {
292
- return featureRegistry;
293
- }
294
- export function getSessionManager() {
295
- return sessionManager;
296
- }
297
- export function invokeFeatureTask(featureName, input, options) {
298
- if (runtimeState !== 'open') {
299
- return Promise.reject(new FeatureRuntimeClosedError());
308
+ function cancelFeatureTask(featureName, reason) {
309
+ return featureTaskRegistry.cancel(featureName, reason);
300
310
  }
301
- return featureTaskRegistry.invoke(featureName, input, options);
302
- }
303
- export function cancelFeatureTask(featureName, reason) {
304
- return featureTaskRegistry.cancel(featureName, reason);
305
- }
306
- /** Core lifecycle boundary, not a user-command or ordinary cancel path. */
307
- export function disposeFeatureSystem(getSnapshot) {
308
- if (disposal) {
309
- return disposal;
310
- }
311
- let complete;
312
- let fail;
313
- disposal = new Promise((resolve, reject) => {
314
- complete = resolve;
315
- fail = reject;
316
- });
317
- runtimeState = 'closing';
318
- const draining = interactionQueue.close();
319
- SessionManager.abortRuntime();
320
- const tasks = featureTaskRegistry.dispose();
321
- // The shared completion is installed before abort/off can reenter disposal.
322
- void (async () => {
323
- const errors = [];
324
- for (const eventName of [...eventBindings.keys()]) {
311
+ /** Core lifecycle boundary, not a user-command or ordinary cancel path. */
312
+ function disposeFeatureSystem(getSnapshot) {
313
+ if (disposal) {
314
+ return disposal;
315
+ }
316
+ let complete;
317
+ let fail;
318
+ disposal = new Promise((resolve, reject) => {
319
+ complete = resolve;
320
+ fail = reject;
321
+ });
322
+ runtimeState = 'closing';
323
+ const draining = interactionQueue.close();
324
+ sessionManager.abortRuntime();
325
+ const tasks = featureTaskRegistry.dispose();
326
+ // The shared completion is installed before abort/off can reenter disposal.
327
+ void (async () => {
328
+ const errors = [];
329
+ for (const eventName of [...eventBindings.keys()]) {
330
+ try {
331
+ removeEventBinding(eventName);
332
+ }
333
+ catch (error) {
334
+ errors.push(error);
335
+ }
336
+ }
337
+ await draining;
325
338
  try {
326
- removeEventBinding(eventName);
339
+ await sessionManager.disposeRuntime(getSnapshot);
327
340
  }
328
341
  catch (error) {
329
342
  errors.push(error);
330
343
  }
331
- }
332
- await draining;
333
- try {
334
- await SessionManager.disposeRuntime(getSnapshot);
335
- }
336
- catch (error) {
337
- errors.push(error);
338
- }
339
- await tasks;
340
- for (const name of featureRegistry.getFeatureNames()) {
341
- try {
342
- unregisterFeature(name);
344
+ await tasks;
345
+ for (const name of featureRegistry.getFeatureNames()) {
346
+ try {
347
+ unregisterFeature(name);
348
+ }
349
+ catch (error) {
350
+ errors.push(error);
351
+ }
343
352
  }
344
- catch (error) {
345
- errors.push(error);
353
+ pendingRegistrations.length = 0;
354
+ corePackages = {};
355
+ isPackagesSet = false;
356
+ if (errors.length > 0) {
357
+ throw errors[0];
346
358
  }
359
+ runtimeState = 'closed';
360
+ })().then(complete, (error) => {
361
+ runtimeState = 'failed';
362
+ fail(error);
363
+ });
364
+ return disposal;
365
+ }
366
+ /** Core calls this only after every old runtime owner has completed cleanup. */
367
+ function beginFeatureSystemRuntime() {
368
+ if (runtimeState !== 'closed') {
369
+ throw new FeatureRuntimeClosedError();
347
370
  }
348
- pendingRegistrations.length = 0;
349
- corePackages = {};
350
- isPackagesSet = false;
351
- if (errors.length > 0) {
352
- throw errors[0];
353
- }
354
- runtimeState = 'closed';
355
- })().then(complete, (error) => {
356
- runtimeState = 'failed';
357
- fail(error);
358
- });
359
- return disposal;
360
- }
361
- /** Core calls this only after every old runtime owner has completed cleanup. */
362
- export function beginFeatureSystemRuntime() {
363
- if (runtimeState !== 'closed') {
364
- throw new FeatureRuntimeClosedError();
371
+ interactionQueue.beginRuntime();
372
+ featureTaskRegistry.beginRuntime();
373
+ sessionManager = new SessionManager(sessions);
374
+ runtimeIdentity = Symbol('feature-runtime');
375
+ disposal = null;
376
+ runtimeState = 'open';
365
377
  }
366
- interactionQueue.beginRuntime();
367
- featureTaskRegistry.beginRuntime();
368
- sessionManager = new SessionManager();
369
- runtimeIdentity = Symbol('feature-runtime');
370
- disposal = null;
371
- runtimeState = 'open';
378
+ return {
379
+ defineFeature,
380
+ setCorePackages,
381
+ getFeature,
382
+ unregisterFeature,
383
+ getFeatureRegistry,
384
+ getSessionManager,
385
+ invokeFeatureTask,
386
+ cancelFeatureTask,
387
+ disposeFeatureSystem,
388
+ beginFeatureSystemRuntime
389
+ };
372
390
  }
391
+ export const { defineFeature, setCorePackages, getFeature, unregisterFeature, getFeatureRegistry, getSessionManager, invokeFeatureTask, cancelFeatureTask, disposeFeatureSystem, beginFeatureSystemRuntime } = composeFeatureSystem(sharedSessions, sharedExecution, sharedTasks);
373
392
  export { FeatureRegistry } from './feature-registry.js';
374
393
  export { SessionManager } from './session-manager.js';
375
394
  //# sourceMappingURL=feature.js.map