@stacksjs/stx 0.2.286 → 0.2.287

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 (165) hide show
  1. package/dist/builtins/index.d.ts +4 -3
  2. package/dist/builtins/index.js +11 -11
  3. package/dist/chunk-122tyfre.js +2 -0
  4. package/dist/{chunk-0fgcnv6y.js → chunk-19nfvxfw.js} +1 -1
  5. package/dist/{chunk-ah4e6e09.js → chunk-1kah92n2.js} +1 -1
  6. package/dist/{chunk-90qr4f9m.js → chunk-1kms3b9d.js} +1 -1
  7. package/dist/{chunk-s2284nbk.js → chunk-1q4y74mh.js} +1 -1
  8. package/dist/{chunk-49kk0s96.js → chunk-248e84r1.js} +1 -1
  9. package/dist/{chunk-zfr4d08r.js → chunk-24ps8kft.js} +1 -1
  10. package/dist/chunk-2et5hxfv.js +2 -0
  11. package/dist/chunk-2r1rd8f0.js +2 -0
  12. package/dist/{chunk-2q630fj4.js → chunk-2tk1zkrz.js} +1 -1
  13. package/dist/{chunk-ysnk7x79.js → chunk-38ejahd9.js} +1 -1
  14. package/dist/chunk-3zv4wz87.js +2 -0
  15. package/dist/chunk-4122k1bh.js +2 -0
  16. package/dist/chunk-45az9zht.js +2 -0
  17. package/dist/{chunk-yq1d9hb3.js → chunk-4qr85f07.js} +1 -1
  18. package/dist/{chunk-m3yaa0v5.js → chunk-4ww3znrr.js} +1 -1
  19. package/dist/chunk-5a19dhx5.js +2 -0
  20. package/dist/{chunk-39f40yc4.js → chunk-5kk8gsj2.js} +1 -1
  21. package/dist/{chunk-kzyhvrp8.js → chunk-5w1e3yxs.js} +1 -1
  22. package/dist/chunk-6gdycmxr.js +2 -0
  23. package/dist/{chunk-e2w23g2r.js → chunk-6hmnaza7.js} +10 -10
  24. package/dist/{chunk-zn5jgmqw.js → chunk-71t0yan0.js} +1 -1
  25. package/dist/chunk-74v15e8z.js +2 -0
  26. package/dist/{chunk-j9g11dzx.js → chunk-7b329e5v.js} +1 -1
  27. package/dist/{chunk-g3fy0tw8.js → chunk-866y9d8b.js} +154 -48
  28. package/dist/chunk-8fwerspy.js +2 -0
  29. package/dist/{chunk-c0an64km.js → chunk-8mjdpr94.js} +1 -1
  30. package/dist/{chunk-q68xmak4.js → chunk-92mj1t26.js} +18 -18
  31. package/dist/{chunk-mkn6qqc7.js → chunk-9b22663r.js} +1 -1
  32. package/dist/chunk-9hjdgm4d.js +2 -0
  33. package/dist/{chunk-y8n174xq.js → chunk-9wr7zcad.js} +2 -2
  34. package/dist/{chunk-qbeffw17.js → chunk-a0nfbmeh.js} +1 -1
  35. package/dist/{chunk-rhs51nmz.js → chunk-acn1b56m.js} +2 -2
  36. package/dist/chunk-awkq3xfx.js +2 -0
  37. package/dist/{chunk-bf8wf3r2.js → chunk-b6ej2fdf.js} +2 -2
  38. package/dist/{chunk-e7jfpyqy.js → chunk-b8rrnqry.js} +1 -1
  39. package/dist/{chunk-s7pc68jf.js → chunk-bfqfs07m.js} +1 -1
  40. package/dist/{chunk-fjkstnz3.js → chunk-bs6kapy7.js} +1 -1
  41. package/dist/{chunk-qd8ggjdx.js → chunk-btav940g.js} +1 -1
  42. package/dist/{chunk-pbk8jxe2.js → chunk-ccspd3mc.js} +1 -1
  43. package/dist/{chunk-7rxtra1g.js → chunk-csbgwaa5.js} +1 -1
  44. package/dist/chunk-d8t4sjsp.js +2 -0
  45. package/dist/chunk-dap191q2.js +2 -0
  46. package/dist/{chunk-ayrjwkyw.js → chunk-de7fye10.js} +1 -1
  47. package/dist/{chunk-2g9jwgs7.js → chunk-dgrt76d2.js} +1 -1
  48. package/dist/{chunk-9zndrzb3.js → chunk-dhh5q7qt.js} +1 -1
  49. package/dist/chunk-dsffsqnt.js +2 -0
  50. package/dist/{chunk-d0c3v7ax.js → chunk-dtq7y5ym.js} +1 -1
  51. package/dist/{chunk-w95sp0k9.js → chunk-fed3xsp9.js} +2 -2
  52. package/dist/{chunk-jbfpc4z7.js → chunk-ferav3bw.js} +1 -1
  53. package/dist/{chunk-a63y3aa0.js → chunk-fvhm8psm.js} +1 -1
  54. package/dist/{chunk-bz2gytfs.js → chunk-g4vpzv6b.js} +1 -1
  55. package/dist/{chunk-n3jyv9z6.js → chunk-g9csmj0s.js} +1 -1
  56. package/dist/chunk-gtcrpmz1.js +2 -0
  57. package/dist/{chunk-hs0387tm.js → chunk-h4xh8cms.js} +1 -1
  58. package/dist/chunk-h8yqsz9m.js +2 -0
  59. package/dist/{chunk-phhzfeh9.js → chunk-hcq5dw7a.js} +1 -1
  60. package/dist/{chunk-qsr3bqav.js → chunk-hm0xha6c.js} +1 -1
  61. package/dist/chunk-jegt35zh.js +2 -0
  62. package/dist/{chunk-nh21517m.js → chunk-k56rjjc0.js} +1 -1
  63. package/dist/{chunk-kmhr1z0m.js → chunk-kdh37tp8.js} +1 -1
  64. package/dist/{chunk-e4hhz9j3.js → chunk-kxzb4et3.js} +1 -1
  65. package/dist/{chunk-3bv8h4r6.js → chunk-mf4n3x1j.js} +1 -1
  66. package/dist/{chunk-5aq35j2e.js → chunk-mkd9kjgb.js} +1 -1
  67. package/dist/chunk-mxfh1nxg.js +2 -0
  68. package/dist/{chunk-snknv47x.js → chunk-nkb3scg6.js} +1 -1
  69. package/dist/{chunk-s67mgegv.js → chunk-nnd4wq8j.js} +1 -1
  70. package/dist/{chunk-w0sqz3cb.js → chunk-nsp1cw38.js} +1 -1
  71. package/dist/chunk-p3242nck.js +2 -0
  72. package/dist/chunk-p98kfh94.js +2 -0
  73. package/dist/{chunk-t1k5dpbr.js → chunk-pkaabd8h.js} +1 -1
  74. package/dist/{chunk-xg57nax9.js → chunk-pzm13sdc.js} +1 -1
  75. package/dist/{chunk-vy8v5xdb.js → chunk-q4p5k2p3.js} +1 -1
  76. package/dist/{chunk-sskbegsz.js → chunk-qc1f74ek.js} +1 -1
  77. package/dist/{chunk-nvgxjvnb.js → chunk-qpyjak7z.js} +1 -1
  78. package/dist/{chunk-an2539bs.js → chunk-qr82je1m.js} +1 -1
  79. package/dist/{chunk-a54n1r1q.js → chunk-qy73j6m4.js} +1 -1
  80. package/dist/{chunk-p396xrew.js → chunk-qzkhpsam.js} +1 -1
  81. package/dist/{chunk-f3hfk78e.js → chunk-r3ayvdz3.js} +1 -1
  82. package/dist/chunk-r7r66978.js +2 -0
  83. package/dist/{chunk-6cye5m9f.js → chunk-rbb7dvja.js} +1 -1
  84. package/dist/{chunk-kdrpx9ft.js → chunk-rj4kajww.js} +1 -1
  85. package/dist/{chunk-areethga.js → chunk-rp4rjjmf.js} +1 -1
  86. package/dist/{chunk-gjemavhx.js → chunk-se0p17c2.js} +1 -1
  87. package/dist/chunk-sj9pmene.js +2 -0
  88. package/dist/{chunk-a2qghr2x.js → chunk-sscwkffs.js} +1 -1
  89. package/dist/chunk-svpqxn2c.js +2 -0
  90. package/dist/chunk-t8y1ggdy.js +2 -0
  91. package/dist/{chunk-y6kw0wb7.js → chunk-tndhnk9e.js} +1 -1
  92. package/dist/{chunk-c6fw33zh.js → chunk-v5e1gxwm.js} +2 -2
  93. package/dist/{chunk-7p9ns60j.js → chunk-vrrax298.js} +1 -1
  94. package/dist/{chunk-9th1wd1d.js → chunk-wrzwgkbx.js} +3 -3
  95. package/dist/{chunk-jn6m8zf7.js → chunk-x650vjcp.js} +1 -1
  96. package/dist/{chunk-mjkfc2v6.js → chunk-xgnc1wy6.js} +1 -1
  97. package/dist/{chunk-52mh63sp.js → chunk-xpp135ad.js} +1 -1
  98. package/dist/chunk-y11cxbxd.js +3757 -0
  99. package/dist/{chunk-cvnh7dma.js → chunk-y98jsjqq.js} +1 -1
  100. package/dist/{chunk-vbdca0k1.js → chunk-ya386h70.js} +1 -1
  101. package/dist/chunk-ydrz60kr.js +2 -0
  102. package/dist/{chunk-0f1kz0x2.js → chunk-ypmqf7tm.js} +1 -1
  103. package/dist/{chunk-jrk8rhwt.js → chunk-z4jhj5e5.js} +1 -1
  104. package/dist/{chunk-fskfes13.js → chunk-zg75gjns.js} +1 -1
  105. package/dist/{chunk-mb518a4n.js → chunk-zqqx1qaj.js} +1 -1
  106. package/dist/cli.js +14 -14
  107. package/dist/client-script.js +27 -7
  108. package/dist/component-client-factories.js +10 -5
  109. package/dist/component-processing.d.ts +13 -0
  110. package/dist/component-processing.js +37 -1
  111. package/dist/component-renderer.js +34 -15
  112. package/dist/conditionals.js +14 -3
  113. package/dist/craft-entry.js +1 -1
  114. package/dist/craft.js +1 -1
  115. package/dist/database.js +1 -1
  116. package/dist/document-shell.d.ts +1 -34
  117. package/dist/document-shell.js +19 -11
  118. package/dist/html-masking.d.ts +65 -9
  119. package/dist/html-masking.js +103 -15
  120. package/dist/misc-directives.d.ts +1 -1
  121. package/dist/misc-directives.js +48 -13
  122. package/dist/process.js +14 -4
  123. package/dist/pwa.js +2 -2
  124. package/dist/reactive-bindings.js +2 -0
  125. package/dist/runtime-globals.d.ts +7 -20
  126. package/dist/runtime-globals.js +28 -3
  127. package/dist/safe-evaluator.d.ts +15 -0
  128. package/dist/safe-evaluator.js +16 -12
  129. package/dist/server-bindings.js +21 -5
  130. package/dist/signal-processing.d.ts +17 -7
  131. package/dist/signal-processing.js +112 -43
  132. package/dist/signals-api.js +5 -2
  133. package/dist/signals.js +153 -47
  134. package/dist/ssg.js +2 -2
  135. package/dist/utils.js +23 -6
  136. package/dist/variable-extractor.js +17 -47
  137. package/dist/visual-testing.js +1 -1
  138. package/package.json +5 -5
  139. package/dist/chunk-3ehv1by2.js +0 -2
  140. package/dist/chunk-4cqgbcy7.js +0 -3756
  141. package/dist/chunk-56ywtaff.js +0 -2
  142. package/dist/chunk-61sj52qh.js +0 -2
  143. package/dist/chunk-7ej1d910.js +0 -2
  144. package/dist/chunk-829pcte9.js +0 -2
  145. package/dist/chunk-8emkx9ja.js +0 -2
  146. package/dist/chunk-ajbfeey7.js +0 -2
  147. package/dist/chunk-b29wbjs5.js +0 -2
  148. package/dist/chunk-b7tjq91c.js +0 -2
  149. package/dist/chunk-ba6tthsm.js +0 -2
  150. package/dist/chunk-e4akvata.js +0 -2
  151. package/dist/chunk-f4k2a7vs.js +0 -2
  152. package/dist/chunk-f80wwn5x.js +0 -2
  153. package/dist/chunk-j03bare5.js +0 -2
  154. package/dist/chunk-jg0axas8.js +0 -2
  155. package/dist/chunk-kawk5ve9.js +0 -2
  156. package/dist/chunk-m7xnzt2t.js +0 -2
  157. package/dist/chunk-qk8tbcwk.js +0 -2
  158. package/dist/chunk-qp97dx7x.js +0 -2
  159. package/dist/chunk-vb10qph4.js +0 -2
  160. package/dist/chunk-vrvehb01.js +0 -2
  161. package/dist/chunk-w8smn72c.js +0 -2
  162. package/dist/chunk-wxk2pbrh.js +0 -2
  163. package/dist/chunk-x1nw1p8z.js +0 -2
  164. package/dist/chunk-xz55q3gr.js +0 -2
  165. package/dist/chunk-ytgnzeeb.js +0 -2
@@ -1,7 +1,7 @@
1
1
  import { registry } from "./component-registry.js";
2
2
  import { processConditionals } from "./conditionals.js";
3
3
  import { registerBuiltins } from "./builtins/index.js";
4
- import { decodeAttributeEntities, decodeStxProp, findComponentTags, parseMultilineAttributes, pascalToKebab, restoreStashedScripts, stashScriptElements, uppercaseHtmlTagSkip } from "./component-processing.js";
4
+ import { decodeAttributeEntities, decodeStxProp, findComponentTags, parseMultilineAttributes, pascalToKebab, readBracedValue, restoreStashedScripts, stashScriptElements, unwrapBracedExpression, uppercaseHtmlTagSkip } from "./component-processing.js";
5
5
  import { maskAtElementPosition, matchHtmlComment } from "./html-masking.js";
6
6
  import { renderComponentWithSlot, userComponentFileExists } from "./utils.js";
7
7
  import { createSafeFunction, isExpressionSafe, safeEvaluateObject, freeIdentifiers } from "./safe-evaluator.js";
@@ -359,6 +359,14 @@ function parseAllAttributes(attributesStr) {
359
359
  value += char;
360
360
  pos++;
361
361
  }
362
+ } else if (attributesStr[pos] === "{") {
363
+ value = readBracedValue(attributesStr, pos);
364
+ pos += value.length;
365
+ const expression = unwrapBracedExpression(value);
366
+ if (expression !== null) {
367
+ props[`:${name}`] = expression;
368
+ continue;
369
+ }
362
370
  } else
363
371
  while (pos < len && !/\s/.test(attributesStr[pos])) {
364
372
  value += attributesStr[pos];
@@ -447,15 +455,13 @@ function resolvePackageDir(spec, fromDir) {
447
455
 
448
456
  export { freeIdentifiers };
449
457
  export async function processESImports(template, context, filePath, options, dependencies) {
450
- if (!template.includes("import"))
458
+ if (!/import\s/.test(template))
451
459
  return template;
452
460
  if (!context.__importedComponents)
453
461
  context.__importedComponents = new Map;
454
- const registered = context.__importedComponents, fromDir = path.dirname(filePath);
455
- let output = template;
456
- const scriptRe = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
457
- output = output.replace(scriptRe, (full, attrs, body) => {
458
- const importRe = /import\s+(?:(\{[^}]*\})|([A-Za-z_$][\w$]*))\s+from\s+['"]([^'"]+)['"]\s*;?\s*\n?/g;
462
+ const registered = context.__importedComponents, fromDir = path.dirname(filePath), replacements = [], scriptRe = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
463
+ for (const scriptMatch of template.matchAll(scriptRe)) {
464
+ const [full, attrs, body] = scriptMatch, importRe = /import\s+(?:(\{[^}]*\})|([A-Za-z_$][\w$]*))\s+from\s+['"]([^'"]+)['"]\s*;?\s*\n?/g;
459
465
  let newBody = body, m;
460
466
  const removals = [];
461
467
  while ((m = importRe.exec(body)) !== null) {
@@ -515,12 +521,25 @@ export async function processESImports(template, context, filePath, options, dep
515
521
  removals.push({ start: m.index, end: m.index + matchStr.length });
516
522
  }
517
523
  if (removals.length === 0)
518
- return full;
524
+ continue;
519
525
  for (let i = removals.length - 1;i >= 0; i--)
520
526
  newBody = newBody.slice(0, removals[i].start) + newBody.slice(removals[i].end);
521
- return `<script${attrs}>${newBody}</script>`;
522
- });
523
- return output;
527
+ replacements.push({
528
+ start: scriptMatch.index,
529
+ end: scriptMatch.index + full.length,
530
+ value: `<script${attrs}>${newBody}</script>`
531
+ });
532
+ }
533
+ if (replacements.length === 0)
534
+ return template;
535
+ const chunks = [];
536
+ let cursor = 0;
537
+ for (const replacement of replacements) {
538
+ chunks.push(template.slice(cursor, replacement.start), replacement.value);
539
+ cursor = replacement.end;
540
+ }
541
+ chunks.push(template.slice(cursor));
542
+ return chunks.join("");
524
543
  }
525
544
  async function processImports(template, context, filePath, options, dependencies) {
526
545
  let output = template;
@@ -630,7 +649,7 @@ async function processCustomElementTags(template, context, filePath, options, de
630
649
  output = await processTagsWithParser(output, /[a-z][a-z0-9]*-[a-z0-9-]*/, !1);
631
650
  output = await processTagsWithParser(output, /[A-Z][a-zA-Z0-9]*/, !0, uppercaseHtmlTagSkip(htmlTags));
632
651
  output = await processTagsWithParser(output, /[a-z][a-z0-9]*/, !1, htmlTags);
633
- output = restoreStashedScripts(output, stashed.scripts);
652
+ output = stashed.restore(output);
634
653
  return output;
635
654
  async function processTagsWithParser(html, tagPattern, isPascalCase, skipTags) {
636
655
  if (!html)
@@ -663,7 +682,7 @@ async function processCustomElementTags(template, context, filePath, options, de
663
682
  mergedProps[key] = value;
664
683
  for (const [key, value] of Object.entries(resolvedProps.serverDynamic))
665
684
  mergedProps[key] = value;
666
- let finalContent = await renderComponentWithSlot(componentPath, mergedProps, restoreStashedScripts(tag.content, stashed.scripts), componentsDir, context, filePath, options, processedComponents, dependencies);
685
+ let finalContent = await renderComponentWithSlot(componentPath, mergedProps, stashed.restore(tag.content), componentsDir, context, filePath, options, processedComponents, dependencies);
667
686
  if (Object.keys(resolvedProps.events).length > 0) {
668
687
  const root = findRenderedComponentRoot(finalContent);
669
688
  if (root) {
@@ -745,7 +764,7 @@ function findRenderedComponentRoot(html) {
745
764
  }
746
765
  export async function processComponents(template, context, filePath, options, dependencies) {
747
766
  if (!builtinsRegistered) {
748
- registerBuiltins();
767
+ registerBuiltins(registry);
749
768
  builtinsRegistered = !0;
750
769
  }
751
770
  let output = await processESImports(template, context, filePath, options, dependencies);
@@ -753,7 +772,7 @@ export async function processComponents(template, context, filePath, options, de
753
772
  output = await processComponentDirectives(output, context, filePath, options, dependencies);
754
773
  const nestedComments = [];
755
774
  for (let pass = 0;pass < 3; pass++) {
756
- const masked = maskAtElementPosition(output, matchHtmlComment, (_token, index) => `\x00STX_COMPONENT_COMMENT_${nestedComments.length + index}\x00`);
775
+ const commentOffset = nestedComments.length, masked = maskAtElementPosition(output, matchHtmlComment, (_token, index) => `\x00STX_COMPONENT_COMMENT_${commentOffset + index}\x00`, `STX_COMPONENT_COMMENT:${commentOffset}`);
757
776
  nestedComments.push(...masked.tokens);
758
777
  const before = output;
759
778
  output = await processCustomElementTags(masked.output, context, filePath, options, dependencies);
@@ -143,6 +143,7 @@ function processConditionalsIn(template, context, filePath) {
143
143
  const ifBlocks = findIfBlocks(output);
144
144
  if (ifBlocks.length === 0)
145
145
  return !1;
146
+ const replacements = Array(ifBlocks.length);
146
147
  for (let i = ifBlocks.length - 1;i >= 0; i--) {
147
148
  const block = ifBlocks[i];
148
149
  try {
@@ -169,12 +170,22 @@ function processConditionalsIn(template, context, filePath) {
169
170
  foundTrueBranch = !0;
170
171
  }
171
172
  }
172
- output = output.substring(0, block.start) + result + output.substring(block.end);
173
+ replacements[i] = result;
173
174
  } catch (error) {
174
- const msg = error instanceof Error ? error.message : String(error), errorMessage = inlineError("If", `Error processing @if block: ${msg}`, ErrorCodes.EVALUATION_ERROR);
175
- output = output.substring(0, block.start) + errorMessage + output.substring(block.end);
175
+ const msg = error instanceof Error ? error.message : String(error);
176
+ replacements[i] = inlineError("If", `Error processing @if block: ${msg}`, ErrorCodes.EVALUATION_ERROR);
176
177
  }
177
178
  }
179
+ const chunks = Array(ifBlocks.length * 2 + 1);
180
+ let cursor = 0;
181
+ for (let i = 0;i < ifBlocks.length; i++) {
182
+ const block = ifBlocks[i];
183
+ chunks[i * 2] = output.slice(cursor, block.start);
184
+ chunks[i * 2 + 1] = replacements[i];
185
+ cursor = block.end;
186
+ }
187
+ chunks[ifBlocks.length * 2] = output.slice(cursor);
188
+ output = chunks.join("");
178
189
  return !0;
179
190
  };
180
191
  while (!0) {
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$j as Aj,Zj as Nj,_j as wj}from"./chunk-jr3jp3ev.js";import{bk as Uj,ck as Xj,dk as Yj,ek as Zj,fk as _j,gk as $j,hk as qj,ik as Fj,jk as Oj,kk as Vj,lk as Ij,mk as Qj,nk as Wj,ok as Kj}from"./chunk-s7pc68jf.js";import"./chunk-y8n174xq.js";import"./chunk-4cqgbcy7.js";import"./chunk-q68xmak4.js";import"./chunk-c0an64km.js";import"./chunk-t1k5dpbr.js";import"./chunk-52mh63sp.js";import"./chunk-9th1wd1d.js";import"./chunk-39f40yc4.js";import"./chunk-ysnk7x79.js";import"./chunk-0f1kz0x2.js";import"./chunk-ayrjwkyw.js";import"./chunk-c6fw33zh.js";import"./chunk-bf8wf3r2.js";import"./chunk-jn6m8zf7.js";import"./chunk-sskbegsz.js";var I=new Map,Q=new Map;function L(j,B){let G=B?.id||g(j),J=h(j),U=I.get(G);if(U&&U.hash===J)return U;let X=S(j),Z=y(j),Y=T(j),_=v(X),{staticParts:q,dynamicParts:$}=C(X),F=u(j),O={id:G,hash:J,tree:X,scripts:Z,styles:Y,staticParts:q,dynamicParts:$,dependencies:F,metadata:_};return I.set(G,O),O}async function r(j,B={},G={}){let J=performance.now();if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`,_=Q.get(Y);if(_&&Date.now()-_.timestamp<(G.cacheTTL||60000))return{html:_.html,styles:j.styles.join(`
2
+ import{$j as Aj,Zj as Nj,_j as wj}from"./chunk-jr3jp3ev.js";import{bk as Uj,ck as Xj,dk as Yj,ek as Zj,fk as _j,gk as $j,hk as qj,ik as Fj,jk as Oj,kk as Vj,lk as Ij,mk as Qj,nk as Wj,ok as Kj}from"./chunk-bfqfs07m.js";import"./chunk-9wr7zcad.js";import"./chunk-y11cxbxd.js";import"./chunk-92mj1t26.js";import"./chunk-8mjdpr94.js";import"./chunk-pkaabd8h.js";import"./chunk-xpp135ad.js";import"./chunk-wrzwgkbx.js";import"./chunk-5kk8gsj2.js";import"./chunk-38ejahd9.js";import"./chunk-ypmqf7tm.js";import"./chunk-de7fye10.js";import"./chunk-v5e1gxwm.js";import"./chunk-b6ej2fdf.js";import"./chunk-x650vjcp.js";import"./chunk-qc1f74ek.js";var I=new Map,Q=new Map;function L(j,B){let G=B?.id||g(j),J=h(j),U=I.get(G);if(U&&U.hash===J)return U;let X=S(j),Z=y(j),Y=T(j),_=v(X),{staticParts:q,dynamicParts:$}=C(X),F=u(j),O={id:G,hash:J,tree:X,scripts:Z,styles:Y,staticParts:q,dynamicParts:$,dependencies:F,metadata:_};return I.set(G,O),O}async function r(j,B={},G={}){let J=performance.now();if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`,_=Q.get(Y);if(_&&Date.now()-_.timestamp<(G.cacheTTL||60000))return{html:_.html,styles:j.styles.join(`
3
3
  `),scripts:j.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:_.html.length,componentCount:j.metadata.componentCount}}}let U;if(G.streaming)U=await H(j.tree,B);else U=W(j.tree,B);let X;if(G.hydrate){let Y=k(U,j,B);U=Y.html,X=Y.data}if(G.minify)U=x(U);if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`;Q.set(Y,{html:U,timestamp:Date.now()})}let Z=performance.now()-J;return{html:U,styles:j.styles.join(`
5
5
  `),scripts:j.scripts.join(`
package/dist/craft.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$j as Aj,Zj as Nj,_j as wj}from"./chunk-jr3jp3ev.js";import{bk as Uj,ck as Xj,dk as Yj,ek as Zj,fk as _j,gk as $j,hk as qj,ik as Fj,jk as Oj,kk as Vj,lk as Ij,mk as Qj,nk as Wj,ok as Kj}from"./chunk-s7pc68jf.js";import"./chunk-y8n174xq.js";import"./chunk-4cqgbcy7.js";import"./chunk-q68xmak4.js";import"./chunk-c0an64km.js";import"./chunk-t1k5dpbr.js";import"./chunk-52mh63sp.js";import"./chunk-9th1wd1d.js";import"./chunk-39f40yc4.js";import"./chunk-ysnk7x79.js";import"./chunk-0f1kz0x2.js";import"./chunk-ayrjwkyw.js";import"./chunk-c6fw33zh.js";import"./chunk-bf8wf3r2.js";import"./chunk-jn6m8zf7.js";import"./chunk-sskbegsz.js";var I=new Map,Q=new Map;function L(j,B){let G=B?.id||g(j),J=h(j),U=I.get(G);if(U&&U.hash===J)return U;let X=S(j),Z=y(j),Y=T(j),_=v(X),{staticParts:q,dynamicParts:$}=C(X),F=u(j),O={id:G,hash:J,tree:X,scripts:Z,styles:Y,staticParts:q,dynamicParts:$,dependencies:F,metadata:_};return I.set(G,O),O}async function r(j,B={},G={}){let J=performance.now();if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`,_=Q.get(Y);if(_&&Date.now()-_.timestamp<(G.cacheTTL||60000))return{html:_.html,styles:j.styles.join(`
2
+ import{$j as Aj,Zj as Nj,_j as wj}from"./chunk-jr3jp3ev.js";import{bk as Uj,ck as Xj,dk as Yj,ek as Zj,fk as _j,gk as $j,hk as qj,ik as Fj,jk as Oj,kk as Vj,lk as Ij,mk as Qj,nk as Wj,ok as Kj}from"./chunk-bfqfs07m.js";import"./chunk-9wr7zcad.js";import"./chunk-y11cxbxd.js";import"./chunk-92mj1t26.js";import"./chunk-8mjdpr94.js";import"./chunk-pkaabd8h.js";import"./chunk-xpp135ad.js";import"./chunk-wrzwgkbx.js";import"./chunk-5kk8gsj2.js";import"./chunk-38ejahd9.js";import"./chunk-ypmqf7tm.js";import"./chunk-de7fye10.js";import"./chunk-v5e1gxwm.js";import"./chunk-b6ej2fdf.js";import"./chunk-x650vjcp.js";import"./chunk-qc1f74ek.js";var I=new Map,Q=new Map;function L(j,B){let G=B?.id||g(j),J=h(j),U=I.get(G);if(U&&U.hash===J)return U;let X=S(j),Z=y(j),Y=T(j),_=v(X),{staticParts:q,dynamicParts:$}=C(X),F=u(j),O={id:G,hash:J,tree:X,scripts:Z,styles:Y,staticParts:q,dynamicParts:$,dependencies:F,metadata:_};return I.set(G,O),O}async function r(j,B={},G={}){let J=performance.now();if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`,_=Q.get(Y);if(_&&Date.now()-_.timestamp<(G.cacheTTL||60000))return{html:_.html,styles:j.styles.join(`
3
3
  `),scripts:j.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:_.html.length,componentCount:j.metadata.componentCount}}}let U;if(G.streaming)U=await H(j.tree,B);else U=W(j.tree,B);let X;if(G.hydrate){let Y=k(U,j,B);U=Y.html,X=Y.data}if(G.minify)U=x(U);if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`;Q.set(Y,{html:U,timestamp:Date.now()})}let Z=performance.now()-J;return{html:U,styles:j.styles.join(`
5
5
  `),scripts:j.scripts.join(`
package/dist/database.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{dv as Q}from"./chunk-sskbegsz.js";var $={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},V={},A={},L=new Map,S=[];function i(z){$={...$,...z}}function o(){return{...$}}function r(){$={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let z of Object.keys(V))delete V[z];L.clear(),S.length=0}function a(z,H){V[z]=H}function F(z){let H=z||$.default;if(V[H])return V[H];let U=$.connections[H];if(!U)throw Error(`Database connection "${H}" not configured`);let W=h(U);return V[H]=W,W}function h(z){switch(z.driver){case"sqlite":return q(z);case"postgres":return y(z);case"mysql":return f(z);default:throw Error(`Unsupported database driver: ${z.driver}`)}}function q(z){let H=null,U=!1;return{async connect(){if(U)return;let{Database:W}=await import("bun:sqlite");H=new W(z.database,{create:!0,readwrite:!0}),U=!0},async disconnect(){if(H)H.close(),H=null,U=!1},async query(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).all(...J);if($.logging)B(W,J,performance.now()-X);return Y}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.lastInsertRowid}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.changes}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!U)await this.connect();H.run("BEGIN TRANSACTION")},async commit(){H.run("COMMIT")},async rollback(){H.run("ROLLBACK")},isConnected(){return U}}}function y(z){let H=!1,U=null;return{async connect(){if(H)return;try{let{Client:W}=await import("pg");U=new W({host:z.host||"localhost",port:z.port||5432,database:z.database,user:z.username,password:z.password,ssl:z.ssl}),await U.connect(),H=!0}catch(W){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rows}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(`${W} RETURNING id`,J);if($.logging)B(W,J,performance.now()-X);return Z.rows[0]?.id}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rowCount||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();await U.query("BEGIN")},async commit(){await U.query("COMMIT")},async rollback(){await U.query("ROLLBACK")},isConnected(){return H}}}function f(z){let H=!1,U=null;return{async connect(){if(H)return;try{U=(await import("mysql2/promise")).createPool({host:z.host||"localhost",port:z.port||3306,database:z.database,user:z.username,password:z.password,waitForConnections:!0,connectionLimit:z.poolSize||10,queueLimit:0}),H=!0}catch(W){throw Error(`MySQL connection failed. Install 'mysql2' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.insertId}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.affectedRows||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();let W=await U.getConnection();return await W.beginTransaction(),W},async commit(){await U.execute("COMMIT")},async rollback(){await U.execute("ROLLBACK")},isConnected(){return H}}}class D{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(z){if(z)this._table=z}table(z){return this._table=z,this}from(z){return this.table(z)}connection(z){return this._connection=z,this}select(...z){return this._columns=z.length>0?z:["*"],this}addSelect(...z){if(this._columns[0]==="*")this._columns=z;else this._columns.push(...z);return this}distinct(){return this._distinct=!0,this}where(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"and"}),this}orWhere(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"or"}),this}whereIn(z,H){return this._wheres.push({column:z,operator:"in",value:H,boolean:"and"}),this}whereNotIn(z,H){return this._wheres.push({column:z,operator:"not in",value:H,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(z,H,U){return this._wheres.push({column:z,operator:"between",value:[H,U],boolean:"and"}),this}whereLike(z,H){return this._wheres.push({column:z,operator:"like",value:H,boolean:"and"}),this}join(z,H,U,W){return this._joins.push({type:"inner",table:z,first:H,operator:U,second:W}),this}leftJoin(z,H,U,W){return this._joins.push({type:"left",table:z,first:H,operator:U,second:W}),this}rightJoin(z,H,U,W){return this._joins.push({type:"right",table:z,first:H,operator:U,second:W}),this}orderBy(z,H="asc"){return this._orders.push({column:z,direction:H}),this}orderByDesc(z){return this.orderBy(z,"desc")}groupBy(...z){return this._groupBy.push(...z),this}having(z,H,U){return this._having.push({column:z,operator:H,value:U,boolean:"and"}),this}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}forPage(z,H=15){return this.offset((z-1)*H).limit(H)}async get(){let{sql:z,bindings:H}=this.toSql();if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H),X=g(J);if(X!==void 0)return X}let W=await F(this._connection).query(z,H);if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H);m(J,W,$.cacheTTL)}return W}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let z=await this.first();if(!z)throw Error("No results found");return z}async find(z,H="id"){return this.where(H,z).first()}async value(z){let H=await this.select(z).first();return H?H[z]:null}async pluck(z){return(await this.select(z).get()).map((U)=>U[z])}async exists(){return(await this.select(E("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(z="*"){let H=await this.select(E(`COUNT(${z}) as count`)).first();return Number(H?.count||0)}async max(z){return(await this.select(E(`MAX(${z}) as max`)).first())?.max}async min(z){return(await this.select(E(`MIN(${z}) as min`)).first())?.min}async sum(z){let H=await this.select(E(`SUM(${z}) as sum`)).first();return Number(H?.sum||0)}async avg(z){return(await this.select(E(`AVG(${z}) as avg`)).first())?.avg}async insert(z){let H=Object.keys(z),U=H.map(()=>"?").join(", "),W=Object.values(z),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES (${U})`,X=F(this._connection);return P(this._table),X.insert(J,W)}async insertAll(z){if(z.length===0)return;let H=Object.keys(z[0]),U=z.map(()=>`(${H.map(()=>"?").join(", ")})`).join(", "),W=z.flatMap((Z)=>Object.values(Z)),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES ${U}`,X=F(this._connection);P(this._table),await X.execute(J,W)}async update(z){this._bindings=[];let H=this.buildWhereClause(),U=[...this._bindings],W=Object.keys(z).map((Y)=>`${Y} = ?`).join(", "),J=[...Object.values(z),...U],X=`UPDATE ${this._table} SET ${W}${H}`,Z=F(this._connection);return P(this._table),Z.execute(X,J)}async increment(z,H=1){this._bindings=[];let U=this.buildWhereClause(),W=`UPDATE ${this._table} SET ${z} = ${z} + ?${U}`,J=F(this._connection);return P(this._table),J.execute(W,[H,...this._bindings])}async decrement(z,H=1){return this.increment(z,-H)}async delete(){this._bindings=[];let z=this.buildWhereClause(),H=`DELETE FROM ${this._table}${z}`,U=F(this._connection);return P(this._table),U.execute(H,this._bindings)}async truncate(){let z=F(this._connection);P(this._table),await z.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let z="SELECT ";if(this._distinct)z+="DISTINCT ";z+=this._columns.map((H)=>{if(typeof H==="object"&&H.__raw)return H.sql;return H}).join(", "),z+=` FROM ${this._table}`;for(let H of this._joins)z+=` ${H.type.toUpperCase()} JOIN ${H.table} ON ${H.first} ${H.operator} ${H.second}`;if(z+=this.buildWhereClause(),this._groupBy.length>0)z+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let H=this._having.map((U,W)=>{let J=W===0?"":` ${U.boolean.toUpperCase()} `;return this._bindings.push(U.value),`${J}${U.column} ${U.operator} ?`});z+=` HAVING ${H.join("")}`}if(this._orders.length>0)z+=` ORDER BY ${this._orders.map((H)=>`${H.column} ${H.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)z+=` OFFSET ${this._offset}`;return{sql:z,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((H,U)=>{let W=U===0?" WHERE ":` ${H.boolean.toUpperCase()} `;switch(H.operator){case"in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} IN (${X})`}case"not in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} NOT IN (${X})`}case"between":{let[J,X]=H.value;return this._bindings.push(J,X),`${W}${H.column} BETWEEN ? AND ?`}case"is null":return`${W}${H.column} IS NULL`;case"is not null":return`${W}${H.column} IS NOT NULL`;default:return this._bindings.push(H.value),`${W}${H.column} ${H.operator} ?`}}).join("")}getCacheKey(z,H){return`${this._table}:${z}:${JSON.stringify(H)}`}clone(){let z=new D(this._table);return z._columns=[...this._columns],z._wheres=[...this._wheres],z._orders=[...this._orders],z._joins=[...this._joins],z._groupBy=[...this._groupBy],z._having=[...this._having],z._limit=this._limit,z._offset=this._offset,z._distinct=this._distinct,z._connection=this._connection,z}}function G(z){return new D(z)}function t(z){return G(z)}function E(z,H=[]){return{__raw:!0,sql:z,bindings:H}}function n(z,H){let U=H.primaryKey||"id",W={name:z,definition:H,async find(J){let X=await G(H.table).where(U,J).first();return X?N(W,X):null},async findOrFail(J){let X=await this.find(J);if(!X)throw Error(`${z} not found with ${U} = ${J}`);return X},async all(){return(await G(H.table).get()).map((X)=>N(W,X))},async create(J){let X={...H.defaults,...J},Z=H.fillable?Object.fromEntries(Object.entries(X).filter(([_])=>H.fillable.includes(_))):X;if(H.timestamps!==!1){let _=new Date().toISOString(),R=typeof H.timestamps==="object"?H.timestamps.createdAt||"created_at":"created_at",T=typeof H.timestamps==="object"?H.timestamps.updatedAt||"updated_at":"updated_at";Z[R]=_,Z[T]=_}let Y=await G(H.table).insert(Z);return this.findOrFail(Y)},async update(J){return G(H.table).update(J)},async destroy(J){let X=Array.isArray(J)?J:[J];return G(H.table).whereIn(U,X).delete()},query(){return G(H.table)},where(J,X,Z){return this.query().where(J,X,Z)},async first(){let J=await this.query().first();return J?N(W,J):null},async get(){return(await this.query().get()).map((X)=>N(W,X))},async count(){return this.query().count()}};return A[z]=W,W}function k(z){let H=A[z];if(!H)throw Error(`Model "${z}" not defined. Use defineModel() first.`);return H}function e(z){return z in A}function N(z,H){let{definition:U}=z,W=U.primaryKey||"id",J={...H},X={...H};if(U.casts){for(let[Y,_]of Object.entries(U.casts))if(Y in X)X[Y]=p(X[Y],_)}let Z={exists:!0,original:J,attributes:X,get(Y){return X[Y]},set(Y,_){X[Y]=_},toJSON(){let Y={...X};if(U.hidden)for(let _ of U.hidden)delete Y[_];return Y},async save(){let Y={};for(let _ of Object.keys(X))if(X[_]!==J[_])Y[_]=X[_];if(Object.keys(Y).length>0){if(U.timestamps!==!1){let _=typeof U.timestamps==="object"?U.timestamps.updatedAt||"updated_at":"updated_at";Y[_]=new Date().toISOString()}await G(U.table).where(W,J[W]).update(Y),Object.assign(J,Y)}},async delete(){if(U.softDeletes){let Y=typeof U.softDeletes==="string"?U.softDeletes:"deleted_at";await G(U.table).where(W,J[W]).update({[Y]:new Date().toISOString()})}else await G(U.table).where(W,J[W]).delete();Z.exists=!1},async refresh(){let Y=await G(U.table).where(W,J[W]).first();if(Y)Object.assign(J,Y),Object.assign(X,Y)},isDirty(Y){if(Y)return X[Y]!==J[Y];return Object.keys(X).some((_)=>X[_]!==J[_])}};if(U.relationships)for(let[Y,_]of Object.entries(U.relationships))Object.defineProperty(Z,Y,{value:async()=>{return b(Z,_,z)},enumerable:!1});return new Proxy(Z,{get(Y,_){if(_ in Y)return Y[_];return X[_]},set(Y,_,R){if(_ in Y)Y[_]=R;else X[_]=R;return!0}})}async function b(z,H,U){let W=k(H.model),J=U.definition.primaryKey||"id";switch(H.type){case"hasOne":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`,Z=await G(W.definition.table).where(X,z.get(J)).first();return Z?N(W,Z):null}case"hasMany":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`;return(await G(W.definition.table).where(X,z.get(J)).get()).map((Y)=>N(W,Y))}case"belongsTo":{let X=H.foreignKey||`${H.model.toLowerCase()}_id`,Z=H.localKey||"id",Y=await G(W.definition.table).where(Z,z.get(X)).first();return Y?N(W,Y):null}case"belongsToMany":{let X=H.pivotTable||[U.name,H.model].sort().join("_").toLowerCase(),Z=H.pivotForeignKey||`${U.name.toLowerCase()}_id`,Y=H.pivotRelatedKey||`${H.model.toLowerCase()}_id`,_=W.definition.primaryKey||"id";return(await G(W.definition.table).join(X,`${W.definition.table}.${_}`,"=",`${X}.${Y}`).where(`${X}.${Z}`,z.get(J)).get()).map((T)=>N(W,T))}default:return null}}function p(z,H){if(z===null||z===void 0)return z;switch(H){case"string":return String(z);case"number":return Number(z);case"boolean":return Boolean(z);case"date":return new Date(z);case"json":case"array":return typeof z==="string"?JSON.parse(z):z;default:return z}}async function zz(z,H){let U=F(H);await U.beginTransaction();try{let W=await z();return await U.commit(),W}catch(W){throw await U.rollback(),W}}function g(z){let H=L.get(z);if(!H)return;if(Date.now()-H.timestamp>H.ttl*1000){L.delete(z);return}return H.result}function m(z,H,U){if(L.size>=($.maxCacheSize||1000)){let W=L.keys().next().value;if(W)L.delete(W)}L.set(z,{result:H,timestamp:Date.now(),ttl:U})}function P(z){for(let H of L.keys())if(H.startsWith(`${z}:`))L.delete(H)}function Hz(){L.clear()}function Jz(){return{size:L.size,keys:[...L.keys()]}}function B(z,H,U){if(S.push({sql:z,bindings:H,duration:U,timestamp:new Date}),S.length>1000)S.shift()}function Uz(){return[...S]}function Wz(){S.length=0}function Xz(z=!0){$.logging=z}class O extends Error{sql;bindings;constructor(z,H,U){super(z);this.sql=H;this.bindings=U;this.name="DatabaseError"}}async function u(z,H,U,W){let J=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=await s(R,T),I=`$${R}`;H[I]=j,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- DB Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function d(z,H,U,W){let J=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=k(R),I=await l(j,T),K=`$${R.toLowerCase()}`;H[K]=I,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- Model Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function c(z,H,U,W){let J=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T,j]=Y;try{let I=T?JSON.parse(T):[],v=await F().query(R,I);H[`$${j}`]=v,X=X.replace(_,"")}catch(I){X=X.replace(_,`<!-- Query Error: ${I instanceof Error?I.message:String(I)} -->`)}}return X}async function s(z,H){let U=G(z),W=/->(\w+)\(([^)]*)\)/g,J=[...H.matchAll(W)],X=U;for(let[,Z,Y]of J){let _=M(Y);if(typeof X[Z]==="function"){if(X=X[Z](..._),X instanceof Promise){X=await X;break}}}if(X instanceof D)X=await X.get();return X}async function l(z,H){let U=/->(\w+)\(([^)]*)\)/g,W=[...H.matchAll(U)],J=z;for(let[,X,Z]of W){let Y=M(Z);if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}else if(J instanceof D){if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}}}if(J instanceof D)J=await J.get();return J}function M(z){if(!z.trim())return[];let H=[],U="",W=0,J=!1,X="";for(let Z=0;Z<z.length;Z++){let Y=z[Z];if(!J&&(Y==='"'||Y==="'"))J=!0,X=Y,U+=Y;else if(J&&Y===X)J=!1,U+=Y;else if(!J&&(Y==="["||Y==="{"||Y==="("))W++,U+=Y;else if(!J&&(Y==="]"||Y==="}"||Y===")"))W--,U+=Y;else if(!J&&W===0&&Y===",")H.push(x(U.trim())),U="";else U+=Y}if(U.trim())H.push(x(U.trim()));return H}function x(z){if(z.startsWith('"')&&z.endsWith('"')||z.startsWith("'")&&z.endsWith("'"))return z.slice(1,-1);if(z==="true")return!0;if(z==="false")return!1;if(z==="null")return null;let H=Number(z);if(!Number.isNaN(H))return H;try{return JSON.parse(z)}catch{return z}}async function Yz(z,H,U,W){let J=z;return J=await c(J,H,U,W),J=await d(J,H,U,W),J=await u(J,H,U,W),J}class w{_connection;connection(z){return this._connection=z,this}async create(z,H){let U=new C(z);H(U);let W=U.toCreateSQL();await F(this._connection).execute(W)}async drop(z){await F(this._connection).execute(`DROP TABLE IF EXISTS ${z}`)}async rename(z,H){await F(this._connection).execute(`ALTER TABLE ${z} RENAME TO ${H}`)}async hasTable(z){let H=F(this._connection);try{return await H.query(`SELECT 1 FROM ${z} LIMIT 1`),!0}catch{return!1}}}class C{table;columns=[];indices=[];constructor(z){this.table=z}id(z="id"){return this.columns.push(`${z} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(z,H=255){return this.columns.push(`${z} VARCHAR(${H})`),this}text(z){return this.columns.push(`${z} TEXT`),this}integer(z){return this.columns.push(`${z} INTEGER`),this}boolean(z){return this.columns.push(`${z} BOOLEAN DEFAULT 0`),this}datetime(z){return this.columns.push(`${z} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(z){return this.columns.push(`${z} TEXT`),this}foreignId(z){return this.columns.push(`${z} INTEGER`),this}index(z){let H=Array.isArray(z)?z:[z],U=`idx_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}unique(z){let H=Array.isArray(z)?z:[z],U=`uniq_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
2
+ import{gv as Q}from"./chunk-qc1f74ek.js";var $={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},V={},A={},L=new Map,S=[];function i(z){$={...$,...z}}function o(){return{...$}}function r(){$={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let z of Object.keys(V))delete V[z];L.clear(),S.length=0}function a(z,H){V[z]=H}function F(z){let H=z||$.default;if(V[H])return V[H];let U=$.connections[H];if(!U)throw Error(`Database connection "${H}" not configured`);let W=h(U);return V[H]=W,W}function h(z){switch(z.driver){case"sqlite":return q(z);case"postgres":return y(z);case"mysql":return f(z);default:throw Error(`Unsupported database driver: ${z.driver}`)}}function q(z){let H=null,U=!1;return{async connect(){if(U)return;let{Database:W}=await import("bun:sqlite");H=new W(z.database,{create:!0,readwrite:!0}),U=!0},async disconnect(){if(H)H.close(),H=null,U=!1},async query(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).all(...J);if($.logging)B(W,J,performance.now()-X);return Y}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.lastInsertRowid}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.changes}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!U)await this.connect();H.run("BEGIN TRANSACTION")},async commit(){H.run("COMMIT")},async rollback(){H.run("ROLLBACK")},isConnected(){return U}}}function y(z){let H=!1,U=null;return{async connect(){if(H)return;try{let{Client:W}=await import("pg");U=new W({host:z.host||"localhost",port:z.port||5432,database:z.database,user:z.username,password:z.password,ssl:z.ssl}),await U.connect(),H=!0}catch(W){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rows}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(`${W} RETURNING id`,J);if($.logging)B(W,J,performance.now()-X);return Z.rows[0]?.id}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rowCount||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();await U.query("BEGIN")},async commit(){await U.query("COMMIT")},async rollback(){await U.query("ROLLBACK")},isConnected(){return H}}}function f(z){let H=!1,U=null;return{async connect(){if(H)return;try{U=(await import("mysql2/promise")).createPool({host:z.host||"localhost",port:z.port||3306,database:z.database,user:z.username,password:z.password,waitForConnections:!0,connectionLimit:z.poolSize||10,queueLimit:0}),H=!0}catch(W){throw Error(`MySQL connection failed. Install 'mysql2' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.insertId}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.affectedRows||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();let W=await U.getConnection();return await W.beginTransaction(),W},async commit(){await U.execute("COMMIT")},async rollback(){await U.execute("ROLLBACK")},isConnected(){return H}}}class D{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(z){if(z)this._table=z}table(z){return this._table=z,this}from(z){return this.table(z)}connection(z){return this._connection=z,this}select(...z){return this._columns=z.length>0?z:["*"],this}addSelect(...z){if(this._columns[0]==="*")this._columns=z;else this._columns.push(...z);return this}distinct(){return this._distinct=!0,this}where(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"and"}),this}orWhere(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"or"}),this}whereIn(z,H){return this._wheres.push({column:z,operator:"in",value:H,boolean:"and"}),this}whereNotIn(z,H){return this._wheres.push({column:z,operator:"not in",value:H,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(z,H,U){return this._wheres.push({column:z,operator:"between",value:[H,U],boolean:"and"}),this}whereLike(z,H){return this._wheres.push({column:z,operator:"like",value:H,boolean:"and"}),this}join(z,H,U,W){return this._joins.push({type:"inner",table:z,first:H,operator:U,second:W}),this}leftJoin(z,H,U,W){return this._joins.push({type:"left",table:z,first:H,operator:U,second:W}),this}rightJoin(z,H,U,W){return this._joins.push({type:"right",table:z,first:H,operator:U,second:W}),this}orderBy(z,H="asc"){return this._orders.push({column:z,direction:H}),this}orderByDesc(z){return this.orderBy(z,"desc")}groupBy(...z){return this._groupBy.push(...z),this}having(z,H,U){return this._having.push({column:z,operator:H,value:U,boolean:"and"}),this}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}forPage(z,H=15){return this.offset((z-1)*H).limit(H)}async get(){let{sql:z,bindings:H}=this.toSql();if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H),X=g(J);if(X!==void 0)return X}let W=await F(this._connection).query(z,H);if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H);m(J,W,$.cacheTTL)}return W}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let z=await this.first();if(!z)throw Error("No results found");return z}async find(z,H="id"){return this.where(H,z).first()}async value(z){let H=await this.select(z).first();return H?H[z]:null}async pluck(z){return(await this.select(z).get()).map((U)=>U[z])}async exists(){return(await this.select(E("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(z="*"){let H=await this.select(E(`COUNT(${z}) as count`)).first();return Number(H?.count||0)}async max(z){return(await this.select(E(`MAX(${z}) as max`)).first())?.max}async min(z){return(await this.select(E(`MIN(${z}) as min`)).first())?.min}async sum(z){let H=await this.select(E(`SUM(${z}) as sum`)).first();return Number(H?.sum||0)}async avg(z){return(await this.select(E(`AVG(${z}) as avg`)).first())?.avg}async insert(z){let H=Object.keys(z),U=H.map(()=>"?").join(", "),W=Object.values(z),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES (${U})`,X=F(this._connection);return P(this._table),X.insert(J,W)}async insertAll(z){if(z.length===0)return;let H=Object.keys(z[0]),U=z.map(()=>`(${H.map(()=>"?").join(", ")})`).join(", "),W=z.flatMap((Z)=>Object.values(Z)),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES ${U}`,X=F(this._connection);P(this._table),await X.execute(J,W)}async update(z){this._bindings=[];let H=this.buildWhereClause(),U=[...this._bindings],W=Object.keys(z).map((Y)=>`${Y} = ?`).join(", "),J=[...Object.values(z),...U],X=`UPDATE ${this._table} SET ${W}${H}`,Z=F(this._connection);return P(this._table),Z.execute(X,J)}async increment(z,H=1){this._bindings=[];let U=this.buildWhereClause(),W=`UPDATE ${this._table} SET ${z} = ${z} + ?${U}`,J=F(this._connection);return P(this._table),J.execute(W,[H,...this._bindings])}async decrement(z,H=1){return this.increment(z,-H)}async delete(){this._bindings=[];let z=this.buildWhereClause(),H=`DELETE FROM ${this._table}${z}`,U=F(this._connection);return P(this._table),U.execute(H,this._bindings)}async truncate(){let z=F(this._connection);P(this._table),await z.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let z="SELECT ";if(this._distinct)z+="DISTINCT ";z+=this._columns.map((H)=>{if(typeof H==="object"&&H.__raw)return H.sql;return H}).join(", "),z+=` FROM ${this._table}`;for(let H of this._joins)z+=` ${H.type.toUpperCase()} JOIN ${H.table} ON ${H.first} ${H.operator} ${H.second}`;if(z+=this.buildWhereClause(),this._groupBy.length>0)z+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let H=this._having.map((U,W)=>{let J=W===0?"":` ${U.boolean.toUpperCase()} `;return this._bindings.push(U.value),`${J}${U.column} ${U.operator} ?`});z+=` HAVING ${H.join("")}`}if(this._orders.length>0)z+=` ORDER BY ${this._orders.map((H)=>`${H.column} ${H.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)z+=` OFFSET ${this._offset}`;return{sql:z,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((H,U)=>{let W=U===0?" WHERE ":` ${H.boolean.toUpperCase()} `;switch(H.operator){case"in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} IN (${X})`}case"not in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} NOT IN (${X})`}case"between":{let[J,X]=H.value;return this._bindings.push(J,X),`${W}${H.column} BETWEEN ? AND ?`}case"is null":return`${W}${H.column} IS NULL`;case"is not null":return`${W}${H.column} IS NOT NULL`;default:return this._bindings.push(H.value),`${W}${H.column} ${H.operator} ?`}}).join("")}getCacheKey(z,H){return`${this._table}:${z}:${JSON.stringify(H)}`}clone(){let z=new D(this._table);return z._columns=[...this._columns],z._wheres=[...this._wheres],z._orders=[...this._orders],z._joins=[...this._joins],z._groupBy=[...this._groupBy],z._having=[...this._having],z._limit=this._limit,z._offset=this._offset,z._distinct=this._distinct,z._connection=this._connection,z}}function G(z){return new D(z)}function t(z){return G(z)}function E(z,H=[]){return{__raw:!0,sql:z,bindings:H}}function n(z,H){let U=H.primaryKey||"id",W={name:z,definition:H,async find(J){let X=await G(H.table).where(U,J).first();return X?N(W,X):null},async findOrFail(J){let X=await this.find(J);if(!X)throw Error(`${z} not found with ${U} = ${J}`);return X},async all(){return(await G(H.table).get()).map((X)=>N(W,X))},async create(J){let X={...H.defaults,...J},Z=H.fillable?Object.fromEntries(Object.entries(X).filter(([_])=>H.fillable.includes(_))):X;if(H.timestamps!==!1){let _=new Date().toISOString(),R=typeof H.timestamps==="object"?H.timestamps.createdAt||"created_at":"created_at",T=typeof H.timestamps==="object"?H.timestamps.updatedAt||"updated_at":"updated_at";Z[R]=_,Z[T]=_}let Y=await G(H.table).insert(Z);return this.findOrFail(Y)},async update(J){return G(H.table).update(J)},async destroy(J){let X=Array.isArray(J)?J:[J];return G(H.table).whereIn(U,X).delete()},query(){return G(H.table)},where(J,X,Z){return this.query().where(J,X,Z)},async first(){let J=await this.query().first();return J?N(W,J):null},async get(){return(await this.query().get()).map((X)=>N(W,X))},async count(){return this.query().count()}};return A[z]=W,W}function k(z){let H=A[z];if(!H)throw Error(`Model "${z}" not defined. Use defineModel() first.`);return H}function e(z){return z in A}function N(z,H){let{definition:U}=z,W=U.primaryKey||"id",J={...H},X={...H};if(U.casts){for(let[Y,_]of Object.entries(U.casts))if(Y in X)X[Y]=p(X[Y],_)}let Z={exists:!0,original:J,attributes:X,get(Y){return X[Y]},set(Y,_){X[Y]=_},toJSON(){let Y={...X};if(U.hidden)for(let _ of U.hidden)delete Y[_];return Y},async save(){let Y={};for(let _ of Object.keys(X))if(X[_]!==J[_])Y[_]=X[_];if(Object.keys(Y).length>0){if(U.timestamps!==!1){let _=typeof U.timestamps==="object"?U.timestamps.updatedAt||"updated_at":"updated_at";Y[_]=new Date().toISOString()}await G(U.table).where(W,J[W]).update(Y),Object.assign(J,Y)}},async delete(){if(U.softDeletes){let Y=typeof U.softDeletes==="string"?U.softDeletes:"deleted_at";await G(U.table).where(W,J[W]).update({[Y]:new Date().toISOString()})}else await G(U.table).where(W,J[W]).delete();Z.exists=!1},async refresh(){let Y=await G(U.table).where(W,J[W]).first();if(Y)Object.assign(J,Y),Object.assign(X,Y)},isDirty(Y){if(Y)return X[Y]!==J[Y];return Object.keys(X).some((_)=>X[_]!==J[_])}};if(U.relationships)for(let[Y,_]of Object.entries(U.relationships))Object.defineProperty(Z,Y,{value:async()=>{return b(Z,_,z)},enumerable:!1});return new Proxy(Z,{get(Y,_){if(_ in Y)return Y[_];return X[_]},set(Y,_,R){if(_ in Y)Y[_]=R;else X[_]=R;return!0}})}async function b(z,H,U){let W=k(H.model),J=U.definition.primaryKey||"id";switch(H.type){case"hasOne":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`,Z=await G(W.definition.table).where(X,z.get(J)).first();return Z?N(W,Z):null}case"hasMany":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`;return(await G(W.definition.table).where(X,z.get(J)).get()).map((Y)=>N(W,Y))}case"belongsTo":{let X=H.foreignKey||`${H.model.toLowerCase()}_id`,Z=H.localKey||"id",Y=await G(W.definition.table).where(Z,z.get(X)).first();return Y?N(W,Y):null}case"belongsToMany":{let X=H.pivotTable||[U.name,H.model].sort().join("_").toLowerCase(),Z=H.pivotForeignKey||`${U.name.toLowerCase()}_id`,Y=H.pivotRelatedKey||`${H.model.toLowerCase()}_id`,_=W.definition.primaryKey||"id";return(await G(W.definition.table).join(X,`${W.definition.table}.${_}`,"=",`${X}.${Y}`).where(`${X}.${Z}`,z.get(J)).get()).map((T)=>N(W,T))}default:return null}}function p(z,H){if(z===null||z===void 0)return z;switch(H){case"string":return String(z);case"number":return Number(z);case"boolean":return Boolean(z);case"date":return new Date(z);case"json":case"array":return typeof z==="string"?JSON.parse(z):z;default:return z}}async function zz(z,H){let U=F(H);await U.beginTransaction();try{let W=await z();return await U.commit(),W}catch(W){throw await U.rollback(),W}}function g(z){let H=L.get(z);if(!H)return;if(Date.now()-H.timestamp>H.ttl*1000){L.delete(z);return}return H.result}function m(z,H,U){if(L.size>=($.maxCacheSize||1000)){let W=L.keys().next().value;if(W)L.delete(W)}L.set(z,{result:H,timestamp:Date.now(),ttl:U})}function P(z){for(let H of L.keys())if(H.startsWith(`${z}:`))L.delete(H)}function Hz(){L.clear()}function Jz(){return{size:L.size,keys:[...L.keys()]}}function B(z,H,U){if(S.push({sql:z,bindings:H,duration:U,timestamp:new Date}),S.length>1000)S.shift()}function Uz(){return[...S]}function Wz(){S.length=0}function Xz(z=!0){$.logging=z}class O extends Error{sql;bindings;constructor(z,H,U){super(z);this.sql=H;this.bindings=U;this.name="DatabaseError"}}async function u(z,H,U,W){let J=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=await s(R,T),I=`$${R}`;H[I]=j,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- DB Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function d(z,H,U,W){let J=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=k(R),I=await l(j,T),K=`$${R.toLowerCase()}`;H[K]=I,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- Model Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function c(z,H,U,W){let J=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T,j]=Y;try{let I=T?JSON.parse(T):[],v=await F().query(R,I);H[`$${j}`]=v,X=X.replace(_,"")}catch(I){X=X.replace(_,`<!-- Query Error: ${I instanceof Error?I.message:String(I)} -->`)}}return X}async function s(z,H){let U=G(z),W=/->(\w+)\(([^)]*)\)/g,J=[...H.matchAll(W)],X=U;for(let[,Z,Y]of J){let _=M(Y);if(typeof X[Z]==="function"){if(X=X[Z](..._),X instanceof Promise){X=await X;break}}}if(X instanceof D)X=await X.get();return X}async function l(z,H){let U=/->(\w+)\(([^)]*)\)/g,W=[...H.matchAll(U)],J=z;for(let[,X,Z]of W){let Y=M(Z);if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}else if(J instanceof D){if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}}}if(J instanceof D)J=await J.get();return J}function M(z){if(!z.trim())return[];let H=[],U="",W=0,J=!1,X="";for(let Z=0;Z<z.length;Z++){let Y=z[Z];if(!J&&(Y==='"'||Y==="'"))J=!0,X=Y,U+=Y;else if(J&&Y===X)J=!1,U+=Y;else if(!J&&(Y==="["||Y==="{"||Y==="("))W++,U+=Y;else if(!J&&(Y==="]"||Y==="}"||Y===")"))W--,U+=Y;else if(!J&&W===0&&Y===",")H.push(x(U.trim())),U="";else U+=Y}if(U.trim())H.push(x(U.trim()));return H}function x(z){if(z.startsWith('"')&&z.endsWith('"')||z.startsWith("'")&&z.endsWith("'"))return z.slice(1,-1);if(z==="true")return!0;if(z==="false")return!1;if(z==="null")return null;let H=Number(z);if(!Number.isNaN(H))return H;try{return JSON.parse(z)}catch{return z}}async function Yz(z,H,U,W){let J=z;return J=await c(J,H,U,W),J=await d(J,H,U,W),J=await u(J,H,U,W),J}class w{_connection;connection(z){return this._connection=z,this}async create(z,H){let U=new C(z);H(U);let W=U.toCreateSQL();await F(this._connection).execute(W)}async drop(z){await F(this._connection).execute(`DROP TABLE IF EXISTS ${z}`)}async rename(z,H){await F(this._connection).execute(`ALTER TABLE ${z} RENAME TO ${H}`)}async hasTable(z){let H=F(this._connection);try{return await H.query(`SELECT 1 FROM ${z} LIMIT 1`),!0}catch{return!1}}}class C{table;columns=[];indices=[];constructor(z){this.table=z}id(z="id"){return this.columns.push(`${z} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(z,H=255){return this.columns.push(`${z} VARCHAR(${H})`),this}text(z){return this.columns.push(`${z} TEXT`),this}integer(z){return this.columns.push(`${z} INTEGER`),this}boolean(z){return this.columns.push(`${z} BOOLEAN DEFAULT 0`),this}datetime(z){return this.columns.push(`${z} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(z){return this.columns.push(`${z} TEXT`),this}foreignId(z){return this.columns.push(`${z} INTEGER`),this}index(z){let H=Array.isArray(z)?z:[z],U=`idx_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}unique(z){let H=Array.isArray(z)?z:[z],U=`uniq_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
3
3
  ${this.columns.join(`,
4
4
  `)}
5
5
  )`}getIndexSQL(){return this.indices}}function Zz(){return new w}export{zz as transaction,t as table,Zz as schema,r as resetDatabaseConfig,a as registerAdapter,E as raw,G as query,c as processQueryDirective,d as processModelDirective,u as processDbDirective,Yz as processDatabaseDirectives,e as hasModel,Uz as getQueryLog,Jz as getQueryCacheStats,k as getModel,o as getDatabaseConfig,F as getAdapter,Xz as enableQueryLogging,n as defineModel,i as configureDatabase,Wz as clearQueryLog,Hz as clearQueryCache,w as SchemaBuilder,D as QueryBuilder,O as DatabaseError,C as Blueprint};
@@ -169,39 +169,6 @@ export declare function generateDocumentShell(content: string, headConfig?: AppH
169
169
  */
170
170
  colorMode?: ColorModeBootConfig;
171
171
  }): string;
172
- /**
173
- * Check if HTML already has a document shell (<!DOCTYPE> or <html>).
174
- * Templates that extend layouts with document shells should not be
175
- * double-wrapped — the visible artifact of a double-wrap is the user's
176
- * `<title>` getting nested under the auto-shell's default `stx App`,
177
- * which then wins for `document.title` because it appears first.
178
- *
179
- * The check is permissive on placement: if the rendered output contains
180
- * a `<!DOCTYPE>` or `<html>` ANYWHERE, the user has supplied a shell.
181
- * Earlier this only checked the leading bytes after stripping comments,
182
- * but other directives (signals runtime, scoped scripts, theme guards)
183
- * happily prepend their own `<script>` tags before any layout markup,
184
- * which made the check spuriously fail and auto-shell wrap the user's
185
- * complete HTML doc as if it were just body content.
186
- */
187
- /**
188
- * Does this string OPEN a full HTML document?
189
- *
190
- * Anchored, but tolerant of what stx's own pipeline prepends: whitespace, HTML
191
- * comments, and `<script>` blocks (the signals runtime, scoped setup scripts,
192
- * theme guards) all routinely land ahead of a layout's markup.
193
- *
194
- * The check used to be `/<!DOCTYPE\b/i` — unanchored — so the literal text
195
- * `<!DOCTYPE` ANYWHERE made a fragment look like a document and sent it through
196
- * wrapper-stripping. Easy to hit on any page that documents HTML: a doctype in
197
- * a comment, in a `<pre><code>` sample, or in a JS string (stacksjs#1787). The
198
- * `<html>` half was already anchored, so the asymmetry was clearly accidental.
199
- *
200
- * Note this is the opposite bias from `hasDocumentShell` in document-shell.ts,
201
- * which stays permissive on purpose: there, a false negative double-wraps a
202
- * complete document, so leaning towards "yes, it's a document" is the safe
203
- * direction. Here a false positive shreds a fragment, so it leans the other way.
204
- */
205
172
  export declare function startsDocument(html: string): boolean;
206
173
  /**
207
174
  * Does this output already carry a document wrapper?
@@ -248,4 +215,4 @@ export declare function injectConfigHeadTags(html: string, headConfig?: AppHeadC
248
215
  * head here — the caller injects config-only head via `injectConfigHeadTags`,
249
216
  * so runtime `useHead` tags aren't double-emitted).
250
217
  */
251
- export declare function ensureDocumentShell(html: string, headConfig?: AppHeadConfig, options?: Parameters<typeof generateDocumentShell>[2]): string;
218
+ export declare function ensureDocumentShell(html: string, headConfig?: AppHeadConfig, options?: Parameters<typeof generateDocumentShell>[2], alreadyHasShell?: boolean): string;
@@ -259,30 +259,38 @@ ${bodyParts.join(`
259
259
  </body>
260
260
  </html>`;
261
261
  }
262
+ const DOCUMENT_PREFIX_WHITESPACE = /\s+/y, DOCUMENT_PREFIX_PREAMBLE = /<(script|style)\b[^>]*>/iy, DOCUMENT_PREFIX_SCRIPT_CLOSE = /<\/script>/gi, DOCUMENT_PREFIX_STYLE_CLOSE = /<\/style>/gi, DOCUMENT_PREFIX_DOCTYPE = /<!DOCTYPE\b/iy, DOCUMENT_PREFIX_HTML = /<html[\s>]/iy;
262
263
  export function startsDocument(html) {
263
264
  let i = 0;
264
265
  while (i < html.length) {
265
- const rest = html.slice(i), ws = rest.match(/^\s+/);
266
- if (ws) {
267
- i += ws[0].length;
266
+ DOCUMENT_PREFIX_WHITESPACE.lastIndex = i;
267
+ if (DOCUMENT_PREFIX_WHITESPACE.exec(html)) {
268
+ i = DOCUMENT_PREFIX_WHITESPACE.lastIndex;
268
269
  continue;
269
270
  }
270
- if (rest.startsWith("<!--")) {
271
+ if (html.startsWith("<!--", i)) {
271
272
  const end = html.indexOf("-->", i);
272
273
  if (end === -1)
273
274
  return !1;
274
275
  i = end + 3;
275
276
  continue;
276
277
  }
277
- const preamble = rest.match(/^<(script|style)\b[^>]*>/i);
278
+ DOCUMENT_PREFIX_PREAMBLE.lastIndex = i;
279
+ const preamble = DOCUMENT_PREFIX_PREAMBLE.exec(html);
278
280
  if (preamble) {
279
- const closeTag = `</${preamble[1].toLowerCase()}>`, end = html.toLowerCase().indexOf(closeTag, i + preamble[0].length);
280
- if (end === -1)
281
+ const close = preamble[1].toLowerCase() === "script" ? DOCUMENT_PREFIX_SCRIPT_CLOSE : DOCUMENT_PREFIX_STYLE_CLOSE;
282
+ close.lastIndex = DOCUMENT_PREFIX_PREAMBLE.lastIndex;
283
+ const end = close.exec(html);
284
+ if (end === null)
281
285
  return !1;
282
- i = end + closeTag.length;
286
+ i = end.index + end[0].length;
283
287
  continue;
284
288
  }
285
- return /^<!DOCTYPE\b/i.test(rest) || /^<html[\s>]/i.test(rest);
289
+ DOCUMENT_PREFIX_DOCTYPE.lastIndex = i;
290
+ if (DOCUMENT_PREFIX_DOCTYPE.test(html))
291
+ return !0;
292
+ DOCUMENT_PREFIX_HTML.lastIndex = i;
293
+ return DOCUMENT_PREFIX_HTML.test(html);
286
294
  }
287
295
  return !1;
288
296
  }
@@ -323,8 +331,8 @@ export function injectConfigHeadTags(html, headConfig = {}) {
323
331
  `)}
324
332
  ${html.slice(headCloseIdx)}`;
325
333
  }
326
- export function ensureDocumentShell(html, headConfig = {}, options = {}) {
327
- if (hasDocumentShell(html))
334
+ export function ensureDocumentShell(html, headConfig = {}, options = {}, alreadyHasShell) {
335
+ if (alreadyHasShell ?? hasDocumentShell(html))
328
336
  return html;
329
337
  return generateDocumentShell(html, headConfig, options);
330
338
  }
@@ -43,6 +43,36 @@ export declare function matchHtmlComment(html: string, i: number): number;
43
43
  * callers never see tag-like text nested inside those regions.
44
44
  */
45
45
  export declare function scanAtElementPosition(html: string, match: TokenMatcher): ElementPositionToken[];
46
+ /**
47
+ * Cheap, conservative preflight for the unresolved-expression cloak pass.
48
+ *
49
+ * A mustache in an element's own text needs at least two opening and two
50
+ * closing braces outside tags, comments, and script/style raw text. They may
51
+ * be separated by child elements, so looking only for contiguous `{{` is NOT
52
+ * sufficient. False positives merely run the normal cloak scan; false
53
+ * negatives would leave an unresolved expression visible.
54
+ */
55
+ export declare function mightContainOwnTextMustache(html: string): boolean;
56
+ /**
57
+ * Drop the oldest entries until there is room for one more.
58
+ *
59
+ * Wholesale `clear()` was the first version and it made the caches useless: a
60
+ * render cycles through more distinct documents than the cap, so hitting the cap
61
+ * wiped the entry that was about to be reused. Measured on the #1945 fixture, one
62
+ * key-and-content pair missed 24 times in a row — computed every time, hit never.
63
+ * A Map iterates in insertion order, so the first key is the oldest.
64
+ */
65
+ export declare function evictOldest(cache: Map<string, unknown>, maxEntries: number): void;
66
+ /**
67
+ * Drop cached mask results.
68
+ *
69
+ * Nothing in the framework calls this, and nothing needs to. Entries are keyed
70
+ * on the input document itself plus the caller's placeholder key, so an edited
71
+ * template is a different key and can never be answered with a stale result --
72
+ * there is no invalidation to perform. It exists for callers that want a cold
73
+ * cache, such as tests.
74
+ */
75
+ export declare function clearMaskCache(): void;
46
76
  /**
47
77
  * Mask every token (per `match`) that begins at element position, replacing it
48
78
  * with `placeholder(token, index)`. Returns the rewritten string plus the ordered
@@ -51,19 +81,45 @@ export declare function scanAtElementPosition(html: string, match: TokenMatcher)
51
81
  * Note: HTML attributes do not use backslash escaping, so a `"`/`'` always
52
82
  * toggles the surrounding quote — matching how browsers parse attribute values.
53
83
  */
54
- export declare function maskAtElementPosition(html: string, match: TokenMatcher, placeholder: (token: string, index: number) => string): {
84
+ export declare function maskAtElementPosition(html: string, match: TokenMatcher, placeholder: (token: string, index: number) => string,
85
+ /**
86
+ * Opt in to memoisation. Must fully determine what `placeholder` returns for
87
+ * a given index — two calls sharing a key MUST be interchangeable.
88
+ */
89
+ cacheKey?: string): {
55
90
  output: string;
56
91
  tokens: string[];
57
92
  };
58
- /**
59
- * Stash genuine `<script>…</script>` ELEMENTS behind NUL-byte sentinels so a
60
- * component scanner doesn't mis-resolve tag-like JS string literals (e.g.
61
- * `div.innerHTML = '<v:shape>'`) as component references (stacksjs/stx#1730), and
62
- * so an attribute-embedded `<script>` is never pulled out and restored unescaped.
63
- */
64
- export declare function stashScriptElements(html: string): {
93
+ export interface StashedScripts {
94
+ /** The document with each `<script>` element replaced by a NUL sentinel. */
65
95
  output: string;
96
+ /** The removed script elements, in placeholder order. */
66
97
  scripts: string[];
67
- };
98
+ /**
99
+ * Put the scripts back.
100
+ *
101
+ * Returns the pre-stash document unchanged when `html` is still the masked
102
+ * output. Stashing replaces each script with a sentinel and restoring puts
103
+ * exactly those scripts back at exactly those sentinels, so when nothing
104
+ * edited the masked document in between, the replace pass can only rebuild,
105
+ * character by character, a string the caller already handed us.
106
+ *
107
+ * That is the common case, not a corner: one render of the #1945 fixture
108
+ * reaches this having changed nothing in FOUR of five passes, rebuilding
109
+ * 445,208 bytes to arrive back where it started. The component loop stashes
110
+ * on every pass but only the first pass resolves anything.
111
+ */
112
+ restore: (html: string) => string;
113
+ }
114
+ export declare function stashScriptElements(html: string): StashedScripts;
115
+ /**
116
+ * Drop cached stash results.
117
+ *
118
+ * Nothing in the framework calls this, and nothing needs to. Entries are keyed
119
+ * on the input document itself, so an edited template is a different key and
120
+ * can never be answered with a stale result -- there is no invalidation to
121
+ * perform. It exists for callers that want a cold cache, such as tests.
122
+ */
123
+ export declare function clearStashCache(): void;
68
124
  /** Restore scripts stashed by {@link stashScriptElements}. */
69
125
  export declare function restoreStashedScripts(html: string, scripts: string[]): string;
@@ -29,17 +29,17 @@ function matchOpaqueRegion(html, i) {
29
29
  const end = matchHtmlComment(html, i);
30
30
  return end === -1 ? html.length : end;
31
31
  }
32
- for (const [open, close] of [
33
- [SCRIPT_OPEN, SCRIPT_CLOSE],
34
- [STYLE_OPEN, STYLE_CLOSE]
35
- ]) {
36
- open.lastIndex = i;
37
- const opening = open.exec(html);
38
- if (!opening || opening.index !== i)
39
- continue;
40
- close.lastIndex = open.lastIndex;
41
- const closing = close.exec(html);
42
- return closing ? closing.index + closing[0].length : html.length;
32
+ SCRIPT_OPEN.lastIndex = i;
33
+ if (SCRIPT_OPEN.exec(html)?.index === i) {
34
+ SCRIPT_CLOSE.lastIndex = SCRIPT_OPEN.lastIndex;
35
+ const close = SCRIPT_CLOSE.exec(html);
36
+ return close ? close.index + close[0].length : html.length;
37
+ }
38
+ STYLE_OPEN.lastIndex = i;
39
+ if (STYLE_OPEN.exec(html)?.index === i) {
40
+ STYLE_CLOSE.lastIndex = STYLE_OPEN.lastIndex;
41
+ const close = STYLE_CLOSE.exec(html);
42
+ return close ? close.index + close[0].length : html.length;
43
43
  }
44
44
  return -1;
45
45
  }
@@ -62,7 +62,10 @@ export function scanAtElementPosition(html, match) {
62
62
  continue;
63
63
  }
64
64
  if (ch !== "<") {
65
- i++;
65
+ const next = html.indexOf("<", i + 1);
66
+ if (next === -1)
67
+ break;
68
+ i = next;
66
69
  continue;
67
70
  }
68
71
  const end = match(html, i);
@@ -76,13 +79,71 @@ export function scanAtElementPosition(html, match) {
76
79
  i = opaqueEnd;
77
80
  continue;
78
81
  }
79
- if (/^<\/?[a-zA-Z]/.test(html.slice(i, i + 2)))
82
+ const letter = html.charCodeAt(i + 1);
83
+ if (letter >= 65 && letter <= 90 || letter >= 97 && letter <= 122)
80
84
  inTag = !0;
81
85
  i++;
82
86
  }
83
87
  return tokens;
84
88
  }
85
- export function maskAtElementPosition(html, match, placeholder) {
89
+ export function mightContainOwnTextMustache(html) {
90
+ let opening = 0, closing = 0, i = 0, inTag = !1, quote = null;
91
+ while (i < html.length) {
92
+ if (inTag) {
93
+ const ch = html[i];
94
+ if (quote) {
95
+ if (ch === quote)
96
+ quote = null;
97
+ } else if (ch === '"' || ch === "'")
98
+ quote = ch;
99
+ else if (ch === ">")
100
+ inTag = !1;
101
+ i++;
102
+ continue;
103
+ }
104
+ const lt = html.indexOf("<", i), textEnd = lt === -1 ? html.length : lt;
105
+ while (i < textEnd) {
106
+ const ch = html[i++];
107
+ if (ch === "{")
108
+ opening++;
109
+ else if (ch === "}")
110
+ closing++;
111
+ if (opening >= 2 && closing >= 2)
112
+ return !0;
113
+ }
114
+ if (lt === -1)
115
+ break;
116
+ const opaqueEnd = matchOpaqueRegion(html, lt);
117
+ if (opaqueEnd > lt) {
118
+ i = opaqueEnd;
119
+ continue;
120
+ }
121
+ const first = html.charCodeAt(lt + 1), letter = first === 47 ? html.charCodeAt(lt + 2) : first;
122
+ if (letter >= 65 && letter <= 90 || letter >= 97 && letter <= 122)
123
+ inTag = !0;
124
+ i = lt + 1;
125
+ }
126
+ return !1;
127
+ }
128
+ export function evictOldest(cache, maxEntries) {
129
+ while (cache.size >= maxEntries) {
130
+ const oldest = cache.keys().next();
131
+ if (oldest.done)
132
+ return;
133
+ cache.delete(oldest.value);
134
+ }
135
+ }
136
+ const MASK_CACHE_MIN_BYTES = 65536, MASK_CACHE_MAX_ENTRIES = 12, maskCache = new Map;
137
+ export function clearMaskCache() {
138
+ maskCache.clear();
139
+ }
140
+ export function maskAtElementPosition(html, match, placeholder, cacheKey) {
141
+ const cacheable = cacheKey !== void 0 && html.length >= MASK_CACHE_MIN_BYTES, key = cacheable ? `${cacheKey}\x00${html}` : "";
142
+ if (cacheable) {
143
+ const hit = maskCache.get(key);
144
+ if (hit)
145
+ return { output: hit.output, tokens: hit.tokens.slice() };
146
+ }
86
147
  const matches = scanAtElementPosition(html, match);
87
148
  if (matches.length === 0)
88
149
  return { output: html, tokens: [] };
@@ -95,11 +156,38 @@ export function maskAtElementPosition(html, match, placeholder) {
95
156
  cursor = item.end;
96
157
  }
97
158
  output += html.slice(cursor);
159
+ if (cacheable) {
160
+ evictOldest(maskCache, MASK_CACHE_MAX_ENTRIES);
161
+ maskCache.set(key, { output, tokens });
162
+ return { output, tokens: tokens.slice() };
163
+ }
98
164
  return { output, tokens };
99
165
  }
166
+ const STASH_CACHE_MIN_BYTES = 65536, STASH_CACHE_MAX_ENTRIES = 4, stashCache = new Map;
167
+ function stashResult(input, output, scripts) {
168
+ return {
169
+ output,
170
+ scripts,
171
+ restore: (html) => html === output ? input : restoreStashedScripts(html, scripts)
172
+ };
173
+ }
100
174
  export function stashScriptElements(html) {
175
+ const cacheable = html.length >= STASH_CACHE_MIN_BYTES;
176
+ if (cacheable) {
177
+ const hit = stashCache.get(html);
178
+ if (hit)
179
+ return stashResult(html, hit.output, hit.scripts.slice());
180
+ }
101
181
  const { output, tokens } = maskAtElementPosition(html, matchScriptElement, (_token, index) => `\x00STX_SCRIPT_${index}\x00`);
102
- return { output, scripts: tokens };
182
+ if (cacheable) {
183
+ evictOldest(stashCache, STASH_CACHE_MAX_ENTRIES);
184
+ stashCache.set(html, { output, scripts: tokens });
185
+ return stashResult(html, output, tokens.slice());
186
+ }
187
+ return stashResult(html, output, tokens);
188
+ }
189
+ export function clearStashCache() {
190
+ stashCache.clear();
103
191
  }
104
192
  export function restoreStashedScripts(html, scripts) {
105
193
  if (scripts.length === 0)
@@ -48,7 +48,7 @@ export declare function processRefAttributes(template: string): string;
48
48
  * so the raw mustache never flashes.
49
49
  *
50
50
  * Only the element that actually holds the expression is stamped — see
51
- * `ownText` for why that scoping is the fix rather than a refinement. An
51
+ * `ownTextContainsMustache` for why that scoping is the fix rather than a refinement. An
52
52
  * element carrying `x-no-cloak` is left visible regardless.
53
53
  */
54
54
  export declare function addCloakToUnresolvedExpressions(html: string): string;