create-prisma-php-app 3.1.4 → 3.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,8 @@
1
1
  <?php
2
2
 
3
- namespace Lib\PHPX;
3
+ declare(strict_types=1);
4
4
 
5
- /**
6
- * Interface IPHPX
7
- *
8
- * The interface for the PHPX component classes.
9
- */
5
+ namespace Lib\PHPX;
10
6
 
11
7
  interface IPHPX
12
8
  {
@@ -1,5 +1,7 @@
1
1
  <?php
2
2
 
3
+ declare(strict_types=1);
4
+
3
5
  namespace Lib\PHPX;
4
6
 
5
7
  use Lib\PHPX\IPHPX;
@@ -18,6 +18,7 @@ use ReflectionClass;
18
18
  use ReflectionProperty;
19
19
  use ReflectionType;
20
20
  use ReflectionNamedType;
21
+ use Lib\PHPX\TypeCoercer;
21
22
  use Lib\PHPX\Exceptions\ComponentValidationException;
22
23
 
23
24
  class TemplateCompiler
@@ -524,48 +525,7 @@ class TemplateCompiler
524
525
 
525
526
  private static function coerce(mixed $value, ?ReflectionType $type): mixed
526
527
  {
527
- if (!$type instanceof ReflectionNamedType || $type->isBuiltin() === false) {
528
- return $value;
529
- }
530
-
531
- $name = $type->getName();
532
- if ($value === '' && $name === 'bool') return true;
533
-
534
- return match ($name) {
535
- 'bool' => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false,
536
- 'int' => (int) $value,
537
- 'float' => (float) $value,
538
- 'array' => self::toArray($value),
539
-
540
- default => $value,
541
- };
542
- }
543
-
544
- private static function toArray(mixed $v): array
545
- {
546
- if (is_array($v)) {
547
- return $v;
548
- }
549
- if (is_string($v)) {
550
- $decoded = json_decode($v, true);
551
- if (is_array($decoded)) {
552
- return $decoded;
553
- }
554
- if (str_contains($v, ',')) {
555
- return array_map('trim', explode(',', $v));
556
- }
557
- return [$decoded ?? self::coerceScalarString($v)];
558
- }
559
- return [$v];
560
- }
561
-
562
- private static function coerceScalarString(string $s): mixed
563
- {
564
- return match (strtolower($s)) {
565
- 'true' => true,
566
- 'false' => false,
567
- default => $s,
568
- };
528
+ return TypeCoercer::coerce($value, $type);
569
529
  }
570
530
 
571
531
  protected static function initializeClassMappings(): void
@@ -0,0 +1,490 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Lib\PHPX;
6
+
7
+ use Lib\Validator;
8
+ use ReflectionType;
9
+ use ReflectionNamedType;
10
+ use ReflectionUnionType;
11
+ use ReflectionIntersectionType;
12
+ use DateTime;
13
+ use DateTimeImmutable;
14
+ use DateTimeInterface;
15
+ use Brick\Math\BigDecimal;
16
+ use Brick\Math\BigInteger;
17
+
18
+ class TypeCoercer
19
+ {
20
+ private static array $typeCache = [];
21
+ private static array $phpTypeMap = [
22
+ 'boolean' => 'bool',
23
+ 'integer' => 'int',
24
+ 'double' => 'float',
25
+ 'string' => 'string',
26
+ 'array' => 'array',
27
+ 'object' => 'object',
28
+ 'resource' => 'resource',
29
+ 'NULL' => 'null',
30
+ ];
31
+
32
+ public static function coerce(mixed $value, ?ReflectionType $type, array $validationRules = []): mixed
33
+ {
34
+ if ($type === null) {
35
+ return $value;
36
+ }
37
+ $typeKey = self::getTypeKey($type);
38
+ if (!isset(self::$typeCache[$typeKey])) {
39
+ self::$typeCache[$typeKey] = self::analyzeType($type);
40
+ }
41
+ $typeInfo = self::$typeCache[$typeKey];
42
+ return self::coerceWithTypeInfo($value, $typeInfo, $validationRules);
43
+ }
44
+
45
+ private static function coerceWithTypeInfo(mixed $value, array $typeInfo, array $validationRules = []): mixed
46
+ {
47
+ if ($value === null && $typeInfo['allowsNull']) {
48
+ return null;
49
+ }
50
+ if ($typeInfo['isUnion']) {
51
+ return self::coerceUnionTypeSmart($value, $typeInfo['types'], $validationRules);
52
+ }
53
+ if (count($typeInfo['types']) === 1) {
54
+ $currentType = self::getNormalizedType($value);
55
+ $targetType = $typeInfo['types'][0]['name'];
56
+ if ($currentType === $targetType) {
57
+ return $value;
58
+ }
59
+ return self::coerceSingleType($value, $typeInfo['types'][0], $validationRules);
60
+ }
61
+ return $value;
62
+ }
63
+
64
+ private static function analyzeType(ReflectionType $type): array
65
+ {
66
+ $info = [
67
+ 'isUnion' => false,
68
+ 'isIntersection' => false,
69
+ 'allowsNull' => false,
70
+ 'types' => [],
71
+ ];
72
+ if ($type instanceof ReflectionUnionType) {
73
+ $info['isUnion'] = true;
74
+ foreach ($type->getTypes() as $unionType) {
75
+ if ($unionType->getName() === 'null') {
76
+ $info['allowsNull'] = true;
77
+ } else {
78
+ $info['types'][] = [
79
+ 'name' => $unionType->getName(),
80
+ 'isBuiltin' => $unionType->isBuiltin(),
81
+ 'allowsNull' => $unionType->allowsNull(),
82
+ ];
83
+ }
84
+ }
85
+ } elseif ($type instanceof ReflectionNamedType) {
86
+ $info['allowsNull'] = $type->allowsNull();
87
+ if ($type->getName() !== 'null') {
88
+ $info['types'][] = [
89
+ 'name' => $type->getName(),
90
+ 'isBuiltin' => $type->isBuiltin(),
91
+ 'allowsNull' => $type->allowsNull(),
92
+ ];
93
+ }
94
+ } elseif ($type instanceof ReflectionIntersectionType) {
95
+ $info['isIntersection'] = true;
96
+ foreach ($type->getTypes() as $intersectionType) {
97
+ if ($intersectionType instanceof ReflectionNamedType) {
98
+ $info['types'][] = [
99
+ 'name' => $intersectionType->getName(),
100
+ 'isBuiltin' => $intersectionType->isBuiltin(),
101
+ 'allowsNull' => $intersectionType->allowsNull(),
102
+ ];
103
+ } else {
104
+ $info['types'][] = [
105
+ 'name' => (string) $intersectionType,
106
+ 'isBuiltin' => false,
107
+ 'allowsNull' => false,
108
+ ];
109
+ }
110
+ }
111
+ }
112
+ return $info;
113
+ }
114
+
115
+ private static function coerceUnionTypeSmart(mixed $value, array $types, array $validationRules = []): mixed
116
+ {
117
+ $typeNames = array_column($types, 'name');
118
+ return match (true) {
119
+ self::hasTypes($typeNames, ['string', 'bool']) =>
120
+ self::coerceStringBoolUnion($value, $types, $validationRules),
121
+ self::hasTypes($typeNames, ['int', 'string']) =>
122
+ self::coerceIntStringUnion($value, $types, $validationRules),
123
+ self::hasTypes($typeNames, ['float', 'string']) =>
124
+ self::coerceFloatStringUnion($value, $types, $validationRules),
125
+ self::hasTypes($typeNames, ['array', 'string']) =>
126
+ self::coerceArrayStringUnion($value, $types, $validationRules),
127
+ self::hasDateTimeTypes($typeNames) =>
128
+ self::coerceDateTimeUnion($value, $types, $validationRules),
129
+ default => self::coerceUnionTypePhpCompliant($value, $types, $validationRules)
130
+ };
131
+ }
132
+
133
+ private static function coerceStringBoolUnion(mixed $value, array $types, array $validationRules = []): mixed
134
+ {
135
+ if (is_bool($value)) {
136
+ return $value;
137
+ }
138
+ if (is_string($value) && self::isBooleanLike($value)) {
139
+ return self::coerceBool($value, $validationRules);
140
+ }
141
+ return self::coerceString($value, $validationRules);
142
+ }
143
+
144
+ private static function coerceIntStringUnion(mixed $value, array $types, array $validationRules = []): mixed
145
+ {
146
+ if (is_int($value)) {
147
+ return $value;
148
+ }
149
+ if (self::isIntegerLike($value)) {
150
+ return self::coerceInt($value, $validationRules);
151
+ }
152
+ return self::coerceString($value, $validationRules);
153
+ }
154
+
155
+ private static function coerceFloatStringUnion(mixed $value, array $types, array $validationRules = []): mixed
156
+ {
157
+ if (is_float($value)) {
158
+ return $value;
159
+ }
160
+ if (is_string($value) && is_numeric($value)) {
161
+ return self::coerceFloat($value, $validationRules);
162
+ }
163
+ return self::coerceString($value, $validationRules);
164
+ }
165
+
166
+ private static function coerceArrayStringUnion(mixed $value, array $types, array $validationRules = []): mixed
167
+ {
168
+ if (is_array($value)) {
169
+ return $value;
170
+ }
171
+ if (is_string($value) && self::isArrayLike($value)) {
172
+ return self::coerceArray($value, $validationRules);
173
+ }
174
+ return self::coerceString($value, $validationRules);
175
+ }
176
+
177
+ private static function coerceDateTimeUnion(mixed $value, array $types, array $validationRules = []): mixed
178
+ {
179
+ if ($value instanceof DateTimeInterface) {
180
+ return $value;
181
+ }
182
+ if (is_string($value) || is_numeric($value)) {
183
+ foreach ($types as $typeInfo) {
184
+ if (in_array($typeInfo['name'], ['DateTime', 'DateTimeImmutable', 'DateTimeInterface'])) {
185
+ $coerced = self::coerceCustomType($value, $typeInfo['name'], $validationRules);
186
+ if ($coerced !== $value) {
187
+ return $coerced;
188
+ }
189
+ }
190
+ }
191
+ }
192
+ return self::coerceString($value, $validationRules);
193
+ }
194
+
195
+ private static function coerceUnionTypePhpCompliant(mixed $value, array $types, array $validationRules = []): mixed
196
+ {
197
+ foreach ($types as $typeInfo) {
198
+ $coerced = self::coerceSingleType($value, $typeInfo, $validationRules);
199
+ if (self::isValidCoercion($value, $coerced, $typeInfo['name'])) {
200
+ return $coerced;
201
+ }
202
+ }
203
+ return $value;
204
+ }
205
+
206
+ private static function hasTypes(array $typeNames, array $requiredTypes): bool
207
+ {
208
+ foreach ($requiredTypes as $required) {
209
+ if (!in_array($required, $typeNames, true)) {
210
+ return false;
211
+ }
212
+ }
213
+ return true;
214
+ }
215
+
216
+ private static function hasDateTimeTypes(array $typeNames): bool
217
+ {
218
+ $dateTimeTypes = ['DateTime', 'DateTimeImmutable', 'DateTimeInterface'];
219
+ return !empty(array_intersect($typeNames, $dateTimeTypes));
220
+ }
221
+
222
+ private static function isBooleanLike(mixed $value): bool
223
+ {
224
+ if (!is_string($value)) {
225
+ return false;
226
+ }
227
+ return in_array(strtolower(trim($value)), [
228
+ 'true',
229
+ 'false',
230
+ '1',
231
+ '0',
232
+ 'yes',
233
+ 'no',
234
+ 'on',
235
+ 'off',
236
+ 'checked',
237
+ ''
238
+ ], true);
239
+ }
240
+
241
+ private static function isIntegerLike(mixed $value): bool
242
+ {
243
+ return is_string($value) && is_numeric($value) && (string)(int)$value === trim($value);
244
+ }
245
+
246
+ private static function isArrayLike(string $value): bool
247
+ {
248
+ return Validator::json($value) ||
249
+ str_contains($value, ',') ||
250
+ str_contains($value, '[') ||
251
+ str_contains($value, '{');
252
+ }
253
+
254
+ private static function getNormalizedType(mixed $value): string
255
+ {
256
+ $type = gettype($value);
257
+ return self::$phpTypeMap[$type] ?? $type;
258
+ }
259
+
260
+ private static function coerceSingleType(mixed $value, array $typeInfo, array $validationRules = []): mixed
261
+ {
262
+ if (!$typeInfo['isBuiltin']) {
263
+ return self::coerceCustomType($value, $typeInfo['name'], $validationRules);
264
+ }
265
+ return match ($typeInfo['name']) {
266
+ 'bool' => self::coerceBool($value, $validationRules),
267
+ 'int' => self::coerceInt($value, $validationRules),
268
+ 'float' => self::coerceFloat($value, $validationRules),
269
+ 'string' => self::coerceString($value, $validationRules),
270
+ 'array' => self::coerceArray($value, $validationRules),
271
+ 'object' => self::coerceObject($value, $validationRules),
272
+ 'mixed' => $value,
273
+ default => $value,
274
+ };
275
+ }
276
+
277
+ private static function coerceBool(mixed $value, array $rules = []): mixed
278
+ {
279
+ $validated = Validator::boolean($value);
280
+ if ($validated !== null) {
281
+ return $validated;
282
+ }
283
+ if (is_string($value)) {
284
+ return match (strtolower(trim($value))) {
285
+ 'true', '1', 'yes', 'on', 'checked' => true,
286
+ 'false', '0', 'no', 'off', '' => false,
287
+ default => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? false,
288
+ };
289
+ }
290
+ return (bool) $value;
291
+ }
292
+
293
+ private static function coerceInt(mixed $value, array $rules = []): mixed
294
+ {
295
+ $validated = Validator::int($value);
296
+ return $validated ?? (int) $value;
297
+ }
298
+
299
+ private static function coerceFloat(mixed $value, array $rules = []): mixed
300
+ {
301
+ $validated = Validator::float($value);
302
+ return $validated ?? (float) $value;
303
+ }
304
+
305
+ private static function coerceString(mixed $value, array $rules = []): mixed
306
+ {
307
+ $escapeHtml = $rules['escapeHtml'] ?? true;
308
+ if (isset($rules['type'])) {
309
+ return match ($rules['type']) {
310
+ 'email' => Validator::email($value) ?? Validator::string($value, $escapeHtml),
311
+ 'url' => Validator::url($value) ?? Validator::string($value, $escapeHtml),
312
+ 'uuid' => Validator::uuid($value) ?? Validator::string($value, $escapeHtml),
313
+ 'ulid' => Validator::ulid($value) ?? Validator::string($value, $escapeHtml),
314
+ 'cuid' => Validator::cuid($value) ?? Validator::string($value, $escapeHtml),
315
+ 'cuid2' => Validator::cuid2($value) ?? Validator::string($value, $escapeHtml),
316
+ 'ip' => Validator::ip($value) ?? Validator::string($value, $escapeHtml),
317
+ 'html' => Validator::html(Validator::string($value, false)),
318
+ 'emojis' => Validator::emojis(Validator::string($value, $escapeHtml)),
319
+ default => Validator::string($value, $escapeHtml),
320
+ };
321
+ }
322
+ return Validator::string($value, $escapeHtml);
323
+ }
324
+
325
+ private static function coerceArray(mixed $value, array $rules = []): array
326
+ {
327
+ if (is_array($value)) {
328
+ return $value;
329
+ }
330
+ if (is_string($value)) {
331
+ if (Validator::json($value)) {
332
+ $decoded = json_decode($value, true);
333
+ if (is_array($decoded)) {
334
+ return $decoded;
335
+ }
336
+ }
337
+ if (str_contains($value, ',')) {
338
+ return array_map('trim', explode(',', $value));
339
+ }
340
+ return [$value];
341
+ }
342
+ return (array) $value;
343
+ }
344
+
345
+ private static function coerceObject(mixed $value, array $rules = []): object
346
+ {
347
+ if (is_object($value)) {
348
+ return $value;
349
+ }
350
+ if (is_array($value)) {
351
+ return (object) $value;
352
+ }
353
+ if (is_string($value) && Validator::json($value)) {
354
+ $decoded = json_decode($value);
355
+ if (is_object($decoded)) {
356
+ return $decoded;
357
+ }
358
+ }
359
+ return (object) $value;
360
+ }
361
+
362
+ private static function coerceCustomType(mixed $value, string $typeName, array $rules = []): mixed
363
+ {
364
+ return match ($typeName) {
365
+ 'DateTime' => self::coerceDateTime($value, $rules),
366
+ 'DateTimeImmutable' => self::coerceDateTimeImmutable($value, $rules),
367
+ 'DateTimeInterface' => self::coerceDateTimeInterface($value, $rules),
368
+ 'BigDecimal' => self::coerceBigDecimal($value, $rules),
369
+ 'BigInteger' => self::coerceBigInteger($value, $rules),
370
+ default => $value,
371
+ };
372
+ }
373
+
374
+ private static function coerceDateTime(mixed $value, array $rules = []): mixed
375
+ {
376
+ if ($value instanceof DateTime) {
377
+ return $value;
378
+ }
379
+ if ($value instanceof DateTimeImmutable) {
380
+ return DateTime::createFromImmutable($value);
381
+ }
382
+ $format = $rules['format'] ?? null;
383
+ try {
384
+ if ($format) {
385
+ return DateTime::createFromFormat($format, (string)$value) ?: $value;
386
+ } else {
387
+ return new DateTime((string)$value);
388
+ }
389
+ } catch (\Exception) {
390
+ return $value;
391
+ }
392
+ }
393
+
394
+ private static function coerceDateTimeImmutable(mixed $value, array $rules = []): mixed
395
+ {
396
+ if ($value instanceof DateTimeImmutable) {
397
+ return $value;
398
+ }
399
+ if ($value instanceof DateTime) {
400
+ return DateTimeImmutable::createFromMutable($value);
401
+ }
402
+ $format = $rules['format'] ?? null;
403
+ try {
404
+ if ($format) {
405
+ return DateTimeImmutable::createFromFormat($format, (string)$value) ?: $value;
406
+ } else {
407
+ return new DateTimeImmutable((string)$value);
408
+ }
409
+ } catch (\Exception) {
410
+ return $value;
411
+ }
412
+ }
413
+
414
+ private static function coerceDateTimeInterface(mixed $value, array $rules = []): mixed
415
+ {
416
+ if ($value instanceof DateTimeInterface) {
417
+ return $value;
418
+ }
419
+ return self::coerceDateTimeImmutable($value, $rules);
420
+ }
421
+
422
+ private static function coerceBigDecimal(mixed $value, array $rules = []): mixed
423
+ {
424
+ $scale = $rules['scale'] ?? 30;
425
+ return Validator::decimal($value, $scale) ?? $value;
426
+ }
427
+
428
+ private static function coerceBigInteger(mixed $value, array $rules = []): mixed
429
+ {
430
+ return Validator::bigInt($value) ?? $value;
431
+ }
432
+
433
+ private static function isValidCoercion(mixed $original, mixed $coerced, string $typeName): bool
434
+ {
435
+ if (gettype($original) === gettype($coerced)) {
436
+ return match ($typeName) {
437
+ 'string' => true,
438
+ 'array' => $original !== $coerced,
439
+ default => $original === $coerced,
440
+ };
441
+ }
442
+ return match ($typeName) {
443
+ 'bool' => is_bool($coerced),
444
+ 'int' => is_int($coerced),
445
+ 'float' => is_float($coerced),
446
+ 'string' => is_string($coerced),
447
+ 'array' => is_array($coerced),
448
+ 'object' => is_object($coerced),
449
+ 'DateTime' => $coerced instanceof DateTime,
450
+ 'DateTimeImmutable' => $coerced instanceof DateTimeImmutable,
451
+ 'DateTimeInterface' => $coerced instanceof DateTimeInterface,
452
+ 'BigDecimal' => $coerced instanceof BigDecimal,
453
+ 'BigInteger' => $coerced instanceof BigInteger,
454
+ default => true,
455
+ };
456
+ }
457
+
458
+ private static function getTypeKey(ReflectionType $type): string
459
+ {
460
+ if ($type instanceof ReflectionUnionType) {
461
+ $types = array_map(fn($t) => $t->getName(), $type->getTypes());
462
+ sort($types);
463
+ return 'union:' . implode('|', $types);
464
+ }
465
+ if ($type instanceof ReflectionNamedType) {
466
+ return 'named:' . $type->getName() . ($type->allowsNull() ? '|null' : '');
467
+ }
468
+ if ($type instanceof ReflectionIntersectionType) {
469
+ $types = array_map(function ($t) {
470
+ return $t instanceof ReflectionNamedType ? $t->getName() : (string) $t;
471
+ }, $type->getTypes());
472
+ sort($types);
473
+ return 'intersection:' . implode('&', $types);
474
+ }
475
+ return 'unknown:' . get_class($type);
476
+ }
477
+
478
+ public static function clearCache(): void
479
+ {
480
+ self::$typeCache = [];
481
+ }
482
+
483
+ public static function getCacheStats(): array
484
+ {
485
+ return [
486
+ 'type_cache_size' => count(self::$typeCache),
487
+ 'cached_types' => array_keys(self::$typeCache),
488
+ ];
489
+ }
490
+ }
@@ -1 +1 @@
1
- (()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let o=i;s.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:o&&void 0===o.passive&&(o={...o,passive:!0})),n.has(this)||n.set(this,new Map);const a=n.get(this),c=a.get(t)||new Set;c.add(r),a.set(t,c),e.call(this,t,r,o)},EventTarget.prototype.removeEventListener=function(e,s,r){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t.delete(s),0===t.size&&n.get(this).delete(e)}t.call(this,e,s,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(!n.has(this))return;const s=n.get(this).get(e);s&&(s.forEach((n=>{t.call(this,e,n)})),n.get(this).delete(e))}})(),function(){const e=console.log;console.log=(...t)=>{const n=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,n)}}();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_proxyCache=new WeakMap;_rawProps={};_refs=new Map;_wheelHandlersStashed=!1;_evaluatorCache=new Map;_depsCache=new Map;_dirtyDeps=new Set;_handlerCache=new Map;_handlerProxyCache=new WeakMap;_sharedStateMap=new Set;_processedLoops=new WeakSet;_hydrated=!1;_currentProcessingHierarchy=null;_stateHierarchy=new Map;_currentTemplateHierarchy=null;_inlineModuleFns=new Map;_currentExecutionScope=null;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _cancelableEvents=new Set(["click","submit","change"]);static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;static _passiveEvents=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),n=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...n].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const n=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",s=e.getAttribute(`pp-${n}`)??null;let r=null;if(s){const t=s.replace(/^{\s*|\s*}$/g,""),n=this.detectElementHierarchy(e);try{r=!!this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n))}catch{r=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:n,expr:s,visible:!e.hasAttribute("hidden"),result:r})})),console.groupEnd(),console.groupEnd()}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{try{await Promise.all([this.initRefs(),this.processInlineModuleScripts(),this._hydrated=!0]),await e(),await this.initializeAllReferencedProps(),await e(),await this.manageAttributeBindings(),await e(),await this.processIfChains(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();const t=250;for(let n=0;n<this._bindings.length;n+=t)this._bindings.slice(n,n+t).forEach((e=>{try{e.update()}catch(e){console.error("Initial binding update error:",e)}})),await e();document.body.removeAttribute("hidden")}catch(e){console.error("Hydration failed:",e),document.body.removeAttribute("hidden")}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}async initCryptoKey(){const e=document.cookie.split("; ").find((e=>e.startsWith("pphp_function_call_jwt=")))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:s,exp:r}=JSON.parse(n);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(s),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),n=(new TextEncoder).encode(e),s=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,n);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(s)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,n]=e.split(":",2),s=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),r=Uint8Array.from(atob(n),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:s},PPHP._cryptoKey,r);return(new TextDecoder).decode(i)}qsa(e,t){return e.querySelectorAll(t)}_inferHierarchyFromEvent(){const e=globalThis.event,t=e?.target??document.activeElement;if(!t||!t.closest)return["app"];const n=[];let s=t;for(;s&&s!==document.documentElement;){const e=s.getAttribute("pp-component");e&&n.unshift(e),s=s.parentElement}return n.length?n:["app"]}callParent(functionNameOrFn,...args){try{const currentHierarchy=this._currentExecutionScope?.split(".")||this._currentProcessingHierarchy||this._inferHierarchyFromEvent();if("function"==typeof functionNameOrFn){const e=functionNameOrFn;return e.name?this.callParentByName(e.name,currentHierarchy,args):this.executeInParentContext(e,currentHierarchy,args)}const str=String(functionNameOrFn).trim();if(!str)return console.warn("callParent: empty functionNameOrFn"),null;if(str.includes("=>"))try{const arrow=eval(str);if("function"==typeof arrow)return this.callParent(arrow)}catch{}const callMatch=str.match(/^([A-Za-z_$]\w*)\s*\(\s*([\s\S]*)\)$/);if(callMatch){const[,e,t]=callMatch;let n;try{n=JSON5.parse(`[${t}]`)}catch{n=t.split(/\s*,\s*/).filter(Boolean).map((e=>{try{return JSON5.parse(e)}catch{return e}}))}const s=this.callParentByName(e,currentHierarchy,n);if(null!==s)return s;if(e.startsWith("set")){const t=e[3].toLowerCase()+e.slice(4),s=PPHP._shared.get(t);if(s)return s.setter(n[0]),null;const r=function(...t){return this[e](...t)};return this.executeInParentContext(r,currentHierarchy,n)}return console.warn(`❌ Parent function '${e}' not found`),null}const assign=str.match(/^\s*([A-Za-z_$]\w*)\s*=\s*([\s\S]+)$/);if(assign){const[,e,t]=assign,n=new Function("ctx",`with(ctx){ return (${t}); }`),s=n(this._createScopedPropsContext(currentHierarchy)),r="set"+e[0].toUpperCase()+e.slice(1),i=this.callParentByName(r,currentHierarchy,[s]);if(null!==i)return i;const o=PPHP._shared.get(e);if(o)return o.setter(s),null;const a=currentHierarchy.slice(0,-1).join("."),c=a?`${a}.${e}`:e;return this.setNested(this.props,c,s),this.scheduleFlush(),null}return this.callParentByName(str,currentHierarchy,args)}catch(e){return console.error("callParent: unexpected error",e),null}}callParentByName(e,t,n){for(let s=t.length-1;s>=0;s--){const r=t.slice(0,s).join("."),i=this._inlineModuleFns.get(r);if(i?.has(e))return i.get(e)(...n)}const s=t.join("."),r=this._inlineModuleFns.get(s);if(r?.has(e))return r.get(e)(...n);for(const[,t]of this._inlineModuleFns)if(t.has(e))return t.get(e)(...n);return null}executeInParentContext(e,t,n){for(let s=t.length-1;s>=0;s--){const r=t.slice(0,s);try{const t=this.createParentScopeContext(r);return this.executeWithContext(e,t,n)}catch(e){console.error(`Error executing anonymous function in parent context (${r.join(".")}):`,e);continue}}return console.warn("No parent scope found for anonymous function execution"),null}createParentScopeContext(e,t={}){const n=e.join("."),s=this.getNested(this.props,n)||{},r=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const o=r.getScopedFunction(n,e);if(o)return o;if(s&&n in s)return s[n];if("string"==typeof n&&n.startsWith("set")){const e=n.charAt(3).toLowerCase()+n.slice(4);for(const[t,n]of r._stateHierarchy.entries())if(n.originalKey===e)return e=>{r.setNested(r.props,t,e),r._dirtyDeps.add(t),r.scheduleFlush()}}for(let t=e.length-1;t>=0;t--){const s=e.slice(0,t).join("."),i=r._inlineModuleFns.get(s);if(i?.has(n))return i.get(n);const o=s?r.getNested(r.props,s):r.props;if(o&&n in o)return o[n]}return n in globalThis?globalThis[n]:void 0},set:(e,t,n,s)=>Reflect.set(e,t,n,s),has:(t,n)=>"string"==typeof n&&(n in t||!!r.getScopedFunction(n,e)||s&&n in s||n in globalThis||e.some(((t,s)=>{const i=e.slice(0,s).join("."),o=i?r.getNested(r.props,i):r.props;return o&&n in o})))})}executeWithContext(e,t,n){try{return e.toString().includes("=>")?this.executeArrowFunctionWithContext(e,t):n.length>0?e.apply(t,n):e.call(t)}catch(e){throw console.error("🚀 ~ executeWithContext ~ error:",e),e}}executeArrowFunctionWithContext(e,t){const n=e.toString();if(n.includes("=>"))try{const e=n.match(/(?:\([^)]*\)|[^=])\s*=>\s*(.+)/);if(e){let n=e[1].trim();n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1));return new Function("context",`with (context) { return (${n}); }`)(t)}}catch(e){console.error("Failed to execute arrow function with context:",e)}return e()}detectComponentHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return t.length>0?t:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const n=this._refs.get(e)??[];if(null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const n=Array.isArray(t),s=n?t:[],r=n&&0===s.length,i=this._currentProcessingHierarchy||["app"],o=s.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(t){const e=t[1];return this.resolveDependencyPath(e,i)}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),a=s.filter((e=>"function"==typeof e&&!e.__pphp_key)),c=new Set(o),l=new Map;for(const e of o)try{l.set(e,this.getResolvedValue(e))}catch(t){l.set(e,void 0)}const h=new Map;for(const e of a)try{const t=e();h.set(e,t)}catch(t){h.set(e,Symbol("error"))}let d=0,p=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const u=PPHP._effectCleanups,f=()=>{const t=u.get(f);if(t){try{t()}catch(e){console.error("cleanup error:",e)}u.delete(f)}const s=performance.now();if(s-p<16)requestAnimationFrame((()=>{performance.now()-p>=16&&f()}));else{if(p=s,++d>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(c)),new Error("PPHP: effect ran >100 times — possible loop");if(!r){let e=!1;const t=[];if(o.length>0)for(const n of o)try{const s=this.getResolvedValue(n),r=l.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push(n),l.set(n,s))}catch(s){e=!0,t.push(n),l.set(n,void 0)}for(const n of a)try{const s=n(),r=h.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push("(function)"),h.set(n,s))}catch(s){h.get(n)!==Symbol("error")&&(e=!0,t.push("(function-error)"),h.set(n,Symbol("error")))}if(n&&(o.length>0||a.length>0)&&!e)return}try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}}};Object.assign(f,{__deps:c,__static:r,__functionDeps:a,__hierarchy:i,__isEffect:!0});try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(e){console.error("effect error (initial):",e)}const m=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return r?this._effects.add(f):m.add(f),()=>{const e=u.get(f);if(e){try{e()}catch(e){console.error("cleanup error:",e)}u.delete(f)}this._effects.delete(f),this._pendingEffects.delete(f)}}resolveDependencyPath(e,t){const n=e.startsWith("app.")?e.substring(4):e,s=n.split(".")[0];if(PPHP._shared.has(s))return n;const r=t.join(".")+"."+e;if(this.hasNested(this.props,r))return r;if(this.hasNested(this.props,e))return e;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?s+"."+e:e;if(this.hasNested(this.props,r))return r}return e}getResolvedValue(e){e.split(".")[0];const t=(e.startsWith("app.")?e.substring(4):e).split("."),n=t[0],s=PPHP._shared.get(n);if(s){if(1===t.length)return s.getter();{const e=s.getter(),n=t.slice(1).join(".");return this.getNested(e,n)}}return this.getNested(this.props,e)}hasValueChanged(e,t){if(e===t)return!1;if(null==e||null==t)return e!==t;if("object"!=typeof e||"object"!=typeof t)return e!==t;try{return JSON.stringify(e)!==JSON.stringify(t)}catch(e){return!0}}resetProps(){this._isNavigating=!1,this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=null,this._responseData=null,Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable&&delete window[e]}})),this._rawProps={},this.clearShare(),this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._processedLoops=new WeakSet,this._depsCache.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1,this.props=this.makeReactive(this._rawProps),this._hydrated=!1}async initReactiveOn(e=document.body){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),this.processInlineModuleScripts(e),this._hydrated=!0]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.processIfChains(e),await t(),await this.manageAttributeBindings(e),await t(),await this.initLoopBindings(e),await t();for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await t();e===document.body&&document.body.removeAttribute("hidden")}async initLoopBindings(e=document.body){this.qsa(e,"template[pp-for]").forEach((e=>{this._processedLoops.has(e)||(this._processedLoops.add(e),this.registerLoop(e))}))}registerLoop(e){const t=this.parseForExpression(e),{marker:n,parent:s,templateHierarchy:r}=this.setupLoopMarker(e),i=this.initializeLoopState(),o=this.createLoopUpdater(e,t,n,s,r,i),a={dependencies:this.extractComprehensiveLoopDependencies(e,t,r),update:o,__isLoop:!0};this._bindings.push(a)}extractComprehensiveLoopDependencies(e,t,n){const s=new Set;let r=null;for(let e=n.length;e>=0;e--){const s=n.slice(0,e),i=s.length>0?`${s.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,i);if(Array.isArray(e)){r=i;break}}catch{}}if(!r)try{const e=this.getNested(this.props,t.arrExpr);Array.isArray(e)&&(r=t.arrExpr)}catch{r=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr}const i=r;null!==i&&s.add(i);const o=this.extractItemPropertiesFromTemplate(e,t);for(const e of o)if(s.add(`${i}.*`),s.add(`${i}.*.${e}`),"string"==typeof i){const t=this.getNested(this.props,i);if(Array.isArray(t))for(let n=0;n<t.length;n++)s.add(`${i}.${n}.${e}`)}return Array.from(s).some((e=>e.includes("*")))||s.add(`${i}.*`),s}extractItemPropertiesFromTemplate(e,t){const n=new Set,s=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),r=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;r.nextNode();){const e=r.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const n=e;for(const e of Array.from(n.attributes))t+=" "+e.value}const i=t.matchAll(s);for(const e of i)n.add(e[1])}return n}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[n,s]=t.split(/\s+in\s+/),[r,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:n,arrExpr:s,itemName:r,idxName:i}}setupLoopMarker(e){const t=e.parentNode,n=document.createComment("pp-for"),s=this.detectElementHierarchy(e);return t.insertBefore(n,e),t.removeChild(e),{marker:n,parent:t,templateHierarchy:s}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,n,s,r){this._currentTemplateHierarchy=r;const i={...this._createScopedPropsContext(r),[s.itemName]:t};s.idxName&&(i[s.idxName]=n);const o=e.content.cloneNode(!0),a=[],c=this.getItemKey(t,n);return this.processTextNodesInFragment(o,s,r,c,t,a),this.processElementBindingsInFragment(o,s,r,c,t,a),this.processEventHandlersInFragment(o,s,t,n),a.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),this._currentTemplateHierarchy=null,{nodes:Array.from(o.childNodes),bindings:a}}processTextNodesInFragment(e,t,n,s,r,i){const o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;o.nextNode();){const e=o.currentNode,a=e.nodeValue||"";if(PPHP._mustacheTest.test(a)){const o=new Set,c=n.join("."),l=c?`${c}.${t.arrExpr}`:t.arrExpr;o.add(l);const h=this.createTextNodeUpdaterWithItemKey(e,a,t,n,s,r);i.push({dependencies:o,update:h}),this.renderTextNode(e,a,t,n,r,0)}}}createTextNodeUpdaterWithItemKey(e,t,n,s,r,i){const o=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const a=o(this._createScopedPropsContext(s));if(Array.isArray(a)){const o=this.findItemByKey(a,r,i),c=a.findIndex((e=>this.getItemKey(e,a.indexOf(e))===r));if(o&&-1!==c){const r={...this._createScopedPropsContext(s),[n.itemName]:o};n.idxName&&(r[n.idxName]=c);const i=this.renderMustacheText(t,s,r);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,n){for(let n=0;n<e.length;n++){const s=e[n];if(this.getItemKey(s,n)===t)return s}return n&&"object"==typeof n&&n.id?e.find((e=>e&&e.id===n.id)):null}processElementBindingsInFragment(e,t,n,s,r,i){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,n,s,r,i)}))}processElementBindings(e,t,n,s,r,i){for(const{name:o,value:a}of Array.from(e.attributes))if("pp-bind"===o)this.createElementBindingWithItemKey(e,a,"text",t,n,s,r,i);else if("pp-bind-expr"===o){const o=this.decodeEntities(a);this.createElementBindingWithItemKey(e,o,"text",t,n,s,r,i)}else if(o.startsWith("pp-bind-")){const c=o.replace(/^pp-bind-/,"");this.createElementBindingWithItemKey(e,a,c,t,n,s,r,i)}}createElementBindingWithItemKey(e,t,n,s,r,i,o,a){const c=new Set,l=r.join("."),h=l?`${l}.${s.arrExpr}`:s.arrExpr;c.add(h);const d=this.createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,o);a.push({dependencies:c,update:d}),this.renderElementBinding(e,t,n,s,r,o,0)}createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,o){const a=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=a(this._createScopedPropsContext(r));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(a&&-1!==l){const i={...this._createScopedPropsContext(r),[s.itemName]:a};s.idxName&&(i[s.idxName]=l),this.updateElementBinding(e,t,n,r,i)}}}}getItemKey(e,t){if(e&&"object"==typeof e){if("id"in e&&null!=e.id)return`id_${e.id}`;if("key"in e&&null!=e.key)return`key_${e.key}`;if("_id"in e&&null!=e._id)return`_id_${e._id}`;const t=Object.keys(e).filter((t=>(t.toLowerCase().includes("id")||t.toLowerCase().includes("uuid"))&&null!=e[t]&&("string"==typeof e[t]||"number"==typeof e[t])));if(t.length>0){const n=t[0];return`${n}_${e[n]}`}}return`idx_${t}`}renderTextNode(e,t,n,s,r,i){const o={...this._createScopedPropsContext(s),[n.itemName]:r};n.idxName&&(o[n.idxName]=i),e.nodeValue=this.renderMustacheText(t,s,o)}renderMustacheText(e,t,n){return e.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch{return""}}))}updateElementBinding(e,t,n,s,r){const i=this.makeScopedEvaluator(t,s)(r);if("text"===n){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,n,i)}renderElementBinding(e,t,n,s,r,i,o){const a={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(a[s.idxName]=o),this.updateElementBinding(e,t,n,r,a)}applyAttributeBinding(e,t,n){if(this._boolAttrs.has(t)){const s=!!n;s!==e.hasAttribute(t)&&(s?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==s&&(e[t]=s)}else{const s=String(n);t in e&&e[t]!==s&&(e[t]=s),e.getAttribute(t)!==s&&e.setAttribute(t,s)}}processEventHandlersInFragment(e,t,n,s){e.querySelectorAll("*").forEach((e=>{for(const{name:r,value:i}of Array.from(e.attributes)){const o=r.toLowerCase();if(!this._eventHandlers.has(o))continue;let a=i;a=a.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),JSON.stringify(n)),t.idxName&&(a=a.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),String(s))),e.setAttribute(r,a)}}))}updateItemNodes(e,t,n,s,r,i){if(t===n)return;if("object"==typeof t&&"object"==typeof n&&JSON.stringify(t)===JSON.stringify(n))return;this._currentTemplateHierarchy=i;const o={...this._createScopedPropsContext(i),[r.itemName]:n};r.idxName&&(o[r.idxName]=s),this.updateNodesContent(e,i,o),this._currentTemplateHierarchy=null}updateNodesContent(e,t,n){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,n)}))}updateElementContent(e,t,n){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;s.nextNode();){const e=s.currentNode,r=e.nodeValue||"",i=this.renderMustacheText(r,t,n);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,n)}))}updateElementBindingsContent(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if("pp-bind"===s)this.updateElementBinding(e,r,"text",t,n);else if(s.startsWith("pp-bind-")){const i=s.replace(/^pp-bind-/,"");this.updateElementBinding(e,r,i,t,n)}}createLoopUpdater(e,t,n,s,r,i){let o;for(let e=r.length;e>=0;e--){const n=r.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,n),s=e(this._createScopedPropsContext(n));if(Array.isArray(s)){o=e;break}}catch{}}return o=this.makeScopedEvaluator(t.arrExpr,r),()=>{this.performLoopUpdate(e,t,n,s,r,i,o)}}captureFocusState(e){const t=document.activeElement,n=t&&e.contains(t),s=n?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:n,focusKey:s,caretPos:n&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const n=t.querySelector(`[key="${e.focusKey}"]`),s=n?.querySelector("input,textarea");if(s&&(s.focus({preventScroll:!0}),null!==e.caretPos&&s instanceof HTMLInputElement)){const t=Math.min(e.caretPos,s.value.length);s.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const n=new Map,s=new Map;e.forEach(((e,t)=>{const s=this.getItemKey(e,t);n.set(s,{item:e,index:t})})),t.forEach(((e,t)=>{const n=this.getItemKey(e,t);s.set(n,{item:e,index:t})}));const r=new Set,i=new Map,o=new Map;for(const[e]of n)s.has(e)||r.add(e);for(const[e,{item:t,index:r}]of s)if(n.has(e)){const s=n.get(e);s.item===t&&s.index===r||o.set(e,{oldItem:s.item,newItem:t,newIndex:r,oldIndex:s.index})}else i.set(e,{item:t,index:r});return{toDelete:r,toInsert:i,toUpdate:o}}applyLoopChanges(e,t,n,s,r,i,o){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,n,i),this.applyLoopInsertions(e.toInsert,t,n,s,r,i,o)}applyLoopUpdates(e,t,n,s){for(const[r,{oldItem:i,newItem:o,newIndex:a,oldIndex:c}]of e){const e=t.renderedItems.get(r);e&&(this.updateItemNodes(e.nodes,i,o,a,n,s),e.item=o,e.index=a,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,n,s,r,i,o){if(0===e.size)return;const a=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of a){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:a,bindings:h}=this.createItemNodes(o,c,l,n,i);let d=s;const p=Array.from(t.renderedItems.entries()).map((([e,t])=>({key:e,...t}))).sort(((e,t)=>e.index-t.index));for(let e=p.length-1;e>=0;e--)if(p[e].index<l){d=p[e].nodes[p[e].nodes.length-1];break}a.forEach((e=>{r.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:a,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,n,s,r,i,o){const a=this.captureFocusState(s);let c,l=[];for(let e=r.length;e>=0;e--){const t=r.slice(0,e);try{c=this._createScopedPropsContext(t);const e=o(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.log("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(r);const e=o(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,n,s,r,e),i.previousList=[...l],this.restoreFocusState(a,s),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const n of e){const e=t.renderedItems.get(n);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(n))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)??[];n.push(e),this._refs.set(t,n),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){const n=this._proxyCache.get(e);if(n)return n;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const s=this,r=new Proxy(e,{get(e,n,r){if("__isReactiveProxy"===n)return!0;const i=Reflect.get(e,n,r);if(Array.isArray(e)&&"string"==typeof n&&s._mutators.has(n)){let o=s._arrayMethodCache.get(e);if(o||(o=new Map,s._arrayMethodCache.set(e,o)),!o.has(n)){const e=i.bind(r),a=t.join("."),c=function(...t){const n=e(...t);return queueMicrotask((()=>{s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies)if(s.dependencyMatches(a,n,t)){s.scheduleBindingUpdate(e);break}}))})),n};o.set(n,c)}return o.get(n)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy)return s.makeReactive(i,[...t,n]);if(Array.isArray(e)&&"function"==typeof i){let t=s._arrayMethodCache.get(e);return t||(t=new Map,s._arrayMethodCache.set(e,t)),t.has(n)||t.set(n,i.bind(e)),t.get(n)}return i},set(e,n,r,i){if("__isReactiveProxy"===n)return!0;let o=r;null===r||"object"!=typeof r||r.__isReactiveProxy||(o=s.makeReactive(r,[...t,n]));const a=e[n],c=Reflect.set(e,n,o,i);if(a===o)return c;const l=[...t,n].join(".");if(s._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&s._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(n))){const e=t.join(".");if(s._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),n=t.split(".")[0];PPHP._shared.has(n)&&s._dirtyDeps.add(`${t}.*`)}o&&"object"==typeof o&&Object.keys(o).forEach((t=>{if(s._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const n=e.substring(4),r=n.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${n}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(s._dirtyDeps.add(`${e}.*.${String(n)}`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${t}.*.${String(n)}`)}}return s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies){if(s.dependencyMatches(l,n,t)){s.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const r=l.substring(4),i=r.split(".")[0];if(PPHP._shared.has(i)&&s.dependencyMatches(r,n,t)){s.scheduleBindingUpdate(e);break}}}})),s._hydrated&&s.scheduleFlush(),c}});return this._proxyCache.set(e,r),r}getBindingType(e){if(e.__isEffect)return"effect";if(e.__isLoop)return"loop";for(const t of e.dependencies)if(t.includes("*")||t.match(/\.\d+\./)||t.endsWith(".*"))return"loop";for(const t of e.dependencies)try{const e=this.getNested(this.props,t);if(Array.isArray(e))return"loop"}catch{}return"binding"}makeAttrTemplateUpdater(e,t,n,s){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=s??r.get(t),o=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,o).forEach((e=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,o),n=this._createScopedPropsContext(o);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}formatValue(e){if("function"==typeof e){if(e.__isReactiveProxy)try{return this.formatValue(e())}catch{}return""}if(e&&"object"==typeof e){if(e.__isReactiveProxy&&"value"in e)try{return this.formatValue(e.value)}catch{return String(e)}if(e.__isReactiveProxy)try{const t={};for(const n in e)if("__isReactiveProxy"!==n&&"__pphp_key"!==n)try{t[n]=e[n]}catch{}return Object.keys(t).length?JSON.stringify(t,null,2):""}catch{return String(e)}try{return JSON.stringify(e,((e,t)=>{if("__isReactiveProxy"!==e&&"__pphp_key"!==e)return t&&"object"==typeof t&&t.__isReactiveProxy?"function"==typeof t&&"value"in t?t.value:"[Reactive Object]":t}),2)}catch{return String(e)}}return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e&&null!==e?(()=>{try{return JSON.stringify(e)}catch{return String(e)}})():String(e))).join(", "):e?.toString()??""}registerBinding(e,t,n="text",s){if(this._assignmentRe.test(t))return;const r=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,r),o=this.makeScopedEvaluator(t,r);if("value"===s||"checked"===s){const t=()=>{try{const t=this._createScopedPropsContext(r),n=o(t),i=this.formatValue(n);let a=!1;if("value"===s){const t=e;"value"in e&&t.value!==i?(t.value=i,a=!0):"value"in e||(e.setAttribute("value",i),a=!0)}else{const t=e,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||!this._hydrated||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const c={};this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);c[t]=t}})),c.value="input",c.checked="change";const l=c[s]||s,h="click"===l?new MouseEvent(l,{bubbles:!0,cancelable:!0}):new Event(l,{bubbles:!0});e.dispatchEvent(h)}catch(e){console.error(`Error evaluating attribute "${s}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(s){const n=s.toLowerCase();if(this._boolAttrs.has(n)){e.removeAttribute(n);const a=()=>{try{const t=this._createScopedPropsContext(r),i=!!o(t);e[s]!==i&&(e[s]=i),i?e.setAttribute(n,""):e.removeAttribute(n)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:a})}const a=e.getAttribute(s)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(a)){const t=this.makeAttrTemplateUpdater(e,s,i,a);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(r),n=o(t),i=this.formatValue(n);s in e&&(e[s]=i),e.setAttribute(s,i)}catch(e){console.error(`Error evaluating attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const a={text(e,t){e.textContent!==t&&(e.textContent=t)},value(e,t){e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked(e,t){e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr(e,t){e.setAttribute("attr",t)}};this._bindings.push({dependencies:i,update:()=>{try{const t=this._createScopedPropsContext(r),s=o(t),i=this.formatValue(s);a[n](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const t=s(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const n=e.trim(),s=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(n)?`${n}; return "";`:`return (${n});`}\n }\n } catch {\n return "";\n }\n `;let r;try{r=new Function("ctx",s)}catch(t){const n=JSON.stringify(e);r=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return n=>{try{for(let s=t.length;s>=0;s--){const i=t.slice(0,s);try{const t=this._createScopedPropsContext(i,n),s=r(t);if(Array.isArray(s)&&"voucherItems"===e)return s;if(null!=s&&""!==s&&"voucherItems"!==e)return s}catch{}}const s=this._createScopedPropsContext(t,n),i=r(s);return null==i?"":i}catch{return""}}}_createScopedPropsContext(e,t={}){const n=e.join("."),s=this.getNested(this.props,n)||{},r=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const o=r.getScopedFunction(n,e);if(o)return o;if(s&&n in s)return s[n];for(let t=e.length-1;t>=0;t--){const s=e.slice(0,t).join("."),i=r.getScopedFunction(n,e.slice(0,t));if(i)return i;const o=s?r.getNested(r.props,s):r.props;if(o&&n in o)return o[n]}return n in globalThis?globalThis[n]:void 0},set(t,s,i,o){if("string"!=typeof s)return Reflect.set(t,s,i,o);if(s in t)return Reflect.set(t,s,i,o);for(let t=e.length;t>=0;t--){const n=e.slice(0,t).join("."),o=n?`${n}.${s}`:s;if(r.hasNested(r.props,o))return r.setNested(r.props,o,i),r._dirtyDeps.add(o),r.scheduleFlush(),!0}const a=n?`${n}.${s}`:s;return r.setNested(r.props,a,i),r._dirtyDeps.add(a),r.scheduleFlush(),!0},has:(t,n)=>"string"==typeof n&&(n in t||!!r.getScopedFunction(n,e)||s&&n in s||n in globalThis||e.some(((t,s)=>{const i=e.slice(0,s).join("."),o=i?r.getNested(r.props,i):r.props;return o&&n in o})))})}extractScopedDependencies(e,t){const n=this.extractDependencies(e),s=new Set,r=t.join(".");for(const e of n){if(this._reservedWords.has(e.split(".")[0]))continue;const n=r+"."+e;if(this._stateHierarchy.has(n)){s.add(n);continue}if(this.hasNested(this.props,n)){s.add(n);continue}let i=!1;for(let n=t.length-1;n>=0&&!i;n--){const r=t.slice(0,n).join("."),o=r?r+"."+e:e;this._stateHierarchy.has(o)?(s.add(o),i=!0):this.hasNested(this.props,o)&&(s.add(o),i=!0)}if(!i){const t=r+"."+e;s.add(t)}}return s}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const n=this.detectElementHierarchy(e),s=[];let r=e;for(;r;){if(r.hasAttribute("pp-if"))s.push({el:r,expr:r.getAttribute("pp-if")});else if(r.hasAttribute("pp-elseif"))s.push({el:r,expr:r.getAttribute("pp-elseif")});else{if(!r.hasAttribute("pp-else"))break;s.push({el:r,expr:null})}t.add(r),r=r.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,n);const s=this.makeScopedEvaluator(t,n);e.evaluate=()=>{const e=this._createScopedPropsContext(n);return!!s(e)}}}));const i=new Set;s.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})}))}async manageAttributeBindings(e=document.body){this.qsa(e,"*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{const n=t.name.toLowerCase(),s=t.value.trim();this._boolAttrs.has(n)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(s)&&(e.removeAttribute(t.name),this.registerBinding(e,s,"text",n))})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;const n=t.name;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(n))return;const s=this.decodeEntities(t.value).replace(/^{{\s*|\s*}}$/g,""),r=n.replace(/^pp-bind-/,""),i="value"===r?"value":"checked"===r?"checked":"text";this.registerBinding(e,s,i,r)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=this.detectElementHierarchy(e),s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),r=new Set;s.forEach((e=>{this.extractScopedDependencies(e,n).forEach((e=>r.add(e)))}));const i=new Set;this._bindings.push({dependencies:r,update:()=>{try{const t={},r=this._createScopedPropsContext(n);s.forEach((e=>{const s=this.makeScopedEvaluator(e,n)(r)??{};Object.assign(t,s)})),i.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),i.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==n||!1===n)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const s="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==s&&e.setAttribute(t,s),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})}))}))}callInlineModule(e,...t){const n=this._currentProcessingHierarchy||["app"],s=this.getScopedFunction(e,n);if(!s)throw new Error(`PPHP: no inline module named "${e}" in scope ${n.join(".")}`);return s(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return r.get(e)}if(e.startsWith("set")){const n=e.charAt(3).toLowerCase()+e.slice(4);for(let e=t.length;e>=0;e--){const s=t.slice(0,e).join("."),r=s?`${s}.${n}`:n;if(this.hasNested(this.props,r))return e=>{this.setNested(this.props,r,e),this._dirtyDeps.add(r),this.scheduleFlush()}}}return null}async processInlineModuleScripts(e=document.body){this._inlineDepth++;try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>!this._processedPhpScripts.has(e)));if(0===t.length)return;const n=t.map((e=>({script:e,hierarchy:this.detectComponentHierarchy(e),depth:this.detectComponentHierarchy(e).length}))).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of n){this._currentProcessingHierarchy=t;const n=t.join(".");let s=(e.textContent||"").trim();s=this.decodeEntities(s),s=this.stripComments(s),s=this.transformStateDeclarations(s),s=this.injectScopedVariables(s,t);const r=this.extractSetters(s);if(r.length){s+="\n\n";for(const e of r)s+=`pphp._registerScopedFunction('${n}', '${e}', ${e});\n`}s=s.replace(/pphp\.(state|share)\(\s*(['"])([^'" ]+)\2\s*,/g,((e,t,n,s)=>`pphp.${t}('${s}',`));const i=[];for(const[,e]of[...s.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${n}', '${e}', ${e});`);i.length&&(s+="\n\n"+i.join("\n"));const o=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(o);try{const e=await import(a);this._inlineModuleFns.has(n)||this._inlineModuleFns.set(n,new Map);const t=this._inlineModuleFns.get(n);for(const[n,s]of Object.entries(e))"function"!=typeof s||t.has(n)||t.set(n,s)}catch(e){console.error("Inline module import failed:",e),console.error("Generated source:",s)}finally{URL.revokeObjectURL(a),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}injectScopedVariables(e,t){const n=this.extractVariableReferences(e),s=this.extractDeclaredVariables(e),r=[],i=new Set;for(const e of n)if(!i.has(e)&&!s.has(e)&&this.hasInScopedContext(e,t)){const n=this.findScopedKeyForVariable(e,t);r.push(`\nconst ${e} = (() => {\n const fn = () => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n };\n \n // Add dependency tracking key\n fn.__pphp_key = '${n}';\n \n // Add value property for direct access\n Object.defineProperty(fn, 'value', {\n get() {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n },\n configurable: true\n });\n \n // Add valueOf and toString for automatic coercion\n fn.valueOf = function() { return this.value; };\n fn.toString = function() { return String(this.value); };\n \n return fn;\n})();`);const o=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(o,t)&&!s.has(o)&&(r.push(`\nconst ${o} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${o}(...args);\n};`),i.add(o)),i.add(e)}return r.length>0?r.join("\n")+"\n\n"+e:e}extractDeclaredVariables(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const s=[/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+\[\s*([^}]+?)\s*\]/g,/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g];for(const e of s){let s;for(;null!==(s=e.exec(n));)if(e.source.includes("\\[")){const e=s[1].split(",").map((e=>e.trim())).filter(Boolean);for(const n of e)t.add(n)}else t.add(s[1])}return t}findScopedKeyForVariable(e,t){const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return`${n}.${e}`;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?this.getNested(this.props,s):this.props;if(r&&"object"==typeof r&&e in r)return s?`${s}.${e}`:e}return`${n}.${e}`}extractVariableReferences(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const s=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let r;for(;null!==(r=s.exec(n));){const e=r[1],s=r.index;if(this._reservedWords.has(e))continue;const i=n.substring(Math.max(0,s-20),s);if(/\b(?:const|let|var|function)\s+$/.test(i))continue;if(/\[\s*[^}]*$/.test(i))continue;if(s>0&&"."===n[s-1])continue;const o=n.substring(s+e.length,s+e.length+5);/^\s*:/.test(o)||t.add(e)}return t}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return!0;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n),r=s.join(".");if(this.getScopedFunction(e,s))return!0;const i=r?this.getNested(this.props,r):this.props;if(i&&"object"==typeof i&&e in i)return!0;const o=r?`${r}.${e}`:e;if(this._stateHierarchy.has(o))return!0}return!1}_registerScopedFunction(e,t,n){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...s)=>{const r=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&s.length>0?n(s[0]):n(...s)}finally{this._currentExecutionScope=r}}))}extractSetters(e){const t=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let s;for(;s=n.exec(e);){const[,e,n,r]=s;"share"===r&&this.markShared(e),this._sharedStateMap.has(e)||t.push(n)}return t}markShared(e){this._sharedStateMap.add(e)}transformStateDeclarations(e){return e=(e=(e=e.replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s,r)=>`${t}${n}, ${s}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}${n}${s}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}[${n}] = pphp.state('${n}', `))}stripComments(e){let t="",n=0,s=!1,r="",i=!1;for(;n<e.length;){const o=e[n],a=e[n+1];if(i||"'"!==o&&'"'!==o&&"`"!==o||"\\"===e[n-1])if(s)t+=o,n++;else if(i||"/"!==o||"*"!==a)if(i)"*"===o&&"/"===a?(i=!1,n+=2):n++;else if("/"!==o||"/"!==a)t+=o,n++;else for(;n<e.length&&"\n"!==e[n];)n++;else i=!0,n+=2;else s=!s,r=s?o:"",t+=o,n++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let n=!1;const s=this.getBindingType(t);for(const r of t.dependencies){for(const t of e)if(this.dependencyMatches(t,r,s)){n=!0;break}if(n)break}if(n)try{t.update()}catch(e){console.error("Binding update error:",e)}})),this._pendingBindings.forEach((e=>{try{e.update()}catch(e){console.error("Pending binding update error:",e)}})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const n=t.__deps||new Set,s=t.__functionDeps||[];if(0===n.size&&0===s.length){try{t()}catch(e){console.error("effect error:",e)}return}const r=[...n].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=s.length>0;if(r||i)try{t()}catch(e){console.error("effect error:",e)}}))}static ARRAY_INTRINSICS=(()=>{const e=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]);return new Set(Object.getOwnPropertyNames(Array.prototype).filter((t=>!e.has(t))))})();static headMatch(e,t){return e===t||e.startsWith(t+".")}dependencyMatches(e,t,n="binding"){const s=e=>{if(e.startsWith("app.")){const t=e.slice(4),n=t.split(".")[0];if(PPHP._shared.has(n))return t}return e},r=s(e),i=s(t);if(r===i||e===t)return!0;const o=i.split(".");if(o.length>1&&PPHP.ARRAY_INTRINSICS.has(o.at(-1))&&PPHP.headMatch(r,o.slice(0,-1).join(".")))return!0;switch(n){case"effect":return this.matchEffectDependency(r,i);case"loop":return!(!PPHP.headMatch(r,i)&&!PPHP.headMatch(i,r))||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchLoopDependency(r,i);default:return!!PPHP.headMatch(r,i)||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchBindingDependency(r,i)}}matchEffectDependency(e,t){if(e.startsWith(t+".")){return!e.substring(t.length+1).includes(".")}return!!t.includes("*")&&this.matchesWildcardPattern(e,t)}matchLoopDependency(e,t){return!(!e.startsWith(t+".")&&!t.startsWith(e+"."))||(!(!this.isArrayPath(t)||!this.isArrayItemPath(e,t))||(t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)))}isArrayPath(e){try{const t=this.getNested(this.props,e);return Array.isArray(t)}catch{return!1}}isArrayItemPath(e,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+($|\\.)`).test(e)}matchBindingDependency(e,t){if(e.startsWith(t+".")){return e.substring(t.length+1).split(".").length<=2}return t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)}matchesWildcardPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if("*"!==t&&t!==r)return!1}return!0}matchesArrayIndexPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=n[e],r=s[e];if(t!==r&&(!/^\d+$/.test(t)||!/^\d+$/.test(r)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const s=t.split("."),r=s.pop(),i=s.reduce(((e,t)=>e[t]??={}),e);null===n||"object"!=typeof n||Array.isArray(n)||n.__isReactiveProxy?i[r]=n:i[r]=this.makeReactive(n,s.concat(r))}hasNested(e,t){return void 0!==this.getNested(e,t)}share(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.share: key must be a non-empty string.");if(this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another share key.`);const n=PPHP._shared.get(e);if(n)return[n.getter,n.setter];const[s,r]=this.state(e,t);return PPHP._shared.set(e,{getter:s,setter:r}),[s,r]}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure the build-time injector rewrote your declaration to pphp.state('foo', 0).");if(arguments.length<2&&(t=void 0),this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another state key.`);const n=this._currentProcessingHierarchy||["app"],s=this.generateScopedKey(n,e);this._stateHierarchy.set(s,{originalKey:e,hierarchy:[...n],level:n.length}),this.hasNested(this.props,s)||this.setNested(this.props,s,t);const r=()=>this.getNested(this.props,s),i=e=>{const t=r(),n="function"==typeof e?e(t):e;this.setNested(this.props,s,n),this._dirtyDeps.add(s),n&&"object"==typeof n&&this.markNestedPropertiesDirty(s,n),this.scheduleFlush()},o=()=>r();Object.defineProperty(o,"value",{get:()=>r(),set:e=>i(e)}),Object.defineProperties(o,{valueOf:{value:()=>r()},toString:{value:()=>String(r())},__isReactiveProxy:{value:!0,writable:!1}}),o.__pphp_key=s;const a=r();if(null===a||"object"!=typeof a)return[o,i];const c=this;return[new Proxy(o,{apply:(e,t,n)=>Reflect.apply(e,t,n),get(e,t,n){if("value"===t)return r();if("__pphp_key"===t)return s;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,n);if("string"==typeof t){const n=r();if(n&&"object"==typeof n){const r=Object.prototype.hasOwnProperty.call(n,t),i=t in e&&void 0!==e[t];if(r||!i){let e=n[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...s.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,n);const i=r();return i&&"object"==typeof i?i[t]:void 0},set(e,t,n){if("value"===t)return i(n),!0;if("__isReactiveProxy"===t)return!0;const o=r();return o&&"object"==typeof o&&(o[t]=n,c._dirtyDeps.add(`${s}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in o)return!0;const n=r();return n&&"object"==typeof n&&t in n}}),i]}markNestedPropertiesDirty(e,t,n=new WeakSet){t&&"object"==typeof t&&!n.has(t)&&(n.add(t),Object.keys(t).forEach((s=>{const r=`${e}.${s}`;this._dirtyDeps.add(r);const i=t[s];i&&"object"==typeof i&&!n.has(i)&&this.markNestedPropertiesDirty(r,i,n)})))}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return n=>{const s=e.get(n);if(void 0!==s)return s;const r=n in globalThis||t.some((e=>n in e));return e.set(n,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let n=e.replace(/\?\./g,".");const s=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(n);){(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)))}const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(n);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const o=e=>{let t="",n=0;for(;n<e.length;)if("`"===e[n])for(n++;n<e.length;)if("\\"===e[n])n+=2;else if("$"===e[n]&&"{"===e[n+1]){n+=2;let s=1;const r=n;for(;n<e.length&&s>0;)"{"===e[n]?s++:"}"===e[n]&&s--,n++;const i=e.slice(r,n-1);t+=o(i)+" "}else{if("`"===e[n]){n++;break}n++}else t+=e[n++];return t};n=o(n),n=n.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),n=n.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const a=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of n.match(c)??[]){const[n,...r]=t.split(".");s.has(n)||(0===r.length&&PPHP._isBuiltIn(n)&&new RegExp(`\\.${n}\\b`).test(e)||a.add(t))}return a}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,n=PPHP._mustacheTest,s=this.props,r=new Set;this.qsa(e,"*").forEach((e=>{const s=this.detectElementHierarchy(e);for(const{name:i,value:o}of Array.from(e.attributes))if(o){if(n.test(o))for(const e of o.matchAll(t))this.extractScopedDependencies(e[1],s).forEach((e=>r.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(o,s).forEach((e=>r.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>n.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const n=e.parentElement;if(!n)continue;const s=this.detectElementHierarchy(n);for(const n of e.nodeValue.matchAll(t))this.extractScopedDependencies(n[1],s).forEach((e=>r.add(e)))}const o=Array.from(r).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of o){const t=e.split(".");let n=s;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(s in n)||!r&&(null==n[s]||"object"!=typeof n[s])){const e=this._stateHierarchy.has(i);r&&e||(n[s]=r?void 0:{})}n=n[s]}}}setNestedProperty(e,t,n){const s=t.split(".");let r=e;for(let e=0;e<s.length-1;e++)s[e]in r||(r[s[e]]={}),r=r[s[e]];r[s[s.length-1]]=n}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(","),t=this.qsa(document.body,e);for(const e of t)for(const t of this._eventHandlers){const n=e.getAttribute(t);if(!n)continue;const s=this.decodeEntities(n).trim();if(!s){e.removeAttribute(t);continue}const r=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(s))} }`;e.removeAttribute(t);const i=t.slice(2);e.removeAllEventListeners(i),e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,r)}return this.handlePassiveWheelStashes(document),Promise.resolve()}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let n=t.value;for(;n.includes("&");){t.innerHTML=n;const e=t.value;if(e===n)break;n=e}return n};unwrapArrowBody=e=>{if(!e.trim())return"";const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{([\s\S]*)\}\s*$/);if(t){let e=t[1].trim();return e&&!e.endsWith(";")&&(e+=";"),e}const n=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(n){let t=e.substring(n[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let s=e.trim();return s&&!s.endsWith(";")&&(s+=";"),s};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}->${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}::${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`}));const{normalized:n,originalParam:s}=this.normalizeToArrow(t),r=this.renameEventParam(n,s);return this.replaceThisReferences(r)}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const n=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(n)?n:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const n=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(n,((e,t,n)=>{const s=n[t-1],r=n[t+e.length];return s&&/[\w$]/.test(s)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,n){const s=e.getAttribute("pp-debounce"),r=s?this.parseTime(s):0,i=e.getAttribute("pp-before-request")??"",o=e.getAttribute("pp-after-request")??"",a=PPHP._cancelableEvents,c=async s=>{a.has(t)&&s.cancelable&&s.preventDefault();try{i&&await this.invokeHandler(e,i,s),await this.invokeHandler(e,n,s),o&&!o.startsWith("@close")&&await this.invokeHandler(e,o,s),this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!a.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(r>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const n=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),r);PPHP._debounceTimers.set(h,n)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),d(e)}),l):e.addEventListener(t,d,l)}debounce(e,t=300,n=!1){let s;return function(...r){const i=this;s&&clearTimeout(s),s=setTimeout((()=>{s=null,n||e.apply(i,r)}),t),n&&!s&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const n=t.getAttribute("pp-autofocus");if(!this.isJsonLike(n))return;const s=this.parseJson(n);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,s),t.type="number"):this.setCursorPosition(t,s))}))}async invokeHandler(e,t,n){try{const s=t.trim();let r=this._handlerCache.get(s);r||(r=this.parseHandler(s),this._handlerCache.set(s,r)),await this.executeHandler(r,e,n,s)}catch(n){this.handleInvokeError(n,t,e)}finally{this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const n=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(n)return{type:"call",name:n[1],args:n[2],isAsync:this.isAsyncFunction(n[1])};const s=t.match(/^(\w+)$/);return s?{type:"simple",name:s[1],isAsync:this.isAsyncFunction(s[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,n="",s=0;for(let r=0;r<e.length-1;r++){const i=e[r],o=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===n&&"\\"!==e[r-1])t=!1,n="";else if(!t&&("("===i&&s++,")"===i&&s--,"="===i&&">"===o&&s>=0))return!0}else t=!0,n=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let n=e.substring(t+2).trim();return n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1).trim()),{type:"arrow",body:n,isAsync:e.includes("async")||this.containsAwait(n)}}findArrowIndex(e){let t=!1,n="";for(let s=0;s<e.length-1;s++){const r=e[s],i=e[s+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===n&&"\\"!==e[s-1])t=!1;else if(!t&&"="===r&&">"===i)return s}else t=!0,n=r}return-1}async executeArrowHandler(e,t,n){const s=this.parseStatements(e.body);let r=!1;for(const e of s)await this.executeSingleStatement(e,t,n)&&(r=!0);r||await this.executeDynamic(e.body,t,n)}async executeComplexHandler(e,t,n){await this.executeDynamic(e.body,t,n)}parseStatements(e){const t=[];let n="",s=0,r=!1,i="";for(let o=0;o<e.length;o++){const a=e[o];r||'"'!==a&&"'"!==a&&"`"!==a?r&&a===i&&"\\"!==e[o-1]&&(r=!1,i=""):(r=!0,i=a),r||("("!==a&&"{"!==a&&"["!==a||s++,")"!==a&&"}"!==a&&"]"!==a||s--,";"!==a||0!==s)?n+=a:n.trim()&&(t.push(n.trim()),n="")}return n.trim()&&t.push(n.trim()),t}async executeInlineModule(e,t,n,s,r){if(t&&t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t);null!==n&&"object"==typeof n?await this.callInlineModule(e,{...n}):await this.callInlineModule(e,n)}else try{const s=this.detectElementHierarchy(n),r=this._createScopedPropsContext(s),i=this.makeScopedEvaluator(t,s)(r);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:n,event:s})}else await this.handleParsedCallback(n,r,s)}async executeSingleStatement(e,t,n){const s=e.trim();if(!s)return!1;const r=s.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return this.executeSingleStatement(r[1],t,n);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(s))return await this.executeDynamic(s,t,n),!0;const i=s.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(e,o);let c=[];if(""!==r.trim())try{c=JSON5.parse(`[${r}]`)}catch{try{const e=this._createScopedPropsContext(o),t=this.getOrCreateProxy(e),s=/\bevent\b/.test(r)?r.replace(/\bevent\b/g,"_evt"):r;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${s} ]; }`)(n,t,e)}catch(e){c=[]}}if(a){const e=this.getScopedFunction(a,o);if(e)return c.length>0?await e(...c):await this.executeInlineModule(a,r,t,n,s),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,s,n),!0}const o=s.match(/^(\w+)$/);if(o){const e=o[1],s=this.detectElementHierarchy(t),r=this.resolveFunctionName(e,s);if(r){if(this.getScopedFunction(r,s))return await this.handleParsedCallback(t,`${r}()`,n),!0}if(r){const e=globalThis[r];if("function"==typeof e)return e.call(globalThis,n),!0}return await this.handleParsedCallback(t,`${e}()`,n),!0}return await this.executeDynamic(s,t,n),!0}async executeCallHandler(e,t,n,s){const{name:r,args:i}=e,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(r,o);if(a){if(this.getScopedFunction(a,o))return void await this.executeInlineModule(a,i||"",t,n,s);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,n)}await this.handleParsedCallback(t,s,n)}resolveFunctionName(e,t){if(t)for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,n){const{name:s}=e,r=this.detectElementHierarchy(t),i=this.resolveFunctionName(s,r);if(i){if(this.getScopedFunction(i,r))return void await this.handleParsedCallback(t,`${i}()`,n);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,n)}await this.handleParsedCallback(t,`${s}()`,n)}async executeHandler(e,t,n,s){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,n);break;case"call":await this.executeCallHandler(e,t,n,s);break;case"simple":await this.executeSimpleHandler(e,t,n);break;case"complex":await this.executeComplexHandler(e,t,n);break;default:await this.handleParsedCallback(t,s,n)}}async executeGlobalFunction(e,t,n,s){if(t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t)??{};e.call(globalThis,{...n})}else{const r=this.detectElementHierarchy(n),i=this._createScopedPropsContext(r),o=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(n,s,o,i,e)}else e.call(globalThis,s)}async executeDynamic(e,t,n){const s=this.detectElementHierarchy(t),r=this._createScopedPropsContext(s),i=this.getOrCreateProxy(r),o=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await o.call(t,n,i,r)}finally{this.scheduleFlush()}}static AsyncFunction=Object.getPrototypeOf((async()=>{})).constructor;getOrCreateEvaluator(e){let t=this._evaluatorCache.get(e);return t||(t=this.makeSafeEvaluator(e),this._evaluatorCache.set(e,t)),t}getOrCreateProxy(e){let t=this._handlerProxyCache.get(e);return t||(t=this.createHandlerProxy(e),this._handlerProxyCache.set(e,t)),t}createHandlerProxy(e){const t=this._currentProcessingHierarchy||["app"],n={alert:window.alert.bind(window),confirm:window.confirm.bind(window),prompt:window.prompt.bind(window),console:window.console,setTimeout:window.setTimeout.bind(window),setInterval:window.setInterval.bind(window),clearTimeout:window.clearTimeout.bind(window),clearInterval:window.clearInterval.bind(window),fetch:window.fetch.bind(window)};return new Proxy(e,{get:(e,s,r)=>{if("string"==typeof s){if(n.hasOwnProperty(s))return n[s];const i=this.getScopedFunction(s,t);if(i)return i;if(s in e){const t=Reflect.get(e,s,r),n=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof n))return t}if(s in globalThis&&!n.hasOwnProperty(s)){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,r)},set:(e,t,n,s)=>Reflect.set(e,t,n,s),has:(e,t)=>{if("string"==typeof t){const s=this._currentProcessingHierarchy||["app"];return n.hasOwnProperty(t)||!!this.getScopedFunction(t,s)||t in e||t in globalThis}return t in e||t in globalThis}})}isAsyncFunction(e){const t=this._inlineModuleFns.get(e)||globalThis[e];return t&&("AsyncFunction"===t.constructor.name||t.toString().includes("async "))}containsAwait(e){return/\bawait\s+/.test(e)}handleInvokeError(e,t,n){const s=e instanceof Error?e.message:String(e),r=n.tagName+(n.id?`#${n.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${s}`,e),n.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:n},bubbles:!0}))}clearHandlerCaches(){this._handlerCache.clear(),this._evaluatorCache.clear()}async handleParsedCallback(e,t,n){const{funcName:s,data:r}=this.parseCallback(e,t);if(!s)return;const i=Array.isArray(s)?s:[s],o=this.detectElementHierarchy(e);let a;for(const e of i){const t=this.getScopedFunction(e,o);if(t){a=t;break}if("function"==typeof this[e]){a=this[e];break}if("function"==typeof window[e]){a=window[e];break}}if(a){const t=e.hasAttribute("pp-after-request"),s="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(r.args)?r.args:[],element:e,data:r,event:n};if(t&&!s){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};i={...i,...e}}await a.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(s)?s[0]:s,r)}async handleUndefinedFunction(e,t,n){const s={callback:await this.encryptCallbackName(t),...n},r=this.createFetchOptions(s),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const s=new URL(window.location.href);let o="",a="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(o=await this.fetchFileWithData(s.href,t,l,n),a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(s.href,r);if(o=await e.text(),this.getRedirectUrl(o))return void await this.redirect(this.getRedirectUrl(o)||"");if(a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",d=e.getAttribute("pp-after-request")||"";if((h||d&&c.success)&&this.restoreSuspenseElement(e),h||d){let e="";if(c.success){e=o.replace(a,"")}else e=o;if(this.appendAfterbegin(e),!d&&!c.success)return}if(d&&c.success){this.handleAfterRequest(d,a);const e=o.replace(a,"");return this.appendAfterbegin(e),a}if("@close"===d)return c.success?a:void 0;const p=await this.fetch(s.href,i),u=await p.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(o,u,a,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const n=this.parseJson(e),s=t?this.parseJson(t):null,r=n.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);let i={};if(s){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?s[e.responseKey]:s.response);break;default:i[t]=n[t]}}else i=n;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,n)=>` data-onwheel-code="${this.decodeEntities(n).replace(/"/g,"&quot;")}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{const t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null,t&&(e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t))}))}async handleResponseRedirectOrUpdate(e,t,n,s){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,n,s),o=(new DOMParser).parseFromString(r,"text/html");i&&o.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(o.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const s=document.createElement("div");if(s.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");s.innerHTML=t}else s.innerHTML=e;return s.innerHTML?s:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const n=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(n),await this.appendCallbackResponse(n),await this.processInlineModuleScripts(n),await this.initializeAllReferencedProps(n),await this.manageAttributeBindings(n),await this.populateDocumentBody(n),await this.initRefs(),await this.processIfChains(),await this.initLoopBindings();for(const e of this._bindings)try{e.update()}catch(e){console.error(e)}this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute(),document.body.removeAttribute("hidden")}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[s,r]=this.decodeHTML(t[n]).split(",");e.classList.replace(s,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const s=this.parseJson(e);n(t,s)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?s(e,t):n(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const s=this.parseJson(t);n(e,s)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),s(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&i(s,n)}));const{targets:t,...s}=r;n(e,s)}else{const{empty:t,...s}=r;n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,n,s={}){const r=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in s)s.hasOwnProperty(e)&&r.append(e,s[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await o.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(this.isJsonLike(e)){const n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}))}else s(t,e)}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),s.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=s;this.updateElementAttributes(e,o),n(e,r)}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}));const{targets:t,...n}=s;this.updateElementAttributes(e,n)}else{if("disabled"===s.empty&&""===e.value)return;const{empty:t,...n}=s;this.updateElementAttributes(e,n)}}else if(t)s(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n];t[s.name]=s.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let n={};const s=e.closest("form");if(s){new FormData(s).forEach(((e,t)=>{n[t]?Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]:n[t]=e}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const r=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(r){const e=r[1].trim(),t=r[2].trim(),s=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e&&(n={...n,...e})}catch(e){console.error("Error parsing JSON args:",e),n.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e?n={...n,...e}:n.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),n.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();n.args=Array.isArray(e)?e:[e]}catch{s.test(t)?n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):n.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);n.args=[e]}catch{n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:n}}return{funcName:t,data:n}}evaluateJavaScriptObject(e){try{const t=this.getOrCreateProxy(this.props);return new Function("proxy","Date","Math","JSON",`\n with (proxy) {\n return ${e};\n }\n `).call(null,t,Date,Math,JSON)}catch(e){throw console.error("Failed to evaluate JavaScript object:",e),e}}handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),s=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===s){const t=e.name||e.id;if(t){const n=new URL(window.location.href),s=new URLSearchParams(n.search);s.has(t)&&(e.value=s.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,s=new URL(window.location.href),r=new URLSearchParams(s.search),i=t.name||t.id;if(i){n?r.set(i,n):r.delete(i);const e=r.toString()?`${s.pathname}?${r.toString()}`:s.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),s=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",s)))}handleVisibilityElementAttribute(e,t,n){const s=e.getAttribute(t);if(s)if(this.isJsonLike(s)){n(e,this.parseJson(s))}else{const n=this.parseTime(s);if(n>0){const s="pp-visibility"===t?"visibility":"display",r="visibility"===s?"hidden":"none";this.scheduleChange(e,n,s,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,s,r){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=s,this.scheduleChange(e,i,n,r),o>0&&this.scheduleChange(e,i+o,n,s)):o>0&&this.scheduleChange(e,o,n,s)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),s=t.getAttribute("target");if(n&&"_blank"!==s&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[r,i]=n.split("#");i&&(s=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const o=`${e.pathname}?${t.toString()}${s}`;history.pushState(null,"",o)}else{const[e,t]=n.split("#"),s=`${e}${t?`#${t}`:""}`;history.pushState(null,"",s)}const s=n.indexOf("#");if(-1!==s){const e=n.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok)return void console.error(`Navigation error: ${t.status} ${t.statusText}`);const n=await t.text(),s=n.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(n)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const s=n.lastIndexOf("/");n=s<=0?"/":n.substring(0,s)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:s}=this.parseTransition(e);await this.fadeOut(t,s),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const s=e.querySelector("[pp-loading-transition]"),r=s?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),n=this.sanitizePassiveHandlers(e),s=(new DOMParser).parseFromString(n,"text/html");this.scrubTemplateValueAttributes(s);const r="pp-dynamic-script",i="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${i}]`).forEach((e=>e.remove())),document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove())),Array.from(s.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(r)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){const t=e;if(t.getAttribute("charset")||"viewport"===t.name)return;const n=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,s=document.head.querySelector(n),r=t.cloneNode(!0);s?document.head.replaceChild(r,s):document.head.querySelector("title")?.nextSibling?document.head.insertBefore(r,document.head.querySelector("title").nextSibling):document.head.appendChild(r)}else if("TITLE"===t){const t=document.head.querySelector("title"),n=e.cloneNode(!0);t?document.head.replaceChild(n,t):document.head.appendChild(n)}else if("LINK"===t){const t=e;if("icon"===t.rel){const e=document.head.querySelector('link[rel="icon"]'),n=t.cloneNode(!0);e?document.head.replaceChild(n,e):document.head.appendChild(n)}else t.hasAttribute(i)&&document.head.appendChild(t.cloneNode(!0))}})),this.resetProps(),await this.processInlineModuleScripts(s),await this.initializeAllReferencedProps(s),await this.manageAttributeBindings(s),await this.populateDocumentBody(s),await this.initRefs(),await this.processIfChains(),await this.initLoopBindings();for(const e of this._bindings)try{e.update()}catch(e){console.error(e)}this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute(),document.body.removeAttribute("hidden")}async rerunInlineScripts(){const e=Array.from(document.querySelectorAll('script[type="text/javascript"]:not([src])')),t=new Map;e.forEach((e=>{const n=(e.textContent||"").trim();if(t.has(n))return void e.remove();t.set(n,e);const s=document.createElement("script");[...e.attributes].forEach((e=>s.setAttribute(e.name,e.value))),s.textContent=e.textContent,e.replaceWith(s)}))}scrubTemplateValueAttributes(e){e.querySelectorAll('input[value*="{{"], textarea[value*="{{"], select[value*="{{"],[checked*="{{"], [selected*="{{"]').forEach((e=>{e.hasAttribute("value")&&e.removeAttribute("value"),e.hasAttribute("checked")&&e.removeAttribute("checked"),e.hasAttribute("selected")&&e.removeAttribute("selected")}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const n=this.getElementKey(t);e[n]&&(t.scrollTop=e[n].scrollTop,t.scrollLeft=e[n].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),s.checked=n.checked,document.activeElement!==n||(null!=n.selectionStart&&(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd),!1)},TEXTAREA(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),document.activeElement!==n||(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd,!1)},SELECT(e,t){const n=e;return t.selectedIndex=n.selectedIndex,document.activeElement!==n},VIDEO(e,t){const n=e,s=t;return s.currentTime=n.currentTime,n.paused?s.pause():s.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,n=e instanceof Document?e.body:e;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const n=new Function("event",t);e.addEventListener("wheel",n,{passive:!0})}})),this._wheelHandlersStashed=!0);const s=this.PRESERVE_HANDLERS;morphdom(t,n,{getNodeKey(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.hasAttribute("pp-sync-script")?`pp-sync-script:${t.getAttribute("pp-sync-script")}`:t.getAttribute("key")||void 0},onBeforeElUpdated(e,t){const n=e.tagName;if("SCRIPT"===n||e.hasAttribute("data-nomorph"))return!1;const r=s[n];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let s;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,s=this._activeAbortController):s=new AbortController,fetch(e,{...t,signal:s.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,n,s){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=s}))}),t)}async fetchFunction(e,t={},n=!1){try{const s={callback:await this.encryptCallbackName(e),...t},r=window.location.href;let i;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const n=s[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(s);const o=await this.fetch(r,i,n);if(!o.ok)throw new Error(`Fetch failed with status: ${o.status} ${o.statusText}`);const a=await o.text();try{return JSON.parse(a)}catch{return a}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const n=e.length?e.map((e=>`[pp-sync="${e}"]`)):['[pp-sync="true"]'],s=await this.fetch(window.location.href,this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()})),r=await s.text(),i=(new DOMParser).parseFromString(r,"text/html");await this.initReactiveOn(i),n.forEach((e=>{const t=document.querySelectorAll(e),n=i.body.querySelectorAll(e);t.forEach(((e,t)=>{const s=n[t];s&&(e.innerHTML=s.innerHTML)}))})),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("pphp.sync failed:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),n=await t.text();await this.updateBodyContent(n)}copyCode(e,t,n,s,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(r);if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){const n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,this.listeners.forEach((e=>e(this.state))),this.saveState(),t)){const e=localStorage.getItem(this.STORAGE_KEY);e&&e!==this.lastSyncedState&&(this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e}),this.lastSyncedState=e)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t}),this.lastSyncedState=t}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const s=e[n];null!==s&&t.set(n,s)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
1
+ (()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let o=i;s.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:o&&void 0===o.passive&&(o={...o,passive:!0})),n.has(this)||n.set(this,new Map);const a=n.get(this),c=a.get(t)||new Set;c.add(r),a.set(t,c),e.call(this,t,r,o)},EventTarget.prototype.removeEventListener=function(e,s,r){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t.delete(s),0===t.size&&n.get(this).delete(e)}t.call(this,e,s,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(!n.has(this))return;const s=n.get(this).get(e);s&&(s.forEach((n=>{t.call(this,e,n)})),n.get(this).delete(e))}})(),function(){const e=console.log;console.log=(...t)=>{const n=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,n)}}();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_proxyCache=new WeakMap;_rawProps={};_refs=new Map;_wheelHandlersStashed=!1;_evaluatorCache=new Map;_depsCache=new Map;_dirtyDeps=new Set;_handlerCache=new Map;_handlerProxyCache=new WeakMap;_sharedStateMap=new Set;_processedLoops=new WeakSet;_hydrated=!1;_currentProcessingHierarchy=null;_stateHierarchy=new Map;_currentTemplateHierarchy=null;_inlineModuleFns=new Map;_currentExecutionScope=null;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _cancelableEvents=new Set(["click","submit","change"]);static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;static _passiveEvents=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),n=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...n].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const n=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",s=e.getAttribute(`pp-${n}`)??null;let r=null;if(s){const t=s.replace(/^{\s*|\s*}$/g,""),n=this.detectElementHierarchy(e);try{r=!!this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n))}catch{r=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:n,expr:s,visible:!e.hasAttribute("hidden"),result:r})})),console.groupEnd(),console.groupEnd()}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{try{await Promise.all([this.initRefs(),this.processInlineModuleScripts(),this._hydrated=!0]),await e(),await this.initializeAllReferencedProps(),await e(),await this.manageAttributeBindings(),await e(),await this.processIfChains(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();const t=250;for(let n=0;n<this._bindings.length;n+=t)this._bindings.slice(n,n+t).forEach((e=>{try{e.update()}catch(e){console.error("Initial binding update error:",e)}})),await e();document.body.removeAttribute("hidden")}catch(e){console.error("Hydration failed:",e),document.body.removeAttribute("hidden")}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}async initCryptoKey(){const e=document.cookie.split("; ").find((e=>e.startsWith("pphp_function_call_jwt=")))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:s,exp:r}=JSON.parse(n);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(s),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),n=(new TextEncoder).encode(e),s=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,n);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(s)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,n]=e.split(":",2),s=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),r=Uint8Array.from(atob(n),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:s},PPHP._cryptoKey,r);return(new TextDecoder).decode(i)}qsa(e,t){return e.querySelectorAll(t)}_inferHierarchyFromEvent(){const e=globalThis.event,t=e?.target??document.activeElement;if(!t||!t.closest)return["app"];const n=[];let s=t;for(;s&&s!==document.documentElement;){const e=s.getAttribute("pp-component");e&&n.unshift(e),s=s.parentElement}return n.length?n:["app"]}callParent(functionNameOrFn,...args){try{const currentHierarchy=this._currentExecutionScope?.split(".")||this._currentProcessingHierarchy||this._inferHierarchyFromEvent();if("function"==typeof functionNameOrFn){const e=functionNameOrFn;return e.name?this.callParentByName(e.name,currentHierarchy,args):this.executeInParentContext(e,currentHierarchy,args)}const str=String(functionNameOrFn).trim();if(!str)return console.warn("callParent: empty functionNameOrFn"),null;if(str.includes("=>"))try{const arrow=eval(str);if("function"==typeof arrow)return this.callParent(arrow)}catch{}const callMatch=str.match(/^([A-Za-z_$]\w*)\s*\(\s*([\s\S]*)\)$/);if(callMatch){const[,e,t]=callMatch;let n;try{n=JSON5.parse(`[${t}]`)}catch{n=t.split(/\s*,\s*/).filter(Boolean).map((e=>{try{return JSON5.parse(e)}catch{return e}}))}const s=this.callParentByName(e,currentHierarchy,n);if(null!==s)return s;if(e.startsWith("set")){const t=e[3].toLowerCase()+e.slice(4),s=PPHP._shared.get(t);if(s)return s.setter(n[0]),null;const r=function(...t){return this[e](...t)};return this.executeInParentContext(r,currentHierarchy,n)}return console.warn(`❌ Parent function '${e}' not found`),null}const assign=str.match(/^\s*([A-Za-z_$]\w*)\s*=\s*([\s\S]+)$/);if(assign){const[,e,t]=assign,n=new Function("ctx",`with(ctx){ return (${t}); }`),s=n(this._createScopedPropsContext(currentHierarchy)),r="set"+e[0].toUpperCase()+e.slice(1),i=this.callParentByName(r,currentHierarchy,[s]);if(null!==i)return i;const o=PPHP._shared.get(e);if(o)return o.setter(s),null;const a=currentHierarchy.slice(0,-1).join("."),c=a?`${a}.${e}`:e;return this.setNested(this.props,c,s),this.scheduleFlush(),null}return this.callParentByName(str,currentHierarchy,args)}catch(e){return console.error("callParent: unexpected error",e),null}}callParentByName(e,t,n){for(let s=t.length-1;s>=0;s--){const r=t.slice(0,s).join("."),i=this._inlineModuleFns.get(r);if(i?.has(e))return i.get(e)(...n)}const s=t.join("."),r=this._inlineModuleFns.get(s);if(r?.has(e))return r.get(e)(...n);for(const[,t]of this._inlineModuleFns)if(t.has(e))return t.get(e)(...n);return null}executeInParentContext(e,t,n){for(let s=t.length-1;s>=0;s--){const r=t.slice(0,s);try{const t=this.createParentScopeContext(r);return this.executeWithContext(e,t,n)}catch(e){console.error(`Error executing anonymous function in parent context (${r.join(".")}):`,e);continue}}return console.warn("No parent scope found for anonymous function execution"),null}createParentScopeContext(e,t={}){const n=e.join("."),s=this.getNested(this.props,n)||{},r=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const o=r.getScopedFunction(n,e);if(o)return o;if(s&&n in s)return s[n];if("string"==typeof n&&n.startsWith("set")){const e=n.charAt(3).toLowerCase()+n.slice(4);for(const[t,n]of r._stateHierarchy.entries())if(n.originalKey===e)return e=>{r.setNested(r.props,t,e),r._dirtyDeps.add(t),r.scheduleFlush()}}for(let t=e.length-1;t>=0;t--){const s=e.slice(0,t).join("."),i=r._inlineModuleFns.get(s);if(i?.has(n))return i.get(n);const o=s?r.getNested(r.props,s):r.props;if(o&&n in o)return o[n]}return n in globalThis?globalThis[n]:void 0},set:(e,t,n,s)=>Reflect.set(e,t,n,s),has:(t,n)=>"string"==typeof n&&(n in t||!!r.getScopedFunction(n,e)||s&&n in s||n in globalThis||e.some(((t,s)=>{const i=e.slice(0,s).join("."),o=i?r.getNested(r.props,i):r.props;return o&&n in o})))})}executeWithContext(e,t,n){try{return e.toString().includes("=>")?this.executeArrowFunctionWithContext(e,t):n.length>0?e.apply(t,n):e.call(t)}catch(e){throw console.error("🚀 ~ executeWithContext ~ error:",e),e}}executeArrowFunctionWithContext(e,t){const n=e.toString();if(n.includes("=>"))try{const e=n.match(/(?:\([^)]*\)|[^=])\s*=>\s*(.+)/);if(e){let n=e[1].trim();n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1));return new Function("context",`with (context) { return (${n}); }`)(t)}}catch(e){console.error("Failed to execute arrow function with context:",e)}return e()}detectComponentHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return t.length>0?t:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const n=this._refs.get(e)??[];if(null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const n=Array.isArray(t),s=n?t:[],r=n&&0===s.length,i=this._currentProcessingHierarchy||["app"],o=s.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(t){const e=t[1];return this.resolveDependencyPath(e,i)}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),a=s.filter((e=>"function"==typeof e&&!e.__pphp_key)),c=new Set(o),l=new Map;for(const e of o)try{l.set(e,this.getResolvedValue(e))}catch(t){l.set(e,void 0)}const h=new Map;for(const e of a)try{const t=e();h.set(e,t)}catch(t){h.set(e,Symbol("error"))}let d=0,p=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const u=PPHP._effectCleanups,f=()=>{const t=u.get(f);if(t){try{t()}catch(e){console.error("cleanup error:",e)}u.delete(f)}const s=performance.now();if(s-p<16)requestAnimationFrame((()=>{performance.now()-p>=16&&f()}));else{if(p=s,++d>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(c)),new Error("PPHP: effect ran >100 times — possible loop");if(!r){let e=!1;const t=[];if(o.length>0)for(const n of o)try{const s=this.getResolvedValue(n),r=l.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push(n),l.set(n,s))}catch(s){e=!0,t.push(n),l.set(n,void 0)}for(const n of a)try{const s=n(),r=h.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push("(function)"),h.set(n,s))}catch(s){h.get(n)!==Symbol("error")&&(e=!0,t.push("(function-error)"),h.set(n,Symbol("error")))}if(n&&(o.length>0||a.length>0)&&!e)return}try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}}};Object.assign(f,{__deps:c,__static:r,__functionDeps:a,__hierarchy:i,__isEffect:!0});try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(e){console.error("effect error (initial):",e)}const m=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return r?this._effects.add(f):m.add(f),()=>{const e=u.get(f);if(e){try{e()}catch(e){console.error("cleanup error:",e)}u.delete(f)}this._effects.delete(f),this._pendingEffects.delete(f)}}resolveDependencyPath(e,t){const n=e.startsWith("app.")?e.substring(4):e,s=n.split(".")[0];if(PPHP._shared.has(s))return n;const r=t.join(".")+"."+e;if(this.hasNested(this.props,r))return r;if(this.hasNested(this.props,e))return e;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?s+"."+e:e;if(this.hasNested(this.props,r))return r}return e}getResolvedValue(e){e.split(".")[0];const t=(e.startsWith("app.")?e.substring(4):e).split("."),n=t[0],s=PPHP._shared.get(n);if(s){if(1===t.length)return s.getter();{const e=s.getter(),n=t.slice(1).join(".");return this.getNested(e,n)}}return this.getNested(this.props,e)}hasValueChanged(e,t){if(e===t)return!1;if(null==e||null==t)return e!==t;if("object"!=typeof e||"object"!=typeof t)return e!==t;try{return JSON.stringify(e)!==JSON.stringify(t)}catch(e){return!0}}resetProps(){this._isNavigating=!1,this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=null,this._responseData=null,Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable&&delete window[e]}})),this._rawProps={},this.clearShare(),this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._processedLoops=new WeakSet,this._depsCache.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1,this.props=this.makeReactive(this._rawProps),this._hydrated=!1}async initReactiveOn(e=document.body){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),this.processInlineModuleScripts(e),this._hydrated=!0]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.processIfChains(e),await t(),await this.manageAttributeBindings(e),await t(),await this.initLoopBindings(e),await t();for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await t();e===document.body&&document.body.removeAttribute("hidden")}async initLoopBindings(e=document.body){this.qsa(e,"template[pp-for]").forEach((e=>{this._processedLoops.has(e)||(this._processedLoops.add(e),this.registerLoop(e))}))}registerLoop(e){const t=this.parseForExpression(e),{marker:n,parent:s,templateHierarchy:r}=this.setupLoopMarker(e),i=this.initializeLoopState(),o=this.createLoopUpdater(e,t,n,s,r,i),a={dependencies:this.extractComprehensiveLoopDependencies(e,t,r),update:o,__isLoop:!0};this._bindings.push(a)}extractComprehensiveLoopDependencies(e,t,n){const s=new Set;let r=null;for(let e=n.length;e>=0;e--){const s=n.slice(0,e),i=s.length>0?`${s.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,i);if(Array.isArray(e)){r=i;break}}catch{}}if(!r)try{const e=this.getNested(this.props,t.arrExpr);Array.isArray(e)&&(r=t.arrExpr)}catch{r=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr}const i=r;null!==i&&s.add(i);const o=this.extractItemPropertiesFromTemplate(e,t);for(const e of o)if(s.add(`${i}.*`),s.add(`${i}.*.${e}`),"string"==typeof i){const t=this.getNested(this.props,i);if(Array.isArray(t))for(let n=0;n<t.length;n++)s.add(`${i}.${n}.${e}`)}return Array.from(s).some((e=>e.includes("*")))||s.add(`${i}.*`),s}extractItemPropertiesFromTemplate(e,t){const n=new Set,s=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),r=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;r.nextNode();){const e=r.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const n=e;for(const e of Array.from(n.attributes))t+=" "+e.value}const i=t.matchAll(s);for(const e of i)n.add(e[1])}return n}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[n,s]=t.split(/\s+in\s+/),[r,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:n,arrExpr:s,itemName:r,idxName:i}}setupLoopMarker(e){const t=e.parentNode,n=document.createComment("pp-for"),s=this.detectElementHierarchy(e);return t.insertBefore(n,e),t.removeChild(e),{marker:n,parent:t,templateHierarchy:s}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,n,s,r){this._currentTemplateHierarchy=r;const i={...this._createScopedPropsContext(r),[s.itemName]:t};s.idxName&&(i[s.idxName]=n);const o=e.content.cloneNode(!0),a=[],c=this.getItemKey(t,n);return this.processTextNodesInFragment(o,s,r,c,t,n,a),this.processElementBindingsInFragment(o,s,r,c,t,n,a),this.processEventHandlersInFragment(o,s,t,n),a.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),this._currentTemplateHierarchy=null,{nodes:Array.from(o.childNodes),bindings:a}}processTextNodesInFragment(e,t,n,s,r,i,o){const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;a.nextNode();){const e=a.currentNode,c=e.nodeValue||"";if(PPHP._mustacheTest.test(c)){const a=new Set,l=n.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;a.add(h);const d=this.createTextNodeUpdaterWithItemKey(e,c,t,n,s,r);o.push({dependencies:a,update:d}),this.renderTextNode(e,c,t,n,r,i)}}}createTextNodeUpdaterWithItemKey(e,t,n,s,r,i){const o=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const a=o(this._createScopedPropsContext(s));if(Array.isArray(a)){const o=this.findItemByKey(a,r,i),c=a.findIndex((e=>this.getItemKey(e,a.indexOf(e))===r));if(o&&-1!==c){const r={...this._createScopedPropsContext(s),[n.itemName]:o};n.idxName&&(r[n.idxName]=c);const i=this.renderMustacheText(t,s,r);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,n){for(let n=0;n<e.length;n++){const s=e[n];if(this.getItemKey(s,n)===t)return s}return n&&"object"==typeof n&&n.id?e.find((e=>e&&e.id===n.id)):null}processElementBindingsInFragment(e,t,n,s,r,i,o){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,n,s,r,i,o)}))}processElementBindings(e,t,n,s,r,i,o){for(const{name:a,value:c}of Array.from(e.attributes))if("pp-bind"===a)this.createElementBindingWithItemKey(e,c,"text",t,n,s,r,i,o);else if("pp-bind-expr"===a){const a=this.decodeEntities(c);this.createElementBindingWithItemKey(e,a,"text",t,n,s,r,i,o)}else if(a.startsWith("pp-bind-")){const l=a.replace(/^pp-bind-/,"");this.createElementBindingWithItemKey(e,c,l,t,n,s,r,i,o)}}createElementBindingWithItemKey(e,t,n,s,r,i,o,a,c){const l=new Set,h=r.join("."),d=h?`${h}.${s.arrExpr}`:s.arrExpr;l.add(d);const p=this.createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,o);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,n,s,r,o,a)}createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,o){const a=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=a(this._createScopedPropsContext(r));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(a&&-1!==l){const i={...this._createScopedPropsContext(r),[s.itemName]:a};s.idxName&&(i[s.idxName]=l),this.updateElementBinding(e,t,n,r,i)}}}}getItemKey(e,t){if(e&&"object"==typeof e){if("id"in e&&null!=e.id)return`id_${e.id}`;if("key"in e&&null!=e.key)return`key_${e.key}`;if("_id"in e&&null!=e._id)return`_id_${e._id}`;const t=Object.keys(e).filter((t=>(t.toLowerCase().includes("id")||t.toLowerCase().includes("uuid"))&&null!=e[t]&&("string"==typeof e[t]||"number"==typeof e[t])));if(t.length>0){const n=t[0];return`${n}_${e[n]}`}}return`idx_${t}`}renderTextNode(e,t,n,s,r,i){const o={...this._createScopedPropsContext(s),[n.itemName]:r};n.idxName&&(o[n.idxName]=i),e.nodeValue=this.renderMustacheText(t,s,o)}renderMustacheText(e,t,n){return e.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch{return""}}))}updateElementBinding(e,t,n,s,r){const i=this.makeScopedEvaluator(t,s)(r);if("text"===n){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,n,i)}renderElementBinding(e,t,n,s,r,i,o){const a={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(a[s.idxName]=o),this.updateElementBinding(e,t,n,r,a)}applyAttributeBinding(e,t,n){if(this._boolAttrs.has(t)){const s=!!n;s!==e.hasAttribute(t)&&(s?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==s&&(e[t]=s)}else{const s=String(n);t in e&&e[t]!==s&&(e[t]=s),e.getAttribute(t)!==s&&e.setAttribute(t,s)}}processEventHandlersInFragment(e,t,n,s){e.querySelectorAll("*").forEach((e=>{for(const{name:r,value:i}of Array.from(e.attributes)){const o=r.toLowerCase();if(!this._eventHandlers.has(o))continue;let a=i;a=a.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),JSON.stringify(n)),t.idxName&&(a=a.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),String(s))),e.setAttribute(r,a)}}))}updateItemNodes(e,t,n,s,r,i){if(t===n)return;if("object"==typeof t&&"object"==typeof n&&JSON.stringify(t)===JSON.stringify(n))return;this._currentTemplateHierarchy=i;const o={...this._createScopedPropsContext(i),[r.itemName]:n};r.idxName&&(o[r.idxName]=s),this.updateNodesContent(e,i,o),this._currentTemplateHierarchy=null}updateNodesContent(e,t,n){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,n)}))}updateElementContent(e,t,n){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;s.nextNode();){const e=s.currentNode,r=e.nodeValue||"",i=this.renderMustacheText(r,t,n);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,n)}))}updateElementBindingsContent(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if("pp-bind"===s)this.updateElementBinding(e,r,"text",t,n);else if(s.startsWith("pp-bind-")){const i=s.replace(/^pp-bind-/,"");this.updateElementBinding(e,r,i,t,n)}}createLoopUpdater(e,t,n,s,r,i){let o;for(let e=r.length;e>=0;e--){const n=r.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,n),s=e(this._createScopedPropsContext(n));if(Array.isArray(s)){o=e;break}}catch{}}return o=this.makeScopedEvaluator(t.arrExpr,r),()=>{this.performLoopUpdate(e,t,n,s,r,i,o)}}captureFocusState(e){const t=document.activeElement,n=t&&e.contains(t),s=n?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:n,focusKey:s,caretPos:n&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const n=t.querySelector(`[key="${e.focusKey}"]`),s=n?.querySelector("input,textarea");if(s&&(s.focus({preventScroll:!0}),null!==e.caretPos&&s instanceof HTMLInputElement)){const t=Math.min(e.caretPos,s.value.length);s.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const n=new Map,s=new Map;e.forEach(((e,t)=>{const s=this.getItemKey(e,t);n.set(s,{item:e,index:t})})),t.forEach(((e,t)=>{const n=this.getItemKey(e,t);s.set(n,{item:e,index:t})}));const r=new Set,i=new Map,o=new Map;for(const[e]of n)s.has(e)||r.add(e);for(const[e,{item:t,index:r}]of s)if(n.has(e)){const s=n.get(e);s.item===t&&s.index===r||o.set(e,{oldItem:s.item,newItem:t,newIndex:r,oldIndex:s.index})}else i.set(e,{item:t,index:r});return{toDelete:r,toInsert:i,toUpdate:o}}applyLoopChanges(e,t,n,s,r,i,o){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,n,i),this.applyLoopInsertions(e.toInsert,t,n,s,r,i,o)}applyLoopUpdates(e,t,n,s){for(const[r,{oldItem:i,newItem:o,newIndex:a,oldIndex:c}]of e){const e=t.renderedItems.get(r);e&&(this.updateItemNodes(e.nodes,i,o,a,n,s),e.item=o,e.index=a,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,n,s,r,i,o){if(0===e.size)return;const a=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of a){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:a,bindings:h}=this.createItemNodes(o,c,l,n,i);let d=s;const p=Array.from(t.renderedItems.entries()).map((([e,t])=>({key:e,...t}))).sort(((e,t)=>e.index-t.index));for(let e=p.length-1;e>=0;e--)if(p[e].index<l){d=p[e].nodes[p[e].nodes.length-1];break}a.forEach((e=>{r.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:a,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,n,s,r,i,o){const a=this.captureFocusState(s);let c,l=[];for(let e=r.length;e>=0;e--){const t=r.slice(0,e);try{c=this._createScopedPropsContext(t);const e=o(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.log("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(r);const e=o(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,n,s,r,e),i.previousList=[...l],this.restoreFocusState(a,s),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const n of e){const e=t.renderedItems.get(n);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(n))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)??[];n.push(e),this._refs.set(t,n),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){const n=this._proxyCache.get(e);if(n)return n;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const s=this,r=new Proxy(e,{get(e,n,r){if("__isReactiveProxy"===n)return!0;const i=Reflect.get(e,n,r);if(Array.isArray(e)&&"string"==typeof n&&s._mutators.has(n)){let o=s._arrayMethodCache.get(e);if(o||(o=new Map,s._arrayMethodCache.set(e,o)),!o.has(n)){const e=i.bind(r),a=t.join("."),c=function(...t){const n=e(...t);return queueMicrotask((()=>{s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies)if(s.dependencyMatches(a,n,t)){s.scheduleBindingUpdate(e);break}}))})),n};o.set(n,c)}return o.get(n)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy)return s.makeReactive(i,[...t,n]);if(Array.isArray(e)&&"function"==typeof i){let t=s._arrayMethodCache.get(e);return t||(t=new Map,s._arrayMethodCache.set(e,t)),t.has(n)||t.set(n,i.bind(e)),t.get(n)}return i},set(e,n,r,i){if("__isReactiveProxy"===n)return!0;let o=r;null===r||"object"!=typeof r||r.__isReactiveProxy||(o=s.makeReactive(r,[...t,n]));const a=e[n],c=Reflect.set(e,n,o,i);if(a===o)return c;const l=[...t,n].join(".");if(s._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&s._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(n))){const e=t.join(".");if(s._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),n=t.split(".")[0];PPHP._shared.has(n)&&s._dirtyDeps.add(`${t}.*`)}o&&"object"==typeof o&&Object.keys(o).forEach((t=>{if(s._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const n=e.substring(4),r=n.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${n}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(s._dirtyDeps.add(`${e}.*.${String(n)}`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${t}.*.${String(n)}`)}}return s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies){if(s.dependencyMatches(l,n,t)){s.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const r=l.substring(4),i=r.split(".")[0];if(PPHP._shared.has(i)&&s.dependencyMatches(r,n,t)){s.scheduleBindingUpdate(e);break}}}})),s._hydrated&&s.scheduleFlush(),c}});return this._proxyCache.set(e,r),r}getBindingType(e){if(e.__isEffect)return"effect";if(e.__isLoop)return"loop";for(const t of e.dependencies)if(t.includes("*")||t.match(/\.\d+\./)||t.endsWith(".*"))return"loop";for(const t of e.dependencies)try{const e=this.getNested(this.props,t);if(Array.isArray(e))return"loop"}catch{}return"binding"}makeAttrTemplateUpdater(e,t,n,s){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=s??r.get(t),o=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,o).forEach((e=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,o),n=this._createScopedPropsContext(o);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}formatValue(e){if("function"==typeof e){if(e.__isReactiveProxy)try{return this.formatValue(e())}catch{}return""}if(e&&"object"==typeof e){if(e.__isReactiveProxy&&"value"in e)try{return this.formatValue(e.value)}catch{return String(e)}if(e.__isReactiveProxy)try{const t={};for(const n in e)if("__isReactiveProxy"!==n&&"__pphp_key"!==n)try{t[n]=e[n]}catch{}return Object.keys(t).length?JSON.stringify(t,null,2):""}catch{return String(e)}try{return JSON.stringify(e,((e,t)=>{if("__isReactiveProxy"!==e&&"__pphp_key"!==e)return t&&"object"==typeof t&&t.__isReactiveProxy?"function"==typeof t&&"value"in t?t.value:"[Reactive Object]":t}),2)}catch{return String(e)}}return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e&&null!==e?(()=>{try{return JSON.stringify(e)}catch{return String(e)}})():String(e))).join(", "):e?.toString()??""}registerBinding(e,t,n="text",s){if(this._assignmentRe.test(t))return;const r=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,r),o=this.makeScopedEvaluator(t,r);if("value"===s||"checked"===s){const t=()=>{try{const t=this._createScopedPropsContext(r),n=o(t),i=this.formatValue(n);let a=!1;if("value"===s){const t=e;"value"in e&&t.value!==i?(t.value=i,a=!0):"value"in e||(e.setAttribute("value",i),a=!0)}else{const t=e,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||!this._hydrated||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const c={};this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);c[t]=t}})),c.value="input",c.checked="change";const l=c[s]||s,h="click"===l?new MouseEvent(l,{bubbles:!0,cancelable:!0}):new Event(l,{bubbles:!0});e.dispatchEvent(h)}catch(e){console.error(`Error evaluating attribute "${s}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(s){const n=s.toLowerCase();if(this._boolAttrs.has(n)){e.removeAttribute(n);const a=()=>{try{const t=this._createScopedPropsContext(r),i=!!o(t);e[s]!==i&&(e[s]=i),i?e.setAttribute(n,""):e.removeAttribute(n)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:a})}const a=e.getAttribute(s)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(a)){const t=this.makeAttrTemplateUpdater(e,s,i,a);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(r),n=o(t),i=this.formatValue(n);s in e&&(e[s]=i),e.setAttribute(s,i)}catch(e){console.error(`Error evaluating attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const a={text(e,t){e.textContent!==t&&(e.textContent=t)},value(e,t){e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked(e,t){e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr(e,t){e.setAttribute("attr",t)}};this._bindings.push({dependencies:i,update:()=>{try{const t=this._createScopedPropsContext(r),s=o(t),i=this.formatValue(s);a[n](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const t=s(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const n=e.trim(),s=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(n)?`${n}; return "";`:`return (${n});`}\n }\n } catch {\n return "";\n }\n `;let r;try{r=new Function("ctx",s)}catch(t){const n=JSON.stringify(e);r=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return n=>{try{for(let s=t.length;s>=0;s--){const i=t.slice(0,s);try{const t=this._createScopedPropsContext(i,n),s=r(t);if(Array.isArray(s)&&"voucherItems"===e)return s;if(null!=s&&""!==s&&"voucherItems"!==e)return s}catch{}}const s=this._createScopedPropsContext(t,n),i=r(s);return null==i?"":i}catch{return""}}}_createScopedPropsContext(e,t={}){const n=e.join("."),s=this.getNested(this.props,n)||{},r=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const o=r.getScopedFunction(n,e);if(o)return o;if(s&&n in s)return s[n];for(let t=e.length-1;t>=0;t--){const s=e.slice(0,t).join("."),i=r.getScopedFunction(n,e.slice(0,t));if(i)return i;const o=s?r.getNested(r.props,s):r.props;if(o&&n in o)return o[n]}return n in globalThis?globalThis[n]:void 0},set(t,s,i,o){if("string"!=typeof s)return Reflect.set(t,s,i,o);if(s in t)return Reflect.set(t,s,i,o);for(let t=e.length;t>=0;t--){const n=e.slice(0,t).join("."),o=n?`${n}.${s}`:s;if(r.hasNested(r.props,o))return r.setNested(r.props,o,i),r._dirtyDeps.add(o),r.scheduleFlush(),!0}const a=n?`${n}.${s}`:s;return r.setNested(r.props,a,i),r._dirtyDeps.add(a),r.scheduleFlush(),!0},has:(t,n)=>"string"==typeof n&&(n in t||!!r.getScopedFunction(n,e)||s&&n in s||n in globalThis||e.some(((t,s)=>{const i=e.slice(0,s).join("."),o=i?r.getNested(r.props,i):r.props;return o&&n in o})))})}extractScopedDependencies(e,t){const n=this.extractDependencies(e),s=new Set,r=t.join(".");for(const e of n){if(this._reservedWords.has(e.split(".")[0]))continue;const n=r+"."+e;if(this._stateHierarchy.has(n)){s.add(n);continue}if(this.hasNested(this.props,n)){s.add(n);continue}let i=!1;for(let n=t.length-1;n>=0&&!i;n--){const r=t.slice(0,n).join("."),o=r?r+"."+e:e;this._stateHierarchy.has(o)?(s.add(o),i=!0):this.hasNested(this.props,o)&&(s.add(o),i=!0)}if(!i){const t=r+"."+e;s.add(t)}}return s}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const n=this.detectElementHierarchy(e),s=[];let r=e;for(;r;){if(r.hasAttribute("pp-if"))s.push({el:r,expr:r.getAttribute("pp-if")});else if(r.hasAttribute("pp-elseif"))s.push({el:r,expr:r.getAttribute("pp-elseif")});else{if(!r.hasAttribute("pp-else"))break;s.push({el:r,expr:null})}t.add(r),r=r.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,n);const s=this.makeScopedEvaluator(t,n);e.evaluate=()=>{const e=this._createScopedPropsContext(n);return!!s(e)}}}));const i=new Set;s.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})}))}async manageAttributeBindings(e=document.body){this.qsa(e,"*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{const n=t.name.toLowerCase(),s=t.value.trim();this._boolAttrs.has(n)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(s)&&(e.removeAttribute(t.name),this.registerBinding(e,s,"text",n))})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;const n=t.name;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(n))return;const s=this.decodeEntities(t.value).replace(/^{{\s*|\s*}}$/g,""),r=n.replace(/^pp-bind-/,""),i="value"===r?"value":"checked"===r?"checked":"text";this.registerBinding(e,s,i,r)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=this.detectElementHierarchy(e),s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),r=new Set;s.forEach((e=>{this.extractScopedDependencies(e,n).forEach((e=>r.add(e)))}));const i=new Set;this._bindings.push({dependencies:r,update:()=>{try{const t={},r=this._createScopedPropsContext(n);s.forEach((e=>{const s=this.makeScopedEvaluator(e,n)(r)??{};Object.assign(t,s)})),i.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),i.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==n||!1===n)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const s="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==s&&e.setAttribute(t,s),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})}))}))}callInlineModule(e,...t){const n=this._currentProcessingHierarchy||["app"],s=this.getScopedFunction(e,n);if(!s)throw new Error(`PPHP: no inline module named "${e}" in scope ${n.join(".")}`);return s(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return r.get(e)}if(e.startsWith("set")){const n=e.charAt(3).toLowerCase()+e.slice(4);for(let e=t.length;e>=0;e--){const s=t.slice(0,e).join("."),r=s?`${s}.${n}`:n;if(this.hasNested(this.props,r))return e=>{this.setNested(this.props,r,e),this._dirtyDeps.add(r),this.scheduleFlush()}}}return null}async processInlineModuleScripts(e=document.body){this._inlineDepth++;try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>!this._processedPhpScripts.has(e)));if(0===t.length)return;const n=t.map((e=>({script:e,hierarchy:this.detectComponentHierarchy(e),depth:this.detectComponentHierarchy(e).length}))).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of n){this._currentProcessingHierarchy=t;const n=t.join(".");let s=(e.textContent||"").trim();s=this.decodeEntities(s),s=this.stripComments(s),s=this.transformStateDeclarations(s),s=this.injectScopedVariables(s,t);const r=this.extractSetters(s);if(r.length){s+="\n\n";for(const e of r)s+=`pphp._registerScopedFunction('${n}', '${e}', ${e});\n`}s=s.replace(/pphp\.(state|share)\(\s*(['"])([^'" ]+)\2\s*,/g,((e,t,n,s)=>`pphp.${t}('${s}',`));const i=[];for(const[,e]of[...s.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${n}', '${e}', ${e});`);i.length&&(s+="\n\n"+i.join("\n"));const o=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(o);try{const e=await import(a);this._inlineModuleFns.has(n)||this._inlineModuleFns.set(n,new Map);const t=this._inlineModuleFns.get(n);for(const[n,s]of Object.entries(e))"function"!=typeof s||t.has(n)||t.set(n,s)}catch(e){console.error("Inline module import failed:",e),console.error("Generated source:",s)}finally{URL.revokeObjectURL(a),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}injectScopedVariables(e,t){const n=this.extractVariableReferences(e),s=this.extractDeclaredVariables(e),r=[],i=new Set;for(const e of n)if(!i.has(e)&&!s.has(e)&&this.hasInScopedContext(e,t)){const n=this.findScopedKeyForVariable(e,t);r.push(`\nconst ${e} = (() => {\n const fn = () => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n };\n \n // Add dependency tracking key\n fn.__pphp_key = '${n}';\n \n // Add value property for direct access\n Object.defineProperty(fn, 'value', {\n get() {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n },\n configurable: true\n });\n \n // Add valueOf and toString for automatic coercion\n fn.valueOf = function() { return this.value; };\n fn.toString = function() { return String(this.value); };\n \n return fn;\n})();`);const o=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(o,t)&&!s.has(o)&&(r.push(`\nconst ${o} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${o}(...args);\n};`),i.add(o)),i.add(e)}return r.length>0?r.join("\n")+"\n\n"+e:e}extractDeclaredVariables(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const s=[/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+\[\s*([^}]+?)\s*\]/g,/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g];for(const e of s){let s;for(;null!==(s=e.exec(n));)if(e.source.includes("\\[")){const e=s[1].split(",").map((e=>e.trim())).filter(Boolean);for(const n of e)t.add(n)}else t.add(s[1])}return t}findScopedKeyForVariable(e,t){const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return`${n}.${e}`;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?this.getNested(this.props,s):this.props;if(r&&"object"==typeof r&&e in r)return s?`${s}.${e}`:e}return`${n}.${e}`}extractVariableReferences(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const s=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let r;for(;null!==(r=s.exec(n));){const e=r[1],s=r.index;if(this._reservedWords.has(e))continue;const i=n.substring(Math.max(0,s-20),s);if(/\b(?:const|let|var|function)\s+$/.test(i))continue;if(/\[\s*[^}]*$/.test(i))continue;if(s>0&&"."===n[s-1])continue;const o=n.substring(s+e.length,s+e.length+5);/^\s*:/.test(o)||t.add(e)}return t}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return!0;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n),r=s.join(".");if(this.getScopedFunction(e,s))return!0;const i=r?this.getNested(this.props,r):this.props;if(i&&"object"==typeof i&&e in i)return!0;const o=r?`${r}.${e}`:e;if(this._stateHierarchy.has(o))return!0}return!1}_registerScopedFunction(e,t,n){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...s)=>{const r=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&s.length>0?n(s[0]):n(...s)}finally{this._currentExecutionScope=r}}))}extractSetters(e){const t=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let s;for(;s=n.exec(e);){const[,e,n,r]=s;"share"===r&&this.markShared(e),this._sharedStateMap.has(e)||t.push(n)}return t}markShared(e){this._sharedStateMap.add(e)}transformStateDeclarations(e){return e=(e=(e=e.replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s,r)=>`${t}${n}, ${s}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}${n}${s}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}[${n}] = pphp.state('${n}', `))}stripComments(e){let t="",n=0,s=!1,r="",i=!1;for(;n<e.length;){const o=e[n],a=e[n+1];if(i||"'"!==o&&'"'!==o&&"`"!==o||"\\"===e[n-1])if(s)t+=o,n++;else if(i||"/"!==o||"*"!==a)if(i)"*"===o&&"/"===a?(i=!1,n+=2):n++;else if("/"!==o||"/"!==a)t+=o,n++;else for(;n<e.length&&"\n"!==e[n];)n++;else i=!0,n+=2;else s=!s,r=s?o:"",t+=o,n++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let n=!1;const s=this.getBindingType(t);for(const r of t.dependencies){for(const t of e)if(this.dependencyMatches(t,r,s)){n=!0;break}if(n)break}if(n)try{t.update()}catch(e){console.error("Binding update error:",e)}})),this._pendingBindings.forEach((e=>{try{e.update()}catch(e){console.error("Pending binding update error:",e)}})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const n=t.__deps||new Set,s=t.__functionDeps||[];if(0===n.size&&0===s.length){try{t()}catch(e){console.error("effect error:",e)}return}const r=[...n].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=s.length>0;if(r||i)try{t()}catch(e){console.error("effect error:",e)}}))}static ARRAY_INTRINSICS=(()=>{const e=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]);return new Set(Object.getOwnPropertyNames(Array.prototype).filter((t=>!e.has(t))))})();static headMatch(e,t){return e===t||e.startsWith(t+".")}dependencyMatches(e,t,n="binding"){const s=e=>{if(e.startsWith("app.")){const t=e.slice(4),n=t.split(".")[0];if(PPHP._shared.has(n))return t}return e},r=s(e),i=s(t);if(r===i||e===t)return!0;const o=i.split(".");if(o.length>1&&PPHP.ARRAY_INTRINSICS.has(o.at(-1))&&PPHP.headMatch(r,o.slice(0,-1).join(".")))return!0;switch(n){case"effect":return this.matchEffectDependency(r,i);case"loop":return!(!PPHP.headMatch(r,i)&&!PPHP.headMatch(i,r))||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchLoopDependency(r,i);default:return!!PPHP.headMatch(r,i)||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchBindingDependency(r,i)}}matchEffectDependency(e,t){if(e.startsWith(t+".")){return!e.substring(t.length+1).includes(".")}return!!t.includes("*")&&this.matchesWildcardPattern(e,t)}matchLoopDependency(e,t){return!(!e.startsWith(t+".")&&!t.startsWith(e+"."))||(!(!this.isArrayPath(t)||!this.isArrayItemPath(e,t))||(t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)))}isArrayPath(e){try{const t=this.getNested(this.props,e);return Array.isArray(t)}catch{return!1}}isArrayItemPath(e,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+($|\\.)`).test(e)}matchBindingDependency(e,t){if(e.startsWith(t+".")){return e.substring(t.length+1).split(".").length<=2}return t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)}matchesWildcardPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if("*"!==t&&t!==r)return!1}return!0}matchesArrayIndexPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=n[e],r=s[e];if(t!==r&&(!/^\d+$/.test(t)||!/^\d+$/.test(r)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const s=t.split("."),r=s.pop(),i=s.reduce(((e,t)=>e[t]??={}),e);null===n||"object"!=typeof n||Array.isArray(n)||n.__isReactiveProxy?i[r]=n:i[r]=this.makeReactive(n,s.concat(r))}hasNested(e,t){return void 0!==this.getNested(e,t)}share(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.share: key must be a non-empty string.");if(this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another share key.`);const n=PPHP._shared.get(e);if(n)return[n.getter,n.setter];const[s,r]=this.state(e,t);return PPHP._shared.set(e,{getter:s,setter:r}),[s,r]}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure the build-time injector rewrote your declaration to pphp.state('foo', 0).");if(arguments.length<2&&(t=void 0),this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another state key.`);const n=this._currentProcessingHierarchy||["app"],s=this.generateScopedKey(n,e);this._stateHierarchy.set(s,{originalKey:e,hierarchy:[...n],level:n.length}),this.hasNested(this.props,s)||this.setNested(this.props,s,t);const r=()=>this.getNested(this.props,s),i=e=>{const t=r(),n="function"==typeof e?e(t):e;this.setNested(this.props,s,n),this._dirtyDeps.add(s),n&&"object"==typeof n&&this.markNestedPropertiesDirty(s,n),this.scheduleFlush()},o=()=>r();Object.defineProperty(o,"value",{get:()=>r(),set:e=>i(e)}),Object.defineProperties(o,{valueOf:{value:()=>r()},toString:{value:()=>String(r())},__isReactiveProxy:{value:!0,writable:!1}}),o.__pphp_key=s;const a=r();if(null===a||"object"!=typeof a)return[o,i];const c=this;return[new Proxy(o,{apply:(e,t,n)=>Reflect.apply(e,t,n),get(e,t,n){if("value"===t)return r();if("__pphp_key"===t)return s;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,n);if("string"==typeof t){const n=r();if(n&&"object"==typeof n){const r=Object.prototype.hasOwnProperty.call(n,t),i=t in e&&void 0!==e[t];if(r||!i){let e=n[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...s.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,n);const i=r();return i&&"object"==typeof i?i[t]:void 0},set(e,t,n){if("value"===t)return i(n),!0;if("__isReactiveProxy"===t)return!0;const o=r();return o&&"object"==typeof o&&(o[t]=n,c._dirtyDeps.add(`${s}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in o)return!0;const n=r();return n&&"object"==typeof n&&t in n}}),i]}markNestedPropertiesDirty(e,t,n=new WeakSet){t&&"object"==typeof t&&!n.has(t)&&(n.add(t),Object.keys(t).forEach((s=>{const r=`${e}.${s}`;this._dirtyDeps.add(r);const i=t[s];i&&"object"==typeof i&&!n.has(i)&&this.markNestedPropertiesDirty(r,i,n)})))}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return n=>{const s=e.get(n);if(void 0!==s)return s;const r=n in globalThis||t.some((e=>n in e));return e.set(n,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let n=e.replace(/\?\./g,".");const s=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(n);){(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)))}const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(n);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const o=e=>{let t="",n=0;for(;n<e.length;)if("`"===e[n])for(n++;n<e.length;)if("\\"===e[n])n+=2;else if("$"===e[n]&&"{"===e[n+1]){n+=2;let s=1;const r=n;for(;n<e.length&&s>0;)"{"===e[n]?s++:"}"===e[n]&&s--,n++;const i=e.slice(r,n-1);t+=o(i)+" "}else{if("`"===e[n]){n++;break}n++}else t+=e[n++];return t};n=o(n),n=n.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),n=n.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const a=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of n.match(c)??[]){const[n,...r]=t.split(".");s.has(n)||(0===r.length&&PPHP._isBuiltIn(n)&&new RegExp(`\\.${n}\\b`).test(e)||a.add(t))}return a}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,n=PPHP._mustacheTest,s=this.props,r=new Set;this.qsa(e,"*").forEach((e=>{const s=this.detectElementHierarchy(e);for(const{name:i,value:o}of Array.from(e.attributes))if(o){if(n.test(o))for(const e of o.matchAll(t))this.extractScopedDependencies(e[1],s).forEach((e=>r.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(o,s).forEach((e=>r.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>n.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const n=e.parentElement;if(!n)continue;const s=this.detectElementHierarchy(n);for(const n of e.nodeValue.matchAll(t))this.extractScopedDependencies(n[1],s).forEach((e=>r.add(e)))}const o=Array.from(r).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of o){const t=e.split(".");let n=s;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(s in n)||!r&&(null==n[s]||"object"!=typeof n[s])){const e=this._stateHierarchy.has(i);r&&e||(n[s]=r?void 0:{})}n=n[s]}}}setNestedProperty(e,t,n){const s=t.split(".");let r=e;for(let e=0;e<s.length-1;e++)s[e]in r||(r[s[e]]={}),r=r[s[e]];r[s[s.length-1]]=n}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(","),t=this.qsa(document.body,e);for(const e of t)for(const t of this._eventHandlers){const n=e.getAttribute(t);if(!n)continue;const s=this.decodeEntities(n).trim();if(!s){e.removeAttribute(t);continue}const r=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(s))} }`;e.removeAttribute(t);const i=t.slice(2);e.removeAllEventListeners(i),e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,r)}return this.handlePassiveWheelStashes(document),Promise.resolve()}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let n=t.value;for(;n.includes("&");){t.innerHTML=n;const e=t.value;if(e===n)break;n=e}return n};unwrapArrowBody=e=>{if(!e.trim())return"";const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{([\s\S]*)\}\s*$/);if(t){let e=t[1].trim();return e&&!e.endsWith(";")&&(e+=";"),e}const n=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(n){let t=e.substring(n[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let s=e.trim();return s&&!s.endsWith(";")&&(s+=";"),s};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}->${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}::${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`}));const{normalized:n,originalParam:s}=this.normalizeToArrow(t),r=this.renameEventParam(n,s);return this.replaceThisReferences(r)}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const n=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(n)?n:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const n=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(n,((e,t,n)=>{const s=n[t-1],r=n[t+e.length];return s&&/[\w$]/.test(s)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,n){const s=e.getAttribute("pp-debounce"),r=s?this.parseTime(s):0,i=e.getAttribute("pp-before-request")??"",o=e.getAttribute("pp-after-request")??"",a=PPHP._cancelableEvents,c=async s=>{a.has(t)&&s.cancelable&&s.preventDefault();try{i&&await this.invokeHandler(e,i,s),await this.invokeHandler(e,n,s),o&&!o.startsWith("@close")&&await this.invokeHandler(e,o,s),this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!a.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(r>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const n=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),r);PPHP._debounceTimers.set(h,n)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),d(e)}),l):e.addEventListener(t,d,l)}debounce(e,t=300,n=!1){let s;return function(...r){const i=this;s&&clearTimeout(s),s=setTimeout((()=>{s=null,n||e.apply(i,r)}),t),n&&!s&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const n=t.getAttribute("pp-autofocus");if(!this.isJsonLike(n))return;const s=this.parseJson(n);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,s),t.type="number"):this.setCursorPosition(t,s))}))}async invokeHandler(e,t,n){try{const s=t.trim();let r=this._handlerCache.get(s);r||(r=this.parseHandler(s),this._handlerCache.set(s,r)),await this.executeHandler(r,e,n,s)}catch(n){this.handleInvokeError(n,t,e)}finally{this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const n=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(n)return{type:"call",name:n[1],args:n[2],isAsync:this.isAsyncFunction(n[1])};const s=t.match(/^(\w+)$/);return s?{type:"simple",name:s[1],isAsync:this.isAsyncFunction(s[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,n="",s=0;for(let r=0;r<e.length-1;r++){const i=e[r],o=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===n&&"\\"!==e[r-1])t=!1,n="";else if(!t&&("("===i&&s++,")"===i&&s--,"="===i&&">"===o&&s>=0))return!0}else t=!0,n=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let n=e.substring(t+2).trim();return n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1).trim()),{type:"arrow",body:n,isAsync:e.includes("async")||this.containsAwait(n)}}findArrowIndex(e){let t=!1,n="";for(let s=0;s<e.length-1;s++){const r=e[s],i=e[s+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===n&&"\\"!==e[s-1])t=!1;else if(!t&&"="===r&&">"===i)return s}else t=!0,n=r}return-1}async executeArrowHandler(e,t,n){const s=this.parseStatements(e.body);let r=!1;for(const e of s)await this.executeSingleStatement(e,t,n)&&(r=!0);r||await this.executeDynamic(e.body,t,n)}async executeComplexHandler(e,t,n){await this.executeDynamic(e.body,t,n)}parseStatements(e){const t=[];let n="",s=0,r=!1,i="";for(let o=0;o<e.length;o++){const a=e[o];r||'"'!==a&&"'"!==a&&"`"!==a?r&&a===i&&"\\"!==e[o-1]&&(r=!1,i=""):(r=!0,i=a),r||("("!==a&&"{"!==a&&"["!==a||s++,")"!==a&&"}"!==a&&"]"!==a||s--,";"!==a||0!==s)?n+=a:n.trim()&&(t.push(n.trim()),n="")}return n.trim()&&t.push(n.trim()),t}async executeInlineModule(e,t,n,s,r){if(t&&t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t);null!==n&&"object"==typeof n?await this.callInlineModule(e,{...n}):await this.callInlineModule(e,n)}else try{const s=this.detectElementHierarchy(n),r=this._createScopedPropsContext(s),i=this.makeScopedEvaluator(t,s)(r);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:n,event:s})}else await this.handleParsedCallback(n,r,s)}async executeSingleStatement(e,t,n){const s=e.trim();if(!s)return!1;const r=s.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return this.executeSingleStatement(r[1],t,n);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(s))return await this.executeDynamic(s,t,n),!0;const i=s.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(e,o);let c=[];if(""!==r.trim())try{c=JSON5.parse(`[${r}]`)}catch{try{const e=this._createScopedPropsContext(o),t=this.getOrCreateProxy(e),s=/\bevent\b/.test(r)?r.replace(/\bevent\b/g,"_evt"):r;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${s} ]; }`)(n,t,e)}catch(e){c=[]}}if(a){const e=this.getScopedFunction(a,o);if(e)return c.length>0?await e(...c):await this.executeInlineModule(a,r,t,n,s),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,s,n),!0}const o=s.match(/^(\w+)$/);if(o){const e=o[1],s=this.detectElementHierarchy(t),r=this.resolveFunctionName(e,s);if(r){if(this.getScopedFunction(r,s))return await this.handleParsedCallback(t,`${r}()`,n),!0}if(r){const e=globalThis[r];if("function"==typeof e)return e.call(globalThis,n),!0}return await this.handleParsedCallback(t,`${e}()`,n),!0}return await this.executeDynamic(s,t,n),!0}async executeCallHandler(e,t,n,s){const{name:r,args:i}=e,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(r,o);if(a){if(this.getScopedFunction(a,o))return void await this.executeInlineModule(a,i||"",t,n,s);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,n)}await this.handleParsedCallback(t,s,n)}resolveFunctionName(e,t){if(t)for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,n){const{name:s}=e,r=this.detectElementHierarchy(t),i=this.resolveFunctionName(s,r);if(i){if(this.getScopedFunction(i,r))return void await this.handleParsedCallback(t,`${i}()`,n);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,n)}await this.handleParsedCallback(t,`${s}()`,n)}async executeHandler(e,t,n,s){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,n);break;case"call":await this.executeCallHandler(e,t,n,s);break;case"simple":await this.executeSimpleHandler(e,t,n);break;case"complex":await this.executeComplexHandler(e,t,n);break;default:await this.handleParsedCallback(t,s,n)}}async executeGlobalFunction(e,t,n,s){if(t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t)??{};e.call(globalThis,{...n})}else{const r=this.detectElementHierarchy(n),i=this._createScopedPropsContext(r),o=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(n,s,o,i,e)}else e.call(globalThis,s)}async executeDynamic(e,t,n){const s=this.detectElementHierarchy(t),r=this._createScopedPropsContext(s),i=this.getOrCreateProxy(r),o=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await o.call(t,n,i,r)}finally{this.scheduleFlush()}}static AsyncFunction=Object.getPrototypeOf((async()=>{})).constructor;getOrCreateEvaluator(e){let t=this._evaluatorCache.get(e);return t||(t=this.makeSafeEvaluator(e),this._evaluatorCache.set(e,t)),t}getOrCreateProxy(e){let t=this._handlerProxyCache.get(e);return t||(t=this.createHandlerProxy(e),this._handlerProxyCache.set(e,t)),t}createHandlerProxy(e){const t=this._currentProcessingHierarchy||["app"],n={alert:window.alert.bind(window),confirm:window.confirm.bind(window),prompt:window.prompt.bind(window),console:window.console,setTimeout:window.setTimeout.bind(window),setInterval:window.setInterval.bind(window),clearTimeout:window.clearTimeout.bind(window),clearInterval:window.clearInterval.bind(window),fetch:window.fetch.bind(window)};return new Proxy(e,{get:(e,s,r)=>{if("string"==typeof s){if(n.hasOwnProperty(s))return n[s];const i=this.getScopedFunction(s,t);if(i)return i;if(s in e){const t=Reflect.get(e,s,r),n=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof n))return t}if(s in globalThis&&!n.hasOwnProperty(s)){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,r)},set:(e,t,n,s)=>Reflect.set(e,t,n,s),has:(e,t)=>{if("string"==typeof t){const s=this._currentProcessingHierarchy||["app"];return n.hasOwnProperty(t)||!!this.getScopedFunction(t,s)||t in e||t in globalThis}return t in e||t in globalThis}})}isAsyncFunction(e){const t=this._inlineModuleFns.get(e)||globalThis[e];return t&&("AsyncFunction"===t.constructor.name||t.toString().includes("async "))}containsAwait(e){return/\bawait\s+/.test(e)}handleInvokeError(e,t,n){const s=e instanceof Error?e.message:String(e),r=n.tagName+(n.id?`#${n.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${s}`,e),n.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:n},bubbles:!0}))}clearHandlerCaches(){this._handlerCache.clear(),this._evaluatorCache.clear()}async handleParsedCallback(e,t,n){const{funcName:s,data:r}=this.parseCallback(e,t);if(!s)return;const i=Array.isArray(s)?s:[s],o=this.detectElementHierarchy(e);let a;for(const e of i){const t=this.getScopedFunction(e,o);if(t){a=t;break}if("function"==typeof this[e]){a=this[e];break}if("function"==typeof window[e]){a=window[e];break}}if(a){const t=e.hasAttribute("pp-after-request"),s="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(r.args)?r.args:[],element:e,data:r,event:n};if(t&&!s){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};i={...i,...e}}await a.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(s)?s[0]:s,r)}async handleUndefinedFunction(e,t,n){const s={callback:await this.encryptCallbackName(t),...n},r=this.createFetchOptions(s),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const s=new URL(window.location.href);let o="",a="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(o=await this.fetchFileWithData(s.href,t,l,n),a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(s.href,r);if(o=await e.text(),this.getRedirectUrl(o))return void await this.redirect(this.getRedirectUrl(o)||"");if(a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",d=e.getAttribute("pp-after-request")||"";if((h||d&&c.success)&&this.restoreSuspenseElement(e),h||d){let e="";if(c.success){e=o.replace(a,"")}else e=o;if(this.appendAfterbegin(e),!d&&!c.success)return}if(d&&c.success){this.handleAfterRequest(d,a);const e=o.replace(a,"");return this.appendAfterbegin(e),a}if("@close"===d)return c.success?a:void 0;const p=await this.fetch(s.href,i),u=await p.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(o,u,a,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const n=this.parseJson(e),s=t?this.parseJson(t):null,r=n.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);let i={};if(s){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?s[e.responseKey]:s.response);break;default:i[t]=n[t]}}else i=n;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,n)=>` data-onwheel-code="${this.decodeEntities(n).replace(/"/g,"&quot;")}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{const t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null,t&&(e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t))}))}async handleResponseRedirectOrUpdate(e,t,n,s){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,n,s),o=(new DOMParser).parseFromString(r,"text/html");i&&o.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(o.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const s=document.createElement("div");if(s.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");s.innerHTML=t}else s.innerHTML=e;return s.innerHTML?s:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const n=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(n),await this.appendCallbackResponse(n),await this.processInlineModuleScripts(n),await this.initializeAllReferencedProps(n),await this.manageAttributeBindings(n),await this.populateDocumentBody(n),await this.initRefs(),await this.processIfChains(),await this.initLoopBindings();for(const e of this._bindings)try{e.update()}catch(e){console.error(e)}this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute(),document.body.removeAttribute("hidden")}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[s,r]=this.decodeHTML(t[n]).split(",");e.classList.replace(s,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const s=this.parseJson(e);n(t,s)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?s(e,t):n(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const s=this.parseJson(t);n(e,s)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),s(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&i(s,n)}));const{targets:t,...s}=r;n(e,s)}else{const{empty:t,...s}=r;n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,n,s={}){const r=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in s)s.hasOwnProperty(e)&&r.append(e,s[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await o.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(this.isJsonLike(e)){const n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}))}else s(t,e)}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),s.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=s;this.updateElementAttributes(e,o),n(e,r)}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}));const{targets:t,...n}=s;this.updateElementAttributes(e,n)}else{if("disabled"===s.empty&&""===e.value)return;const{empty:t,...n}=s;this.updateElementAttributes(e,n)}}else if(t)s(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n];t[s.name]=s.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let n={};const s=e.closest("form");if(s){new FormData(s).forEach(((e,t)=>{n[t]?Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]:n[t]=e}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const r=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(r){const e=r[1].trim(),t=r[2].trim(),s=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e&&(n={...n,...e})}catch(e){console.error("Error parsing JSON args:",e),n.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e?n={...n,...e}:n.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),n.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();n.args=Array.isArray(e)?e:[e]}catch{s.test(t)?n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):n.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);n.args=[e]}catch{n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:n}}return{funcName:t,data:n}}evaluateJavaScriptObject(e){try{const t=this.getOrCreateProxy(this.props);return new Function("proxy","Date","Math","JSON",`\n with (proxy) {\n return ${e};\n }\n `).call(null,t,Date,Math,JSON)}catch(e){throw console.error("Failed to evaluate JavaScript object:",e),e}}handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),s=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===s){const t=e.name||e.id;if(t){const n=new URL(window.location.href),s=new URLSearchParams(n.search);s.has(t)&&(e.value=s.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,s=new URL(window.location.href),r=new URLSearchParams(s.search),i=t.name||t.id;if(i){n?r.set(i,n):r.delete(i);const e=r.toString()?`${s.pathname}?${r.toString()}`:s.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),s=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",s)))}handleVisibilityElementAttribute(e,t,n){const s=e.getAttribute(t);if(s)if(this.isJsonLike(s)){n(e,this.parseJson(s))}else{const n=this.parseTime(s);if(n>0){const s="pp-visibility"===t?"visibility":"display",r="visibility"===s?"hidden":"none";this.scheduleChange(e,n,s,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,s,r){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=s,this.scheduleChange(e,i,n,r),o>0&&this.scheduleChange(e,i+o,n,s)):o>0&&this.scheduleChange(e,o,n,s)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),s=t.getAttribute("target");if(n&&"_blank"!==s&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[r,i]=n.split("#");i&&(s=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const o=`${e.pathname}?${t.toString()}${s}`;history.pushState(null,"",o)}else{const[e,t]=n.split("#"),s=`${e}${t?`#${t}`:""}`;history.pushState(null,"",s)}const s=n.indexOf("#");if(-1!==s){const e=n.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok)return void console.error(`Navigation error: ${t.status} ${t.statusText}`);const n=await t.text(),s=n.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(n)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const s=n.lastIndexOf("/");n=s<=0?"/":n.substring(0,s)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:s}=this.parseTransition(e);await this.fadeOut(t,s),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const s=e.querySelector("[pp-loading-transition]"),r=s?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),n=this.sanitizePassiveHandlers(e),s=(new DOMParser).parseFromString(n,"text/html");this.scrubTemplateValueAttributes(s);const r="pp-dynamic-script",i="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${i}]`).forEach((e=>e.remove())),document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove())),Array.from(s.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(r)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){const t=e;if(t.getAttribute("charset")||"viewport"===t.name)return;const n=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,s=document.head.querySelector(n),r=t.cloneNode(!0);s?document.head.replaceChild(r,s):document.head.querySelector("title")?.nextSibling?document.head.insertBefore(r,document.head.querySelector("title").nextSibling):document.head.appendChild(r)}else if("TITLE"===t){const t=document.head.querySelector("title"),n=e.cloneNode(!0);t?document.head.replaceChild(n,t):document.head.appendChild(n)}else if("LINK"===t){const t=e;if("icon"===t.rel){const e=document.head.querySelector('link[rel="icon"]'),n=t.cloneNode(!0);e?document.head.replaceChild(n,e):document.head.appendChild(n)}else t.hasAttribute(i)&&document.head.appendChild(t.cloneNode(!0))}})),this.resetProps(),await this.processInlineModuleScripts(s),await this.initializeAllReferencedProps(s),await this.manageAttributeBindings(s),await this.populateDocumentBody(s),await this.initRefs(),await this.processIfChains(),await this.initLoopBindings();for(const e of this._bindings)try{e.update()}catch(e){console.error(e)}this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute(),document.body.removeAttribute("hidden")}async rerunInlineScripts(){const e=Array.from(document.querySelectorAll('script[type="text/javascript"]:not([src])')),t=new Map;e.forEach((e=>{const n=(e.textContent||"").trim();if(t.has(n))return void e.remove();t.set(n,e);const s=document.createElement("script");[...e.attributes].forEach((e=>s.setAttribute(e.name,e.value))),s.textContent=e.textContent,e.replaceWith(s)}))}scrubTemplateValueAttributes(e){e.querySelectorAll('input[value*="{{"], textarea[value*="{{"], select[value*="{{"],[checked*="{{"], [selected*="{{"]').forEach((e=>{e.hasAttribute("value")&&e.removeAttribute("value"),e.hasAttribute("checked")&&e.removeAttribute("checked"),e.hasAttribute("selected")&&e.removeAttribute("selected")}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const n=this.getElementKey(t);e[n]&&(t.scrollTop=e[n].scrollTop,t.scrollLeft=e[n].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),s.checked=n.checked,document.activeElement!==n||(null!=n.selectionStart&&(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd),!1)},TEXTAREA(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),document.activeElement!==n||(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd,!1)},SELECT(e,t){const n=e;return t.selectedIndex=n.selectedIndex,document.activeElement!==n},VIDEO(e,t){const n=e,s=t;return s.currentTime=n.currentTime,n.paused?s.pause():s.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,n=e instanceof Document?e.body:e;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const n=new Function("event",t);e.addEventListener("wheel",n,{passive:!0})}})),this._wheelHandlersStashed=!0);const s=this.PRESERVE_HANDLERS;morphdom(t,n,{getNodeKey(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.hasAttribute("pp-sync-script")?`pp-sync-script:${t.getAttribute("pp-sync-script")}`:t.getAttribute("key")||void 0},onBeforeElUpdated(e,t){const n=e.tagName;if("SCRIPT"===n||e.hasAttribute("data-nomorph"))return!1;const r=s[n];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let s;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,s=this._activeAbortController):s=new AbortController,fetch(e,{...t,signal:s.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,n,s){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=s}))}),t)}async fetchFunction(e,t={},n=!1){try{const s={callback:await this.encryptCallbackName(e),...t},r=window.location.href;let i;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const n=s[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(s);const o=await this.fetch(r,i,n);if(!o.ok)throw new Error(`Fetch failed with status: ${o.status} ${o.statusText}`);const a=await o.text();try{return JSON.parse(a)}catch{return a}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const n=e.length?e.map((e=>`[pp-sync="${e}"]`)):['[pp-sync="true"]'],s=await this.fetch(window.location.href,this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()})),r=await s.text(),i=(new DOMParser).parseFromString(r,"text/html");await this.initReactiveOn(i),n.forEach((e=>{const t=document.querySelectorAll(e),n=i.body.querySelectorAll(e);t.forEach(((e,t)=>{const s=n[t];s&&(e.innerHTML=s.innerHTML)}))})),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("pphp.sync failed:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),n=await t.text();await this.updateBodyContent(n)}copyCode(e,t,n,s,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(r);if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){const n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,this.listeners.forEach((e=>e(this.state))),this.saveState(),t)){const e=localStorage.getItem(this.STORAGE_KEY);e&&e!==this.lastSyncedState&&(this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e}),this.lastSyncedState=e)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t}),this.lastSyncedState=t}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const s=e[n];null!==s&&t.set(n,s)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "3.1.4",
3
+ "version": "3.1.6",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",