slicejs-web-framework 3.3.6 → 3.3.8

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/Slice/Slice.js CHANGED
@@ -1,577 +1,618 @@
1
-
2
- /**
3
- * Main Slice.js runtime.
4
- */
5
- export default class Slice {
6
- /**
7
- * @param {Object} sliceConfig
8
- */
9
- constructor(sliceConfig, frameworkClasses = null) {
10
- this.frameworkClasses = frameworkClasses;
11
- const ControllerClass = frameworkClasses?.Controller;
12
- const StylesManagerClass = frameworkClasses?.StylesManager;
13
-
14
- this.controller = ControllerClass ? new ControllerClass() : null;
15
- this.stylesManager = StylesManagerClass ? new StylesManagerClass() : null;
16
- this.paths = sliceConfig.paths;
17
- this.themeConfig = sliceConfig.themeManager;
18
- this.stylesConfig = sliceConfig.stylesManager;
19
- this.loggerConfig = sliceConfig.logger;
20
- this.debuggerConfig = sliceConfig.debugger;
21
- this.loadingConfig = sliceConfig.loading;
22
- this.eventsConfig = sliceConfig.events;
23
-
24
- // Default to production until init() resolves the actual mode.
25
- // Safe to call isProduction() before init() completes.
26
- this._mode = 'production';
27
- this._publicEnv = {};
28
-
29
- // 📦 Bundle system is initialized automatically via import in index.js
30
- }
31
-
32
- /**
33
- * Dynamically import a module and return its default export.
34
- * @param {string} module
35
- * @returns {Promise<any>}
36
- */
37
- async getClass(module) {
38
- try {
39
- const { default: myClass } = await import(module);
40
- return await myClass;
41
- } catch (error) {
42
- this.logger.logError('Slice', `Error loading class ${module}`, error);
43
- }
44
- }
45
-
46
- /**
47
- * Returns true when running in production mode.
48
- * Reliable after init() has completed.
49
- * @returns {boolean}
50
- */
51
- isProduction() {
52
- return this._mode === 'production';
53
- }
54
-
55
- setPublicEnv(envPayload = {}) {
56
- const normalized = {};
57
-
58
- for (const [key, value] of Object.entries(envPayload || {})) {
59
- if (!key.startsWith('SLICE_PUBLIC_')) continue;
60
- normalized[key] = String(value ?? '');
61
- }
62
-
63
- this._publicEnv = normalized;
64
- }
65
-
66
- getEnv(name, fallbackValue = undefined) {
67
- if (!name || typeof name !== 'string') {
68
- return fallbackValue;
69
- }
70
-
71
- if (Object.prototype.hasOwnProperty.call(this._publicEnv, name)) {
72
- return this._publicEnv[name];
73
- }
74
-
75
- return fallbackValue;
76
- }
77
-
78
- getPublicEnv() {
79
- return { ...this._publicEnv };
80
- }
81
-
82
- /**
83
- * Get a component instance by sliceId.
84
- * @param {string} componentSliceId
85
- * @returns {HTMLElement|undefined}
86
- */
87
- getComponent(componentSliceId) {
88
- return this.controller.activeComponents.get(componentSliceId);
89
- }
90
-
91
- /**
92
- * Build a component instance and run init.
93
- *
94
- * Pass `{ singleton: true }` to get-or-create one shared instance keyed by
95
- * `sliceId` (defaults to `componentName`). Concurrent singleton builds of the
96
- * same id share a single in-flight build, so they never race on a duplicate
97
- * sliceId. Singletons are only supported for Service components — for app-wide
98
- * UI build a Provider Service that manages the Visual (see ToastProvider /
99
- * ToolTipProvider), because a DOM node can only live in one place.
100
- *
101
- * Note: `props` only apply on the first (creating) call; later calls return
102
- * the existing instance and ignore them.
103
- *
104
- * @param {string} componentName
105
- * @param {Object} [props]
106
- * @param {boolean} [props.singleton] Reuse a single instance per sliceId.
107
- * @returns {Promise<HTMLElement|Object|null>}
108
- */
109
- async build(componentName, props = {}) {
110
- if (!props || props.singleton !== true) {
111
- return this._build(componentName, props);
112
- }
113
-
114
- const { singleton, ...rest } = props;
115
- const sliceId = rest.sliceId || componentName;
116
-
117
- const category = this.controller.componentCategories.get(componentName);
118
- if (category !== 'Service') {
119
- this.logger.logError(
120
- 'Slice',
121
- `singleton:true is only supported for Service components ('${componentName}' is ${category || 'unknown'}). ` +
122
- `For app-wide UI build a Provider Service that manages the Visual (see ToastProvider/ToolTipProvider).`
123
- );
124
- return null;
125
- }
126
-
127
- return this.controller.getOrCreate(sliceId, () =>
128
- this._build(componentName, { ...rest, sliceId })
129
- );
130
- }
131
-
132
- /**
133
- * Internal build: load resources, construct, run init, register. Always
134
- * creates a new instance. Public `build` delegates here (and wraps it with
135
- * get-or-create when `singleton:true`).
136
- * @param {string} componentName
137
- * @param {Object} [props]
138
- * @returns {Promise<HTMLElement|Object|null>}
139
- */
140
- async _build(componentName, props = {}) {
141
- if (!componentName) {
142
- this.logger.logError('Slice', null, `Component name is required to build a component`);
143
- return null;
144
- }
145
-
146
- if (typeof componentName !== 'string') {
147
- this.logger.logError('Slice', null, `Component name must be a string`);
148
- return null;
149
- }
150
-
151
- // 📦 Try to load from bundles first
152
- const bundleName = this.controller.getBundleForComponent(componentName);
153
- if (bundleName && !this.controller.loadedBundles.has(bundleName)) {
154
- await this.controller.loadBundle(bundleName);
155
- }
156
-
157
- // After bundle loading attempt, allow build when class is already available
158
- // even if components map has no category entry (stale/components.js mismatch).
159
- if (!this.controller.componentCategories.has(componentName) && !this.controller.classes.has(componentName)) {
160
- this.logger.logError('Slice', null, `Component ${componentName} not found in components.js file`);
161
- return null;
162
- }
163
-
164
- let componentCategory = this.controller.componentCategories.get(componentName);
165
- if (!componentCategory && this.controller.classes.has(componentName)) {
166
- componentCategory = 'AppComponents';
167
- }
168
-
169
- // 📦 Check if component is already available from loaded bundles
170
- const isFromBundle = this.controller.isComponentFromBundle(componentName);
171
-
172
- if (componentCategory === 'Structural') {
173
- this.logger.logError(
174
- 'Slice',
175
- null,
176
- `Component ${componentName} is a Structural component and cannot be built`
177
- );
178
- return null;
179
- }
180
-
181
- let isVisual = slice.paths.components[componentCategory]?.type === 'Visual';
182
- let modulePath = `${slice.paths.components[componentCategory].path}/${componentName}/${componentName}.js`;
183
- const isJsOnlyVisualComponent = isVisual && (componentName === 'MultiRoute' || componentName === 'Route');
184
-
185
- // Load template, class, and CSS concurrently if needed
186
- try {
187
- // 📦 Skip individual loading if component is available from bundles
188
- const loadTemplate =
189
- isFromBundle || !isVisual || isJsOnlyVisualComponent || this.controller.templates.has(componentName)
190
- ? Promise.resolve(null)
191
- : this.controller.fetchText(componentName, 'html', componentCategory);
192
-
193
- const loadClass =
194
- isFromBundle || this.controller.classes.has(componentName)
195
- ? Promise.resolve(null)
196
- : this.getClass(modulePath);
197
-
198
- const loadCSS =
199
- isFromBundle || !isVisual || isJsOnlyVisualComponent || this.controller.requestedStyles.has(componentName)
200
- ? Promise.resolve(null)
201
- : this.controller.fetchText(componentName, 'css', componentCategory);
202
-
203
- const [html, ComponentClass, css] = await Promise.all([loadTemplate, loadClass, loadCSS]);
204
-
205
- // 📦 If component is from bundle but not in cache, it should have been registered by registerBundle
206
- if (isFromBundle) {
207
- this.logger.logInfo('Slice', `📦 Using bundled component: ${componentName}`);
208
- }
209
-
210
- if (html || html === '') {
211
- const template = document.createElement('template');
212
- template.innerHTML = html;
213
- this.controller.templates.set(componentName, template);
214
- this.logger.logInfo('Slice', `Template ${componentName} loaded`);
215
- }
216
-
217
- if (ComponentClass) {
218
- this.controller.classes.set(componentName, ComponentClass);
219
- this.logger.logInfo('Slice', `Class ${componentName} loaded`);
220
- }
221
-
222
- if (css) {
223
- this.stylesManager.registerComponentStyles(componentName, css);
224
- this.logger.logInfo('Slice', `CSS ${componentName} loaded`);
225
- }
226
- } catch (error) {
227
- this.logger.logError('Slice', `Error loading resources for ${componentName}`, error);
228
- return null;
229
- }
230
-
231
- // Create instance
232
- try {
233
- let componentIds = {};
234
- if (props.id) componentIds.id = props.id;
235
- if (props.sliceId) componentIds.sliceId = props.sliceId;
236
-
237
- delete props.id;
238
- delete props.sliceId;
239
- // `singleton` is a build directive (handled in the public build()
240
- // wrapper). Strip it here too so it is consistently reserved and never
241
- // leaks into a component's props on the non-singleton path.
242
- delete props.singleton;
243
-
244
- const ComponentClass = this.controller.classes.get(componentName);
245
- this.logger.logInfo(
246
- 'Slice',
247
- `🔎 Build component: ${componentName} (classType: ${typeof ComponentClass}, isFunction: ${typeof ComponentClass === 'function'})`
248
- );
249
- const componentInstance = new ComponentClass(props);
250
-
251
- if (componentIds.id && isVisual) componentInstance.id = componentIds.id;
252
- if (componentIds.sliceId) componentInstance.sliceId = componentIds.sliceId;
253
-
254
- if (!this.controller.verifyComponentIds(componentInstance)) {
255
- this.logger.logError('Slice', `Error registering instance ${componentName} ${componentInstance.sliceId}`);
256
- return null;
257
- }
258
-
259
- if (componentInstance.init) await componentInstance.init();
260
-
261
- if (slice.debuggerConfig.enabled && isVisual) {
262
- this.debugger.attachDebugMode(componentInstance);
263
- }
264
-
265
- this.controller.registerComponent(componentInstance);
266
- if (isVisual) {
267
- this.controller.registerComponentsRecursively(componentInstance);
268
- }
269
-
270
- this.logger.logInfo('Slice', `Instance ${componentInstance.sliceId} created`);
271
- return componentInstance;
272
- } catch (error) {
273
- this.logger.logError('Slice', `Error creating instance ${componentName}`, error);
274
- return null;
275
- }
276
- }
277
-
278
- /**
279
- * Apply a theme by name.
280
- * @param {string} themeName
281
- * @returns {Promise<void>}
282
- */
283
- async setTheme(themeName) {
284
- await this.stylesManager.themeManager.applyTheme(themeName);
285
- }
286
-
287
- /**
288
- * Current theme name.
289
- * @returns {string|null}
290
- */
291
- get theme() {
292
- return this.stylesManager.themeManager.currentTheme;
293
- }
294
-
295
- /**
296
- * Attach HTML template to a component instance.
297
- * @param {HTMLElement} componentInstance
298
- * @returns {void}
299
- */
300
- attachTemplate(componentInstance) {
301
- this.controller.loadTemplateToComponent(componentInstance);
302
- }
303
- }
304
-
305
- async function loadConfig() {
306
- try {
307
- const response = await fetch('/sliceConfig.json'); // 🔹 Express lo sirve desde `src/`
308
- if (!response.ok) throw new Error('Error loading sliceConfig.json');
309
- const json = await response.json();
310
- return json;
311
- } catch (error) {
312
- console.error(`Error loading config file: ${error.message}`);
313
- return null;
314
- }
315
- }
316
-
317
- async function init() {
318
- const sliceConfig = await loadConfig();
319
- if (!sliceConfig) {
320
- //Display error message in console with colors and alert in english
321
- console.error('%c⛔️ Error loading Slice configuration ⛔️', 'color: red; font-size: 20px;');
322
- alert('Error loading Slice configuration');
323
- return;
324
- }
325
-
326
- // 1+2. Fetch mode endpoint and bundle config in parallel — both are independent.
327
- // In production, /slice-env.json returns 404 (catch is expected and normal).
328
- // bundleConfigJson.production serves as a mode fallback when env endpoint is absent.
329
- let frameworkClasses = null;
330
- const [envResult, configResult] = await Promise.all([
331
- fetch('/slice-env.json', { cache: 'no-store' })
332
- .then(r => r.ok ? r.json() : null)
333
- .catch(() => null),
334
- fetch('/bundles/bundle.config.json', { cache: 'no-store' })
335
- .then(r => r.ok ? r.json() : null)
336
- .catch(() => null)
337
- ]);
338
- const envMode = envResult?.mode ?? null;
339
- const bundleConfigJson = configResult;
340
-
341
- // 3. Determine canonical mode: env endpoint takes precedence, then bundle config
342
- let resolvedMode;
343
- if (envMode) {
344
- resolvedMode = envMode;
345
- } else if (bundleConfigJson?.production) {
346
- resolvedMode = 'production';
347
- } else {
348
- resolvedMode = 'development';
349
- }
350
-
351
- // 4. Load framework classes.
352
- // In production the bundler generates slice-bundle.framework.js which
353
- // sets window.SLICE_FRAMEWORK_CLASSES. In dev mode always use individual
354
- // imports so the live /Slice/ source is served directly without bundles.
355
- if (resolvedMode === 'production' && bundleConfigJson?.bundles?.framework?.file) {
356
- try {
357
- await import(`/bundles/${bundleConfigJson.bundles.framework.file}`);
358
- if (window.SLICE_FRAMEWORK_CLASSES) {
359
- frameworkClasses = window.SLICE_FRAMEWORK_CLASSES;
360
- }
361
- } catch (e) {
362
- // framework bundle failed fall through to individual imports
363
- console.error('[Slice.js] framework bundle import failed:', e?.message || e);
364
- }
365
- }
366
-
367
- if (!frameworkClasses) {
368
- try {
369
- const imports = await Promise.all([
370
- import('./Components/Structural/Controller/Controller.js'),
371
- import('./Components/Structural/StylesManager/StylesManager.js')
372
- ]);
373
- frameworkClasses = {
374
- Controller: imports[0].default,
375
- StylesManager: imports[1].default
376
- };
377
- } catch (e) {
378
- console.error('[Slice.js] individual imports fallback failed:', e?.message || e);
379
- throw e;
380
- }
381
- }
382
-
383
- // 5. Create Slice instance and set resolved mode
384
- window.slice = new Slice(sliceConfig, frameworkClasses);
385
- window.slice._mode = resolvedMode;
386
- window.slice.setPublicEnv(envResult?.env || {});
387
-
388
- const createBundlingInitError = (step, error) => {
389
- const detail = error instanceof Error ? error.message : String(error);
390
- return new Error(`Bundling V2 initialization failed (${step}): ${detail}`, { cause: error });
391
- };
392
-
393
- // Initialize bundles before building components.
394
- // Only in production — dev mode loads each component individually from source.
395
- // bundleConfigJson was already fetched above (step 2); reuse it.
396
- if (resolvedMode === 'production' && bundleConfigJson) {
397
- window.slice.controller.bundleConfig = bundleConfigJson;
398
- }
399
-
400
- if (resolvedMode === 'production' && window.slice.controller.bundleConfig) {
401
- const config = window.slice.controller.bundleConfig;
402
- if (!window.__SLICE_SHARED_DEPS__ || typeof window.__SLICE_SHARED_DEPS__ !== 'object') {
403
- window.__SLICE_SHARED_DEPS__ = {};
404
- }
405
- const criticalFile = config?.bundles?.critical?.file;
406
- if (criticalFile) {
407
- try {
408
- await window.slice.controller.loadBundle('critical');
409
- } catch (error) {
410
- throw createBundlingInitError(`critical bundle "${criticalFile}"`, error);
411
- }
412
- }
413
-
414
- const routeBundles = config?.routeBundles || {};
415
- const initialPath = window.location.pathname || '/';
416
- const bundlesForRoute = routeBundles[initialPath] || [];
417
-
418
- const loadRouteBundles = async () => {
419
- for (const bundleName of bundlesForRoute) {
420
- if (bundleName === 'critical') continue;
421
- const bundleInfo = config?.bundles?.routes?.[bundleName];
422
- if (!bundleInfo?.file) continue;
423
- await window.slice.controller.loadBundle(bundleName);
424
- }
425
- };
426
-
427
- const preloadRouteBundles = () => {
428
- loadRouteBundles().catch((error) => {
429
- const bundlingError = createBundlingInitError(
430
- `idle route preload "${initialPath}"`,
431
- error
432
- );
433
- queueMicrotask(() => {
434
- throw bundlingError;
435
- });
436
- });
437
- };
438
-
439
- if (typeof requestIdleCallback === 'function') {
440
- requestIdleCallback(() => preloadRouteBundles());
441
- } else {
442
- setTimeout(() => preloadRouteBundles(), 0);
443
- }
444
- }
445
-
446
- slice.paths.structuralComponentFolderPath = '/Slice/Components/Structural';
447
-
448
- if (sliceConfig.logger.enabled) {
449
- const LoggerModule = window.slice.frameworkClasses?.Logger
450
- || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/Logger/Logger.js`);
451
- window.slice.logger = new LoggerModule();
452
- } else {
453
- window.slice.logger = {
454
- logError: () => {},
455
- logWarning: () => {},
456
- logInfo: () => {},
457
- };
458
- }
459
-
460
- if (sliceConfig.debugger.enabled) {
461
- const DebuggerModule = window.slice.frameworkClasses?.Debugger
462
- || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/Debugger/Debugger.js`);
463
- window.slice.debugger = new DebuggerModule();
464
- await window.slice.debugger.enableDebugMode();
465
- document.body.appendChild(window.slice.debugger);
466
- }
467
-
468
- if (sliceConfig.events?.ui?.enabled) {
469
- const EventsDebuggerModule = window.slice.frameworkClasses?.EventManagerDebugger
470
- || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/EventManager/EventManagerDebugger.js`);
471
- window.slice.eventsDebugger = new EventsDebuggerModule();
472
- await window.slice.eventsDebugger.init();
473
- document.body.appendChild(window.slice.eventsDebugger);
474
- }
475
-
476
- if (sliceConfig.context?.ui?.enabled) {
477
- const ContextDebuggerModule = window.slice.frameworkClasses?.ContextManagerDebugger
478
- || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/ContextManager/ContextManagerDebugger.js`);
479
- window.slice.contextDebugger = new ContextDebuggerModule();
480
- await window.slice.contextDebugger.init();
481
- document.body.appendChild(window.slice.contextDebugger);
482
- }
483
-
484
- if (sliceConfig.events?.enabled) {
485
- const EventManagerModule = window.slice.frameworkClasses?.EventManager
486
- || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/EventManager/EventManager.js`);
487
- window.slice.events = new EventManagerModule();
488
- if (typeof window.slice.events.init === 'function') {
489
- await window.slice.events.init();
490
- }
491
- } else {
492
- window.slice.events = {
493
- subscribe: () => null,
494
- subscribeOnce: () => null,
495
- unsubscribe: () => false,
496
- emit: () => {},
497
- bind: () => ({
498
- subscribe: () => null,
499
- subscribeOnce: () => null,
500
- emit: () => {},
501
- }),
502
- cleanupComponent: () => 0,
503
- hasSubscribers: () => false,
504
- subscriberCount: () => 0,
505
- clear: () => {},
506
- };
507
- window.slice.logger.logError('Slice', 'EventManager disabled');
508
- }
509
-
510
- if (sliceConfig.context?.enabled) {
511
- const ContextManagerModule = window.slice.frameworkClasses?.ContextManager
512
- || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/ContextManager/ContextManager.js`);
513
- window.slice.context = new ContextManagerModule();
514
- if (typeof window.slice.context.init === 'function') {
515
- await window.slice.context.init();
516
- }
517
- } else {
518
- window.slice.context = {
519
- create: () => false,
520
- getState: () => null,
521
- setState: () => {},
522
- watch: () => null,
523
- has: () => false,
524
- destroy: () => false,
525
- list: () => [],
526
- };
527
- window.slice.logger.logError('Slice', 'ContextManager disabled');
528
- }
529
-
530
- if (sliceConfig.loading.enabled) {
531
- const loading = await window.slice.build('Loading', {});
532
- window.slice.loading = loading;
533
- if (typeof loading?.start === 'function') {
534
- loading.start();
535
- }
536
- }
537
-
538
- const stylesInitPromise = window.slice.stylesManager.init();
539
- const routesModulePromise = import(slice.paths.routesFile);
540
-
541
- if (sliceConfig.events?.ui?.shortcut || sliceConfig.context?.ui?.shortcut) {
542
- const normalize = (value) => (typeof value === 'string' ? value.toLowerCase() : '');
543
- const toKey = (event) => {
544
- const parts = [];
545
- if (event.ctrlKey) parts.push('ctrl');
546
- if (event.shiftKey) parts.push('shift');
547
- if (event.altKey) parts.push('alt');
548
- if (event.metaKey) parts.push('meta');
549
- const key = event.key?.toLowerCase();
550
- if (key && !['control', 'shift', 'alt', 'meta'].includes(key)) {
551
- parts.push(key);
552
- }
553
- return parts.join('+');
554
- };
555
-
556
- const handlers = {
557
- [normalize(sliceConfig.events?.ui?.shortcut)]: () => window.slice.eventsDebugger?.toggle?.(),
558
- [normalize(sliceConfig.context?.ui?.shortcut)]: () => window.slice.contextDebugger?.toggle?.(),
559
- };
560
-
561
- document.addEventListener('keydown', (event) => {
562
- const key = toKey(event);
563
- if (!key || !handlers[key]) return;
564
- event.preventDefault();
565
- handlers[key]();
566
- });
567
- }
568
-
569
- const [, routesModule] = await Promise.all([stylesInitPromise, routesModulePromise]);
570
- const routes = routesModule.default;
571
- const RouterModule = window.slice.frameworkClasses?.Router
572
- || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/Router/Router.js`);
573
- window.slice.router = new RouterModule(routes);
574
- await window.slice.router.init();
575
- }
576
-
577
- await init();
1
+
2
+ /**
3
+ * Main Slice.js runtime.
4
+ */
5
+ export default class Slice {
6
+ /**
7
+ * @param {Object} sliceConfig
8
+ */
9
+ constructor(sliceConfig, frameworkClasses = null) {
10
+ this.frameworkClasses = frameworkClasses;
11
+ const ControllerClass = frameworkClasses?.Controller;
12
+ const StylesManagerClass = frameworkClasses?.StylesManager;
13
+
14
+ this.controller = ControllerClass ? new ControllerClass() : null;
15
+ this.stylesManager = StylesManagerClass ? new StylesManagerClass() : null;
16
+ this.paths = sliceConfig.paths;
17
+ this.themeConfig = sliceConfig.themeManager;
18
+ this.stylesConfig = sliceConfig.stylesManager;
19
+ this.loggerConfig = sliceConfig.logger;
20
+ this.debuggerConfig = sliceConfig.debugger;
21
+ this.loadingConfig = sliceConfig.loading;
22
+ this.eventsConfig = sliceConfig.events;
23
+
24
+ // Default to production until init() resolves the actual mode.
25
+ // Safe to call isProduction() before init() completes.
26
+ this._mode = 'production';
27
+ this._publicEnv = {};
28
+
29
+ // 📦 Bundle system is initialized automatically via import in index.js
30
+ }
31
+
32
+ /**
33
+ * Dynamically import a module and return its default export.
34
+ * @param {string} module
35
+ * @returns {Promise<any>}
36
+ */
37
+ async getClass(module) {
38
+ try {
39
+ const { default: myClass } = await import(module);
40
+ return await myClass;
41
+ } catch (error) {
42
+ this.logger.error('Slice', `Error loading class ${module}`, error);
43
+ throw error;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Returns true when running in production mode.
49
+ * Reliable after init() has completed.
50
+ * @returns {boolean}
51
+ */
52
+ isProduction() {
53
+ return this._mode === 'production';
54
+ }
55
+
56
+ setPublicEnv(envPayload = {}) {
57
+ const normalized = {};
58
+
59
+ for (const [key, value] of Object.entries(envPayload || {})) {
60
+ if (!key.startsWith('SLICE_PUBLIC_')) continue;
61
+ normalized[key] = String(value ?? '');
62
+ }
63
+
64
+ this._publicEnv = normalized;
65
+ }
66
+
67
+ getEnv(name, fallbackValue = undefined) {
68
+ if (!name || typeof name !== 'string') {
69
+ return fallbackValue;
70
+ }
71
+
72
+ if (Object.prototype.hasOwnProperty.call(this._publicEnv, name)) {
73
+ return this._publicEnv[name];
74
+ }
75
+
76
+ return fallbackValue;
77
+ }
78
+
79
+ getPublicEnv() {
80
+ return { ...this._publicEnv };
81
+ }
82
+
83
+ /**
84
+ * Typed accessors over the public env, so callers stop re-parsing strings.
85
+ * slice.env.get('SLICE_PUBLIC_API_URL', '')
86
+ * slice.env.bool('SLICE_PUBLIC_AUTH_ENABLED') // '1'|'true'|'yes'|'on' → true
87
+ * slice.env.int('SLICE_PUBLIC_TIMEOUT', 5000)
88
+ * slice.env.list('SLICE_PUBLIC_MODELS') // 'a, b' → ['a','b']
89
+ * slice.env.has('X') / slice.env.all()
90
+ * @returns {{ get: Function, has: Function, all: Function, bool: Function, int: Function, list: Function }}
91
+ */
92
+ get env() {
93
+ const read = (name) =>
94
+ Object.prototype.hasOwnProperty.call(this._publicEnv, name) ? this._publicEnv[name] : undefined;
95
+ const present = (v) => v !== undefined && String(v).trim() !== '';
96
+
97
+ return {
98
+ get: (name, fallback = undefined) => this.getEnv(name, fallback),
99
+ has: (name) => Object.prototype.hasOwnProperty.call(this._publicEnv, name),
100
+ all: () => this.getPublicEnv(),
101
+ bool: (name, fallback = false) => {
102
+ const v = read(name);
103
+ return present(v) ? ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase()) : fallback;
104
+ },
105
+ int: (name, fallback = 0) => {
106
+ const v = read(name);
107
+ const n = parseInt(v, 10);
108
+ return Number.isNaN(n) ? fallback : n;
109
+ },
110
+ list: (name, fallback = []) => {
111
+ const v = read(name);
112
+ if (!present(v)) return fallback;
113
+ return String(v)
114
+ .split(',')
115
+ .map((s) => s.trim())
116
+ .filter(Boolean);
117
+ },
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Get a component instance by sliceId.
123
+ * @param {string} componentSliceId
124
+ * @returns {HTMLElement|undefined}
125
+ */
126
+ getComponent(componentSliceId) {
127
+ return this.controller.activeComponents.get(componentSliceId);
128
+ }
129
+
130
+ /**
131
+ * Build a component instance and run init.
132
+ *
133
+ * Pass `{ singleton: true }` to get-or-create one shared instance keyed by
134
+ * `sliceId` (defaults to `componentName`). Concurrent singleton builds of the
135
+ * same id share a single in-flight build, so they never race on a duplicate
136
+ * sliceId. Singletons are only supported for Service components — for app-wide
137
+ * UI build a Provider Service that manages the Visual (see ToastProvider /
138
+ * ToolTipProvider), because a DOM node can only live in one place.
139
+ *
140
+ * Note: `props` only apply on the first (creating) call; later calls return
141
+ * the existing instance and ignore them.
142
+ *
143
+ * @param {string} componentName
144
+ * @param {Object} [props]
145
+ * @param {boolean} [props.singleton] Reuse a single instance per sliceId.
146
+ * @returns {Promise<HTMLElement|Object|null>}
147
+ */
148
+ async build(componentName, props = {}) {
149
+ if (!props || props.singleton !== true) {
150
+ return this._build(componentName, props);
151
+ }
152
+
153
+ const { singleton, ...rest } = props;
154
+ const sliceId = rest.sliceId || componentName;
155
+
156
+ // Singletons are allowed for any category whose *type* is 'Service' — not
157
+ // only the built-in 'Service' category. Custom categories declared in
158
+ // sliceConfig with `"type": "Service"` (e.g. AppServices) are services too.
159
+ const category = this.controller.componentCategories.get(componentName);
160
+ const categoryType = slice.paths?.components?.[category]?.type;
161
+ if (categoryType !== 'Service') {
162
+ this.logger.logError(
163
+ 'Slice',
164
+ `singleton:true is only supported for Service-type components ('${componentName}' is in category '${category || 'unknown'}', type '${categoryType || 'unknown'}'). ` +
165
+ `For app-wide UI build a Provider Service that manages the Visual (see ToastProvider/ToolTipProvider).`
166
+ );
167
+ return null;
168
+ }
169
+
170
+ return this.controller.getOrCreate(sliceId, () =>
171
+ this._build(componentName, { ...rest, sliceId })
172
+ );
173
+ }
174
+
175
+ /**
176
+ * Internal build: load resources, construct, run init, register. Always
177
+ * creates a new instance. Public `build` delegates here (and wraps it with
178
+ * get-or-create when `singleton:true`).
179
+ * @param {string} componentName
180
+ * @param {Object} [props]
181
+ * @returns {Promise<HTMLElement|Object|null>}
182
+ */
183
+ async _build(componentName, props = {}) {
184
+ if (!componentName) {
185
+ this.logger.error('Slice', 'Component name is required to build a component');
186
+ return null;
187
+ }
188
+
189
+ if (typeof componentName !== 'string') {
190
+ this.logger.error('Slice', 'Component name must be a string');
191
+ return null;
192
+ }
193
+
194
+ // 📦 Try to load from bundles first
195
+ const bundleName = this.controller.getBundleForComponent(componentName);
196
+ if (bundleName && !this.controller.loadedBundles.has(bundleName)) {
197
+ await this.controller.loadBundle(bundleName);
198
+ }
199
+
200
+ if (!this.controller.componentCategories.has(componentName) && !this.controller.classes.has(componentName)) {
201
+ this.logger.error('Slice', `Component ${componentName} not found in components.js file`);
202
+ return null;
203
+ }
204
+
205
+ let componentCategory = this.controller.componentCategories.get(componentName);
206
+ if (!componentCategory && this.controller.classes.has(componentName)) {
207
+ componentCategory = 'AppComponents';
208
+ }
209
+
210
+ // 📦 Check if component is already available from loaded bundles
211
+ const isFromBundle = this.controller.isComponentFromBundle(componentName);
212
+
213
+ if (componentCategory === 'Structural') {
214
+ this.logger.error('Slice', `Component ${componentName} is a Structural component and cannot be built`);
215
+ return null;
216
+ }
217
+
218
+ let isVisual = slice.paths.components[componentCategory]?.type === 'Visual';
219
+ let modulePath = `${slice.paths.components[componentCategory].path}/${componentName}/${componentName}.js`;
220
+ const isJsOnlyVisualComponent = isVisual && (componentName === 'MultiRoute' || componentName === 'Route');
221
+
222
+ // Load template, class, and CSS concurrently if needed
223
+ try {
224
+ // 📦 Skip individual loading if component is available from bundles
225
+ const loadTemplate =
226
+ isFromBundle || !isVisual || isJsOnlyVisualComponent || this.controller.templates.has(componentName)
227
+ ? Promise.resolve(null)
228
+ : this.controller.fetchText(componentName, 'html', componentCategory);
229
+
230
+ const loadClass =
231
+ isFromBundle || this.controller.classes.has(componentName)
232
+ ? Promise.resolve(null)
233
+ : this.getClass(modulePath);
234
+
235
+ const loadCSS =
236
+ isFromBundle || !isVisual || isJsOnlyVisualComponent || this.controller.requestedStyles.has(componentName)
237
+ ? Promise.resolve(null)
238
+ : this.controller.fetchText(componentName, 'css', componentCategory);
239
+
240
+ const [html, ComponentClass, css] = await Promise.all([loadTemplate, loadClass, loadCSS]);
241
+
242
+ // 📦 If component is from bundle but not in cache, it should have been registered by registerBundle
243
+ if (isFromBundle) {
244
+ this.logger.logInfo('Slice', `📦 Using bundled component: ${componentName}`);
245
+ }
246
+
247
+ if (html || html === '') {
248
+ const template = document.createElement('template');
249
+ template.innerHTML = html;
250
+ this.controller.templates.set(componentName, template);
251
+ this.logger.logInfo('Slice', `Template ${componentName} loaded`);
252
+ }
253
+
254
+ if (ComponentClass) {
255
+ this.controller.classes.set(componentName, ComponentClass);
256
+ this.logger.logInfo('Slice', `Class ${componentName} loaded`);
257
+ }
258
+
259
+ if (css) {
260
+ this.stylesManager.registerComponentStyles(componentName, css);
261
+ this.logger.logInfo('Slice', `CSS ${componentName} loaded`);
262
+ }
263
+ } catch (error) {
264
+ this.logger.logError('Slice', `Error loading resources for ${componentName}`, error);
265
+ return null;
266
+ }
267
+
268
+ // Create instance
269
+ try {
270
+ let componentIds = {};
271
+ if (props.id) componentIds.id = props.id;
272
+ if (props.sliceId) componentIds.sliceId = props.sliceId;
273
+
274
+ delete props.id;
275
+ delete props.sliceId;
276
+ // `singleton` is a build directive (handled in the public build()
277
+ // wrapper). Strip it here too so it is consistently reserved and never
278
+ // leaks into a component's props on the non-singleton path.
279
+ delete props.singleton;
280
+
281
+ const ComponentClass = this.controller.classes.get(componentName);
282
+ this.logger.logInfo(
283
+ 'Slice',
284
+ `🔎 Build component: ${componentName} (classType: ${typeof ComponentClass}, isFunction: ${typeof ComponentClass === 'function'})`
285
+ );
286
+ const componentInstance = new ComponentClass(props);
287
+
288
+ if (componentIds.id && isVisual) componentInstance.id = componentIds.id;
289
+ if (componentIds.sliceId) componentInstance.sliceId = componentIds.sliceId;
290
+
291
+ if (!this.controller.verifyComponentIds(componentInstance)) {
292
+ this.logger.logError('Slice', `Error registering instance ${componentName} ${componentInstance.sliceId}`);
293
+ return null;
294
+ }
295
+
296
+ if (componentInstance.init) await componentInstance.init();
297
+
298
+ if (slice.debuggerConfig.enabled && isVisual) {
299
+ this.debugger.attachDebugMode(componentInstance);
300
+ }
301
+
302
+ this.controller.registerComponent(componentInstance);
303
+ if (isVisual) {
304
+ this.controller.registerComponentsRecursively(componentInstance);
305
+ }
306
+
307
+ this.logger.logInfo('Slice', `Instance ${componentInstance.sliceId} created`);
308
+ return componentInstance;
309
+ } catch (error) {
310
+ this.logger.logError('Slice', `Error creating instance ${componentName}`, error);
311
+ return null;
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Apply a theme by name.
317
+ * @param {string} themeName
318
+ * @returns {Promise<void>}
319
+ */
320
+ async setTheme(themeName) {
321
+ await this.stylesManager.themeManager.applyTheme(themeName);
322
+ }
323
+
324
+ /**
325
+ * Current theme name.
326
+ * @returns {string|null}
327
+ */
328
+ get theme() {
329
+ return this.stylesManager.themeManager.currentTheme;
330
+ }
331
+
332
+ /**
333
+ * Attach HTML template to a component instance.
334
+ * @param {HTMLElement} componentInstance
335
+ * @returns {void}
336
+ */
337
+ attachTemplate(componentInstance) {
338
+ this.controller.loadTemplateToComponent(componentInstance);
339
+ }
340
+ }
341
+
342
+ async function loadConfig() {
343
+ try {
344
+ const response = await fetch('/sliceConfig.json');
345
+ if (!response.ok) throw new Error('Error loading sliceConfig.json');
346
+ const json = await response.json();
347
+ return json;
348
+ } catch (error) {
349
+ console.error('Error loading config file:', error);
350
+ return null;
351
+ }
352
+ }
353
+
354
+ async function init() {
355
+ const sliceConfig = await loadConfig();
356
+ if (!sliceConfig) {
357
+ console.error('%c\u26A0\uFE0F Error loading Slice configuration', 'color: red; font-size: 20px;');
358
+ alert('Error loading Slice configuration');
359
+ throw new Error('Slice initialization failed: unable to load sliceConfig.json');
360
+ }
361
+
362
+ // 1+2. Fetch mode endpoint and bundle config in parallel both are independent.
363
+ // In production, /slice-env.json returns 404 (catch is expected and normal).
364
+ // bundleConfigJson.production serves as a mode fallback when env endpoint is absent.
365
+ let frameworkClasses = null;
366
+ const [envResult, configResult] = await Promise.all([
367
+ fetch('/slice-env.json', { cache: 'no-store' })
368
+ .then(r => r.ok ? r.json() : null)
369
+ .catch(error => { console.error('[Slice.js] Error fetching /slice-env.json:', error); return null; }),
370
+ fetch('/bundles/bundle.config.json', { cache: 'no-store' })
371
+ .then(r => r.ok ? r.json() : null)
372
+ .catch(error => { console.error('[Slice.js] Error fetching bundle.config.json:', error); return null; })
373
+ ]);
374
+ const envMode = envResult?.mode ?? null;
375
+ const bundleConfigJson = configResult;
376
+
377
+ // 3. Determine canonical mode: env endpoint takes precedence, then bundle config
378
+ let resolvedMode;
379
+ if (envMode) {
380
+ resolvedMode = envMode;
381
+ } else if (bundleConfigJson?.production) {
382
+ resolvedMode = 'production';
383
+ } else {
384
+ resolvedMode = 'development';
385
+ }
386
+
387
+ // 4. Load framework classes.
388
+ // In production the bundler generates slice-bundle.framework.js which
389
+ // sets window.SLICE_FRAMEWORK_CLASSES. In dev mode always use individual
390
+ // imports so the live /Slice/ source is served directly without bundles.
391
+ if (resolvedMode === 'production' && bundleConfigJson?.bundles?.framework?.file) {
392
+ try {
393
+ await import(`/bundles/${bundleConfigJson.bundles.framework.file}`);
394
+ if (window.SLICE_FRAMEWORK_CLASSES) {
395
+ frameworkClasses = window.SLICE_FRAMEWORK_CLASSES;
396
+ }
397
+ } catch (e) {
398
+ console.error('[Slice.js] framework bundle import failed, falling through to individual imports:', e);
399
+ }
400
+ }
401
+
402
+ if (!frameworkClasses) {
403
+ try {
404
+ const imports = await Promise.all([
405
+ import('./Components/Structural/Controller/Controller.js'),
406
+ import('./Components/Structural/StylesManager/StylesManager.js')
407
+ ]);
408
+ frameworkClasses = {
409
+ Controller: imports[0].default,
410
+ StylesManager: imports[1].default
411
+ };
412
+ } catch (e) {
413
+ console.error('[Slice.js] individual imports fallback failed:', e);
414
+ throw e;
415
+ }
416
+ }
417
+
418
+ // 5. Create Slice instance and set resolved mode
419
+ window.slice = new Slice(sliceConfig, frameworkClasses);
420
+ window.slice._mode = resolvedMode;
421
+ window.slice.setPublicEnv(envResult?.env || {});
422
+
423
+ const createBundlingInitError = (step, error) => {
424
+ const detail = error instanceof Error ? error.message : String(error);
425
+ return new Error(`Bundling V2 initialization failed (${step}): ${detail}`, { cause: error });
426
+ };
427
+
428
+ // Initialize bundles before building components.
429
+ // Only in production — dev mode loads each component individually from source.
430
+ // bundleConfigJson was already fetched above (step 2); reuse it.
431
+ if (resolvedMode === 'production' && bundleConfigJson) {
432
+ window.slice.controller.bundleConfig = bundleConfigJson;
433
+ }
434
+
435
+ if (resolvedMode === 'production' && window.slice.controller.bundleConfig) {
436
+ const config = window.slice.controller.bundleConfig;
437
+ if (!window.__SLICE_SHARED_DEPS__ || typeof window.__SLICE_SHARED_DEPS__ !== 'object') {
438
+ window.__SLICE_SHARED_DEPS__ = {};
439
+ }
440
+ const criticalFile = config?.bundles?.critical?.file;
441
+ if (criticalFile) {
442
+ try {
443
+ await window.slice.controller.loadBundle('critical');
444
+ } catch (error) {
445
+ throw createBundlingInitError(`critical bundle "${criticalFile}"`, error);
446
+ }
447
+ }
448
+
449
+ const routeBundles = config?.routeBundles || {};
450
+ const initialPath = window.location.pathname || '/';
451
+ const bundlesForRoute = routeBundles[initialPath] || [];
452
+
453
+ const loadRouteBundles = async () => {
454
+ for (const bundleName of bundlesForRoute) {
455
+ if (bundleName === 'critical') continue;
456
+ const bundleInfo = config?.bundles?.routes?.[bundleName];
457
+ if (!bundleInfo?.file) continue;
458
+ await window.slice.controller.loadBundle(bundleName);
459
+ }
460
+ };
461
+
462
+ const preloadRouteBundles = () => {
463
+ loadRouteBundles().catch((error) => {
464
+ window.slice?.logger?.error('Slice', `Idle route preload failed for "${initialPath}"`, error);
465
+ });
466
+ };
467
+
468
+ const safePreload = () => {
469
+ try {
470
+ preloadRouteBundles();
471
+ } catch (error) {
472
+ window.slice?.logger?.error('Slice', 'Error in route preload callback', error);
473
+ }
474
+ };
475
+
476
+ if (typeof requestIdleCallback === 'function') {
477
+ requestIdleCallback(() => safePreload());
478
+ } else {
479
+ setTimeout(() => safePreload(), 0);
480
+ }
481
+ }
482
+
483
+ slice.paths.structuralComponentFolderPath = '/Slice/Components/Structural';
484
+
485
+ if (sliceConfig.logger.enabled) {
486
+ const LoggerModule = window.slice.frameworkClasses?.Logger
487
+ || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/Logger/Logger.js`);
488
+ window.slice.logger = new LoggerModule();
489
+ } else {
490
+ const noop = () => {};
491
+ window.slice.logger = {
492
+ error: noop, warn: noop, info: noop, debug: noop,
493
+ logError: noop, logWarning: noop, logInfo: noop,
494
+ };
495
+ }
496
+
497
+ if (sliceConfig.debugger.enabled) {
498
+ const DebuggerModule = window.slice.frameworkClasses?.Debugger
499
+ || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/Debugger/Debugger.js`);
500
+ window.slice.debugger = new DebuggerModule();
501
+ await window.slice.debugger.enableDebugMode();
502
+ document.body.appendChild(window.slice.debugger);
503
+ }
504
+
505
+ if (sliceConfig.events?.ui?.enabled) {
506
+ const EventsDebuggerModule = window.slice.frameworkClasses?.EventManagerDebugger
507
+ || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/EventManager/EventManagerDebugger.js`);
508
+ window.slice.eventsDebugger = new EventsDebuggerModule();
509
+ await window.slice.eventsDebugger.init();
510
+ document.body.appendChild(window.slice.eventsDebugger);
511
+ }
512
+
513
+ if (sliceConfig.context?.ui?.enabled) {
514
+ const ContextDebuggerModule = window.slice.frameworkClasses?.ContextManagerDebugger
515
+ || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/ContextManager/ContextManagerDebugger.js`);
516
+ window.slice.contextDebugger = new ContextDebuggerModule();
517
+ await window.slice.contextDebugger.init();
518
+ document.body.appendChild(window.slice.contextDebugger);
519
+ }
520
+
521
+ if (sliceConfig.events?.enabled) {
522
+ const EventManagerModule = window.slice.frameworkClasses?.EventManager
523
+ || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/EventManager/EventManager.js`);
524
+ window.slice.events = new EventManagerModule();
525
+ if (typeof window.slice.events.init === 'function') {
526
+ await window.slice.events.init();
527
+ }
528
+ } else {
529
+ window.slice.events = {
530
+ subscribe: () => null,
531
+ subscribeOnce: () => null,
532
+ unsubscribe: () => false,
533
+ emit: () => {},
534
+ bind: () => ({
535
+ subscribe: () => null,
536
+ subscribeOnce: () => null,
537
+ emit: () => {},
538
+ }),
539
+ cleanupComponent: () => 0,
540
+ hasSubscribers: () => false,
541
+ subscriberCount: () => 0,
542
+ clear: () => {},
543
+ };
544
+ window.slice.logger.logError('Slice', 'EventManager disabled');
545
+ }
546
+
547
+ if (sliceConfig.context?.enabled) {
548
+ const ContextManagerModule = window.slice.frameworkClasses?.ContextManager
549
+ || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/ContextManager/ContextManager.js`);
550
+ window.slice.context = new ContextManagerModule();
551
+ if (typeof window.slice.context.init === 'function') {
552
+ await window.slice.context.init();
553
+ }
554
+ } else {
555
+ window.slice.context = {
556
+ create: () => false,
557
+ getState: () => null,
558
+ setState: () => {},
559
+ watch: () => null,
560
+ has: () => false,
561
+ destroy: () => false,
562
+ list: () => [],
563
+ };
564
+ window.slice.logger.logError('Slice', 'ContextManager disabled');
565
+ }
566
+
567
+ if (sliceConfig.loading.enabled) {
568
+ const loading = await window.slice.build('Loading', {});
569
+ window.slice.loading = loading;
570
+ if (typeof loading?.start === 'function') {
571
+ loading.start();
572
+ }
573
+ }
574
+
575
+ const stylesInitPromise = window.slice.stylesManager.init();
576
+ const routesModulePromise = import(slice.paths.routesFile);
577
+
578
+ if (sliceConfig.events?.ui?.shortcut || sliceConfig.context?.ui?.shortcut) {
579
+ const normalize = (value) => (typeof value === 'string' ? value.toLowerCase() : '');
580
+ const toKey = (event) => {
581
+ const parts = [];
582
+ if (event.ctrlKey) parts.push('ctrl');
583
+ if (event.shiftKey) parts.push('shift');
584
+ if (event.altKey) parts.push('alt');
585
+ if (event.metaKey) parts.push('meta');
586
+ const key = event.key?.toLowerCase();
587
+ if (key && !['control', 'shift', 'alt', 'meta'].includes(key)) {
588
+ parts.push(key);
589
+ }
590
+ return parts.join('+');
591
+ };
592
+
593
+ const handlers = {
594
+ [normalize(sliceConfig.events?.ui?.shortcut)]: () => window.slice.eventsDebugger?.toggle?.(),
595
+ [normalize(sliceConfig.context?.ui?.shortcut)]: () => window.slice.contextDebugger?.toggle?.(),
596
+ };
597
+
598
+ document.addEventListener('keydown', (event) => {
599
+ const key = toKey(event);
600
+ if (!key || !handlers[key]) return;
601
+ event.preventDefault();
602
+ handlers[key]();
603
+ });
604
+ }
605
+
606
+ const [, routesModule] = await Promise.all([stylesInitPromise, routesModulePromise]);
607
+ const routes = routesModule.default;
608
+ const RouterModule = window.slice.frameworkClasses?.Router
609
+ || await window.slice.getClass(`${slice.paths.structuralComponentFolderPath}/Router/Router.js`);
610
+ window.slice.router = new RouterModule(routes);
611
+ await window.slice.router.init();
612
+ }
613
+
614
+ try {
615
+ await init();
616
+ } catch (initError) {
617
+ console.error('[Slice.js] Initialization failed:', initError);
618
+ }