@therealtinhtute/baroiplayer 1.2.0 → 1.2.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.
Files changed (97) hide show
  1. package/README.md +1 -2
  2. package/dist/context/media.js +1 -2
  3. package/dist/context/media.mjs +3 -15
  4. package/dist/context/store.js +1 -2
  5. package/dist/context/store.mjs +3 -5
  6. package/dist/context-Bzd5QCKM.cjs +7 -0
  7. package/dist/context-Bzd5QCKM.cjs.map +1 -0
  8. package/dist/context-DD_SH4tT.js +1053 -0
  9. package/dist/context-DD_SH4tT.js.map +1 -0
  10. package/dist/core-events-BRnLMB7s.cjs +2 -0
  11. package/dist/core-events-BRnLMB7s.cjs.map +1 -0
  12. package/dist/core-events-v_mKdj5p.js +417 -0
  13. package/dist/core-events-v_mKdj5p.js.map +1 -0
  14. package/dist/core-plugins-CMBv-yVh.cjs +2 -0
  15. package/dist/core-plugins-CMBv-yVh.cjs.map +1 -0
  16. package/dist/core-plugins-CqCxLkbd.js +754 -0
  17. package/dist/core-plugins-CqCxLkbd.js.map +1 -0
  18. package/dist/core.js +7 -29
  19. package/dist/core.js.map +1 -1
  20. package/dist/core.mjs +947 -1220
  21. package/dist/core.mjs.map +1 -1
  22. package/dist/enhanced-components-BwjBqSA1.js +2858 -0
  23. package/dist/enhanced-components-BwjBqSA1.js.map +1 -0
  24. package/dist/enhanced-components-C-ka-XLp.cjs +2 -0
  25. package/dist/enhanced-components-C-ka-XLp.cjs.map +1 -0
  26. package/dist/hooks-B-IIWPJr.js +1842 -0
  27. package/dist/hooks-B-IIWPJr.js.map +1 -0
  28. package/dist/hooks-DcHzmBwA.cjs +4 -0
  29. package/dist/hooks-DcHzmBwA.cjs.map +1 -0
  30. package/dist/index.js +27 -97
  31. package/dist/index.js.map +1 -1
  32. package/dist/index.mjs +5613 -6208
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/minimal-components-BYsMQde5.js +1610 -0
  35. package/dist/minimal-components-BYsMQde5.js.map +1 -0
  36. package/dist/minimal-components-CsxQbDp7.cjs +2 -0
  37. package/dist/minimal-components-CsxQbDp7.cjs.map +1 -0
  38. package/dist/performance-monitor-DCSijLJg.js +312 -0
  39. package/dist/performance-monitor-DCSijLJg.js.map +1 -0
  40. package/dist/performance-monitor-wNFKmqMr.cjs +2 -0
  41. package/dist/performance-monitor-wNFKmqMr.cjs.map +1 -0
  42. package/dist/rolldown-runtime-BmowowmI.js +14 -0
  43. package/dist/rolldown-runtime-mLOUI7ql.cjs +1 -0
  44. package/dist/utils-D2gQ7c2R.js +64 -0
  45. package/dist/utils-D2gQ7c2R.js.map +1 -0
  46. package/dist/utils-DJaAwiZ9.cjs +2 -0
  47. package/dist/utils-DJaAwiZ9.cjs.map +1 -0
  48. package/dist/utils.js +1 -2
  49. package/dist/utils.mjs +3 -11
  50. package/package.json +28 -22
  51. package/src/components/AnimateLoading.tsx +14 -10
  52. package/src/components/examples/loading-states-demo.tsx +1 -2
  53. package/src/components/examples/react-19-demo.tsx +6 -10
  54. package/src/components/examples/volume-orientation-demo.tsx +1 -2
  55. package/src/components/ui/blur-poster.tsx +18 -15
  56. package/src/components/variants/minimal/components/VideoElement.tsx +3 -1
  57. package/src/core/performance/media-loading-optimizer.ts +2 -1
  58. package/src/hooks/useScreenshot.ts +60 -44
  59. package/src/types/assets.d.ts +29 -0
  60. package/dist/context/media.js.map +0 -1
  61. package/dist/context/media.mjs.map +0 -1
  62. package/dist/context/store.js.map +0 -1
  63. package/dist/context/store.mjs.map +0 -1
  64. package/dist/context-BYwDoSRX.js +0 -1172
  65. package/dist/context-BYwDoSRX.js.map +0 -1
  66. package/dist/context-eNS62_ac.cjs +0 -23
  67. package/dist/context-eNS62_ac.cjs.map +0 -1
  68. package/dist/core-events-B1iM2F46.cjs +0 -2
  69. package/dist/core-events-B1iM2F46.cjs.map +0 -1
  70. package/dist/core-events-DunPHKRE.js +0 -484
  71. package/dist/core-events-DunPHKRE.js.map +0 -1
  72. package/dist/core-plugins-By-4-kGs.cjs +0 -2
  73. package/dist/core-plugins-By-4-kGs.cjs.map +0 -1
  74. package/dist/core-plugins-DSBWcTuX.js +0 -821
  75. package/dist/core-plugins-DSBWcTuX.js.map +0 -1
  76. package/dist/enhanced-components-B_l3cist.js +0 -1142
  77. package/dist/enhanced-components-B_l3cist.js.map +0 -1
  78. package/dist/enhanced-components-BspFs9OO.cjs +0 -2
  79. package/dist/enhanced-components-BspFs9OO.cjs.map +0 -1
  80. package/dist/hooks-BXwI8QG6.cjs +0 -4
  81. package/dist/hooks-BXwI8QG6.cjs.map +0 -1
  82. package/dist/hooks-Bpi-jDiO.js +0 -1816
  83. package/dist/hooks-Bpi-jDiO.js.map +0 -1
  84. package/dist/minimal-components-C4z900Ro.js +0 -1926
  85. package/dist/minimal-components-C4z900Ro.js.map +0 -1
  86. package/dist/minimal-components-v4qBp6jv.cjs +0 -2
  87. package/dist/minimal-components-v4qBp6jv.cjs.map +0 -1
  88. package/dist/performance-monitor-C5k6FDXw.js +0 -301
  89. package/dist/performance-monitor-C5k6FDXw.js.map +0 -1
  90. package/dist/performance-monitor-lJmuUjQQ.cjs +0 -2
  91. package/dist/performance-monitor-lJmuUjQQ.cjs.map +0 -1
  92. package/dist/utils-CFOue_9K.cjs +0 -9
  93. package/dist/utils-CFOue_9K.cjs.map +0 -1
  94. package/dist/utils-Dzpl2ArK.js +0 -2844
  95. package/dist/utils-Dzpl2ArK.js.map +0 -1
  96. package/dist/utils.js.map +0 -1
  97. package/dist/utils.mjs.map +0 -1
package/dist/core.mjs CHANGED
@@ -1,1233 +1,960 @@
1
- var k = Object.defineProperty;
2
- var A = (o, e, t) => e in o ? k(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
- var u = (o, e, t) => A(o, typeof e != "symbol" ? e + "" : e, t);
4
- import { C as B, P as R } from "./core-plugins-DSBWcTuX.js";
5
- import { A as ye, B as we, a as Te, d as Se, c as ve, i as be, b as Pe, h as Me, j as Le, g as Ee, f as Ce, e as ke, l as Ae, k as Be } from "./core-plugins-DSBWcTuX.js";
6
- import { E as I } from "./core-events-DunPHKRE.js";
7
- import { a as Ie, b as Ne, M as $e, f as Fe, c as xe, d as Ue, e as De, n as Oe, u as ze, m as _e, p as Ve, h as He, j as je, k as Ye, g as Qe, l as We, i as Ke, o as Je } from "./core-events-DunPHKRE.js";
8
- import { j as f } from "./context-BYwDoSRX.js";
9
- import m, { useMemo as N, createContext as $, useContext as F, lazy as h } from "react";
10
- import { a as x } from "./performance-monitor-C5k6FDXw.js";
11
- import { b as Ge, P as Xe, d as Ze, p as et, u as tt, w as rt } from "./performance-monitor-C5k6FDXw.js";
12
- class P {
13
- constructor() {
14
- u(this, "results", []);
15
- u(this, "regressionDetector", new x());
16
- }
17
- async runTest(e, t) {
18
- const r = [];
19
- let n = 0, s = 0, i;
20
- try {
21
- for (let d = 0; d < e.warmupIterations; d++)
22
- await t();
23
- global.gc && global.gc(), n = this.getMemoryUsage();
24
- for (let d = 0; d < e.iterations; d++) {
25
- const S = performance.now();
26
- await t();
27
- const C = performance.now();
28
- r.push(C - S);
29
- }
30
- s = this.getMemoryUsage();
31
- } catch (d) {
32
- i = d instanceof Error ? d.message : String(d);
33
- }
34
- const a = r.reduce((d, S) => d + S, 0) / r.length, c = Math.min(...r), g = Math.max(...r), T = s - n, y = !i && a <= e.expectedThreshold.renderTime && T <= e.expectedThreshold.memoryUsage, w = {
35
- testName: e.name,
36
- passed: y,
37
- metrics: {
38
- averageRenderTime: a,
39
- minRenderTime: isFinite(c) ? c : 0,
40
- maxRenderTime: isFinite(g) ? g : 0,
41
- memoryUsage: T,
42
- iterations: e.iterations
43
- },
44
- threshold: e.expectedThreshold,
45
- error: i
46
- };
47
- return this.results.push(w), w;
48
- }
49
- getMemoryUsage() {
50
- return "memory" in performance && performance.memory.usedJSHeapSize || 0;
51
- }
52
- // Component rendering performance test
53
- async testComponentRender(e, t, r = 16) {
54
- const n = {
55
- name: `${e} Render Performance`,
56
- iterations: 100,
57
- warmupIterations: 10,
58
- timeout: 5e3,
59
- expectedThreshold: {
60
- renderTime: r,
61
- memoryUsage: 1048576
62
- // 1MB
63
- }
64
- };
65
- return this.runTest(n, t);
66
- }
67
- // Bundle loading performance test
68
- async testBundleLoading(e, t = 1e3) {
69
- const r = {
70
- name: `Bundle Loading: ${e}`,
71
- iterations: 5,
72
- warmupIterations: 1,
73
- timeout: 1e4,
74
- expectedThreshold: {
75
- renderTime: t,
76
- memoryUsage: 5242880
77
- // 5MB
78
- }
79
- };
80
- return this.runTest(r, async () => {
81
- const n = performance.now();
82
- try {
83
- const i = await fetch(e);
84
- if (!i.ok)
85
- throw new Error(`Failed to load bundle: ${i.status}`);
86
- await i.blob();
87
- } catch (i) {
88
- console.warn(`Bundle loading test failed for ${e}:`, i);
89
- }
90
- return performance.now() - n;
91
- });
92
- }
93
- // Memory leak detection test
94
- async testMemoryLeaks(e, t = 1e3) {
95
- const r = {
96
- name: "Memory Leak Detection",
97
- iterations: t,
98
- warmupIterations: 100,
99
- timeout: 3e4,
100
- expectedThreshold: {
101
- renderTime: 1 / 0,
102
- // Not testing render time
103
- memoryUsage: 10485760
104
- // 10MB max increase
105
- }
106
- }, n = this.getMemoryUsage(), s = await this.runTest(r, e), a = this.getMemoryUsage() - n, c = a > r.expectedThreshold.memoryUsage;
107
- return {
108
- ...s,
109
- passed: s.passed && !c,
110
- error: c ? `Potential memory leak detected: ${Math.round(a / 1024 / 1024)}MB increase` : s.error
111
- };
112
- }
113
- // Interaction delay test
114
- async testInteractionDelay(e, t = 100) {
115
- const r = {
116
- name: "Interaction Delay",
117
- iterations: 50,
118
- warmupIterations: 5,
119
- timeout: 5e3,
120
- expectedThreshold: {
121
- renderTime: t,
122
- memoryUsage: 1048576
123
- // 1MB
124
- }
125
- };
126
- return this.runTest(r, e);
127
- }
128
- // Regression testing
129
- async runRegressionTests(e, t) {
130
- t && this.regressionDetector.setBaseline(t);
131
- const r = this.regressionDetector.detectRegression(e);
132
- return { passed: r.length === 0, regressions: r };
133
- }
134
- // Get all test results
135
- getResults() {
136
- return [...this.results];
137
- }
138
- // Get test summary
139
- getSummary() {
140
- const e = this.results.length, t = this.results.filter((s) => s.passed).length, r = e - t, n = e > 0 ? t / e * 100 : 0;
141
- return { totalTests: e, passedTests: t, failedTests: r, passRate: n };
142
- }
143
- // Clear test results
144
- clearResults() {
145
- this.results = [];
146
- }
147
- // Generate performance report
148
- generateReport() {
149
- const e = this.getSummary();
150
- let t = `Performance Test Report
151
- `;
152
- return t += `========================
153
-
154
- `, t += `Total Tests: ${e.totalTests}
155
- `, t += `Passed: ${e.passedTests}
156
- `, t += `Failed: ${e.failedTests}
157
- `, t += `Pass Rate: ${e.passRate.toFixed(1)}%
158
-
159
- `, this.results.length > 0 && (t += `Detailed Results:
160
- `, t += `-----------------
161
-
162
- `, this.results.forEach((r, n) => {
163
- t += `${n + 1}. ${r.testName}
164
- `, t += ` Status: ${r.passed ? "PASS" : "FAIL"}
165
- `, t += ` Average Render Time: ${r.metrics.averageRenderTime.toFixed(2)}ms
166
- `, t += ` Min/Max Render Time: ${r.metrics.minRenderTime.toFixed(2)}ms / ${r.metrics.maxRenderTime.toFixed(2)}ms
167
- `, t += ` Memory Usage: ${Math.round(r.metrics.memoryUsage / 1024)} KB
168
- `, t += ` Iterations: ${r.metrics.iterations}
169
- `, r.error && (t += ` Error: ${r.error}
170
- `), t += `
171
- `;
172
- })), t;
173
- }
174
- }
175
- const v = new P(), te = {
176
- // Test component rendering performance
177
- async testComponent(o, e = {}, t = 16) {
178
- return v.testComponentRender(
179
- o.displayName || o.name || "Component",
180
- () => ({ type: o, props: e }),
181
- t
182
- );
183
- },
184
- // Test hook performance
185
- async testHook(o, e, t = 1) {
186
- const r = {
187
- name: `Hook Performance: ${e}`,
188
- iterations: 1e3,
189
- warmupIterations: 100,
190
- timeout: 5e3,
191
- expectedThreshold: {
192
- renderTime: t,
193
- memoryUsage: 1048576
194
- // 1MB
195
- }
196
- };
197
- return v.runTest(r, o);
198
- },
199
- // Test async operation performance
200
- async testAsyncOperation(o, e, t = 1e3) {
201
- const r = {
202
- name: `Async Operation: ${e}`,
203
- iterations: 10,
204
- warmupIterations: 2,
205
- timeout: 3e4,
206
- expectedThreshold: {
207
- renderTime: t,
208
- memoryUsage: 2097152
209
- // 2MB
210
- }
211
- };
212
- return v.runTest(r, o);
213
- },
214
- // Test bundle size impact
215
- async measureBundleImpact(o, e, t) {
216
- const r = performance.memory?.usedJSHeapSize || 0, n = performance.now();
217
- o();
218
- const s = performance.memory?.usedJSHeapSize || 0, i = performance.now();
219
- e();
220
- const a = performance.memory?.usedJSHeapSize || 0, c = performance.now();
221
- return {
222
- bundleIncrease: a - r,
223
- memoryIncrease: s - r,
224
- renderTimeImpact: c - i - (i - n)
225
- };
226
- }
227
- };
228
- class U {
229
- constructor() {
230
- u(this, "benchmark", new P());
231
- u(this, "suites", /* @__PURE__ */ new Map());
232
- }
233
- // Register a test suite
234
- registerSuite(e, t) {
235
- this.suites.set(e, t);
236
- }
237
- // Run all tests in a suite
238
- async runSuite(e, t) {
239
- const r = this.suites.get(e);
240
- if (!r)
241
- throw new Error(`Test suite '${e}' not found`);
242
- const n = [];
243
- for (const s of r) {
244
- const i = t.get(s.name);
245
- if (!i) {
246
- console.warn(`No implementation found for test '${s.name}'`);
247
- continue;
248
- }
249
- const a = await this.benchmark.runTest(s, i);
250
- n.push(a);
251
- }
252
- return n;
253
- }
254
- // Run all registered test suites
255
- async runAllSuites(e) {
256
- const t = /* @__PURE__ */ new Map();
257
- for (const [r] of this.suites) {
258
- const n = e.get(r);
259
- if (!n) {
260
- console.warn(`No implementations found for suite '${r}'`);
261
- continue;
262
- }
263
- const s = await this.runSuite(r, n);
264
- t.set(r, s);
265
- }
266
- return t;
267
- }
268
- // Generate comprehensive report
269
- generateComprehensiveReport() {
270
- this.benchmark.getSummary();
271
- let e = this.benchmark.generateReport();
272
- if (this.suites.size > 0) {
273
- e += `
274
- Test Suites:
275
- `, e += `============
276
-
277
- `;
278
- for (const [t, r] of this.suites)
279
- e += `Suite: ${t}
280
- `, e += `Tests: ${r.length}
281
-
282
- `;
283
- }
284
- return e;
285
- }
286
- }
287
- const re = new U(), D = [
288
- // Bundle size budgets
289
- {
290
- name: "Main Bundle Size (ESM)",
291
- category: "bundle",
292
- limit: 250 * 1024,
293
- // 250KB
294
- unit: "bytes",
295
- severity: "error",
296
- description: "Main bundle should stay under 250KB for fast initial loading"
297
- },
298
- {
299
- name: "Main Bundle Size (CJS)",
300
- category: "bundle",
301
- limit: 200 * 1024,
302
- // 200KB
303
- unit: "bytes",
304
- severity: "error",
305
- description: "CJS bundle should be smaller due to better compression"
306
- },
307
- {
308
- name: "Core Module Size",
309
- category: "bundle",
310
- limit: 15 * 1024,
311
- // 15KB
312
- unit: "bytes",
313
- severity: "warning",
314
- description: "Core architecture should remain lightweight"
315
- },
316
- {
317
- name: "Enhanced Components Size",
318
- category: "bundle",
319
- limit: 40 * 1024,
320
- // 40KB
321
- unit: "bytes",
322
- severity: "warning",
323
- description: "Enhanced components bundle size"
324
- },
325
- // Runtime performance budgets
326
- {
327
- name: "Component Render Time",
328
- category: "runtime",
329
- limit: 16,
330
- // 16ms for 60fps
331
- unit: "ms",
332
- severity: "error",
333
- description: "Component rendering should complete within one frame"
334
- },
335
- {
336
- name: "First Input Delay",
337
- category: "runtime",
338
- limit: 100,
339
- // 100ms
340
- unit: "ms",
341
- severity: "error",
342
- description: "First Input Delay should be under 100ms for good UX"
343
- },
344
- {
345
- name: "Largest Contentful Paint",
346
- category: "runtime",
347
- limit: 2500,
348
- // 2.5s
349
- unit: "ms",
350
- severity: "warning",
351
- description: "LCP should be under 2.5s for good Core Web Vitals score"
352
- },
353
- {
354
- name: "Cumulative Layout Shift",
355
- category: "runtime",
356
- limit: 0.1,
357
- unit: "score",
358
- severity: "warning",
359
- description: "CLS should be under 0.1 for good visual stability"
360
- },
361
- // Memory budgets
362
- {
363
- name: "Memory Usage",
364
- category: "memory",
365
- limit: 50 * 1024 * 1024,
366
- // 50MB
367
- unit: "bytes",
368
- severity: "warning",
369
- description: "Memory usage should stay under 50MB for good performance"
370
- },
371
- {
372
- name: "Memory Increase Per Operation",
373
- category: "memory",
374
- limit: 1024 * 1024,
375
- // 1MB
376
- unit: "bytes",
377
- severity: "error",
378
- description: "Each operation should not increase memory by more than 1MB"
379
- },
380
- // Network budgets (for media loading)
381
- {
382
- name: "Media Load Time",
383
- category: "network",
384
- limit: 3e3,
385
- // 3s
386
- unit: "ms",
387
- severity: "warning",
388
- description: "Media should start loading within 3 seconds"
389
- }
390
- ];
391
- class O {
392
- constructor(e = D, t = {
393
- enabled: !0,
394
- channels: [{ type: "console", config: {} }],
395
- threshold: 1,
396
- cooldown: 300 * 1e3
397
- // 5 minutes
398
- }) {
399
- u(this, "budgets", /* @__PURE__ */ new Map());
400
- u(this, "violations", []);
401
- u(this, "alertConfig");
402
- u(this, "lastAlertTime", 0);
403
- e.forEach((r) => {
404
- this.budgets.set(r.name, r);
405
- }), this.alertConfig = t;
406
- }
407
- // Check a single metric against budgets
408
- checkMetric(e, t, r = "runtime") {
409
- const n = [];
410
- for (const [s, i] of this.budgets)
411
- if (i.category === r && (s.includes(e) || e.includes(s.split(" ")[0]?.toLowerCase() || "")) && t > i.limit) {
412
- const a = {
413
- budget: i,
414
- actualValue: t,
415
- overageAmount: t - i.limit,
416
- overagePercentage: (t - i.limit) / i.limit * 100,
417
- timestamp: Date.now()
418
- };
419
- n.push(a), this.violations.push(a);
420
- }
421
- return n.length > 0 && this.handleViolations(n), n;
422
- }
423
- // Check bundle sizes
424
- async checkBundleSizes(e) {
425
- const t = [];
426
- return typeof window < "u" || typeof process > "u" ? (console.warn("Bundle size checking is only available in Node.js environment"), t) : (console.warn(
427
- "Bundle size checking disabled - use Node.js cicdIntegration from @therealtinhtute/baroiplayer/core/performance/cicd for CI/CD environments"
428
- ), t);
429
- }
430
- // Check runtime performance
431
- checkRuntimeMetrics(e) {
432
- const t = [];
433
- return e.renderTime !== void 0 && t.push(
434
- ...this.checkMetric("Component Render Time", e.renderTime, "runtime")
435
- ), e.fid !== void 0 && t.push(...this.checkMetric("First Input Delay", e.fid, "runtime")), e.lcp !== void 0 && t.push(...this.checkMetric("Largest Contentful Paint", e.lcp, "runtime")), e.cls !== void 0 && t.push(...this.checkMetric("Cumulative Layout Shift", e.cls, "runtime")), e.memoryUsage !== void 0 && t.push(...this.checkMetric("Memory Usage", e.memoryUsage, "memory")), e.mediaLoadTime !== void 0 && t.push(...this.checkMetric("Media Load Time", e.mediaLoadTime, "network")), t;
436
- }
437
- // Handle budget violations
438
- async handleViolations(e) {
439
- if (!this.alertConfig.enabled) return;
440
- const t = Date.now();
441
- e.filter((n) => n.budget.severity === "error").length >= this.alertConfig.threshold && t - this.lastAlertTime >= this.alertConfig.cooldown && (await this.sendAlerts(e), this.lastAlertTime = t);
442
- }
443
- // Send alerts through configured channels
444
- async sendAlerts(e) {
445
- const t = this.formatAlertMessage(e);
446
- for (const r of this.alertConfig.channels)
447
- try {
448
- await this.sendAlert(r, t);
449
- } catch (n) {
450
- console.error(`Failed to send alert via ${r.type}:`, n);
451
- }
452
- }
453
- // Format alert message
454
- formatAlertMessage(e) {
455
- let t = `🚨 Performance Budget Violations Detected!
456
-
457
- `;
458
- return e.forEach((r) => {
459
- const { budget: n, actualValue: s, overageAmount: i, overagePercentage: a } = r;
460
- this.getUnitDisplay(n.unit), t += `❌ ${n.name}
461
- `, t += ` Limit: ${this.formatValue(n.limit, n.unit)}
462
- `, t += ` Actual: ${this.formatValue(s, n.unit)}
463
- `, t += ` Overage: ${this.formatValue(i, n.unit)} (+${a.toFixed(1)}%)
464
- `, t += ` Severity: ${n.severity.toUpperCase()}
465
-
466
- `;
467
- }), t += `Time: ${(/* @__PURE__ */ new Date()).toISOString()}
468
- `, t += `Total Violations: ${e.length}`, t;
469
- }
470
- // Send alert to specific channel
471
- async sendAlert(e, t) {
472
- switch (e.type) {
473
- case "console":
474
- console.error(t);
475
- break;
476
- case "webhook":
477
- if (e.config.url) {
478
- const r = await fetch(e.config.url, {
479
- method: "POST",
480
- headers: { "Content-Type": "application/json" },
481
- body: JSON.stringify({ text: t, timestamp: Date.now() })
482
- });
483
- if (!r.ok)
484
- throw new Error(`Webhook failed: ${r.status}`);
485
- }
486
- break;
487
- case "slack":
488
- if (e.config.url) {
489
- const r = await fetch(e.config.url, {
490
- method: "POST",
491
- headers: { "Content-Type": "application/json" },
492
- body: JSON.stringify({
493
- text: t,
494
- channel: e.config.channel,
495
- username: "BaroiPlayer Performance Monitor"
496
- })
497
- });
498
- if (!r.ok)
499
- throw new Error(`Slack webhook failed: ${r.status}`);
500
- }
501
- break;
502
- default:
503
- console.warn(`Unsupported alert channel: ${e.type}`);
504
- }
505
- }
506
- // Helper methods
507
- formatValue(e, t) {
508
- switch (t) {
509
- case "bytes":
510
- return this.formatBytes(e);
511
- case "ms":
512
- return `${e.toFixed(2)}ms`;
513
- case "score":
514
- return e.toFixed(3);
515
- case "percent":
516
- return `${e.toFixed(1)}%`;
517
- default:
518
- return e.toString();
519
- }
520
- }
521
- formatBytes(e) {
522
- return e >= 1024 * 1024 ? `${(e / 1024 / 1024).toFixed(2)}MB` : e >= 1024 ? `${(e / 1024).toFixed(2)}KB` : `${e}B`;
523
- }
524
- getUnitDisplay(e) {
525
- return {
526
- bytes: "bytes",
527
- ms: "milliseconds",
528
- score: "score",
529
- percent: "percent"
530
- }[e] || e;
531
- }
532
- // Management methods
533
- addBudget(e) {
534
- this.budgets.set(e.name, e);
535
- }
536
- removeBudget(e) {
537
- this.budgets.delete(e);
538
- }
539
- updateBudget(e, t) {
540
- const r = this.budgets.get(e);
541
- r && this.budgets.set(e, { ...r, ...t });
542
- }
543
- getBudgets() {
544
- return Array.from(this.budgets.values());
545
- }
546
- getViolations(e) {
547
- return e ? this.violations.filter((t) => t.timestamp >= e) : [...this.violations];
548
- }
549
- clearViolations() {
550
- this.violations = [];
551
- }
552
- getViolationSummary() {
553
- const e = {}, t = {};
554
- return this.violations.forEach((r) => {
555
- const n = r.budget.category, s = r.budget.severity;
556
- e[n] = (e[n] || 0) + 1, t[s] = (t[s] || 0) + 1;
557
- }), {
558
- total: this.violations.length,
559
- byCategory: e,
560
- bySeverity: t
561
- };
562
- }
1
+ import { i as e, r as t } from "./context-DD_SH4tT.js";
2
+ import { a as n, i as r, n as i, o as a, r as o, s, t as c } from "./performance-monitor-DCSijLJg.js";
3
+ import { a as l, c as u, d, f as ee, g as te, h as f, i as p, l as m, m as h, n as g, o as _, p as ne, r as re, s as v, t as ie, u as ae } from "./core-plugins-CqCxLkbd.js";
4
+ import { _ as y, a as oe, c as se, d as ce, f as le, g as ue, h as de, i as fe, l as pe, m as me, n as he, o as ge, p as b, r as x, s as S, t as C, u as w, v as T, y as E } from "./core-events-v_mKdj5p.js";
5
+ import D, { createContext as O, lazy as k, useContext as A, useMemo as j } from "react";
6
+ //#region src/core/performance/performance-testing.ts
7
+ var M = class {
8
+ constructor() {
9
+ t(this, "results", []), t(this, "regressionDetector", new o());
10
+ }
11
+ async runTest(e, t) {
12
+ let n = [], r = 0, i = 0, a;
13
+ try {
14
+ for (let n = 0; n < e.warmupIterations; n++) await t();
15
+ global.gc && global.gc(), r = this.getMemoryUsage();
16
+ for (let r = 0; r < e.iterations; r++) {
17
+ let e = performance.now();
18
+ await t();
19
+ let r = performance.now();
20
+ n.push(r - e);
21
+ }
22
+ i = this.getMemoryUsage();
23
+ } catch (e) {
24
+ a = e instanceof Error ? e.message : String(e);
25
+ }
26
+ let o = n.reduce((e, t) => e + t, 0) / n.length, s = Math.min(...n), c = Math.max(...n), l = i - r, u = {
27
+ testName: e.name,
28
+ passed: !a && o <= e.expectedThreshold.renderTime && l <= e.expectedThreshold.memoryUsage,
29
+ metrics: {
30
+ averageRenderTime: o,
31
+ minRenderTime: isFinite(s) ? s : 0,
32
+ maxRenderTime: isFinite(c) ? c : 0,
33
+ memoryUsage: l,
34
+ iterations: e.iterations
35
+ },
36
+ threshold: e.expectedThreshold,
37
+ error: a
38
+ };
39
+ return this.results.push(u), u;
40
+ }
41
+ getMemoryUsage() {
42
+ return "memory" in performance && performance.memory.usedJSHeapSize || 0;
43
+ }
44
+ async testComponentRender(e, t, n = 16) {
45
+ let r = {
46
+ name: `${e} Render Performance`,
47
+ iterations: 100,
48
+ warmupIterations: 10,
49
+ timeout: 5e3,
50
+ expectedThreshold: {
51
+ renderTime: n,
52
+ memoryUsage: 1024 * 1024
53
+ }
54
+ };
55
+ return this.runTest(r, t);
56
+ }
57
+ async testBundleLoading(e, t = 1e3) {
58
+ let n = {
59
+ name: `Bundle Loading: ${e}`,
60
+ iterations: 5,
61
+ warmupIterations: 1,
62
+ timeout: 1e4,
63
+ expectedThreshold: {
64
+ renderTime: t,
65
+ memoryUsage: 5 * 1024 * 1024
66
+ }
67
+ };
68
+ return this.runTest(n, async () => {
69
+ let t = performance.now();
70
+ try {
71
+ let t = await fetch(e);
72
+ if (!t.ok) throw Error(`Failed to load bundle: ${t.status}`);
73
+ await t.blob();
74
+ } catch (t) {
75
+ console.warn(`Bundle loading test failed for ${e}:`, t);
76
+ }
77
+ return performance.now() - t;
78
+ });
79
+ }
80
+ async testMemoryLeaks(e, t = 1e3) {
81
+ let n = {
82
+ name: "Memory Leak Detection",
83
+ iterations: t,
84
+ warmupIterations: 100,
85
+ timeout: 3e4,
86
+ expectedThreshold: {
87
+ renderTime: Infinity,
88
+ memoryUsage: 10 * 1024 * 1024
89
+ }
90
+ }, r = this.getMemoryUsage(), i = await this.runTest(n, e), a = this.getMemoryUsage() - r, o = a > n.expectedThreshold.memoryUsage;
91
+ return {
92
+ ...i,
93
+ passed: i.passed && !o,
94
+ error: o ? `Potential memory leak detected: ${Math.round(a / 1024 / 1024)}MB increase` : i.error
95
+ };
96
+ }
97
+ async testInteractionDelay(e, t = 100) {
98
+ let n = {
99
+ name: "Interaction Delay",
100
+ iterations: 50,
101
+ warmupIterations: 5,
102
+ timeout: 5e3,
103
+ expectedThreshold: {
104
+ renderTime: t,
105
+ memoryUsage: 1024 * 1024
106
+ }
107
+ };
108
+ return this.runTest(n, e);
109
+ }
110
+ async runRegressionTests(e, t) {
111
+ t && this.regressionDetector.setBaseline(t);
112
+ let n = this.regressionDetector.detectRegression(e);
113
+ return {
114
+ passed: n.length === 0,
115
+ regressions: n
116
+ };
117
+ }
118
+ getResults() {
119
+ return [...this.results];
120
+ }
121
+ getSummary() {
122
+ let e = this.results.length, t = this.results.filter((e) => e.passed).length;
123
+ return {
124
+ totalTests: e,
125
+ passedTests: t,
126
+ failedTests: e - t,
127
+ passRate: e > 0 ? t / e * 100 : 0
128
+ };
129
+ }
130
+ clearResults() {
131
+ this.results = [];
132
+ }
133
+ generateReport() {
134
+ let e = this.getSummary(), t = "Performance Test Report\n";
135
+ return t += "========================\n\n", t += `Total Tests: ${e.totalTests}\n`, t += `Passed: ${e.passedTests}\n`, t += `Failed: ${e.failedTests}\n`, t += `Pass Rate: ${e.passRate.toFixed(1)}%\n\n`, this.results.length > 0 && (t += "Detailed Results:\n", t += "-----------------\n\n", this.results.forEach((e, n) => {
136
+ t += `${n + 1}. ${e.testName}\n`, t += ` Status: ${e.passed ? "PASS" : "FAIL"}\n`, t += ` Average Render Time: ${e.metrics.averageRenderTime.toFixed(2)}ms\n`, t += ` Min/Max Render Time: ${e.metrics.minRenderTime.toFixed(2)}ms / ${e.metrics.maxRenderTime.toFixed(2)}ms\n`, t += ` Memory Usage: ${Math.round(e.metrics.memoryUsage / 1024)} KB\n`, t += ` Iterations: ${e.metrics.iterations}\n`, e.error && (t += ` Error: ${e.error}\n`), t += "\n";
137
+ })), t;
138
+ }
139
+ }, N = new M(), P = {
140
+ async testComponent(e, t = {}, n = 16) {
141
+ return N.testComponentRender(e.displayName || e.name || "Component", () => ({
142
+ type: e,
143
+ props: t
144
+ }), n);
145
+ },
146
+ async testHook(e, t, n = 1) {
147
+ let r = {
148
+ name: `Hook Performance: ${t}`,
149
+ iterations: 1e3,
150
+ warmupIterations: 100,
151
+ timeout: 5e3,
152
+ expectedThreshold: {
153
+ renderTime: n,
154
+ memoryUsage: 1024 * 1024
155
+ }
156
+ };
157
+ return N.runTest(r, e);
158
+ },
159
+ async testAsyncOperation(e, t, n = 1e3) {
160
+ let r = {
161
+ name: `Async Operation: ${t}`,
162
+ iterations: 10,
163
+ warmupIterations: 2,
164
+ timeout: 3e4,
165
+ expectedThreshold: {
166
+ renderTime: n,
167
+ memoryUsage: 2 * 1024 * 1024
168
+ }
169
+ };
170
+ return N.runTest(r, e);
171
+ },
172
+ async measureBundleImpact(e, t, n) {
173
+ let r = performance.memory?.usedJSHeapSize || 0, i = performance.now();
174
+ e();
175
+ let a = performance.memory?.usedJSHeapSize || 0, o = performance.now();
176
+ t();
177
+ let s = performance.memory?.usedJSHeapSize || 0, c = performance.now();
178
+ return {
179
+ bundleIncrease: s - r,
180
+ memoryIncrease: a - r,
181
+ renderTimeImpact: c - o - (o - i)
182
+ };
183
+ }
184
+ }, F = class {
185
+ constructor() {
186
+ t(this, "benchmark", new M()), t(this, "suites", /* @__PURE__ */ new Map());
187
+ }
188
+ registerSuite(e, t) {
189
+ this.suites.set(e, t);
190
+ }
191
+ async runSuite(e, t) {
192
+ let n = this.suites.get(e);
193
+ if (!n) throw Error(`Test suite '${e}' not found`);
194
+ let r = [];
195
+ for (let e of n) {
196
+ let n = t.get(e.name);
197
+ if (!n) {
198
+ console.warn(`No implementation found for test '${e.name}'`);
199
+ continue;
200
+ }
201
+ let i = await this.benchmark.runTest(e, n);
202
+ r.push(i);
203
+ }
204
+ return r;
205
+ }
206
+ async runAllSuites(e) {
207
+ let t = /* @__PURE__ */ new Map();
208
+ for (let [n] of this.suites) {
209
+ let r = e.get(n);
210
+ if (!r) {
211
+ console.warn(`No implementations found for suite '${n}'`);
212
+ continue;
213
+ }
214
+ let i = await this.runSuite(n, r);
215
+ t.set(n, i);
216
+ }
217
+ return t;
218
+ }
219
+ generateComprehensiveReport() {
220
+ this.benchmark.getSummary();
221
+ let e = this.benchmark.generateReport();
222
+ if (this.suites.size > 0) {
223
+ e += "\nTest Suites:\n", e += "============\n\n";
224
+ for (let [t, n] of this.suites) e += `Suite: ${t}\n`, e += `Tests: ${n.length}\n\n`;
225
+ }
226
+ return e;
227
+ }
228
+ }, I = new F(), L = [
229
+ {
230
+ name: "Main Bundle Size (ESM)",
231
+ category: "bundle",
232
+ limit: 250 * 1024,
233
+ unit: "bytes",
234
+ severity: "error",
235
+ description: "Main bundle should stay under 250KB for fast initial loading"
236
+ },
237
+ {
238
+ name: "Main Bundle Size (CJS)",
239
+ category: "bundle",
240
+ limit: 200 * 1024,
241
+ unit: "bytes",
242
+ severity: "error",
243
+ description: "CJS bundle should be smaller due to better compression"
244
+ },
245
+ {
246
+ name: "Core Module Size",
247
+ category: "bundle",
248
+ limit: 15 * 1024,
249
+ unit: "bytes",
250
+ severity: "warning",
251
+ description: "Core architecture should remain lightweight"
252
+ },
253
+ {
254
+ name: "Enhanced Components Size",
255
+ category: "bundle",
256
+ limit: 40 * 1024,
257
+ unit: "bytes",
258
+ severity: "warning",
259
+ description: "Enhanced components bundle size"
260
+ },
261
+ {
262
+ name: "Component Render Time",
263
+ category: "runtime",
264
+ limit: 16,
265
+ unit: "ms",
266
+ severity: "error",
267
+ description: "Component rendering should complete within one frame"
268
+ },
269
+ {
270
+ name: "First Input Delay",
271
+ category: "runtime",
272
+ limit: 100,
273
+ unit: "ms",
274
+ severity: "error",
275
+ description: "First Input Delay should be under 100ms for good UX"
276
+ },
277
+ {
278
+ name: "Largest Contentful Paint",
279
+ category: "runtime",
280
+ limit: 2500,
281
+ unit: "ms",
282
+ severity: "warning",
283
+ description: "LCP should be under 2.5s for good Core Web Vitals score"
284
+ },
285
+ {
286
+ name: "Cumulative Layout Shift",
287
+ category: "runtime",
288
+ limit: .1,
289
+ unit: "score",
290
+ severity: "warning",
291
+ description: "CLS should be under 0.1 for good visual stability"
292
+ },
293
+ {
294
+ name: "Memory Usage",
295
+ category: "memory",
296
+ limit: 50 * 1024 * 1024,
297
+ unit: "bytes",
298
+ severity: "warning",
299
+ description: "Memory usage should stay under 50MB for good performance"
300
+ },
301
+ {
302
+ name: "Memory Increase Per Operation",
303
+ category: "memory",
304
+ limit: 1024 * 1024,
305
+ unit: "bytes",
306
+ severity: "error",
307
+ description: "Each operation should not increase memory by more than 1MB"
308
+ },
309
+ {
310
+ name: "Media Load Time",
311
+ category: "network",
312
+ limit: 3e3,
313
+ unit: "ms",
314
+ severity: "warning",
315
+ description: "Media should start loading within 3 seconds"
316
+ }
317
+ ], R = class {
318
+ constructor(e = L, n = {
319
+ enabled: !0,
320
+ channels: [{
321
+ type: "console",
322
+ config: {}
323
+ }],
324
+ threshold: 1,
325
+ cooldown: 300 * 1e3
326
+ }) {
327
+ t(this, "budgets", /* @__PURE__ */ new Map()), t(this, "violations", []), t(this, "alertConfig", void 0), t(this, "lastAlertTime", 0), e.forEach((e) => {
328
+ this.budgets.set(e.name, e);
329
+ }), this.alertConfig = n;
330
+ }
331
+ checkMetric(e, t, n = "runtime") {
332
+ let r = [];
333
+ for (let [i, a] of this.budgets) if (a.category === n && (i.includes(e) || e.includes(i.split(" ")[0]?.toLowerCase() || "")) && t > a.limit) {
334
+ let e = {
335
+ budget: a,
336
+ actualValue: t,
337
+ overageAmount: t - a.limit,
338
+ overagePercentage: (t - a.limit) / a.limit * 100,
339
+ timestamp: Date.now()
340
+ };
341
+ r.push(e), this.violations.push(e);
342
+ }
343
+ return r.length > 0 && this.handleViolations(r), r;
344
+ }
345
+ async checkBundleSizes(e) {
346
+ let t = [];
347
+ return typeof window < "u" || typeof process > "u" ? (console.warn("Bundle size checking is only available in Node.js environment"), t) : (console.warn("Bundle size checking disabled - use Node.js cicdIntegration from @therealtinhtute/baroiplayer/core/performance/cicd for CI/CD environments"), t);
348
+ }
349
+ checkRuntimeMetrics(e) {
350
+ let t = [];
351
+ return e.renderTime !== void 0 && t.push(...this.checkMetric("Component Render Time", e.renderTime, "runtime")), e.fid !== void 0 && t.push(...this.checkMetric("First Input Delay", e.fid, "runtime")), e.lcp !== void 0 && t.push(...this.checkMetric("Largest Contentful Paint", e.lcp, "runtime")), e.cls !== void 0 && t.push(...this.checkMetric("Cumulative Layout Shift", e.cls, "runtime")), e.memoryUsage !== void 0 && t.push(...this.checkMetric("Memory Usage", e.memoryUsage, "memory")), e.mediaLoadTime !== void 0 && t.push(...this.checkMetric("Media Load Time", e.mediaLoadTime, "network")), t;
352
+ }
353
+ async handleViolations(e) {
354
+ if (!this.alertConfig.enabled) return;
355
+ let t = Date.now();
356
+ e.filter((e) => e.budget.severity === "error").length >= this.alertConfig.threshold && t - this.lastAlertTime >= this.alertConfig.cooldown && (await this.sendAlerts(e), this.lastAlertTime = t);
357
+ }
358
+ async sendAlerts(e) {
359
+ let t = this.formatAlertMessage(e);
360
+ for (let e of this.alertConfig.channels) try {
361
+ await this.sendAlert(e, t);
362
+ } catch (t) {
363
+ console.error(`Failed to send alert via ${e.type}:`, t);
364
+ }
365
+ }
366
+ formatAlertMessage(e) {
367
+ let t = "🚨 Performance Budget Violations Detected!\n\n";
368
+ return e.forEach((e) => {
369
+ let { budget: n, actualValue: r, overageAmount: i, overagePercentage: a } = e;
370
+ this.getUnitDisplay(n.unit), t += `❌ ${n.name}\n`, t += ` Limit: ${this.formatValue(n.limit, n.unit)}\n`, t += ` Actual: ${this.formatValue(r, n.unit)}\n`, t += ` Overage: ${this.formatValue(i, n.unit)} (+${a.toFixed(1)}%)\n`, t += ` Severity: ${n.severity.toUpperCase()}\n\n`;
371
+ }), t += `Time: ${(/* @__PURE__ */ new Date()).toISOString()}\n`, t += `Total Violations: ${e.length}`, t;
372
+ }
373
+ async sendAlert(e, t) {
374
+ switch (e.type) {
375
+ case "console":
376
+ console.error(t);
377
+ break;
378
+ case "webhook":
379
+ if (e.config.url) {
380
+ let n = await fetch(e.config.url, {
381
+ method: "POST",
382
+ headers: { "Content-Type": "application/json" },
383
+ body: JSON.stringify({
384
+ text: t,
385
+ timestamp: Date.now()
386
+ })
387
+ });
388
+ if (!n.ok) throw Error(`Webhook failed: ${n.status}`);
389
+ }
390
+ break;
391
+ case "slack":
392
+ if (e.config.url) {
393
+ let n = await fetch(e.config.url, {
394
+ method: "POST",
395
+ headers: { "Content-Type": "application/json" },
396
+ body: JSON.stringify({
397
+ text: t,
398
+ channel: e.config.channel,
399
+ username: "BaroiPlayer Performance Monitor"
400
+ })
401
+ });
402
+ if (!n.ok) throw Error(`Slack webhook failed: ${n.status}`);
403
+ }
404
+ break;
405
+ default: console.warn(`Unsupported alert channel: ${e.type}`);
406
+ }
407
+ }
408
+ formatValue(e, t) {
409
+ switch (t) {
410
+ case "bytes": return this.formatBytes(e);
411
+ case "ms": return `${e.toFixed(2)}ms`;
412
+ case "score": return e.toFixed(3);
413
+ case "percent": return `${e.toFixed(1)}%`;
414
+ default: return e.toString();
415
+ }
416
+ }
417
+ formatBytes(e) {
418
+ return e >= 1024 * 1024 ? `${(e / 1024 / 1024).toFixed(2)}MB` : e >= 1024 ? `${(e / 1024).toFixed(2)}KB` : `${e}B`;
419
+ }
420
+ getUnitDisplay(e) {
421
+ return {
422
+ bytes: "bytes",
423
+ ms: "milliseconds",
424
+ score: "score",
425
+ percent: "percent"
426
+ }[e] || e;
427
+ }
428
+ addBudget(e) {
429
+ this.budgets.set(e.name, e);
430
+ }
431
+ removeBudget(e) {
432
+ this.budgets.delete(e);
433
+ }
434
+ updateBudget(e, t) {
435
+ let n = this.budgets.get(e);
436
+ n && this.budgets.set(e, {
437
+ ...n,
438
+ ...t
439
+ });
440
+ }
441
+ getBudgets() {
442
+ return Array.from(this.budgets.values());
443
+ }
444
+ getViolations(e) {
445
+ return e ? this.violations.filter((t) => t.timestamp >= e) : [...this.violations];
446
+ }
447
+ clearViolations() {
448
+ this.violations = [];
449
+ }
450
+ getViolationSummary() {
451
+ let e = {}, t = {};
452
+ return this.violations.forEach((n) => {
453
+ let r = n.budget.category, i = n.budget.severity;
454
+ e[r] = (e[r] || 0) + 1, t[i] = (t[i] || 0) + 1;
455
+ }), {
456
+ total: this.violations.length,
457
+ byCategory: e,
458
+ bySeverity: t
459
+ };
460
+ }
461
+ }, _e = new R(), z = {
462
+ preloadStrategy: "metadata",
463
+ adaptiveBitrate: !0,
464
+ maxPreloadSize: 2 * 1024 * 1024,
465
+ networkThresholds: {
466
+ "2g": {
467
+ maxBitrate: 128,
468
+ preload: !1
469
+ },
470
+ "3g": {
471
+ maxBitrate: 500,
472
+ preload: !1
473
+ },
474
+ "4g": {
475
+ maxBitrate: 2e3,
476
+ preload: !0
477
+ },
478
+ "5g": {
479
+ maxBitrate: 1e4,
480
+ preload: !0
481
+ }
482
+ },
483
+ bufferSize: 10,
484
+ enableServiceWorker: !0
485
+ }, B = class {
486
+ constructor() {
487
+ if (t(this, "connection", void 0), t(this, "listeners", /* @__PURE__ */ new Set()), t(this, "currentInfo", void 0), typeof window > "u" || typeof navigator > "u") {
488
+ this.connection = null, this.currentInfo = {
489
+ effectiveType: "unknown",
490
+ downlink: 0,
491
+ rtt: 0,
492
+ saveData: !1,
493
+ isOnline: !0
494
+ };
495
+ return;
496
+ }
497
+ this.connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection, this.currentInfo = this.getNetworkInfo(), this.initializeListeners();
498
+ }
499
+ getNetworkInfo() {
500
+ if (typeof navigator > "u") return {
501
+ effectiveType: "unknown",
502
+ downlink: 0,
503
+ rtt: 0,
504
+ saveData: !1,
505
+ isOnline: !0
506
+ };
507
+ let e = navigator.onLine;
508
+ return this.connection ? {
509
+ effectiveType: this.connection.effectiveType || "unknown",
510
+ downlink: this.connection.downlink || 0,
511
+ rtt: this.connection.rtt || 0,
512
+ saveData: this.connection.saveData || !1,
513
+ isOnline: e
514
+ } : {
515
+ effectiveType: "unknown",
516
+ downlink: 0,
517
+ rtt: 0,
518
+ saveData: !1,
519
+ isOnline: e
520
+ };
521
+ }
522
+ initializeListeners() {
523
+ typeof window > "u" || (this.connection && this.connection.addEventListener("change", this.handleNetworkChange.bind(this)), window.addEventListener("online", this.handleNetworkChange.bind(this)), window.addEventListener("offline", this.handleNetworkChange.bind(this)));
524
+ }
525
+ handleNetworkChange() {
526
+ let e = this.getNetworkInfo();
527
+ this.currentInfo = e, this.listeners.forEach((t) => t(e));
528
+ }
529
+ getCurrentNetworkInfo() {
530
+ return { ...this.currentInfo };
531
+ }
532
+ subscribe(e) {
533
+ return this.listeners.add(e), () => this.listeners.delete(e);
534
+ }
535
+ async estimateBandwidth() {
536
+ if (this.connection && this.connection.downlink) return this.connection.downlink * 1e3;
537
+ try {
538
+ let e = performance.now(), t = await (await fetch("/api/bandwidth-test?size=100kb")).blob(), n = (performance.now() - e) / 1e3;
539
+ return t.size * 8 / n / 1e3;
540
+ } catch (e) {
541
+ return console.warn("Bandwidth estimation failed:", e), 1e3;
542
+ }
543
+ }
544
+ }, V = class {
545
+ constructor(e = {}) {
546
+ t(this, "config", void 0), t(this, "networkMonitor", void 0), t(this, "loadingMetrics", /* @__PURE__ */ new Map()), t(this, "preloadCache", /* @__PURE__ */ new Map()), this.config = {
547
+ ...z,
548
+ ...e
549
+ }, this.networkMonitor = new B(), this.initializeNetworkMonitoring();
550
+ }
551
+ initializeNetworkMonitoring() {
552
+ this.networkMonitor.subscribe((e) => {
553
+ this.handleNetworkChange(e);
554
+ });
555
+ }
556
+ handleNetworkChange(e) {
557
+ console.log("Network changed:", e), this.config.adaptiveBitrate && this.adjustQualityForNetwork(e), (e.effectiveType === "2g" || e.saveData) && this.clearPreloadCache();
558
+ }
559
+ async optimizeMediaLoading(e, t, n = {}) {
560
+ let r = performance.now(), i = this.networkMonitor.getCurrentNetworkInfo(), a = {
561
+ loadStartTime: r,
562
+ bytesLoaded: 0,
563
+ loadSpeed: 0,
564
+ networkType: i.effectiveType,
565
+ quality: n.quality || "auto",
566
+ bufferHealth: 0,
567
+ stallsCount: 0,
568
+ stallsDuration: 0
569
+ };
570
+ this.loadingMetrics.set(e, a);
571
+ try {
572
+ let r = this.chooseLoadingStrategy(i, n);
573
+ return r.shouldPreload && await this.preloadMedia(e, r.preloadAmount), t.preload = r.preloadAttribute, this.monitorLoadingProgress(t, a), this.config.adaptiveBitrate && r.suggestedQuality && this.applyQualitySettings(t, r.suggestedQuality), a;
574
+ } catch (e) {
575
+ return console.error("Media loading optimization failed:", e), a;
576
+ }
577
+ }
578
+ chooseLoadingStrategy(e, t) {
579
+ let n = e.effectiveType === "unknown" ? "4g" : e.effectiveType, r = this.config.networkThresholds[n] || this.config.networkThresholds["4g"];
580
+ return {
581
+ shouldPreload: t.preload !== !1 && r.preload && !e.saveData,
582
+ preloadAmount: e.saveData ? 0 : this.config.maxPreloadSize,
583
+ preloadAttribute: this.getPreloadAttribute(e),
584
+ suggestedQuality: this.getSuggestedQuality(e, r.maxBitrate),
585
+ bufferTarget: this.getBufferTarget(e)
586
+ };
587
+ }
588
+ getPreloadAttribute(e) {
589
+ return e.saveData || e.effectiveType === "2g" ? "none" : e.effectiveType === "3g" ? "metadata" : this.config.preloadStrategy;
590
+ }
591
+ getSuggestedQuality(e, t) {
592
+ let n = e.downlink * 1e3;
593
+ return n >= t * 2 ? "high" : n >= t ? "medium" : "low";
594
+ }
595
+ getBufferTarget(e) {
596
+ switch (e.effectiveType) {
597
+ case "2g": return 2;
598
+ case "3g": return 5;
599
+ case "4g": return this.config.bufferSize;
600
+ case "5g": return this.config.bufferSize * 1.5;
601
+ default: return this.config.bufferSize;
602
+ }
603
+ }
604
+ async preloadMedia(e, t) {
605
+ if (this.preloadCache.has(e)) return;
606
+ let n = this.fetchWithProgress(e, t);
607
+ this.preloadCache.set(e, n);
608
+ try {
609
+ await n;
610
+ } catch (t) {
611
+ console.warn(`Preload failed for ${e}:`, t), this.preloadCache.delete(e);
612
+ }
613
+ }
614
+ async fetchWithProgress(e, t) {
615
+ let n = await fetch(e, { headers: { Range: `bytes=0-${t - 1}` } });
616
+ if (!n.ok) throw Error(`Failed to preload: ${n.status}`);
617
+ let r = n.body?.getReader();
618
+ if (!r) throw Error("Response body not readable");
619
+ let i = [], a = 0;
620
+ try {
621
+ for (; a < t;) {
622
+ let { done: e, value: t } = await r.read();
623
+ if (e) break;
624
+ i.push(t), a += t.length;
625
+ }
626
+ } finally {
627
+ r.releaseLock();
628
+ }
629
+ return new Blob(i);
630
+ }
631
+ monitorLoadingProgress(e, t) {
632
+ let n = null, r = () => {
633
+ if (e.buffered.length > 0) {
634
+ let n = e.buffered.end(e.buffered.length - 1);
635
+ t.bufferHealth = Math.min((n - e.currentTime) / this.config.bufferSize, 1);
636
+ }
637
+ }, i = () => {
638
+ t.firstByteTime = performance.now();
639
+ }, a = () => {
640
+ t.loadCompleteTime = performance.now(), t.totalLoadTime = t.loadCompleteTime - t.loadStartTime, t.totalLoadTime && t.bytesLoaded > 0 && (t.loadSpeed = t.bytesLoaded / (t.totalLoadTime / 1e3));
641
+ }, o = () => {
642
+ n === null && (n = performance.now(), t.stallsCount++);
643
+ }, s = () => {
644
+ n !== null && (t.stallsDuration += performance.now() - n, n = null), r();
645
+ }, c = () => {
646
+ e.buffered.length > 0 && (t.bytesLoaded = e.buffered.end(0) * 1e3), r();
647
+ };
648
+ e.addEventListener("loadstart", i), e.addEventListener("canplay", a), e.addEventListener("waiting", o), e.addEventListener("playing", s), e.addEventListener("progress", c), setTimeout(() => {
649
+ e.removeEventListener("loadstart", i), e.removeEventListener("canplay", a), e.removeEventListener("waiting", o), e.removeEventListener("playing", s), e.removeEventListener("progress", c);
650
+ }, 300 * 1e3);
651
+ }
652
+ applyQualitySettings(e, t) {
653
+ console.log(`Applying quality setting: ${t} to`, e);
654
+ }
655
+ adjustQualityForNetwork(e) {
656
+ console.log("Adjusting quality for network conditions:", e.effectiveType);
657
+ }
658
+ clearPreloadCache() {
659
+ this.preloadCache.clear();
660
+ }
661
+ getLoadingMetrics(e) {
662
+ return this.loadingMetrics.get(e);
663
+ }
664
+ getAllMetrics() {
665
+ return Array.from(this.loadingMetrics.values());
666
+ }
667
+ getAverageLoadingTime() {
668
+ let e = this.getAllMetrics().filter((e) => e.totalLoadTime !== void 0);
669
+ return e.length === 0 ? 0 : e.reduce((e, t) => e + (t.totalLoadTime || 0), 0) / e.length;
670
+ }
671
+ getNetworkPerformanceStats() {
672
+ let e = /* @__PURE__ */ new Map();
673
+ return this.getAllMetrics().forEach((t) => {
674
+ let n = t.networkType;
675
+ e.has(n) || e.set(n, []), e.get(n).push(t);
676
+ }), Array.from(e.entries()).map(([e, t]) => ({
677
+ networkType: e,
678
+ avgLoadTime: t.reduce((e, t) => e + (t.totalLoadTime || 0), 0) / t.length,
679
+ avgStalls: t.reduce((e, t) => e + t.stallsCount, 0) / t.length,
680
+ avgBufferHealth: t.reduce((e, t) => e + t.bufferHealth, 0) / t.length
681
+ }));
682
+ }
683
+ }, H = new V();
684
+ function ve(e) {
685
+ let [t] = D.useState(() => e ? new V(e) : H), [n, r] = D.useState(null), [i, a] = D.useState([]);
686
+ return D.useEffect(() => {
687
+ let e = t.networkMonitor.subscribe(r);
688
+ r(t.networkMonitor.getCurrentNetworkInfo());
689
+ let n = setInterval(() => {
690
+ a(t.getAllMetrics());
691
+ }, 1e3);
692
+ return () => {
693
+ e(), clearInterval(n);
694
+ };
695
+ }, [t]), {
696
+ networkInfo: n,
697
+ loadingMetrics: i,
698
+ optimizeLoading: D.useCallback((e, n, r) => t.optimizeMediaLoading(e, n, r), [t]),
699
+ averageLoadTime: t.getAverageLoadingTime(),
700
+ networkStats: t.getNetworkPerformanceStats()
701
+ };
563
702
  }
564
- const ne = new O(), z = {
565
- preloadStrategy: "metadata",
566
- adaptiveBitrate: !0,
567
- maxPreloadSize: 2 * 1024 * 1024,
568
- // 2MB
569
- networkThresholds: {
570
- "2g": { maxBitrate: 128, preload: !1 },
571
- // 128 kbps
572
- "3g": { maxBitrate: 500, preload: !1 },
573
- // 500 kbps
574
- "4g": { maxBitrate: 2e3, preload: !0 },
575
- // 2 Mbps
576
- "5g": { maxBitrate: 1e4, preload: !0 }
577
- // 10 Mbps
578
- },
579
- bufferSize: 10,
580
- // 10 seconds
581
- enableServiceWorker: !0
582
- };
583
- class _ {
584
- constructor() {
585
- u(this, "connection");
586
- u(this, "listeners", /* @__PURE__ */ new Set());
587
- u(this, "currentInfo");
588
- if (typeof window > "u" || typeof navigator > "u") {
589
- this.connection = null, this.currentInfo = {
590
- effectiveType: "unknown",
591
- downlink: 0,
592
- rtt: 0,
593
- saveData: !1,
594
- isOnline: !0
595
- };
596
- return;
597
- }
598
- this.connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection, this.currentInfo = this.getNetworkInfo(), this.initializeListeners();
599
- }
600
- getNetworkInfo() {
601
- if (typeof navigator > "u")
602
- return {
603
- effectiveType: "unknown",
604
- downlink: 0,
605
- rtt: 0,
606
- saveData: !1,
607
- isOnline: !0
608
- };
609
- const e = navigator.onLine;
610
- return this.connection ? {
611
- effectiveType: this.connection.effectiveType || "unknown",
612
- downlink: this.connection.downlink || 0,
613
- rtt: this.connection.rtt || 0,
614
- saveData: this.connection.saveData || !1,
615
- isOnline: e
616
- } : {
617
- effectiveType: "unknown",
618
- downlink: 0,
619
- rtt: 0,
620
- saveData: !1,
621
- isOnline: e
622
- };
623
- }
624
- initializeListeners() {
625
- typeof window > "u" || (this.connection && this.connection.addEventListener("change", this.handleNetworkChange.bind(this)), window.addEventListener("online", this.handleNetworkChange.bind(this)), window.addEventListener("offline", this.handleNetworkChange.bind(this)));
626
- }
627
- handleNetworkChange() {
628
- const e = this.getNetworkInfo();
629
- this.currentInfo = e, this.listeners.forEach((t) => t(e));
630
- }
631
- getCurrentNetworkInfo() {
632
- return { ...this.currentInfo };
633
- }
634
- subscribe(e) {
635
- return this.listeners.add(e), () => this.listeners.delete(e);
636
- }
637
- // Estimate available bandwidth with fallback detection
638
- async estimateBandwidth() {
639
- if (this.connection && this.connection.downlink)
640
- return this.connection.downlink * 1e3;
641
- try {
642
- const e = performance.now(), n = await (await fetch("/api/bandwidth-test?size=100kb")).blob(), i = (performance.now() - e) / 1e3;
643
- return n.size * 8 / i / 1e3;
644
- } catch (e) {
645
- return console.warn("Bandwidth estimation failed:", e), 1e3;
646
- }
647
- }
648
- }
649
- class M {
650
- constructor(e = {}) {
651
- u(this, "config");
652
- u(this, "networkMonitor");
653
- u(this, "loadingMetrics", /* @__PURE__ */ new Map());
654
- u(this, "preloadCache", /* @__PURE__ */ new Map());
655
- this.config = { ...z, ...e }, this.networkMonitor = new _(), this.initializeNetworkMonitoring();
656
- }
657
- initializeNetworkMonitoring() {
658
- this.networkMonitor.subscribe((e) => {
659
- this.handleNetworkChange(e);
660
- });
661
- }
662
- handleNetworkChange(e) {
663
- console.log("Network changed:", e), this.config.adaptiveBitrate && this.adjustQualityForNetwork(e), (e.effectiveType === "2g" || e.saveData) && this.clearPreloadCache();
664
- }
665
- // Optimize media loading based on network conditions
666
- async optimizeMediaLoading(e, t, r = {}) {
667
- const n = performance.now(), s = this.networkMonitor.getCurrentNetworkInfo(), i = {
668
- loadStartTime: n,
669
- bytesLoaded: 0,
670
- loadSpeed: 0,
671
- networkType: s.effectiveType,
672
- quality: r.quality || "auto",
673
- bufferHealth: 0,
674
- stallsCount: 0,
675
- stallsDuration: 0
676
- };
677
- this.loadingMetrics.set(e, i);
678
- try {
679
- const a = this.chooseLoadingStrategy(s, r);
680
- return a.shouldPreload && await this.preloadMedia(e, a.preloadAmount), t.preload = a.preloadAttribute, this.monitorLoadingProgress(t, i), this.config.adaptiveBitrate && a.suggestedQuality && this.applyQualitySettings(t, a.suggestedQuality), i;
681
- } catch (a) {
682
- return console.error("Media loading optimization failed:", a), i;
683
- }
684
- }
685
- chooseLoadingStrategy(e, t) {
686
- const r = e.effectiveType === "unknown" ? "4g" : e.effectiveType, n = this.config.networkThresholds[r] || this.config.networkThresholds["4g"];
687
- return {
688
- shouldPreload: t.preload !== !1 && n.preload && !e.saveData,
689
- preloadAmount: e.saveData ? 0 : this.config.maxPreloadSize,
690
- preloadAttribute: this.getPreloadAttribute(e),
691
- suggestedQuality: this.getSuggestedQuality(e, n.maxBitrate),
692
- bufferTarget: this.getBufferTarget(e)
693
- };
694
- }
695
- getPreloadAttribute(e) {
696
- return e.saveData || e.effectiveType === "2g" ? "none" : e.effectiveType === "3g" ? "metadata" : this.config.preloadStrategy;
697
- }
698
- getSuggestedQuality(e, t) {
699
- const r = e.downlink * 1e3;
700
- return r >= t * 2 ? "high" : r >= t ? "medium" : "low";
701
- }
702
- getBufferTarget(e) {
703
- switch (e.effectiveType) {
704
- case "2g":
705
- return 2;
706
- // 2 seconds
707
- case "3g":
708
- return 5;
709
- // 5 seconds
710
- case "4g":
711
- return this.config.bufferSize;
712
- case "5g":
713
- return this.config.bufferSize * 1.5;
714
- default:
715
- return this.config.bufferSize;
716
- }
717
- }
718
- // Preload media content
719
- async preloadMedia(e, t) {
720
- if (this.preloadCache.has(e))
721
- return;
722
- const r = this.fetchWithProgress(e, t);
723
- this.preloadCache.set(e, r);
724
- try {
725
- await r;
726
- } catch (n) {
727
- console.warn(`Preload failed for ${e}:`, n), this.preloadCache.delete(e);
728
- }
729
- }
730
- async fetchWithProgress(e, t) {
731
- const r = await fetch(e, {
732
- headers: {
733
- Range: `bytes=0-${t - 1}`
734
- // Limit preload size
735
- }
736
- });
737
- if (!r.ok)
738
- throw new Error(`Failed to preload: ${r.status}`);
739
- const n = r.body?.getReader();
740
- if (!n)
741
- throw new Error("Response body not readable");
742
- const s = [];
743
- let i = 0;
744
- try {
745
- for (; i < t; ) {
746
- const { done: a, value: c } = await n.read();
747
- if (a) break;
748
- s.push(c), i += c.length;
749
- }
750
- } finally {
751
- n.releaseLock();
752
- }
753
- return new Blob(s);
754
- }
755
- // Monitor loading progress and update metrics
756
- monitorLoadingProgress(e, t) {
757
- let r = null;
758
- const n = () => {
759
- if (e.buffered.length > 0) {
760
- const y = e.buffered.end(e.buffered.length - 1), w = e.currentTime;
761
- t.bufferHealth = Math.min((y - w) / this.config.bufferSize, 1);
762
- }
763
- }, s = () => {
764
- t.firstByteTime = performance.now();
765
- }, i = () => {
766
- t.loadCompleteTime = performance.now(), t.totalLoadTime = t.loadCompleteTime - t.loadStartTime, t.totalLoadTime && t.bytesLoaded > 0 && (t.loadSpeed = t.bytesLoaded / (t.totalLoadTime / 1e3));
767
- }, a = () => {
768
- r === null && (r = performance.now(), t.stallsCount++);
769
- }, c = () => {
770
- r !== null && (t.stallsDuration += performance.now() - r, r = null), n();
771
- }, g = () => {
772
- if (e.buffered.length > 0) {
773
- const y = e.buffered.end(0) * 1e3;
774
- t.bytesLoaded = y;
775
- }
776
- n();
777
- };
778
- e.addEventListener("loadstart", s), e.addEventListener("canplay", i), e.addEventListener("waiting", a), e.addEventListener("playing", c), e.addEventListener("progress", g), setTimeout(() => {
779
- e.removeEventListener("loadstart", s), e.removeEventListener("canplay", i), e.removeEventListener("waiting", a), e.removeEventListener("playing", c), e.removeEventListener("progress", g);
780
- }, 300 * 1e3);
781
- }
782
- // Apply quality settings (would integrate with HLS.js or similar)
783
- applyQualitySettings(e, t) {
784
- console.log(`Applying quality setting: ${t} to`, e);
785
- }
786
- adjustQualityForNetwork(e) {
787
- console.log("Adjusting quality for network conditions:", e.effectiveType);
788
- }
789
- // Clear preload cache to save memory
790
- clearPreloadCache() {
791
- this.preloadCache.clear();
792
- }
793
- // Get loading metrics for a specific media URL
794
- getLoadingMetrics(e) {
795
- return this.loadingMetrics.get(e);
796
- }
797
- // Get all loading metrics
798
- getAllMetrics() {
799
- return Array.from(this.loadingMetrics.values());
800
- }
801
- // Calculate average loading performance
802
- getAverageLoadingTime() {
803
- const t = this.getAllMetrics().filter((n) => n.totalLoadTime !== void 0);
804
- return t.length === 0 ? 0 : t.reduce((n, s) => n + (s.totalLoadTime || 0), 0) / t.length;
805
- }
806
- // Get network-specific performance stats
807
- getNetworkPerformanceStats() {
808
- const e = /* @__PURE__ */ new Map();
809
- return this.getAllMetrics().forEach((t) => {
810
- const r = t.networkType;
811
- e.has(r) || e.set(r, []), e.get(r).push(t);
812
- }), Array.from(e.entries()).map(([t, r]) => ({
813
- networkType: t,
814
- avgLoadTime: r.reduce((n, s) => n + (s.totalLoadTime || 0), 0) / r.length,
815
- avgStalls: r.reduce((n, s) => n + s.stallsCount, 0) / r.length,
816
- avgBufferHealth: r.reduce((n, s) => n + s.bufferHealth, 0) / r.length
817
- }));
818
- }
819
- }
820
- const V = new M();
821
- function oe(o) {
822
- const [e] = m.useState(
823
- () => o ? new M(o) : V
824
- ), [t, r] = m.useState(null), [n, s] = m.useState([]);
825
- m.useEffect(() => {
826
- const a = e.networkMonitor.subscribe(r);
827
- r(e.networkMonitor.getCurrentNetworkInfo());
828
- const c = setInterval(() => {
829
- s(e.getAllMetrics());
830
- }, 1e3);
831
- return () => {
832
- a(), clearInterval(c);
833
- };
834
- }, [e]);
835
- const i = m.useCallback(
836
- (a, c, g) => e.optimizeMediaLoading(a, c, g),
837
- [e]
838
- );
839
- return {
840
- networkInfo: t,
841
- loadingMetrics: n,
842
- optimizeLoading: i,
843
- averageLoadTime: e.getAverageLoadingTime(),
844
- networkStats: e.getNetworkPerformanceStats()
845
- };
846
- }
847
- class H {
848
- get(e) {
849
- try {
850
- const t = localStorage.getItem(`baroi-player-${e}`);
851
- return t ? JSON.parse(t) : null;
852
- } catch {
853
- return null;
854
- }
855
- }
856
- set(e, t) {
857
- try {
858
- localStorage.setItem(`baroi-player-${e}`, JSON.stringify(t));
859
- } catch (r) {
860
- console.warn("Failed to store data:", r);
861
- }
862
- }
863
- remove(e) {
864
- try {
865
- localStorage.removeItem(`baroi-player-${e}`);
866
- } catch (t) {
867
- console.warn("Failed to remove data:", t);
868
- }
869
- }
870
- clear() {
871
- try {
872
- Object.keys(localStorage).forEach((e) => {
873
- e.startsWith("baroi-player-") && localStorage.removeItem(e);
874
- });
875
- } catch (e) {
876
- console.warn("Failed to clear data:", e);
877
- }
878
- }
879
- }
880
- class j {
881
- track(e, t) {
882
- console.log("Analytics:", e, t);
883
- }
884
- identify(e, t) {
885
- console.log("Analytics identify:", e, t);
886
- }
887
- page(e, t) {
888
- console.log("Analytics page:", e, t);
889
- }
703
+ //#endregion
704
+ //#region src/core/providers/service-provider.tsx
705
+ var U = e(), ye = class {
706
+ get(e) {
707
+ try {
708
+ let t = localStorage.getItem(`baroi-player-${e}`);
709
+ return t ? JSON.parse(t) : null;
710
+ } catch {
711
+ return null;
712
+ }
713
+ }
714
+ set(e, t) {
715
+ try {
716
+ localStorage.setItem(`baroi-player-${e}`, JSON.stringify(t));
717
+ } catch (e) {
718
+ console.warn("Failed to store data:", e);
719
+ }
720
+ }
721
+ remove(e) {
722
+ try {
723
+ localStorage.removeItem(`baroi-player-${e}`);
724
+ } catch (e) {
725
+ console.warn("Failed to remove data:", e);
726
+ }
727
+ }
728
+ clear() {
729
+ try {
730
+ Object.keys(localStorage).forEach((e) => {
731
+ e.startsWith("baroi-player-") && localStorage.removeItem(e);
732
+ });
733
+ } catch (e) {
734
+ console.warn("Failed to clear data:", e);
735
+ }
736
+ }
737
+ }, be = class {
738
+ track(e, t) {
739
+ console.log("Analytics:", e, t);
740
+ }
741
+ identify(e, t) {
742
+ console.log("Analytics identify:", e, t);
743
+ }
744
+ page(e, t) {
745
+ console.log("Analytics page:", e, t);
746
+ }
747
+ }, W = O(null);
748
+ function G({ children: e, services: t = {} }) {
749
+ let n = j(() => {
750
+ let e = t.logger || new v("[BaroiPlayer]");
751
+ return {
752
+ eventBus: t.eventBus || new y(),
753
+ pluginRegistry: t.pluginRegistry || new _(e),
754
+ storage: t.storage || new ye(),
755
+ analytics: t.analytics || new be(),
756
+ logger: e
757
+ };
758
+ }, [t]);
759
+ return /* @__PURE__ */ (0, U.jsx)(W.Provider, {
760
+ value: n,
761
+ children: e
762
+ });
890
763
  }
891
- const L = $(null);
892
- function Y({ children: o, services: e = {} }) {
893
- const t = N(() => {
894
- const r = e.logger || new B("[BaroiPlayer]"), n = e.eventBus || new I(), s = e.pluginRegistry || new R(r), i = e.storage || new H(), a = e.analytics || new j();
895
- return {
896
- eventBus: n,
897
- pluginRegistry: s,
898
- storage: i,
899
- analytics: a,
900
- logger: r
901
- };
902
- }, [e]);
903
- return /* @__PURE__ */ f.jsx(L.Provider, { value: t, children: o });
764
+ function K() {
765
+ let e = A(W);
766
+ if (!e) throw Error("useServices must be used within ServiceProvider");
767
+ return e;
904
768
  }
905
- function p() {
906
- const o = F(L);
907
- if (!o)
908
- throw new Error("useServices must be used within ServiceProvider");
909
- return o;
769
+ function xe() {
770
+ return K().eventBus;
910
771
  }
911
- function se() {
912
- return p().eventBus;
772
+ function Se() {
773
+ return K().pluginRegistry;
913
774
  }
914
- function ie() {
915
- return p().pluginRegistry;
775
+ function Ce() {
776
+ return K().storage;
916
777
  }
917
- function ae() {
918
- return p().storage;
778
+ function we() {
779
+ return K().analytics;
919
780
  }
920
- function ce() {
921
- return p().analytics;
781
+ function Te() {
782
+ return K().logger;
922
783
  }
923
- function le() {
924
- return p().logger;
784
+ function Ee(e) {
785
+ return function(t) {
786
+ let n = K();
787
+ return /* @__PURE__ */ (0, U.jsx)(e, {
788
+ ...t,
789
+ services: n
790
+ });
791
+ };
925
792
  }
926
- function ue(o) {
927
- return function(t) {
928
- const r = p();
929
- return /* @__PURE__ */ f.jsx(o, { ...t, services: r });
930
- };
793
+ //#endregion
794
+ //#region src/core/utils.tsx
795
+ function q(e = {}) {
796
+ return function({ children: t }) {
797
+ return /* @__PURE__ */ (0, U.jsx)(G, {
798
+ services: e.services,
799
+ children: t
800
+ });
801
+ };
931
802
  }
932
- function de(o = {}) {
933
- return function({ children: t }) {
934
- return /* @__PURE__ */ f.jsx(Y, { services: o.services, children: t });
935
- };
936
- }
937
- const l = {
938
- SUBTITLES: "subtitles",
939
- PLAYLISTS: "playlists",
940
- ADVANCED_CONTROLS: "advanced_controls",
941
- ANALYTICS: "analytics",
942
- PICTURE_IN_PICTURE: "picture_in_picture",
943
- QUALITY_SELECTOR: "quality_selector",
944
- PLAYBACK_SPEED: "playback_speed",
945
- CHAPTERS: "chapters",
946
- THUMBNAILS: "thumbnails",
947
- KEYBOARD_SHORTCUTS: "keyboard_shortcuts"
948
- }, Q = {
949
- enabledFeatures: [l.SUBTITLES, l.ADVANCED_CONTROLS, l.KEYBOARD_SHORTCUTS],
950
- loadingStrategy: "lazy",
951
- fallbackTimeout: 5e3,
952
- retryAttempts: 3
953
- }, me = {
954
- // Subtitle system
955
- SubtitleSelector: h(
956
- () => import("./enhanced-components-B_l3cist.js").then((o) => o.g).then((o) => ({
957
- default: o.SubtitleSelector
958
- }))
959
- ),
960
- // Playlist functionality
961
- PlaylistManager: h(
962
- () => import("./enhanced-components-B_l3cist.js").then((o) => o.g).then((o) => ({
963
- default: o.SubtitleSelector
964
- }))
965
- // Use existing component as placeholder
966
- ),
967
- // Advanced controls
968
- QualitySelector: h(
969
- () => import("./enhanced-components-B_l3cist.js").then((o) => o.g).then((o) => ({
970
- default: o.QualitySelector
971
- }))
972
- ),
973
- PlaybackSpeedSelector: h(
974
- () => import("./enhanced-components-B_l3cist.js").then((o) => o.g).then((o) => ({
975
- default: o.PlaybackSpeedSelector
976
- }))
977
- ),
978
- ChaptersPanel: h(
979
- () => import("./enhanced-components-B_l3cist.js").then((o) => o.g).then((o) => ({
980
- default: o.ChaptersPanel
981
- }))
982
- ),
983
- PictureInPictureButton: h(
984
- () => import("./enhanced-components-B_l3cist.js").then((o) => o.g).then((o) => ({
985
- default: o.PictureInPictureButton
986
- }))
987
- ),
988
- // Analytics
989
- AnalyticsTracker: h(
990
- () => import("./enhanced-components-B_l3cist.js").then((o) => o.g).then((o) => ({
991
- default: o.SubtitleSelector
992
- }))
993
- // Use existing component as placeholder
994
- )
803
+ //#endregion
804
+ //#region src/core/progressive-loading.tsx
805
+ var J = {
806
+ SUBTITLES: "subtitles",
807
+ PLAYLISTS: "playlists",
808
+ ADVANCED_CONTROLS: "advanced_controls",
809
+ ANALYTICS: "analytics",
810
+ PICTURE_IN_PICTURE: "picture_in_picture",
811
+ QUALITY_SELECTOR: "quality_selector",
812
+ PLAYBACK_SPEED: "playback_speed",
813
+ CHAPTERS: "chapters",
814
+ THUMBNAILS: "thumbnails",
815
+ KEYBOARD_SHORTCUTS: "keyboard_shortcuts"
816
+ }, Y = {
817
+ enabledFeatures: [
818
+ J.SUBTITLES,
819
+ J.ADVANCED_CONTROLS,
820
+ J.KEYBOARD_SHORTCUTS
821
+ ],
822
+ loadingStrategy: "lazy",
823
+ fallbackTimeout: 5e3,
824
+ retryAttempts: 3
825
+ }, De = {
826
+ SubtitleSelector: k(() => import("./enhanced-components-BwjBqSA1.js").then((e) => e.f).then((e) => ({ default: e.SubtitleSelector }))),
827
+ PlaylistManager: k(() => import("./enhanced-components-BwjBqSA1.js").then((e) => e.f).then((e) => ({ default: e.SubtitleSelector }))),
828
+ QualitySelector: k(() => import("./enhanced-components-BwjBqSA1.js").then((e) => e.f).then((e) => ({ default: e.QualitySelector }))),
829
+ PlaybackSpeedSelector: k(() => import("./enhanced-components-BwjBqSA1.js").then((e) => e.f).then((e) => ({ default: e.PlaybackSpeedSelector }))),
830
+ ChaptersPanel: k(() => import("./enhanced-components-BwjBqSA1.js").then((e) => e.f).then((e) => ({ default: e.ChaptersPanel }))),
831
+ PictureInPictureButton: k(() => import("./enhanced-components-BwjBqSA1.js").then((e) => e.f).then((e) => ({ default: e.PictureInPictureButton }))),
832
+ AnalyticsTracker: k(() => import("./enhanced-components-BwjBqSA1.js").then((e) => e.f).then((e) => ({ default: e.SubtitleSelector })))
833
+ }, X = class {
834
+ static async isSupported(e) {
835
+ if (this.cache.has(e)) return this.cache.get(e);
836
+ let t = await this.checkFeatureSupport(e);
837
+ return this.cache.set(e, t), t;
838
+ }
839
+ static async checkFeatureSupport(e) {
840
+ if (typeof window > "u" || typeof document > "u") return !0;
841
+ switch (e) {
842
+ case J.SUBTITLES: return "TextTrack" in window;
843
+ case J.PICTURE_IN_PICTURE: return "pictureInPictureEnabled" in document;
844
+ case J.ADVANCED_CONTROLS: return !0;
845
+ case J.PLAYLISTS: return "MediaSession" in window;
846
+ case J.ANALYTICS: return "IntersectionObserver" in window;
847
+ case J.QUALITY_SELECTOR: return "MediaSource" in window;
848
+ case J.PLAYBACK_SPEED: return !0;
849
+ case J.CHAPTERS: return "TextTrack" in window;
850
+ case J.THUMBNAILS: return "OffscreenCanvas" in window || "canvas" in document.createElement("canvas");
851
+ case J.KEYBOARD_SHORTCUTS: return "KeyboardEvent" in window;
852
+ default: return !1;
853
+ }
854
+ }
995
855
  };
996
- class E {
997
- static async isSupported(e) {
998
- if (this.cache.has(e))
999
- return this.cache.get(e);
1000
- const t = await this.checkFeatureSupport(e);
1001
- return this.cache.set(e, t), t;
1002
- }
1003
- static async checkFeatureSupport(e) {
1004
- if (typeof window > "u" || typeof document > "u")
1005
- return !0;
1006
- switch (e) {
1007
- case l.SUBTITLES:
1008
- return "TextTrack" in window;
1009
- case l.PICTURE_IN_PICTURE:
1010
- return "pictureInPictureEnabled" in document;
1011
- case l.ADVANCED_CONTROLS:
1012
- return !0;
1013
- // Always supported
1014
- case l.PLAYLISTS:
1015
- return "MediaSession" in window;
1016
- case l.ANALYTICS:
1017
- return "IntersectionObserver" in window;
1018
- case l.QUALITY_SELECTOR:
1019
- return "MediaSource" in window;
1020
- case l.PLAYBACK_SPEED:
1021
- return !0;
1022
- // HTML5 video supports this
1023
- case l.CHAPTERS:
1024
- return "TextTrack" in window;
1025
- case l.THUMBNAILS:
1026
- return "OffscreenCanvas" in window || "canvas" in document.createElement("canvas");
1027
- case l.KEYBOARD_SHORTCUTS:
1028
- return "KeyboardEvent" in window;
1029
- default:
1030
- return !1;
1031
- }
1032
- }
1033
- }
1034
- u(E, "cache", /* @__PURE__ */ new Map());
1035
- class W {
1036
- constructor(e = {}) {
1037
- u(this, "config");
1038
- u(this, "loadedFeatures", /* @__PURE__ */ new Set());
1039
- u(this, "loadingPromises", /* @__PURE__ */ new Map());
1040
- this.config = { ...Q, ...e };
1041
- }
1042
- async loadFeature(e) {
1043
- if (!this.config.enabledFeatures.includes(e))
1044
- return null;
1045
- if (this.loadedFeatures.has(e))
1046
- return this.getLoadedFeature(e);
1047
- if (this.loadingPromises.has(e))
1048
- return this.loadingPromises.get(e);
1049
- if (!await E.isSupported(e))
1050
- return console.warn(`Feature ${e} is not supported in this browser`), null;
1051
- const r = this.loadWithRetry(e);
1052
- this.loadingPromises.set(e, r);
1053
- try {
1054
- const n = await r;
1055
- return this.loadedFeatures.add(e), n;
1056
- } catch (n) {
1057
- return console.error(`Failed to load feature ${e}:`, n), this.loadingPromises.delete(e), null;
1058
- }
1059
- }
1060
- async loadWithRetry(e, t = 1) {
1061
- try {
1062
- return await this.loadFeatureModule(e);
1063
- } catch (r) {
1064
- if (t < this.config.retryAttempts)
1065
- return console.warn(
1066
- `Loading feature ${e} failed, retrying (${t}/${this.config.retryAttempts})`
1067
- ), await new Promise((n) => setTimeout(n, 1e3 * t)), this.loadWithRetry(e, t + 1);
1068
- throw r;
1069
- }
1070
- }
1071
- async loadFeatureModule(e) {
1072
- switch (e) {
1073
- case l.SUBTITLES:
1074
- return import("./hooks-Bpi-jDiO.js").then((t) => t.v);
1075
- case l.PLAYLISTS:
1076
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1077
- // Use existing features
1078
- case l.ADVANCED_CONTROLS:
1079
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1080
- case l.ANALYTICS:
1081
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1082
- // Use existing features
1083
- case l.PICTURE_IN_PICTURE:
1084
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1085
- // Use existing features
1086
- case l.QUALITY_SELECTOR:
1087
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1088
- // Use existing features
1089
- case l.PLAYBACK_SPEED:
1090
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1091
- // Use existing features
1092
- case l.CHAPTERS:
1093
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1094
- // Use existing features
1095
- case l.THUMBNAILS:
1096
- return import("./enhanced-components-B_l3cist.js").then((t) => t.g);
1097
- // Use existing features
1098
- case l.KEYBOARD_SHORTCUTS:
1099
- return import("./hooks-Bpi-jDiO.js").then((t) => t.t);
1100
- default:
1101
- throw new Error(`Unknown feature: ${e}`);
1102
- }
1103
- }
1104
- getLoadedFeature(e) {
1105
- return this.loadingPromises.get(e);
1106
- }
1107
- // Preload features for faster access
1108
- async preloadFeatures(e = this.config.enabledFeatures) {
1109
- const t = e.map((r) => this.loadFeature(r));
1110
- await Promise.allSettled(t);
1111
- }
1112
- // Get loading state
1113
- getLoadingState() {
1114
- return {
1115
- loaded: Array.from(this.loadedFeatures),
1116
- loading: Array.from(this.loadingPromises.keys()),
1117
- enabled: this.config.enabledFeatures
1118
- };
1119
- }
1120
- }
1121
- const b = new W();
1122
- function K(o) {
1123
- const [e, t] = m.useState(null), [r, n] = m.useState(!1), [s, i] = m.useState(null), a = m.useCallback(async () => {
1124
- if (!(r || e)) {
1125
- n(!0), i(null);
1126
- try {
1127
- const c = await b.loadFeature(o);
1128
- t(c);
1129
- } catch (c) {
1130
- i(c);
1131
- } finally {
1132
- n(!1);
1133
- }
1134
- }
1135
- }, [o, r, e]);
1136
- return m.useEffect(() => {
1137
- b.config.loadingStrategy === "immediate" && a();
1138
- }, [a]), {
1139
- feature: e,
1140
- loading: r,
1141
- error: s,
1142
- load: a
1143
- };
856
+ t(X, "cache", /* @__PURE__ */ new Map());
857
+ var Z = class {
858
+ constructor(e = {}) {
859
+ t(this, "config", void 0), t(this, "loadedFeatures", /* @__PURE__ */ new Set()), t(this, "loadingPromises", /* @__PURE__ */ new Map()), this.config = {
860
+ ...Y,
861
+ ...e
862
+ };
863
+ }
864
+ async loadFeature(e) {
865
+ if (!this.config.enabledFeatures.includes(e)) return null;
866
+ if (this.loadedFeatures.has(e)) return this.getLoadedFeature(e);
867
+ if (this.loadingPromises.has(e)) return this.loadingPromises.get(e);
868
+ if (!await X.isSupported(e)) return console.warn(`Feature ${e} is not supported in this browser`), null;
869
+ let t = this.loadWithRetry(e);
870
+ this.loadingPromises.set(e, t);
871
+ try {
872
+ let n = await t;
873
+ return this.loadedFeatures.add(e), n;
874
+ } catch (t) {
875
+ return console.error(`Failed to load feature ${e}:`, t), this.loadingPromises.delete(e), null;
876
+ }
877
+ }
878
+ async loadWithRetry(e, t = 1) {
879
+ try {
880
+ return await this.loadFeatureModule(e);
881
+ } catch (n) {
882
+ if (t < this.config.retryAttempts) return console.warn(`Loading feature ${e} failed, retrying (${t}/${this.config.retryAttempts})`), await new Promise((e) => setTimeout(e, 1e3 * t)), this.loadWithRetry(e, t + 1);
883
+ throw n;
884
+ }
885
+ }
886
+ async loadFeatureModule(e) {
887
+ switch (e) {
888
+ case J.SUBTITLES: return import("./hooks-B-IIWPJr.js").then((e) => e.d);
889
+ case J.PLAYLISTS: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
890
+ case J.ADVANCED_CONTROLS: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
891
+ case J.ANALYTICS: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
892
+ case J.PICTURE_IN_PICTURE: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
893
+ case J.QUALITY_SELECTOR: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
894
+ case J.PLAYBACK_SPEED: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
895
+ case J.CHAPTERS: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
896
+ case J.THUMBNAILS: return import("./enhanced-components-BwjBqSA1.js").then((e) => e.f);
897
+ case J.KEYBOARD_SHORTCUTS: return import("./hooks-B-IIWPJr.js").then((e) => e.b);
898
+ default: throw Error(`Unknown feature: ${e}`);
899
+ }
900
+ }
901
+ getLoadedFeature(e) {
902
+ return this.loadingPromises.get(e);
903
+ }
904
+ async preloadFeatures(e = this.config.enabledFeatures) {
905
+ let t = e.map((e) => this.loadFeature(e));
906
+ await Promise.allSettled(t);
907
+ }
908
+ getLoadingState() {
909
+ return {
910
+ loaded: Array.from(this.loadedFeatures),
911
+ loading: Array.from(this.loadingPromises.keys()),
912
+ enabled: this.config.enabledFeatures
913
+ };
914
+ }
915
+ }, Q = new Z();
916
+ function $(e) {
917
+ let [t, n] = D.useState(null), [r, i] = D.useState(!1), [a, o] = D.useState(null), s = D.useCallback(async () => {
918
+ if (!(r || t)) {
919
+ i(!0), o(null);
920
+ try {
921
+ let t = await Q.loadFeature(e);
922
+ n(t);
923
+ } catch (e) {
924
+ o(e);
925
+ } finally {
926
+ i(!1);
927
+ }
928
+ }
929
+ }, [
930
+ e,
931
+ r,
932
+ t
933
+ ]);
934
+ return D.useEffect(() => {
935
+ Q.config.loadingStrategy === "immediate" && s();
936
+ }, [s]), {
937
+ feature: t,
938
+ loading: r,
939
+ error: a,
940
+ load: s
941
+ };
1144
942
  }
1145
- function ge(o, e, t) {
1146
- return function(n) {
1147
- const { feature: s, loading: i, error: a } = K(e);
1148
- if (i)
1149
- return /* @__PURE__ */ f.jsx("div", { className: "h-8 animate-pulse rounded bg-gray-200" });
1150
- if (a || !s) {
1151
- const c = t;
1152
- return c ? /* @__PURE__ */ f.jsx(c, { ...n }) : null;
1153
- }
1154
- return /* @__PURE__ */ f.jsx(o, { ...n });
1155
- };
943
+ function Oe(e, t, n) {
944
+ return function(r) {
945
+ let { feature: i, loading: a, error: o } = $(t);
946
+ if (a) return /* @__PURE__ */ (0, U.jsx)("div", { className: "h-8 animate-pulse rounded bg-gray-200" });
947
+ if (o || !i) {
948
+ let e = n;
949
+ return e ? /* @__PURE__ */ (0, U.jsx)(e, { ...r }) : null;
950
+ }
951
+ return /* @__PURE__ */ (0, U.jsx)(e, { ...r });
952
+ };
1156
953
  }
1157
- const he = "1.0.0";
1158
- export {
1159
- ye as AnalyticsPlugin,
1160
- we as BasePlugin,
1161
- he as CORE_ARCHITECTURE_VERSION,
1162
- B as ConsolePluginLogger,
1163
- Ie as EVENT_SYSTEM_VERSION,
1164
- I as EventBus,
1165
- Ne as EventDelegator,
1166
- l as FEATURES,
1167
- E as FeatureDetector,
1168
- M as MediaLoadingOptimizer,
1169
- $e as MiddlewareBuilder,
1170
- _ as NetworkMonitor,
1171
- Te as PLUGIN_SYSTEM_VERSION,
1172
- P as PerformanceBenchmark,
1173
- O as PerformanceBudgetMonitor,
1174
- Ge as PerformanceDashboard,
1175
- Xe as PerformanceMonitor,
1176
- x as PerformanceRegressionDetector,
1177
- U as PerformanceTestFramework,
1178
- Se as PluginConflictError,
1179
- ve as PluginDependencyError,
1180
- be as PluginDevelopmentHelpers,
1181
- Pe as PluginError,
1182
- Me as PluginPerformanceMonitor,
1183
- R as PluginRegistry,
1184
- Le as PluginStorage,
1185
- Ee as PluginValidator,
1186
- W as ProgressiveLoader,
1187
- Y as ServiceProvider,
1188
- Fe as commonMiddlewares,
1189
- Ce as createAnalyticsPlugin,
1190
- de as createArchitecture,
1191
- xe as createMiddleware,
1192
- ke as createPlugin,
1193
- Ue as defaultEventBus,
1194
- z as defaultMediaLoadingConfig,
1195
- D as defaultPerformanceBudgets,
1196
- Ae as defaultPerformanceMonitor,
1197
- Be as defaultPluginLogger,
1198
- Q as defaultProgressiveConfig,
1199
- Ze as defaultThresholds,
1200
- De as eventMiddlewares,
1201
- me as lazyComponents,
1202
- V as mediaLoadingOptimizer,
1203
- v as performanceBenchmark,
1204
- ne as performanceBudgetMonitor,
1205
- et as performanceMonitor,
1206
- re as performanceTestFramework,
1207
- te as performanceTestUtils,
1208
- b as progressiveLoader,
1209
- ce as useAnalytics,
1210
- Oe as useConditionalEventListener,
1211
- ze as useEventBus,
1212
- _e as useEventDebugger,
1213
- Ve as useEventEffect,
1214
- He as useEventEmitter,
1215
- je as useEventHandlers,
1216
- Ye as useEventHistory,
1217
- Qe as useEventListener,
1218
- We as useEventMetrics,
1219
- Ke as useEventOnce,
1220
- Je as useEventState,
1221
- le as useLogger,
1222
- oe as useMediaLoadingOptimizer,
1223
- tt as usePerformanceMonitor,
1224
- ie as usePluginRegistry,
1225
- K as useProgressiveFeature,
1226
- se as useServiceEventBus,
1227
- p as useServices,
1228
- ae as useStorage,
1229
- rt as withPerformanceMonitoring,
1230
- ge as withProgressiveFeature,
1231
- ue as withServices
1232
- };
1233
- //# sourceMappingURL=core.mjs.map
954
+ //#endregion
955
+ //#region src/core/index.ts
956
+ var ke = "1.0.0";
957
+ //#endregion
958
+ export { g as AnalyticsPlugin, p as BasePlugin, ke as CORE_ARCHITECTURE_VERSION, v as ConsolePluginLogger, C as EVENT_SYSTEM_VERSION, y as EventBus, T as EventDelegator, J as FEATURES, X as FeatureDetector, V as MediaLoadingOptimizer, b as MiddlewareBuilder, B as NetworkMonitor, ie as PLUGIN_SYSTEM_VERSION, M as PerformanceBenchmark, R as PerformanceBudgetMonitor, c as PerformanceDashboard, i as PerformanceMonitor, o as PerformanceRegressionDetector, F as PerformanceTestFramework, h as PluginConflictError, f as PluginDependencyError, u as PluginDevelopmentHelpers, te as PluginError, m as PluginPerformanceMonitor, _ as PluginRegistry, ae as PluginStorage, d as PluginValidator, Z as ProgressiveLoader, G as ServiceProvider, me as commonMiddlewares, re as createAnalyticsPlugin, q as createArchitecture, de as createMiddleware, l as createPlugin, E as defaultEventBus, z as defaultMediaLoadingConfig, L as defaultPerformanceBudgets, ee as defaultPerformanceMonitor, ne as defaultPluginLogger, Y as defaultProgressiveConfig, r as defaultThresholds, ue as eventMiddlewares, De as lazyComponents, H as mediaLoadingOptimizer, N as performanceBenchmark, _e as performanceBudgetMonitor, n as performanceMonitor, I as performanceTestFramework, P as performanceTestUtils, Q as progressiveLoader, we as useAnalytics, he as useConditionalEventListener, x as useEventBus, fe as useEventDebugger, oe as useEventEffect, ge as useEventEmitter, S as useEventHandlers, se as useEventHistory, pe as useEventListener, w as useEventMetrics, ce as useEventOnce, le as useEventState, Te as useLogger, ve as useMediaLoadingOptimizer, a as usePerformanceMonitor, Se as usePluginRegistry, $ as useProgressiveFeature, xe as useServiceEventBus, K as useServices, Ce as useStorage, s as withPerformanceMonitoring, Oe as withProgressiveFeature, Ee as withServices };
959
+
960
+ //# sourceMappingURL=core.mjs.map