@stacksjs/stx 0.2.801 → 0.2.802

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/{chunk-gzfvj15b.js → chunk-06hc6rs6.js} +1 -1
  2. package/dist/{chunk-wqt2hep2.js → chunk-077dwzpp.js} +1 -1
  3. package/dist/{chunk-2fh4wvtv.js → chunk-0vztrb90.js} +32 -32
  4. package/dist/chunk-1338vj5g.js +2 -0
  5. package/dist/chunk-14qhn86r.js +2 -0
  6. package/dist/{chunk-kydgndkt.js → chunk-1pz11ez9.js} +1 -1
  7. package/dist/{chunk-25q462jp.js → chunk-24x7s0x5.js} +3 -3
  8. package/dist/chunk-27p6cxa2.js +2 -0
  9. package/dist/chunk-2jwmtbsj.js +2 -0
  10. package/dist/{chunk-akcyaxwv.js → chunk-2vqpz4qv.js} +2 -2
  11. package/dist/{chunk-1htxem27.js → chunk-3dtp59r9.js} +1 -1
  12. package/dist/{chunk-wz3gk8js.js → chunk-3j9zzpbd.js} +2 -2
  13. package/dist/{chunk-e08hzdpw.js → chunk-3vfxn6g5.js} +1 -1
  14. package/dist/{chunk-hyz90d8w.js → chunk-4gf3khd9.js} +2 -2
  15. package/dist/{chunk-c2x9wea0.js → chunk-4q2fh4r4.js} +1 -1
  16. package/dist/{chunk-2ehn5r6d.js → chunk-50be1xy0.js} +1 -1
  17. package/dist/{chunk-h72d9174.js → chunk-5hgghq24.js} +1 -1
  18. package/dist/chunk-6cgak0k1.js +2 -0
  19. package/dist/{chunk-pmf53mgj.js → chunk-7j4tf0ba.js} +1 -1
  20. package/dist/{chunk-zfzjn93c.js → chunk-7tkxshah.js} +8 -8
  21. package/dist/{chunk-26505qjh.js → chunk-8fnhv8jq.js} +1 -1
  22. package/dist/{chunk-j0bbr6ee.js → chunk-8fvgsd9v.js} +3 -3
  23. package/dist/chunk-8hm4a8p2.js +2 -0
  24. package/dist/{chunk-vse4ewax.js → chunk-9767yz39.js} +1 -1
  25. package/dist/{chunk-3gcdq401.js → chunk-a0xxm3eh.js} +1 -1
  26. package/dist/{chunk-2yb1rwmy.js → chunk-a5byhf8f.js} +1 -1
  27. package/dist/{chunk-v47yfe9k.js → chunk-aj5na3d3.js} +1 -1
  28. package/dist/{chunk-9kadf7pv.js → chunk-antc6crh.js} +1 -1
  29. package/dist/chunk-b22yj5j5.js +2 -0
  30. package/dist/{chunk-vy92xwbg.js → chunk-b29x9hsz.js} +1 -1
  31. package/dist/{chunk-sprgkk9j.js → chunk-bs02d6mm.js} +8 -8
  32. package/dist/{chunk-x8m28yea.js → chunk-byatzyvf.js} +2 -2
  33. package/dist/chunk-bz3papjy.js +2 -0
  34. package/dist/{chunk-f52esq8m.js → chunk-c36bj74x.js} +1 -1
  35. package/dist/{chunk-fw9dhsd9.js → chunk-casq5t61.js} +1 -1
  36. package/dist/{chunk-k3rcpnzm.js → chunk-cmnze7at.js} +2 -2
  37. package/dist/{chunk-gctyy7r9.js → chunk-cs38hg43.js} +8 -8
  38. package/dist/chunk-d3gncxq1.js +2 -0
  39. package/dist/{chunk-j2v9f2dk.js → chunk-dbbc84mj.js} +2 -2
  40. package/dist/{chunk-r32pqvpq.js → chunk-ddk34ppv.js} +5 -5
  41. package/dist/chunk-dwn8ye99.js +2 -0
  42. package/dist/{chunk-6162chg7.js → chunk-dxemdr58.js} +41 -41
  43. package/dist/{chunk-8xx1yf34.js → chunk-e1g3ns8y.js} +2 -2
  44. package/dist/{chunk-s85s2kd3.js → chunk-e5fszb5z.js} +1 -1
  45. package/dist/chunk-e88bsw36.js +2 -0
  46. package/dist/{chunk-ddhkhhc7.js → chunk-eayewa2s.js} +2 -2
  47. package/dist/{chunk-q3dsjk2b.js → chunk-esm9sdyf.js} +3 -3
  48. package/dist/chunk-ewhkvqce.js +72 -0
  49. package/dist/chunk-fq1dw4ph.js +3 -0
  50. package/dist/{chunk-3ajbbtqx.js → chunk-fsfj0s13.js} +6 -6
  51. package/dist/{chunk-gqdkvwjp.js → chunk-fy6sdbak.js} +48 -48
  52. package/dist/{chunk-gqgcsgc3.js → chunk-g02jnsz5.js} +1 -1
  53. package/dist/chunk-g4sdthck.js +2 -0
  54. package/dist/chunk-gabw11g3.js +2 -0
  55. package/dist/{chunk-s763dt8e.js → chunk-gk214p91.js} +2 -2
  56. package/dist/{chunk-dd1vqndp.js → chunk-gxrpf87x.js} +1 -1
  57. package/dist/{chunk-dwydz68f.js → chunk-h1dwth11.js} +1 -1
  58. package/dist/{chunk-8kvj2wz0.js → chunk-hzhsg5j7.js} +6 -6
  59. package/dist/chunk-j0jgc426.js +2 -0
  60. package/dist/{chunk-qkck7zx0.js → chunk-jdjv5x6q.js} +1 -1
  61. package/dist/chunk-jkn9garq.js +2 -0
  62. package/dist/chunk-jy9qmwpm.js +2 -0
  63. package/dist/chunk-krqj3cx9.js +2 -0
  64. package/dist/chunk-kzny87pz.js +2 -0
  65. package/dist/{chunk-1yhrq2nx.js → chunk-kzt46v41.js} +1 -1
  66. package/dist/{chunk-8adf5x29.js → chunk-m0c64sna.js} +1 -1
  67. package/dist/{chunk-9nbv6nk4.js → chunk-m4w61tyq.js} +2 -2
  68. package/dist/{chunk-nm20k22y.js → chunk-md55r6zp.js} +1 -1
  69. package/dist/chunk-mv9k42dn.js +2 -0
  70. package/dist/{chunk-8ey61ppd.js → chunk-mz1kffvs.js} +2 -2
  71. package/dist/{chunk-33vr7x2t.js → chunk-n7arptzc.js} +3 -3
  72. package/dist/chunk-nhfksrce.js +3 -0
  73. package/dist/{chunk-cas0vn5m.js → chunk-ntwgk0tf.js} +1 -1
  74. package/dist/{chunk-t0bcbhvs.js → chunk-nya33asw.js} +3 -3
  75. package/dist/{chunk-83myk906.js → chunk-p4aaxpaw.js} +1 -1
  76. package/dist/{chunk-hcwjdpzv.js → chunk-p8wq37hd.js} +2 -2
  77. package/dist/{chunk-nn1f1h3q.js → chunk-pamtcna7.js} +1 -1
  78. package/dist/{chunk-gvnfb6s2.js → chunk-q7zwv88b.js} +2 -2
  79. package/dist/{chunk-61h00ba5.js → chunk-qx5jhe7h.js} +5 -5
  80. package/dist/{chunk-2yxva96k.js → chunk-r9e0r6jx.js} +2 -2
  81. package/dist/{chunk-xtwcz8dg.js → chunk-r9eyepbk.js} +6 -6
  82. package/dist/{chunk-vzmkex8f.js → chunk-rs0ejvjm.js} +1 -1
  83. package/dist/{chunk-t5vjt37c.js → chunk-rxhymzj8.js} +1 -1
  84. package/dist/{chunk-t0qh1m5e.js → chunk-s81y1dw3.js} +4 -4
  85. package/dist/chunk-sfvdj9dj.js +2 -0
  86. package/dist/chunk-szma9dby.js +2 -0
  87. package/dist/{chunk-x8h81amr.js → chunk-t4j2rw91.js} +2 -2
  88. package/dist/chunk-txyyvtdp.js +2 -0
  89. package/dist/{chunk-vg3scf4d.js → chunk-v18816jj.js} +8 -8
  90. package/dist/chunk-ved3r01r.js +420 -0
  91. package/dist/chunk-vxd3akt4.js +2 -0
  92. package/dist/{chunk-hp9e8nz6.js → chunk-we6jnjjp.js} +1 -1
  93. package/dist/{chunk-k4nhwd9p.js → chunk-wes7vsze.js} +2 -2
  94. package/dist/chunk-wf6vjd41.js +2 -0
  95. package/dist/{chunk-ps9fcjyg.js → chunk-wghv9vr6.js} +1 -1
  96. package/dist/{chunk-w0zayhmg.js → chunk-wpendr22.js} +2 -2
  97. package/dist/{chunk-hzs3h76s.js → chunk-wvnzq8w8.js} +3 -3
  98. package/dist/{chunk-qxt6hdat.js → chunk-wy0gghvh.js} +1 -1
  99. package/dist/{chunk-56j2egg3.js → chunk-x0ttkvr7.js} +2 -2
  100. package/dist/chunk-xbvx8j82.js +2 -0
  101. package/dist/{chunk-2vejgrj7.js → chunk-xndhzwdj.js} +5 -5
  102. package/dist/{chunk-dq87xd5c.js → chunk-xrvdef6x.js} +3 -3
  103. package/dist/{chunk-fn4jk05k.js → chunk-yxsrerew.js} +1 -1
  104. package/dist/chunk-z0kx564w.js +2 -0
  105. package/dist/{chunk-jce3scvg.js → chunk-zwptpjjt.js} +16 -16
  106. package/dist/cli.js +13 -13
  107. package/dist/client-parameter-bindings.js +10 -6
  108. package/dist/craft-entry.js +1 -1
  109. package/dist/craft.js +1 -1
  110. package/dist/native/compiler/inline-style.js +51 -28
  111. package/dist/native/runtime/craft-bridge.js +37 -4
  112. package/dist/performance-utils.d.ts +255 -115
  113. package/dist/pwa.js +2 -2
  114. package/dist/safe-evaluator.js +28 -3
  115. package/dist/ssg.js +3 -3
  116. package/package.json +5 -5
  117. package/dist/chunk-1zy94dxs.js +0 -2
  118. package/dist/chunk-3rgb6kc1.js +0 -2
  119. package/dist/chunk-5fzvcr9v.js +0 -2
  120. package/dist/chunk-6b10096c.js +0 -2
  121. package/dist/chunk-6mdvx2bf.js +0 -2
  122. package/dist/chunk-6q0c9j7p.js +0 -2
  123. package/dist/chunk-7m4eesp0.js +0 -2
  124. package/dist/chunk-92te36hf.js +0 -2
  125. package/dist/chunk-9sgzv5ze.js +0 -2
  126. package/dist/chunk-acwqb3ys.js +0 -2
  127. package/dist/chunk-amc8xdcz.js +0 -2
  128. package/dist/chunk-b3b9tfpx.js +0 -2
  129. package/dist/chunk-bb3y1g34.js +0 -2
  130. package/dist/chunk-bf3va62c.js +0 -2
  131. package/dist/chunk-ef8p88as.js +0 -2
  132. package/dist/chunk-ej8q3kyc.js +0 -2
  133. package/dist/chunk-eszpqrxy.js +0 -2
  134. package/dist/chunk-kdhsev5v.js +0 -3
  135. package/dist/chunk-nq4d91zm.js +0 -2
  136. package/dist/chunk-nv0n2hjg.js +0 -431
  137. package/dist/chunk-p9j909eq.js +0 -2
  138. package/dist/chunk-pxxhhaaw.js +0 -3
  139. package/dist/chunk-q38vjqv2.js +0 -2
  140. package/dist/chunk-q78jxqnr.js +0 -2
  141. package/dist/chunk-se44tmvx.js +0 -61
  142. package/dist/chunk-shag9bcm.js +0 -2
  143. package/dist/chunk-t4yy48dh.js +0 -2
  144. package/dist/chunk-t55nk8sw.js +0 -2
  145. package/dist/chunk-ys46rqxg.js +0 -2
  146. package/dist/chunk-zhz8er14.js +0 -2
@@ -1,3 +1,82 @@
1
+ /**
2
+ * Performance optimization utilities for stx
3
+ */
4
+ /**
5
+ * Generic LRU (Least Recently Used) cache implementation
6
+ * Automatically evicts least recently used items when capacity is reached
7
+ */
8
+ /**
9
+ * How a cache measures what it is holding, when entry count is not enough.
10
+ *
11
+ * A count-bounded cache assumes entries are roughly one size. That holds for
12
+ * the caches here that store paths or small fragments, and stops holding as
13
+ * soon as the values are rendered output: one entry can be tens of kilobytes
14
+ * and another a few bytes, so `maxSize` stops describing the footprint at all
15
+ * (stacksjs/stx#1945). Passing `sizeOf` and `maxBytes` bounds the bytes as
16
+ * well, which is the number a memory-constrained host actually has to budget.
17
+ */
18
+ export interface LRUCacheOptions<V> {
19
+ /** Bytes this cache may retain across all entries. */
20
+ maxBytes: number;
21
+ /** What one value costs. Called once per `set`, so keep it cheap. */
22
+ sizeOf: (value: V) => number;
23
+ }
24
+ export declare class LRUCache<K, V> {
25
+ private cache;
26
+ private readonly maxSize;
27
+ private options;
28
+ private sizes;
29
+ private bytes;
30
+ constructor(maxSize?: number, options?: LRUCacheOptions<V>);
31
+ /** Bytes currently retained. Zero unless the cache is byte-bounded. */
32
+ get byteSize(): number;
33
+ /**
34
+ * Change the byte budget, evicting immediately down to the new one.
35
+ *
36
+ * The caches here are module state, built when the module loads and so before
37
+ * any config has been read. A host that wants a different ceiling -- or none
38
+ * at all -- can only say so afterwards, and it should take effect on what is
39
+ * already held rather than only on what arrives next: a container that has
40
+ * just told stx to keep 4MB is not helped by a cache that keeps its current
41
+ * 32MB until the entries happen to age out.
42
+ *
43
+ * A no-op on a cache built without a budget: giving one bytes it never
44
+ * measured would evict against a total that is always zero.
45
+ */
46
+ setMaxBytes(maxBytes: number): void;
47
+ /**
48
+ * Get a value from the cache, moving it to most recently used
49
+ */
50
+ get(key: K): V | undefined;
51
+ /**
52
+ * Set a value in the cache
53
+ */
54
+ set(key: K, value: V): void;
55
+ /**
56
+ * Check if key exists in cache
57
+ */
58
+ has(key: K): boolean;
59
+ /**
60
+ * Delete a key from the cache
61
+ */
62
+ delete(key: K): boolean;
63
+ /**
64
+ * Clear all entries from the cache
65
+ */
66
+ clear(): void;
67
+ /**
68
+ * Get the current size of the cache
69
+ */
70
+ get size(): number;
71
+ /**
72
+ * Get all keys in the cache (oldest to newest)
73
+ */
74
+ keys(): IterableIterator<K>;
75
+ /**
76
+ * Get all values in the cache (oldest to newest)
77
+ */
78
+ values(): IterableIterator<V>;
79
+ }
1
80
  /**
2
81
  * Get a cached regex pattern or compile and cache it.
3
82
  *
@@ -23,6 +102,39 @@ export declare function getCachedRegex(pattern: string, flags?: string): RegExp;
23
102
  * Clear the regex cache (useful for testing)
24
103
  */
25
104
  export declare function clearRegexCache(): void;
105
+ /**
106
+ * Cache for template processing results
107
+ */
108
+ export declare class TemplateCache {
109
+ private cache;
110
+ private maxSize;
111
+ private ttl;
112
+ constructor(maxSize?: number, ttl?: number);
113
+ /**
114
+ * Get cached result if available and not expired
115
+ */
116
+ get(key: string): string | null;
117
+ /**
118
+ * Store result in cache
119
+ */
120
+ set(key: string, result: string, dependencies?: Set<string>): void;
121
+ /**
122
+ * Invalidate cache entries that depend on a specific file
123
+ */
124
+ invalidateDependency(filePath: string): number;
125
+ /**
126
+ * Clear all cached entries
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Get cache statistics
131
+ */
132
+ getStats(): {
133
+ size: number;
134
+ maxSize: number;
135
+ hitRate?: number;
136
+ };
137
+ }
26
138
  /**
27
139
  * Debounce function calls to avoid excessive processing
28
140
  */
@@ -40,139 +152,167 @@ export declare function memoize<T extends (...args: any[]) => any>(func: T, maxC
40
152
  */
41
153
  export declare function optimizedReplace(text: string, pattern: string | RegExp, replacement: string | ((match: string, ...args: any[]) => string), flags?: string): string;
42
154
  /**
43
- * Get the global performance monitor instance (lazy-loaded)
44
- * This avoids instantiating the monitor until it's actually needed
45
- */
46
- export declare function getPerformanceMonitor(): PerformanceMonitor;
47
- /**
48
- * Apply default performance budgets to the monitor
49
- */
50
- export declare function applyDefaultBudgets(monitor?: PerformanceMonitor): void;
51
- /**
52
- * Reset the performance monitor instance (useful for testing)
53
- */
54
- export declare function resetPerformanceMonitor(): void;
55
- // Global expression evaluator pool
56
- export declare const expressionEvaluatorPool: ExpressionEvaluatorPool;
57
- /**
58
- * Default performance budgets for common operations
59
- * @defaultValue
60
- * ```ts
61
- * {
62
- * processDirectives: { maxTime: 500, warnThreshold: 0.8, action: 'warn' },
63
- * processTemplate: { maxTime: 200, warnThreshold: 0.8, action: 'warn' },
64
- * processIncludes: { maxTime: 100, warnThreshold: 0.8, action: 'warn' },
65
- * processLoops: { maxTime: 50, warnThreshold: 0.8, action: 'warn' },
66
- * processConditionals: { maxTime: 50, warnThreshold: 0.8, action: 'warn' },
67
- * processExpressions: { maxTime: 100, warnThreshold: 0.8, action: 'warn' },
68
- * renderComponent: { maxTime: 150, warnThreshold: 0.8, action: 'warn' },
69
- * buildWebComponents: { maxTime: 1000, warnThreshold: 0.8, action: 'warn' }
70
- * }
71
- * ```
72
- */
73
- export declare const defaultPerformanceBudgets: Record<string, PerformanceBudget>;
74
- /**
75
- * Global performance monitor instance
76
- * @deprecated Use getPerformanceMonitor() for lazy loading
77
- */
78
- export declare const performanceMonitor: PerformanceMonitor;
79
- /* eslint-disable prefer-const, style/max-statements-per-line, no-super-linear-backtracking, regexp/no-unused-capturing-group, pickier/no-unused-vars */
80
- /**
81
- * Performance optimization utilities for stx
82
- */
83
- /**
84
- * Generic LRU (Least Recently Used) cache implementation
85
- * Automatically evicts least recently used items when capacity is reached
86
- */
87
- /**
88
- * How a cache measures what it is holding, when entry count is not enough.
89
- *
90
- * A count-bounded cache assumes entries are roughly one size. That holds for
91
- * the caches here that store paths or small fragments, and stops holding as
92
- * soon as the values are rendered output: one entry can be tens of kilobytes
93
- * and another a few bytes, so `maxSize` stops describing the footprint at all
94
- * (stacksjs/stx#1945). Passing `sizeOf` and `maxBytes` bounds the bytes as
95
- * well, which is the number a memory-constrained host actually has to budget.
155
+ * Pool of worker contexts to avoid creating new Function instances
96
156
  */
97
- export declare interface LRUCacheOptions<V> {
98
- maxBytes: number
99
- sizeOf: (value: V) => number
157
+ declare class ExpressionEvaluatorPool {
158
+ private pool;
159
+ private maxPoolSize;
160
+ private fnCache;
161
+ private fnCacheMaxSize;
162
+ getEvaluator(contextKeys: string[]): (...args: any[]) => any;
163
+ clear(): void;
100
164
  }
165
+ export declare const expressionEvaluatorPool: ExpressionEvaluatorPool;
101
166
  /**
102
167
  * Performance budget configuration
103
168
  */
104
- export declare interface PerformanceBudget {
105
- maxTime: number
106
- warnThreshold?: number
107
- action?: 'log' | 'warn' | 'error' | 'throw'
169
+ export interface PerformanceBudget {
170
+ /** Maximum allowed time in milliseconds */
171
+ maxTime: number;
172
+ /** Warning threshold (percentage of maxTime, e.g., 0.8 = 80%) */
173
+ warnThreshold?: number;
174
+ /** Action to take on budget violation: 'log', 'warn', 'error', 'throw' */
175
+ action?: 'log' | 'warn' | 'error' | 'throw';
108
176
  }
109
177
  /**
110
178
  * Performance budget violation event
111
179
  */
112
- export declare interface BudgetViolation {
113
- label: string
114
- actualTime: number
115
- budgetTime: number
116
- exceedancePercent: number
117
- timestamp: Date
118
- isWarning: boolean
180
+ export interface BudgetViolation {
181
+ label: string;
182
+ actualTime: number;
183
+ budgetTime: number;
184
+ exceedancePercent: number;
185
+ timestamp: Date;
186
+ isWarning: boolean;
119
187
  }
120
188
  /**
121
189
  * Performance budget violation handler type
122
190
  */
123
- // eslint-disable-next-line pickier/no-unused-vars
124
191
  export type BudgetViolationHandler = (violation: BudgetViolation) => void;
125
- export declare class LRUCache<K, V> {
126
- constructor(maxSize?: number, options?: LRUCacheOptions<V>);
127
- get byteSize(): number;
128
- setMaxBytes(maxBytes: number): void;
129
- get(key: K): V | undefined;
130
- set(key: K, value: V): void;
131
- has(key: K): boolean;
132
- delete(key: K): boolean;
133
- clear(): void;
134
- get size(): number;
135
- keys(): IterableIterator<K>;
136
- values(): IterableIterator<V>;
137
- }
138
192
  /**
139
- * Cache for template processing results
193
+ * Performance monitor for tracking processing times with budget support
140
194
  */
141
- export declare class TemplateCache {
142
- constructor(maxSize?: number, ttl?: number);
143
- get(key: string): string | null;
144
- set(key: string, result: string, dependencies?: Set<string>): void;
145
- invalidateDependency(filePath: string): number;
146
- clear(): void;
147
- getStats(): { size: number, maxSize: number, hitRate?: number };
195
+ export declare class PerformanceMonitor {
196
+ private metrics;
197
+ private budgets;
198
+ private violations;
199
+ private maxViolations;
200
+ private violationHandlers;
201
+ private enabled;
202
+ /**
203
+ * Enable or disable performance monitoring
204
+ */
205
+ setEnabled(enabled: boolean): void;
206
+ /**
207
+ * Check if monitoring is enabled
208
+ */
209
+ isEnabled(): boolean;
210
+ /**
211
+ * Set a performance budget for a specific operation
212
+ *
213
+ * @param label - Operation label
214
+ * @param budget - Budget configuration
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * performanceMonitor.setBudget('processDirectives', {
219
+ * maxTime: 100, // 100ms max
220
+ * warnThreshold: 0.8, // warn at 80ms
221
+ * action: 'warn'
222
+ * })
223
+ * ```
224
+ */
225
+ setBudget(label: string, budget: PerformanceBudget): void;
226
+ /**
227
+ * Set multiple performance budgets at once
228
+ */
229
+ setBudgets(budgets: Record<string, PerformanceBudget>): void;
230
+ /**
231
+ * Remove a performance budget
232
+ */
233
+ removeBudget(label: string): void;
234
+ /**
235
+ * Get all configured budgets
236
+ */
237
+ getBudgets(): Record<string, PerformanceBudget>;
238
+ /**
239
+ * Add a handler for budget violations
240
+ */
241
+ onViolation(handler: BudgetViolationHandler): void;
242
+ /**
243
+ * Remove a violation handler
244
+ */
245
+ offViolation(handler: BudgetViolationHandler): void;
246
+ /**
247
+ * Time a function execution
248
+ */
249
+ time<T>(label: string, fn: () => T): T;
250
+ /**
251
+ * Time an async function execution
252
+ */
253
+ timeAsync<T>(label: string, fn: () => Promise<T>): Promise<T>;
254
+ /**
255
+ * Check if a duration violates the budget
256
+ */
257
+ private checkBudget;
258
+ /**
259
+ * Record a timing measurement
260
+ */
261
+ recordTime(label: string, duration: number): void;
262
+ /**
263
+ * Get performance statistics
264
+ */
265
+ getStats(label?: string): Record<string, any>;
266
+ /**
267
+ * Get all budget violations
268
+ */
269
+ getViolations(label?: string): BudgetViolation[];
270
+ /**
271
+ * Get violation statistics
272
+ */
273
+ getViolationStats(): {
274
+ total: number;
275
+ byLabel: Record<string, number>;
276
+ warnings: number;
277
+ errors: number;
278
+ };
279
+ /**
280
+ * Clear all metrics
281
+ */
282
+ clear(): void;
283
+ /**
284
+ * Clear all violations
285
+ */
286
+ clearViolations(): void;
287
+ /**
288
+ * Clear budgets
289
+ */
290
+ clearBudgets(): void;
291
+ /**
292
+ * Reset everything (metrics, violations, budgets)
293
+ */
294
+ reset(): void;
148
295
  }
149
296
  /**
150
- * Pool of worker contexts to avoid creating new Function instances
297
+ * Default performance budgets for common operations
151
298
  */
152
- declare class ExpressionEvaluatorPool {
153
- getEvaluator(contextKeys: string[]): (...args: any[]) => any;
154
- clear(): void;
155
- }
299
+ export declare const defaultPerformanceBudgets: Record<string, PerformanceBudget>;
156
300
  /**
157
- * Performance monitor for tracking processing times with budget support
301
+ * Get the global performance monitor instance (lazy-loaded)
302
+ * This avoids instantiating the monitor until it's actually needed
158
303
  */
159
- export declare class PerformanceMonitor {
160
- setEnabled(enabled: boolean): void;
161
- isEnabled(): boolean;
162
- setBudget(label: string, budget: PerformanceBudget): void;
163
- setBudgets(budgets: Record<string, PerformanceBudget>): void;
164
- removeBudget(label: string): void;
165
- getBudgets(): Record<string, PerformanceBudget>;
166
- onViolation(handler: BudgetViolationHandler): void;
167
- offViolation(handler: BudgetViolationHandler): void;
168
- time<T>(label: string, fn: () => T): T;
169
- timeAsync<T>(label: string, fn: () => Promise<T>): Promise<T>;
170
- recordTime(label: string, duration: number): void;
171
- getStats(label?: string): Record<string, any>;
172
- getViolations(label?: string): BudgetViolation[];
173
- getViolationStats(): { total: number, byLabel: Record<string, number>, warnings: number, errors: number };
174
- clear(): void;
175
- clearViolations(): void;
176
- clearBudgets(): void;
177
- reset(): void;
178
- }
304
+ export declare function getPerformanceMonitor(): PerformanceMonitor;
305
+ /**
306
+ * Global performance monitor instance
307
+ * @deprecated Use getPerformanceMonitor() for lazy loading
308
+ */
309
+ export declare const performanceMonitor: PerformanceMonitor;
310
+ /**
311
+ * Apply default performance budgets to the monitor
312
+ */
313
+ export declare function applyDefaultBudgets(monitor?: PerformanceMonitor): void;
314
+ /**
315
+ * Reset the performance monitor instance (useful for testing)
316
+ */
317
+ export declare function resetPerformanceMonitor(): void;
318
+ export {};
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{eo,Ht,Sl,Cg}from"./chunk-83myk906.js";import{Qs,Ii,Sg,kg,_g}from"./chunk-t5vjt37c.js";import{wl,vl,xl,vg,xg}from"./chunk-d8rcba53.js";import{Ue,Tn,Oi}from"./chunk-y9bj3566.js";import{Eg,Tg,$g,Rg,to,dy}from"./chunk-gqjb1y7c.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-acwqb3ys.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
2
+ import{eo,Ht,Sl,Cg}from"./chunk-p4aaxpaw.js";import{Qs,Ii,Sg,kg,_g}from"./chunk-rxhymzj8.js";import{wl,vl,xl,vg,xg}from"./chunk-d8rcba53.js";import{Ue,Tn,Oi}from"./chunk-y9bj3566.js";import{Eg,Tg,$g,Rg,to,dy}from"./chunk-gqjb1y7c.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-mv9k42dn.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -1,3 +1,4 @@
1
+ import { LRUCache } from "./performance-utils.js";
1
2
  const defaultConfig = {
2
3
  maxSanitizeDepth: 10,
3
4
  allowBracketNotation: !1
@@ -5,9 +6,11 @@ const defaultConfig = {
5
6
  let currentConfig = { ...defaultConfig };
6
7
  export function configureSafeEvaluator(config) {
7
8
  currentConfig = { ...currentConfig, ...config };
9
+ expressionPlans.clear();
8
10
  }
9
11
  export function resetSafeEvaluatorConfig() {
10
12
  currentConfig = { ...defaultConfig };
13
+ expressionPlans.clear();
11
14
  }
12
15
  export function getSafeEvaluatorConfig() {
13
16
  return { ...currentConfig };
@@ -482,7 +485,21 @@ const VALID_PARAM_IDENT = /^[A-Za-z_$][\w$]*$/;
482
485
  export function isUsableParamName(name) {
483
486
  return VALID_PARAM_IDENT.test(name) && !RESERVED_PARAM_NAMES.has(name);
484
487
  }
488
+ const expressionPlans = new LRUCache(2000, {
489
+ maxBytes: 2097152,
490
+ sizeOf: (plan) => plan.sourceBytes
491
+ });
485
492
  export function createSafeFunction(expression, contextKeys, onMissingIdentifier) {
493
+ const key = JSON.stringify([expression, contextKeys]);
494
+ let plan = expressionPlans.get(key);
495
+ if (!plan) {
496
+ plan = prepareFunctionPlan(expression, [...contextKeys]);
497
+ plan.sourceBytes += key.length * 2;
498
+ expressionPlans.set(key, plan);
499
+ }
500
+ return guardDynamicKeys(bindProjection(plan.buildFunc, plan.filteredKeys, plan.contextKeys, plan.validEntries, plan.validIndices, onMissingIdentifier), plan.contextKeys, plan.dynamicKeys);
501
+ }
502
+ function prepareFunctionPlan(expression, contextKeys) {
486
503
  const { source: sanitizedExpr, usesSafeConstructors, dynamicKeys } = prepareExpression(expression), validEntries = [];
487
504
  for (let i = 0;i < contextKeys.length; i++) {
488
505
  if (!isUsableParamName(contextKeys[i]))
@@ -503,14 +520,22 @@ catch (e) {
503
520
  }
504
521
  throw e;
505
522
  }
506
- `;
507
- return guardDynamicKeys(bindProjection(usesSafeConstructors ? (extraParams) => {
523
+ `, buildFunc = usesSafeConstructors ? (extraParams) => {
508
524
  const compiled = compileFunctionBody([SAFE_CTOR_PARAM, "Object", ...SHADOWED_GLOBAL_NAMES, ...filteredKeys, ...extraParams], body);
509
525
  return (...args) => compiled(SAFE_CONSTRUCTORS, SAFE_OBJECT, ...SHADOWED_GLOBAL_VALUES, ...args);
510
526
  } : (extraParams) => {
511
527
  const compiled = compileFunctionBody(["Object", ...SHADOWED_GLOBAL_NAMES, ...filteredKeys, ...extraParams], body);
512
528
  return (...args) => compiled(SAFE_OBJECT, ...SHADOWED_GLOBAL_VALUES, ...args);
513
- }, filteredKeys, contextKeys, validEntries, validIndices, onMissingIdentifier), contextKeys, dynamicKeys);
529
+ }, initialFunc = buildFunc([]);
530
+ return {
531
+ sourceBytes: expression.length * 2 + contextKeys.reduce((bytes, key) => bytes + key.length * 2, 0),
532
+ contextKeys,
533
+ filteredKeys,
534
+ validEntries,
535
+ validIndices,
536
+ dynamicKeys,
537
+ buildFunc: (extraParams) => extraParams.length === 0 ? initialFunc : buildFunc(extraParams)
538
+ };
514
539
  }
515
540
  function guardDynamicKeys(evaluate, contextKeys, dynamicKeys) {
516
541
  if (dynamicKeys.length === 0)
package/dist/ssg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunk-7sh9fa3q.js";import{w,rl}from"./chunk-se44tmvx.js";import"./chunk-t65tn8ee.js";import"./chunk-2yxva96k.js";import{Rt,S}from"./chunk-nv0n2hjg.js";import"./chunk-akcyaxwv.js";import"./chunk-fw9dhsd9.js";import"./chunk-9gwhs0gk.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-j2v9f2dk.js";import{a}from"./chunk-gqdkvwjp.js";import{Ts}from"./chunk-dq87xd5c.js";import"./chunk-qpvwxppw.js";import"./chunk-wz3gk8js.js";import{he,en,tn}from"./chunk-gctyy7r9.js";import"./chunk-x8m28yea.js";import{y}from"./chunk-t0bcbhvs.js";import{yt,i}from"./chunk-2fh4wvtv.js";import"./chunk-3ajbbtqx.js";import"./chunk-vg3scf4d.js";import{gs}from"./chunk-xtwcz8dg.js";import"./chunk-61h00ba5.js";import"./chunk-c84pxd2k.js";import{Za,Qa,ec}from"./chunk-gjf8cjdt.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-v47yfe9k.js";import"./chunk-pxxhhaaw.js";import"./chunk-2yb1rwmy.js";import{K,we}from"./chunk-8kvj2wz0.js";import"./chunk-kydgndkt.js";import"./chunk-56j2egg3.js";import{c}from"./chunk-brhas9mp.js";import{r,ge}from"./chunk-b9d70mgr.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,n={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,o=t.replace(Dt,(e,u,g,v)=>{let x=v.trim();if(!x)return e;if(/\bdata-stx-src=/.test(g))return e;if(n.minify)x=Pt(x);let p=It(x);if(!s.has(p))s.set(p,x);let P=n.integrity?` data-stx-integrity="sha384-${vt("sha384").update(x).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),l=Array.from(s,([e,u])=>({hash:e,code:u}));return{html:o,chunks:l}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(t))!==null)n.set(o[1],o[2]);let l=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(n.get(u[1])||""))l.add(u[2]);let g=/<\/head\s*>/iy,v=S(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(l.size===0||v===-1)return t;let x=Array.from(l).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!x)return t;return t.slice(0,v)+x+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function X(t){let n=t.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let n of jt){let s=t[n];if(!s)continue;let o=X(s);if(o)return{url:o,source:"env",via:n}}return null}function lt(t){if(!t||typeof t!=="object")return null;let n=t,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?X(s):null}async function At(t){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let l=s.resolve(t,o);if(!n(l))continue;try{let e=await import(l),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let n=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let u=X(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let l=await At(n);if(l)return{url:l,source:"site.config",via:"url"};let e=Ft(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
2
+ import"./chunk-7sh9fa3q.js";import{w,rl}from"./chunk-ewhkvqce.js";import"./chunk-t65tn8ee.js";import"./chunk-r9e0r6jx.js";import{Rt,S}from"./chunk-ved3r01r.js";import"./chunk-2vqpz4qv.js";import"./chunk-casq5t61.js";import"./chunk-9gwhs0gk.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-dbbc84mj.js";import{a}from"./chunk-fy6sdbak.js";import{Ts}from"./chunk-xrvdef6x.js";import"./chunk-qpvwxppw.js";import"./chunk-3j9zzpbd.js";import{he,en,tn}from"./chunk-cs38hg43.js";import"./chunk-byatzyvf.js";import{y}from"./chunk-nya33asw.js";import{yt,i}from"./chunk-0vztrb90.js";import"./chunk-fsfj0s13.js";import"./chunk-v18816jj.js";import{gs}from"./chunk-r9eyepbk.js";import"./chunk-qx5jhe7h.js";import"./chunk-c84pxd2k.js";import{Za,Qa,ec}from"./chunk-gjf8cjdt.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-aj5na3d3.js";import"./chunk-fq1dw4ph.js";import"./chunk-a5byhf8f.js";import{X,we}from"./chunk-hzhsg5j7.js";import"./chunk-1pz11ez9.js";import"./chunk-x0ttkvr7.js";import{c}from"./chunk-brhas9mp.js";import{r,ge}from"./chunk-b9d70mgr.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,n={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,o=t.replace(Dt,(e,u,g,v)=>{let x=v.trim();if(!x)return e;if(/\bdata-stx-src=/.test(g))return e;if(n.minify)x=Pt(x);let p=It(x);if(!s.has(p))s.set(p,x);let P=n.integrity?` data-stx-integrity="sha384-${vt("sha384").update(x).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),l=Array.from(s,([e,u])=>({hash:e,code:u}));return{html:o,chunks:l}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(t))!==null)n.set(o[1],o[2]);let l=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(n.get(u[1])||""))l.add(u[2]);let g=/<\/head\s*>/iy,v=S(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(l.size===0||v===-1)return t;let x=Array.from(l).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!x)return t;return t.slice(0,v)+x+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function K(t){let n=t.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let n of jt){let s=t[n];if(!s)continue;let o=K(s);if(o)return{url:o,source:"env",via:n}}return null}function lt(t){if(!t||typeof t!=="object")return null;let n=t,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?K(s):null}async function At(t){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let l=s.resolve(t,o);if(!n(l))continue;try{let e=await import(l),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let n=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let u=K(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let l=await At(n);if(l)return{url:l,source:"site.config",via:"url"};let e=Ft(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
3
  `)}function q(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let n=r(t),{depths:s}=ge(n),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,l;while((l=o.exec(n))!==null){if(s[l.index]!==0)continue;let u=w(n,"(",")",o.lastIndex-1),g=n.indexOf("{",u+1),v=w(n,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(l.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((l=e.exec(n))!==null){if(s[l.index]!==0)continue;let u=rl(n,e.lastIndex).endPos;return t.slice(e.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function gt(t){let n="read";try{let s=await Bun.file(t).text();n="parse";let o=Qt(s),l=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(r(e.attrs))).sort((e,u)=>s.indexOf(e.fullTag)-s.indexOf(u.fullTag));for(let e of l){if(!/\bgetStaticPaths\b/.test(r(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(r(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(r(g))&&Rt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");n="execute";let v=Function("defineStaticPaths",`return (${g})`)(q);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let x=await v();n="result";let p=Array.isArray(x)?{paths:x}:x;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let P of p.paths)if(!P||typeof P!=="object"||!P.params||typeof P.params!=="object"||Array.isArray(P.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(s){return{kind:"error",phase:n,error:s instanceof Error?s:Error(String(s))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,n=""){this.cacheDir=t,this.salt=n}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let n=JSON.parse(await Bun.file(t).text());for(let[s,o]of Object.entries(n))this.cache.set(s,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),n={};for(let[s,o]of this.cache)n[s]=o;await Bun.write(t,JSON.stringify(n))}getHash(t,n){let s=D.statSync(t),o=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of n)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let l=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);l=(l<<5)-l+u,l=l&l}return Math.abs(l).toString(36)}get(t,n){let s=this.cache.get(t);if(!s)return null;let o=ft(n).some((u)=>D.existsSync(u)),l=[n,...s.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&gs(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||l)return this.cache.delete(t),null;let e=this.getHash(n,s.dependencies??[]);if(s.hash!==e)return this.cache.delete(t),null;return s.html}set(t,n,s,o){let l=this.getHash(n,s);this.cache.set(t,{hash:l,html:o,generatedAt:Date.now(),dependencies:s})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let n=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",n)}async get(t){let n=this.getFilePath(t);if(!await Bun.file(n).exists())return null;try{return JSON.parse(await Bun.file(n).text())}catch{return null}}async set(t,n){let s=this.getFilePath(t);await D.promises.mkdir(f.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(n))}async invalidate(t){let n=this.getFilePath(t);if(await Bun.file(n).exists())await D.promises.unlink(n)}async invalidatePattern(t){let n=f.join(this.cacheDir,"isr");if(!D.existsSync(n))return;let s=await D.promises.readdir(n);for(let o of s){let l=o.replace(/_/g,"/").replace(".json","");if(t.test(l))await D.promises.unlink(f.join(n,o))}}async needsRevalidation(t){let n=await this.get(t);if(!n)return!0;return Date.now()>n.revalidateAfter}}async function Ut(t){let n=[];if(!t.isDynamic)n.push({url:t.pattern,params:{}});else{let s=await gt(t.filePath);if(s.kind==="error")throw Error(`getStaticPaths ${s.phase} failed for ${t.pattern} (${t.filePath}): ${s.error.message}`,{cause:s.error});if(s.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),n;let o=s.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),n;for(let l of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(l.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);n.push({url:e,params:l.params,props:l.props,revalidate:l.revalidate})}}return n}function ft(t){return[t.replace(/\.stx$/,".data.ts"),t.replace(/\.stx$/,".data.js"),t+".data.ts",t+".data.js"]}async function Mt(t){for(let n of ft(t))if(await Bun.file(n).exists())try{let s=await import(n);if(typeof s.default==="function")return await s.default();else if(typeof s.default==="object")return s.default;else if(typeof s.getData==="function")return await s.getData();else{let{default:o,...l}=s;return l}}catch(s){console.error(`Error loading data file ${n}:`,s)}return null}async function Gt(t,n,s){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let l=o[1];if(!l.includes("getStaticProps"))return null;try{let e=l.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
4
4
  return (async function getStaticProps() {
5
5
  ${e[1]}
@@ -37,7 +37,7 @@ ${t.map((o)=>{let l=new URL(o.loc,n).href,e=` <url>
37
37
  ${s.join(`
38
38
  `)}
39
39
  </channel>
40
- </rss>`}async function Vt(t={}){let n=Date.now();tn();let s=await a(process.cwd()),o=s.build||{},l=await ut({explicit:t.domain||o.domain,stxConfig:s});if(l.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:l.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||c(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,x={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-26505qjh.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-f52esq8m.js"),R=await b(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-26505qjh.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=s?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=s?.routeMiddleware?.global||[];ec(s?.layoutsDir,c(process.cwd()));let Z=K(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
40
+ </rss>`}async function Vt(t={}){let n=Date.now();tn();let s=await a(process.cwd()),o=s.build||{},l=await ut({explicit:t.domain||o.domain,stxConfig:s});if(l.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:l.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||c(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,x={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-8fnhv8jq.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-c36bj74x.js"),R=await b(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-8fnhv8jq.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=s?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=s?.routeMiddleware?.global||[];ec(s?.layoutsDir,c(process.cwd()));let Z=X(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
41
41
  const validate = ${it[1]};
42
42
  return validate(route);
43
43
  `)({params:G})){console.warn(`Validation failed for ${h}, skipping...`);return}}catch{}let I=null,st=!1;if(e.cache){if(I=T.get(h,k.filePath),I)st=!0,u.cachedCount++}if(!I){let B=await mt(k,G,xt,e,s);if(I=B.html,e.failOnIncludeError&&B.includeFailures.length>0)throw Error(`${B.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
@@ -77,7 +77,7 @@ Build complete!
77
77
  Cached: ${u.cachedCount}
78
78
  Failed: ${u.failedCount}
79
79
  Time: ${u.buildTime}ms${P}
80
- `),u}async function Y(t,n){await D.promises.mkdir(n,{recursive:!0});let s=await D.promises.readdir(t,{withFileTypes:!0});for(let o of s){let l=f.join(t,o.name),e=f.join(n,o.name);if(o.isDirectory())await D.promises.mkdir(e,{recursive:!0}),await Y(l,e);else await D.promises.copyFile(l,e)}}function Kt(t={}){let n=t.cacheDir||c(process.cwd(),"ssg-cache"),s=new ht(n),o=t.revalidate||3600;return{async get(l){let e=await s.get(l);if(!e)return null;if(Date.now()>e.revalidateAfter)this.revalidate(l).catch(console.error);return{html:e.html,headers:{"Cache-Control":`public, max-age=${o}, stale-while-revalidate=${o*2}`,ETag:e.etag,"X-ISR-Generated":new Date(e.generatedAt).toISOString(),...e.headers}}},async revalidate(l){let u=K(".",{pagesDir:t.pagesDir||"pages"}).find((P)=>l.match(P.regex)!==null);if(!u){console.warn(`Route not found for revalidation: ${l}`);return}let g=l.match(u.regex),v={};if(g)u.params.forEach((P,E)=>{v[P]=g[E+1]});let x=await a(),{html:p}=await mt(u,v,{},t,x);await s.set(l,{html:p,generatedAt:Date.now(),revalidateAfter:Date.now()+o*1000,etag:zt(p)}),console.log(`Revalidated: ${l}`)},async invalidate(l){if(typeof l==="string")await s.invalidate(l);else await s.invalidatePattern(l)}}}function Xt(){return{name:"markdown",extensions:[".md",".mdx"],async load(t){let n=await Bun.file(t).text(),s=n.match(/^---\n([\s\S]*?)\n---/),o={},l=n;if(s){let x=s[1];l=n.slice(s[0].length).trim();for(let p of x.split(`
80
+ `),u}async function Y(t,n){await D.promises.mkdir(n,{recursive:!0});let s=await D.promises.readdir(t,{withFileTypes:!0});for(let o of s){let l=f.join(t,o.name),e=f.join(n,o.name);if(o.isDirectory())await D.promises.mkdir(e,{recursive:!0}),await Y(l,e);else await D.promises.copyFile(l,e)}}function Kt(t={}){let n=t.cacheDir||c(process.cwd(),"ssg-cache"),s=new ht(n),o=t.revalidate||3600;return{async get(l){let e=await s.get(l);if(!e)return null;if(Date.now()>e.revalidateAfter)this.revalidate(l).catch(console.error);return{html:e.html,headers:{"Cache-Control":`public, max-age=${o}, stale-while-revalidate=${o*2}`,ETag:e.etag,"X-ISR-Generated":new Date(e.generatedAt).toISOString(),...e.headers}}},async revalidate(l){let u=X(".",{pagesDir:t.pagesDir||"pages"}).find((P)=>l.match(P.regex)!==null);if(!u){console.warn(`Route not found for revalidation: ${l}`);return}let g=l.match(u.regex),v={};if(g)u.params.forEach((P,E)=>{v[P]=g[E+1]});let x=await a(),{html:p}=await mt(u,v,{},t,x);await s.set(l,{html:p,generatedAt:Date.now(),revalidateAfter:Date.now()+o*1000,etag:zt(p)}),console.log(`Revalidated: ${l}`)},async invalidate(l){if(typeof l==="string")await s.invalidate(l);else await s.invalidatePattern(l)}}}function Xt(){return{name:"markdown",extensions:[".md",".mdx"],async load(t){let n=await Bun.file(t).text(),s=n.match(/^---\n([\s\S]*?)\n---/),o={},l=n;if(s){let x=s[1];l=n.slice(s[0].length).trim();for(let p of x.split(`
81
81
  `)){let P=p.indexOf(":");if(P>0){let E=p.slice(0,P).trim(),b=p.slice(P+1).trim();if(b==="true")b=!0;else if(b==="false")b=!1;else if(/^\d+$/.test(b))b=parseInt(b,10);else if(/^\d+\.\d+$/.test(b))b=parseFloat(b);else if(b.startsWith("[")&&b.endsWith("]"))b=b.slice(1,-1).split(",").map((R)=>R.trim().replace(/^['"]|['"]$/g,""));o[E]=b}}}let e=l.replace(/^### (.*$)/gim,"<h3>$1</h3>").replace(/^## (.*$)/gim,"<h2>$1</h2>").replace(/^# (.*$)/gim,"<h1>$1</h1>").replace(/\*\*(.*)\*\*/gim,"<strong>$1</strong>").replace(/\*(.*)\*/gim,"<em>$1</em>").replace(/`([^`]+)`/gim,"<code>$1</code>").replace(/\[([^\]]+)\]\(([^)]+)\)/gim,'<a href="$2">$1</a>').replace(/\n/gim,"<br>"),u=[],g=/<h([1-6])>([^<]+)<\/h[1-6]>/gi,v;while((v=g.exec(e))!==null){let x=parseInt(v[1],10),p=v[2],P=p.toLowerCase().replace(/[^a-z0-9]+/g,"-");u.push({id:P,text:p,level:x})}return{content:e,data:o,toc:u}}}}function Yt(t){return yt(t)}function te(t,n){return`<!DOCTYPE html>
82
82
  <html>
83
83
  <head>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/stx",
3
3
  "type": "module",
4
- "version": "0.2.801",
4
+ "version": "0.2.802",
5
5
  "description": "A performant UI Framework. Powered by Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -128,12 +128,12 @@
128
128
  "dependencies": {
129
129
  "@stacksjs/ts-css": "^0.3.21",
130
130
  "@stacksjs/clapp": "^0.2.16",
131
- "@stacksjs/desktop": "0.2.801",
132
- "@stacksjs/sanitizer": "0.2.801",
131
+ "@stacksjs/desktop": "0.2.802",
132
+ "@stacksjs/sanitizer": "0.2.802",
133
133
  "@stacksjs/ts-i18n": "^0.1.11",
134
- "bun-plugin-stx": "0.2.801",
134
+ "bun-plugin-stx": "0.2.802",
135
135
  "bunfig": "^0.15.21",
136
- "stx-router": "0.2.801",
136
+ "stx-router": "0.2.802",
137
137
  "ts-broadcasting": "^0.0.11",
138
138
  "ts-images": "^0.2.22",
139
139
  "ts-syntax-highlighter": "^0.2.1"
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ia,Yg,aa,Zg,Ll,jl,Qg,em}from"./chunk-9nbv6nk4.js";import"./chunk-k4nhwd9p.js";import"./chunk-gctyy7r9.js";import"./chunk-wz3gk8js.js";import"./chunk-7sh9fa3q.js";import"./chunk-xtwcz8dg.js";import"./chunk-8kvj2wz0.js";import"./chunk-kydgndkt.js";import"./chunk-gqdkvwjp.js";import"./chunk-56j2egg3.js";import"./chunk-9gwhs0gk.js";import"./chunk-qpvwxppw.js";import"./chunk-dq87xd5c.js";import"./chunk-j2v9f2dk.js";import{It,Yf}from"./chunk-nv0n2hjg.js";import"./chunk-fw9dhsd9.js";import"./chunk-akcyaxwv.js";import"./chunk-se44tmvx.js";import"./chunk-2yxva96k.js";import"./chunk-t65tn8ee.js";export{ia as buildScriptVirtualFile,Yg as buildVirtualSource,It as extractScriptBlocks,Yf as extractTemplateExpressions,Ll as findRuntimeTypeDeclarations,jl as findStxModuleDeclarations,em as formatTypecheckDiagnostics,Zg as sourcePathFor,Qg as typecheckStxFiles,aa as virtualPathFor};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Xg}from"./chunk-kdhsev5v.js";import"./chunk-2vejgrj7.js";import"./chunk-v47yfe9k.js";import"./chunk-wz3gk8js.js";import"./chunk-pxxhhaaw.js";import"./chunk-8kvj2wz0.js";import"./chunk-gqdkvwjp.js";import"./chunk-56j2egg3.js";import"./chunk-9gwhs0gk.js";import"./chunk-qpvwxppw.js";import"./chunk-dq87xd5c.js";import"./chunk-j2v9f2dk.js";import"./chunk-nv0n2hjg.js";import"./chunk-fw9dhsd9.js";import"./chunk-akcyaxwv.js";import"./chunk-se44tmvx.js";import"./chunk-2yxva96k.js";import"./chunk-t65tn8ee.js";export{Xg as startProductionServer};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ha,ya,ql,Xl,Kl,Gl,Rm}from"./chunk-q3dsjk2b.js";export{ha as createVirtualList,Rm as default,ql as generateVirtualListCSS,Kl as processInfiniteListDirectives,Gl as processVirtualGridDirectives,ya as processVirtualListDirectives,Xl as useVirtualList};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{zl,gm,Hl,Vl,mm,hm}from"./chunk-s85s2kd3.js";import"./chunk-nv0n2hjg.js";import"./chunk-fw9dhsd9.js";import"./chunk-akcyaxwv.js";import"./chunk-se44tmvx.js";import"./chunk-2yxva96k.js";import"./chunk-t65tn8ee.js";export{hm as applySlots,mm as extractSlotContent,gm as parseSlotElement,zl as parseSlots,Vl as processSlots,Hl as renderSlot};