@stacksjs/stx 0.2.319 → 0.2.321

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 (168) hide show
  1. package/dist/builtins/image-alpha.d.ts +26 -0
  2. package/dist/builtins/image-alpha.js +57 -0
  3. package/dist/builtins/image-delivery.d.ts +9 -0
  4. package/dist/builtins/image-delivery.js +77 -11
  5. package/dist/builtins/image-placeholder.d.ts +5 -0
  6. package/dist/builtins/image-placeholder.js +19 -3
  7. package/dist/builtins/stx-image.js +19 -6
  8. package/dist/{chunk-85p4dmft.js → chunk-0en7mkpa.js} +1 -1
  9. package/dist/{chunk-0mnv8pf5.js → chunk-0eydszkp.js} +1 -1
  10. package/dist/chunk-129fa2d9.js +2 -0
  11. package/dist/{chunk-acctstj3.js → chunk-1b2wksq3.js} +1 -1
  12. package/dist/{chunk-wm86mmgq.js → chunk-1q1qmmfn.js} +1 -1
  13. package/dist/{chunk-4ee1aaet.js → chunk-1r3ydhkx.js} +1 -1
  14. package/dist/chunk-1rdcew9t.js +2 -0
  15. package/dist/{chunk-ajhrz96a.js → chunk-1yv1v7hh.js} +1 -1
  16. package/dist/{chunk-tqayztkh.js → chunk-222swfwr.js} +1 -1
  17. package/dist/chunk-25m79xdw.js +2 -0
  18. package/dist/{chunk-2kv2gnzc.js → chunk-2925bmqr.js} +1 -1
  19. package/dist/{chunk-raxr83fs.js → chunk-2btrq8sz.js} +2 -2
  20. package/dist/chunk-2rkq7pd1.js +2 -0
  21. package/dist/chunk-2tcn2rw4.js +2 -0
  22. package/dist/{chunk-prry9kgy.js → chunk-33gkb5pr.js} +1 -1
  23. package/dist/{chunk-vhan24as.js → chunk-373fc0m2.js} +1 -1
  24. package/dist/{chunk-6c1ebjat.js → chunk-3erkb524.js} +1 -1
  25. package/dist/{chunk-ybct46zd.js → chunk-3ntb5zkk.js} +1 -1
  26. package/dist/{chunk-r3220h2n.js → chunk-3qt3cxh0.js} +1 -1
  27. package/dist/{chunk-b73h0vd8.js → chunk-3x0b8j25.js} +1 -1
  28. package/dist/chunk-48w09pf7.js +2 -0
  29. package/dist/chunk-4a2wcz8h.js +2 -0
  30. package/dist/chunk-4dtjqc90.js +2 -0
  31. package/dist/{chunk-djf1p5cy.js → chunk-4kp87md5.js} +1 -1
  32. package/dist/{chunk-3pv0qj5f.js → chunk-4zz9edh0.js} +1 -1
  33. package/dist/{chunk-51gea48g.js → chunk-526rr83q.js} +1 -1
  34. package/dist/{chunk-18p8dqya.js → chunk-5mdvkpt8.js} +1 -1
  35. package/dist/chunk-5sz2tmw3.js +2 -0
  36. package/dist/{chunk-322qz0cj.js → chunk-6r72pp2t.js} +1 -1
  37. package/dist/{chunk-397rqs12.js → chunk-70zb3560.js} +1 -1
  38. package/dist/{chunk-yzy6e4je.js → chunk-7b09hmk4.js} +10 -10
  39. package/dist/chunk-7je3fd68.js +2 -0
  40. package/dist/chunk-7kk2jb1j.js +3759 -0
  41. package/dist/chunk-7v72zj7x.js +2 -0
  42. package/dist/{chunk-0saq3nwy.js → chunk-8mspafdh.js} +1 -1
  43. package/dist/{chunk-bnq0p4r4.js → chunk-8q3a8g7m.js} +1 -1
  44. package/dist/{chunk-zebypbks.js → chunk-8q9qfy2v.js} +2 -2
  45. package/dist/chunk-8x78ed8t.js +2 -0
  46. package/dist/chunk-99yynes4.js +2 -0
  47. package/dist/{chunk-pknc4efv.js → chunk-9fjhmyje.js} +1 -1
  48. package/dist/{chunk-1ztjv7a4.js → chunk-9qxv7emz.js} +1 -1
  49. package/dist/{chunk-px0hqf1q.js → chunk-9whbqxsv.js} +1 -1
  50. package/dist/chunk-9zrmwtgh.js +2 -0
  51. package/dist/{chunk-0gbptqh2.js → chunk-a6q5dmq7.js} +1 -1
  52. package/dist/{chunk-s5wwa0t4.js → chunk-akefvpqr.js} +2 -2
  53. package/dist/chunk-bdwe7er9.js +2 -0
  54. package/dist/chunk-c5zfgpgx.js +2 -0
  55. package/dist/chunk-ced1qbdw.js +2 -0
  56. package/dist/{chunk-jryjwara.js → chunk-cey6rhqw.js} +1 -1
  57. package/dist/{chunk-v02j99gh.js → chunk-cfj7y2tp.js} +2 -2
  58. package/dist/{chunk-y4dd2n2n.js → chunk-cjf5h08r.js} +1 -1
  59. package/dist/chunk-cpa76anv.js +2 -0
  60. package/dist/{chunk-kexk6z9s.js → chunk-dr2rpkb4.js} +1 -1
  61. package/dist/{chunk-t5kwx6fa.js → chunk-eh66m9ar.js} +1 -1
  62. package/dist/{chunk-604qr43v.js → chunk-esq6ydx5.js} +1 -1
  63. package/dist/chunk-fh33afkv.js +2 -0
  64. package/dist/{chunk-msmhta0w.js → chunk-fs5gwtd9.js} +1 -1
  65. package/dist/{chunk-7c1qq9zq.js → chunk-g38wktfx.js} +1 -1
  66. package/dist/chunk-g5v7gw13.js +2 -0
  67. package/dist/{chunk-4hk5ewgp.js → chunk-gnk0xd8n.js} +1 -1
  68. package/dist/{chunk-7yzyn9k7.js → chunk-gyrf55m1.js} +1 -1
  69. package/dist/chunk-hg77c5m2.js +2 -0
  70. package/dist/{chunk-yzb20ane.js → chunk-hgc3n1xq.js} +1 -1
  71. package/dist/chunk-hhjrtjc9.js +3 -0
  72. package/dist/chunk-hmrv7qv5.js +2 -0
  73. package/dist/{chunk-egr5663e.js → chunk-hrd56xw7.js} +3 -3
  74. package/dist/{chunk-gcavh7hk.js → chunk-hrrynmne.js} +1 -1
  75. package/dist/{chunk-wkcnyv6m.js → chunk-j8bwgnz5.js} +2 -2
  76. package/dist/{chunk-ycgtkfbm.js → chunk-jgfkmkpb.js} +1 -1
  77. package/dist/{chunk-xcsf7my7.js → chunk-jtaxnnq3.js} +1 -1
  78. package/dist/chunk-jxx9apw6.js +2 -0
  79. package/dist/{chunk-s2kxa1tb.js → chunk-kncbae57.js} +1 -1
  80. package/dist/{chunk-8q8gj45z.js → chunk-krvreaxb.js} +1 -1
  81. package/dist/chunk-m1n5a725.js +2 -0
  82. package/dist/{chunk-zr1r73p3.js → chunk-mgd0vre2.js} +1 -1
  83. package/dist/{chunk-s3pvp8qv.js → chunk-mjbrbnv2.js} +1 -1
  84. package/dist/{chunk-n43zq50e.js → chunk-mmhdgz5x.js} +1 -1
  85. package/dist/{chunk-jd9nv63q.js → chunk-mnhwgk4x.js} +1 -1
  86. package/dist/{chunk-w6ncyp18.js → chunk-n3qsg135.js} +1 -1
  87. package/dist/{chunk-szkq9s8n.js → chunk-nn17da2e.js} +1 -1
  88. package/dist/{chunk-b8cteeha.js → chunk-pavfpmwj.js} +1 -1
  89. package/dist/chunk-pn1syk7x.js +2 -0
  90. package/dist/{chunk-f044qmn3.js → chunk-q5hwa8dn.js} +1 -1
  91. package/dist/chunk-qqvwfhd5.js +2 -0
  92. package/dist/{chunk-ka5wtqmw.js → chunk-qz462c22.js} +1 -1
  93. package/dist/{chunk-snmtft92.js → chunk-rpnjwpw3.js} +1 -1
  94. package/dist/{chunk-wb24hk90.js → chunk-rwq2qzpx.js} +1 -1
  95. package/dist/{chunk-wwghzbbg.js → chunk-rypa8b99.js} +1 -1
  96. package/dist/{chunk-ry1key0g.js → chunk-sb2g9f73.js} +1 -1
  97. package/dist/{chunk-9ebfmdyb.js → chunk-sqkz8tf3.js} +1 -1
  98. package/dist/{chunk-ttny9g8k.js → chunk-sr042pkc.js} +1 -1
  99. package/dist/chunk-ssdzdsm1.js +2 -0
  100. package/dist/{chunk-3by4c2g9.js → chunk-tbw7qn8b.js} +1 -1
  101. package/dist/{chunk-jdcn0ms1.js → chunk-tk459ykz.js} +2 -2
  102. package/dist/chunk-tv2qdq7h.js +2 -0
  103. package/dist/{chunk-5g39e9ra.js → chunk-twdvqqft.js} +1 -1
  104. package/dist/{chunk-jg2gbd58.js → chunk-vmjktkm9.js} +1 -1
  105. package/dist/{chunk-bbq82jww.js → chunk-w913decg.js} +2 -2
  106. package/dist/chunk-wn9z19wm.js +2 -0
  107. package/dist/{chunk-5qseeh5t.js → chunk-wr011j4b.js} +1 -1
  108. package/dist/{chunk-ksqba0cq.js → chunk-wtdkz7wz.js} +1 -1
  109. package/dist/{chunk-tph7b269.js → chunk-x2j5b308.js} +1 -1
  110. package/dist/{chunk-tzhcjtkr.js → chunk-x7eb8e98.js} +1 -1
  111. package/dist/chunk-xaeamzng.js +2 -0
  112. package/dist/chunk-xc5swjjg.js +2 -0
  113. package/dist/{chunk-gpesxpwq.js → chunk-xnj5h0bq.js} +2 -2
  114. package/dist/{chunk-zdzd2jb4.js → chunk-ycmsckjw.js} +1 -1
  115. package/dist/{chunk-a50hb40e.js → chunk-yhebk7kd.js} +1 -1
  116. package/dist/{chunk-nnv8wytm.js → chunk-ymfh9wan.js} +1 -1
  117. package/dist/{chunk-at84gyvf.js → chunk-z698hwht.js} +1 -1
  118. package/dist/{chunk-64ttktzc.js → chunk-zeqktcby.js} +1 -1
  119. package/dist/{chunk-aqrp68m6.js → chunk-zsapb653.js} +1 -1
  120. package/dist/cli.js +14 -14
  121. package/dist/craft-entry.js +1 -1
  122. package/dist/craft.js +1 -1
  123. package/dist/database.js +1 -1
  124. package/dist/first-script-tag.d.ts +24 -0
  125. package/dist/first-script-tag.js +44 -0
  126. package/dist/includes.d.ts +2 -0
  127. package/dist/includes.js +12 -4
  128. package/dist/loops.d.ts +15 -1
  129. package/dist/loops.js +18 -4
  130. package/dist/process.js +4 -29
  131. package/dist/pwa.js +2 -2
  132. package/dist/runtime-injection.js +2 -1
  133. package/dist/ssg.js +2 -2
  134. package/dist/visual-testing.js +1 -1
  135. package/package.json +6 -6
  136. package/dist/chunk-0ggq64sc.js +0 -2
  137. package/dist/chunk-1ppaw4xs.js +0 -2
  138. package/dist/chunk-455m2k1y.js +0 -2
  139. package/dist/chunk-65hqene1.js +0 -2
  140. package/dist/chunk-6vt9ddra.js +0 -2
  141. package/dist/chunk-6xmx6stb.js +0 -2
  142. package/dist/chunk-8618n28z.js +0 -2
  143. package/dist/chunk-8avktqwz.js +0 -2
  144. package/dist/chunk-8z11nkyk.js +0 -2
  145. package/dist/chunk-95jjdgmb.js +0 -2
  146. package/dist/chunk-9aw5d4rr.js +0 -2
  147. package/dist/chunk-9g14542g.js +0 -2
  148. package/dist/chunk-9h4fkwtj.js +0 -2
  149. package/dist/chunk-bxvqqejm.js +0 -2
  150. package/dist/chunk-bzmxbz48.js +0 -2
  151. package/dist/chunk-f9qrz82p.js +0 -2
  152. package/dist/chunk-g8vf2fc7.js +0 -2
  153. package/dist/chunk-h63vszd3.js +0 -2
  154. package/dist/chunk-h78pksyp.js +0 -2
  155. package/dist/chunk-hxf6zg80.js +0 -2
  156. package/dist/chunk-jr79tvvs.js +0 -2
  157. package/dist/chunk-jwnbwemq.js +0 -3
  158. package/dist/chunk-mvj75wef.js +0 -2
  159. package/dist/chunk-n0t2at1c.js +0 -2
  160. package/dist/chunk-spzbfqjn.js +0 -3759
  161. package/dist/chunk-v1j4myd8.js +0 -2
  162. package/dist/chunk-v33qvj8y.js +0 -2
  163. package/dist/chunk-vnh668fb.js +0 -2
  164. package/dist/chunk-vpbw6g2t.js +0 -2
  165. package/dist/chunk-w33gx25k.js +0 -2
  166. package/dist/chunk-w3dfvxar.js +0 -2
  167. package/dist/chunk-wcp0dt2c.js +0 -2
  168. package/dist/chunk-z82sc99z.js +0 -2
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{Ha as a,He as F,Je as v,Ke as P,Va as r,de as s,ee as t,nb as n,o as m,oa as l,ob as p,qb as i,wb as e}from"./chunk-yzy6e4je.js";import"./chunk-5qseeh5t.js";import"./chunk-2ver2s2y.js";import"./chunk-wb24hk90.js";import"./chunk-r3220h2n.js";import"./chunk-prry9kgy.js";import"./chunk-ym3r8ktq.js";import"./chunk-a50hb40e.js";import"./chunk-ka5wtqmw.js";import"./chunk-zdzd2jb4.js";import"./chunk-6c1ebjat.js";import"./chunk-pknc4efv.js";import"./chunk-gpesxpwq.js";import"./chunk-dvvx1wny.js";import"./chunk-xz3evxqp.js";import"./chunk-tqayztkh.js";import"./chunk-0gbptqh2.js";import"./chunk-f044qmn3.js";import"./chunk-vd5xvsnv.js";import"./chunk-64djh88a.js";import"./chunk-9368t9jm.js";import"./chunk-5tefa8qb.js";import"./chunk-mwh3ymwc.js";import"./chunk-fqq5k9ve.js";import"./chunk-ya5m5vbn.js";import"./chunk-y4nzmkea.js";import"./chunk-7kw3grq5.js";import"./chunk-c79nfdyj.js";import"./chunk-ej8mv2k6.js";import"./chunk-cr8v8k53.js";import"./chunk-yzb20ane.js";import"./chunk-acctstj3.js";import"./chunk-xwxdwqn9.js";import"./chunk-szkq9s8n.js";import"./chunk-tph7b269.js";import"./chunk-t41aaehf.js";import"./chunk-jg2gbd58.js";import"./chunk-s5wwa0t4.js";import"./chunk-0saq3nwy.js";import"./chunk-09zjty4k.js";import{jl as u,kl as c}from"./chunk-s2kxa1tb.js";import"./chunk-zebypbks.js";import"./chunk-spzbfqjn.js";import{_s as f}from"./chunk-raxr83fs.js";import"./chunk-at84gyvf.js";import"./chunk-397rqs12.js";import"./chunk-aqrp68m6.js";import{wt as A}from"./chunk-egr5663e.js";import"./chunk-jwnbwemq.js";import"./chunk-ry1key0g.js";import"./chunk-4ee1aaet.js";import"./chunk-wkcnyv6m.js";import"./chunk-18p8dqya.js";import"./chunk-64ttktzc.js";import"./chunk-xcsf7my7.js";import"./chunk-2kv2gnzc.js";import"./chunk-ttny9g8k.js";import"./chunk-bbq82jww.js";import"./chunk-9ebfmdyb.js";import{ew as B}from"./chunk-jryjwara.js";import{spawn as o}from"child_process";import L from"fs";import zb from"os";import $ from"path";import w from"process";import{CLI as wb}from"@stacksjs/clapp";var N="0.2.319";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",E=new wb("stx");function h(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(Z<1024||Z>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function d(J){try{if(!L.existsSync(J)){let K=$.dirname(J),x=$.basename(J);if(L.existsSync(K)){let z=L.readdirSync(K).filter((j)=>j.toLowerCase().includes(x.toLowerCase().substring(0,3))||j.endsWith(".stx")||j.endsWith(".md")),k=z.length>0?`File not found. Similar files in ${K}: ${z.slice(0,3).join(", ")}`:`File not found. Directory ${K} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${J}`,suggestion:k}}return{isValid:!1,error:`File does not exist: ${J}`,suggestion:"Check the file path and try again"}}if(L.statSync(J).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${J}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(Z){return{isValid:!1,error:`Cannot access file: ${J}`,suggestion:"Check file permissions and path"}}}function y(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(Z<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(Z>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var V=(J)=>J.includes("*")||J.includes("?")||J.includes("{")||J.includes("["),jb=(J)=>J.endsWith(".stx")||J.endsWith(".md");function S(J,Z=1){if(console.error(`\u274C ${J.error}`),J.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${J.suggestion}`);w.exit(Z)}function kb(J){if(!J)return;let Z;try{Z=JSON.parse(J)}catch(K){console.error(`\u274C --info-plist is not valid JSON: ${K.message}`),w.exit(1)}if(typeof Z!=="object"||Z===null||Array.isArray(Z))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),w.exit(1);for(let[K,x]of Object.entries(Z))if(typeof x!=="string"&&typeof x!=="number"&&typeof x!=="boolean")console.error(`\u274C --info-plist value for "${K}" must be a string, number or boolean`),w.exit(1);return Z}async function Hb(J,Z){try{let K=["test"],x=[];if(J&&J.length>0)for(let W of J)if(V(W))try{let H=await Array.fromAsync(new Bun.Glob(W).scan({onlyFiles:!0,absolute:!0}));if(H.length===0)console.warn(`Warning: No files found matching pattern: ${W}`);else if(x.push(...H),Z.verbose)console.log(`Found ${H.length} file(s) matching pattern: ${W}`)}catch(H){return console.error(`Error expanding glob pattern ${W}:`,H),!1}else x.push(W);if(x.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(K.push(...x),Z.filter)K.push("--pattern",Z.filter);if(Z.timeout)K.push("--timeout",Z.timeout.toString());if(Z.reporter&&Z.reporter!=="default")if(Z.reporter==="junit"){let W=$.join(zb.tmpdir(),`stx-test-report-${Date.now()}.xml`);K.push("--reporter",Z.reporter),K.push("--reporter-outfile",W)}else console.warn(`Warning: Reporter '${Z.reporter}' is not supported. Using default reporter.`);if(Z.coverage)K.push("--coverage");if(Z.watch)K.push("--watch");K.push("--preload",$.join(__dirname,"../../../test-utils/happy-dom.ts"));let b={...w.env,STX_TEST_MODE:"true",STX_TEST_UI:Z.ui?"true":"false",STX_TEST_VERBOSE:Z.verbose?"true":"false"},z="bun";if(Z.verbose)console.log(`Running: ${z} ${K.join(" ")}`);let k=performance.now(),j=o(z,K,{stdio:"inherit",shell:!1,env:b});return new Promise((W)=>{j.on("close",(H)=>{let Y=((performance.now()-k)/1000).toFixed(2);if(H===0)W(!0);else W(!1)}),w.on("SIGINT",()=>{console.log(`
4
- Test run interrupted`),j.kill("SIGINT"),w.exit(1)})})}catch(K){return console.error("Error running tests:",K instanceof Error?K.message:String(K)),!1}}var Qb=w.argv.length>=3&&(jb(w.argv[2])&&L.existsSync(w.argv[2])||V(w.argv[2]));if(Qb){let J=w.argv[2],Z={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let K=3;K<w.argv.length;K++){let x=w.argv[K];if(x==="--port"&&K+1<w.argv.length){let b=h(w.argv[++K]);if(!b.isValid)S(b);Z.port=Number.parseInt(w.argv[K],10)}else if(x==="--no-watch")Z.watch=!1;else if(x==="--highlight-theme"&&K+1<w.argv.length){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.defaultTheme=w.argv[++K]}else if(x==="--no-highlight"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.enabled=!1}else if(x==="--no-highlight-unknown"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(x==="--no-cache")Z.cache=!1;else if(x==="--native")Z.native=!0}if(V(J))try{let K=await Array.fromAsync(new Bun.Glob(J).scan({onlyFiles:!0,absolute:!0})),x=J.endsWith(".stx")?K.filter((j)=>j.endsWith(".stx")):J.endsWith(".md")?K.filter((j)=>j.endsWith(".md")):K.filter((j)=>j.endsWith(".stx")||j.endsWith(".md")),b=J.split("*")[0].replace(/\/$/,"")||".",z=$.resolve(b);try{let j=new Bun.Glob("**/*.stx"),H=(await Array.fromAsync(j.scan({cwd:z,onlyFiles:!0,absolute:!0}))).filter((U)=>/\[.+\]/.test($.basename(U)));for(let U of H)if(!x.includes(U))x.push(U)}catch{}if(x.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${J}`),w.exit(1);if(!await v(x,Z))w.exit(1)}catch(K){console.error("Failed to process files:",K),w.exit(1)}else F(J,Z).catch((K)=>{console.error("Failed to start dev server:",K),w.exit(1)})}else{let J=function(x,b){let z=[];for(let k=0;k<=b.length;k++)z[k]=[k];for(let k=0;k<=x.length;k++)z[0][k]=k;for(let k=1;k<=b.length;k++)for(let j=1;j<=x.length;j++)if(b.charAt(k-1)===x.charAt(j-1))z[k][j]=z[k-1][j-1];else z[k][j]=Math.min(z[k-1][j-1]+1,z[k][j-1]+1,z[k-1][j]+1);return z[b.length][x.length]};E.command("docs","Generate documentation for components, templates, and directives").option("--output <dir>","Output directory for documentation",{default:"docs"}).option("--format <format>","Documentation format (markdown, html, json)",{default:"markdown"}).option("--components-dir <dir>","Components directory",{default:"components"}).option("--templates-dir <dir>","Templates directory",{default:"."}).option("--no-components","Disable components documentation").option("--no-templates","Disable templates documentation").option("--no-directives","Disable directives documentation").option("--extra-content <content>","Extra content to include in documentation").example("stx docs --output docs --format html").action(async(x)=>{try{if(await r(x))console.log("Documentation generated successfully."),w.exit(0);else console.error("Documentation generation failed."),w.exit(1)}catch(b){console.error("Error generating documentation:",b),w.exit(1)}}),E.command("iconify <command>","Generate Iconify icon packages").option("--output <dir>","Output directory for generated packages",{default:"packages"}).option("--icons <icons>","Comma-separated list of specific icons to generate").example("stx iconify list").example("stx iconify generate mdi").example("stx iconify generate lucide --icons home,settings,user").action(async(x,b)=>{try{let{fetchCollections:z,generatePackage:k}=await import("./chunk-5g39e9ra.js");if(x==="list"){console.log(`
3
+ import{Ha as a,He as F,Je as v,Ke as P,Va as r,de as s,ee as t,nb as n,o as m,oa as l,ob as p,qb as i,wb as e}from"./chunk-7b09hmk4.js";import"./chunk-wr011j4b.js";import"./chunk-2ver2s2y.js";import"./chunk-rwq2qzpx.js";import"./chunk-3qt3cxh0.js";import"./chunk-33gkb5pr.js";import"./chunk-ym3r8ktq.js";import"./chunk-yhebk7kd.js";import"./chunk-qz462c22.js";import"./chunk-ycmsckjw.js";import"./chunk-3erkb524.js";import"./chunk-9fjhmyje.js";import"./chunk-xnj5h0bq.js";import"./chunk-dvvx1wny.js";import"./chunk-xz3evxqp.js";import"./chunk-222swfwr.js";import"./chunk-a6q5dmq7.js";import"./chunk-q5hwa8dn.js";import"./chunk-vd5xvsnv.js";import"./chunk-64djh88a.js";import"./chunk-9368t9jm.js";import"./chunk-5tefa8qb.js";import"./chunk-mwh3ymwc.js";import"./chunk-fqq5k9ve.js";import"./chunk-ya5m5vbn.js";import"./chunk-y4nzmkea.js";import"./chunk-7kw3grq5.js";import"./chunk-c79nfdyj.js";import"./chunk-ej8mv2k6.js";import"./chunk-cr8v8k53.js";import"./chunk-hgc3n1xq.js";import"./chunk-1b2wksq3.js";import"./chunk-xwxdwqn9.js";import"./chunk-nn17da2e.js";import"./chunk-x2j5b308.js";import"./chunk-t41aaehf.js";import"./chunk-vmjktkm9.js";import"./chunk-akefvpqr.js";import"./chunk-8mspafdh.js";import"./chunk-09zjty4k.js";import{jl as u,kl as c}from"./chunk-kncbae57.js";import"./chunk-8q9qfy2v.js";import"./chunk-7kk2jb1j.js";import{at as f}from"./chunk-2btrq8sz.js";import"./chunk-z698hwht.js";import"./chunk-70zb3560.js";import"./chunk-zsapb653.js";import{yt as A}from"./chunk-hrd56xw7.js";import"./chunk-hhjrtjc9.js";import"./chunk-sb2g9f73.js";import"./chunk-1r3ydhkx.js";import"./chunk-j8bwgnz5.js";import"./chunk-5mdvkpt8.js";import"./chunk-zeqktcby.js";import"./chunk-jtaxnnq3.js";import"./chunk-2925bmqr.js";import"./chunk-sr042pkc.js";import"./chunk-w913decg.js";import"./chunk-sqkz8tf3.js";import{jw as B}from"./chunk-cey6rhqw.js";import{spawn as o}from"child_process";import L from"fs";import zb from"os";import $ from"path";import w from"process";import{CLI as wb}from"@stacksjs/clapp";var N="0.2.321";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",E=new wb("stx");function h(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(Z<1024||Z>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function d(J){try{if(!L.existsSync(J)){let K=$.dirname(J),x=$.basename(J);if(L.existsSync(K)){let z=L.readdirSync(K).filter((j)=>j.toLowerCase().includes(x.toLowerCase().substring(0,3))||j.endsWith(".stx")||j.endsWith(".md")),k=z.length>0?`File not found. Similar files in ${K}: ${z.slice(0,3).join(", ")}`:`File not found. Directory ${K} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${J}`,suggestion:k}}return{isValid:!1,error:`File does not exist: ${J}`,suggestion:"Check the file path and try again"}}if(L.statSync(J).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${J}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(Z){return{isValid:!1,error:`Cannot access file: ${J}`,suggestion:"Check file permissions and path"}}}function y(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(Z<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(Z>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var V=(J)=>J.includes("*")||J.includes("?")||J.includes("{")||J.includes("["),jb=(J)=>J.endsWith(".stx")||J.endsWith(".md");function S(J,Z=1){if(console.error(`\u274C ${J.error}`),J.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${J.suggestion}`);w.exit(Z)}function kb(J){if(!J)return;let Z;try{Z=JSON.parse(J)}catch(K){console.error(`\u274C --info-plist is not valid JSON: ${K.message}`),w.exit(1)}if(typeof Z!=="object"||Z===null||Array.isArray(Z))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),w.exit(1);for(let[K,x]of Object.entries(Z))if(typeof x!=="string"&&typeof x!=="number"&&typeof x!=="boolean")console.error(`\u274C --info-plist value for "${K}" must be a string, number or boolean`),w.exit(1);return Z}async function Hb(J,Z){try{let K=["test"],x=[];if(J&&J.length>0)for(let W of J)if(V(W))try{let H=await Array.fromAsync(new Bun.Glob(W).scan({onlyFiles:!0,absolute:!0}));if(H.length===0)console.warn(`Warning: No files found matching pattern: ${W}`);else if(x.push(...H),Z.verbose)console.log(`Found ${H.length} file(s) matching pattern: ${W}`)}catch(H){return console.error(`Error expanding glob pattern ${W}:`,H),!1}else x.push(W);if(x.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(K.push(...x),Z.filter)K.push("--pattern",Z.filter);if(Z.timeout)K.push("--timeout",Z.timeout.toString());if(Z.reporter&&Z.reporter!=="default")if(Z.reporter==="junit"){let W=$.join(zb.tmpdir(),`stx-test-report-${Date.now()}.xml`);K.push("--reporter",Z.reporter),K.push("--reporter-outfile",W)}else console.warn(`Warning: Reporter '${Z.reporter}' is not supported. Using default reporter.`);if(Z.coverage)K.push("--coverage");if(Z.watch)K.push("--watch");K.push("--preload",$.join(__dirname,"../../../test-utils/happy-dom.ts"));let b={...w.env,STX_TEST_MODE:"true",STX_TEST_UI:Z.ui?"true":"false",STX_TEST_VERBOSE:Z.verbose?"true":"false"},z="bun";if(Z.verbose)console.log(`Running: ${z} ${K.join(" ")}`);let k=performance.now(),j=o(z,K,{stdio:"inherit",shell:!1,env:b});return new Promise((W)=>{j.on("close",(H)=>{let Y=((performance.now()-k)/1000).toFixed(2);if(H===0)W(!0);else W(!1)}),w.on("SIGINT",()=>{console.log(`
4
+ Test run interrupted`),j.kill("SIGINT"),w.exit(1)})})}catch(K){return console.error("Error running tests:",K instanceof Error?K.message:String(K)),!1}}var Qb=w.argv.length>=3&&(jb(w.argv[2])&&L.existsSync(w.argv[2])||V(w.argv[2]));if(Qb){let J=w.argv[2],Z={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let K=3;K<w.argv.length;K++){let x=w.argv[K];if(x==="--port"&&K+1<w.argv.length){let b=h(w.argv[++K]);if(!b.isValid)S(b);Z.port=Number.parseInt(w.argv[K],10)}else if(x==="--no-watch")Z.watch=!1;else if(x==="--highlight-theme"&&K+1<w.argv.length){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.defaultTheme=w.argv[++K]}else if(x==="--no-highlight"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.enabled=!1}else if(x==="--no-highlight-unknown"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(x==="--no-cache")Z.cache=!1;else if(x==="--native")Z.native=!0}if(V(J))try{let K=await Array.fromAsync(new Bun.Glob(J).scan({onlyFiles:!0,absolute:!0})),x=J.endsWith(".stx")?K.filter((j)=>j.endsWith(".stx")):J.endsWith(".md")?K.filter((j)=>j.endsWith(".md")):K.filter((j)=>j.endsWith(".stx")||j.endsWith(".md")),b=J.split("*")[0].replace(/\/$/,"")||".",z=$.resolve(b);try{let j=new Bun.Glob("**/*.stx"),H=(await Array.fromAsync(j.scan({cwd:z,onlyFiles:!0,absolute:!0}))).filter((U)=>/\[.+\]/.test($.basename(U)));for(let U of H)if(!x.includes(U))x.push(U)}catch{}if(x.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${J}`),w.exit(1);if(!await v(x,Z))w.exit(1)}catch(K){console.error("Failed to process files:",K),w.exit(1)}else F(J,Z).catch((K)=>{console.error("Failed to start dev server:",K),w.exit(1)})}else{let J=function(x,b){let z=[];for(let k=0;k<=b.length;k++)z[k]=[k];for(let k=0;k<=x.length;k++)z[0][k]=k;for(let k=1;k<=b.length;k++)for(let j=1;j<=x.length;j++)if(b.charAt(k-1)===x.charAt(j-1))z[k][j]=z[k-1][j-1];else z[k][j]=Math.min(z[k-1][j-1]+1,z[k][j-1]+1,z[k-1][j]+1);return z[b.length][x.length]};E.command("docs","Generate documentation for components, templates, and directives").option("--output <dir>","Output directory for documentation",{default:"docs"}).option("--format <format>","Documentation format (markdown, html, json)",{default:"markdown"}).option("--components-dir <dir>","Components directory",{default:"components"}).option("--templates-dir <dir>","Templates directory",{default:"."}).option("--no-components","Disable components documentation").option("--no-templates","Disable templates documentation").option("--no-directives","Disable directives documentation").option("--extra-content <content>","Extra content to include in documentation").example("stx docs --output docs --format html").action(async(x)=>{try{if(await r(x))console.log("Documentation generated successfully."),w.exit(0);else console.error("Documentation generation failed."),w.exit(1)}catch(b){console.error("Error generating documentation:",b),w.exit(1)}}),E.command("iconify <command>","Generate Iconify icon packages").option("--output <dir>","Output directory for generated packages",{default:"packages"}).option("--icons <icons>","Comma-separated list of specific icons to generate").example("stx iconify list").example("stx iconify generate mdi").example("stx iconify generate lucide --icons home,settings,user").action(async(x,b)=>{try{let{fetchCollections:z,generatePackage:k}=await import("./chunk-twdvqqft.js");if(x==="list"){console.log(`
5
5
  \uD83D\uDCDA Fetching available icon collections...
6
6
  `);let j=await z(),W=Object.entries(j).sort((H,U)=>U[1].total-H[1].total);console.log(`Available collections:
7
7
  `);for(let[H,U]of W){let Y=U;console.log(` ${H.padEnd(30)} ${Y.name} (${Y.total} icons)`)}console.log(`
8
8
  Total: ${W.length} collections`)}else if(x.startsWith("generate")){let j=x==="generate"?"":x.replace("generate:","").replace("generate-","").replace("generate","").trim();if(!j)console.error("Error: Please specify a collection prefix"),console.error("Usage: stx iconify generate <prefix> [--icons icon1,icon2,...]"),w.exit(1);let W=b.output||$.join(w.cwd(),"packages/collections"),H=b.icons?b.icons.split(",").map((U)=>U.trim()):void 0;await k(j,W,H),console.log(`
9
9
  \u2713 Package generated successfully!`),console.log(`
10
- To use the package:`),console.log(` 1. cd packages/collections/iconify-${j}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${x}`),console.error("Available commands: list, generate"),w.exit(1)}catch(z){console.error("Error:",z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(x,b)=>{try{if(x==="audit"){let{runPwaAudit:z,formatAuditResult:k}=await import("./chunk-3pv0qj5f.js"),{loadConfig:j}=await import("./chunk-w3dfvxar.js");console.log(`
10
+ To use the package:`),console.log(` 1. cd packages/collections/iconify-${j}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${x}`),console.error("Available commands: list, generate"),w.exit(1)}catch(z){console.error("Error:",z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(x,b)=>{try{if(x==="audit"){let{runPwaAudit:z,formatAuditResult:k}=await import("./chunk-4zz9edh0.js"),{loadConfig:j}=await import("./chunk-2tcn2rw4.js");console.log(`
11
11
  \uD83D\uDD0D Running PWA audit...
12
12
  `);let W=await j(),H=b.output||"dist",U=z(W,H);if(console.log(k(U)),U.failed>0)w.exit(1)}else console.error(`Unknown pwa command: ${x}`),console.error("Available commands: audit"),w.exit(1)}catch(z){console.error("Error:",z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("dev [file]","Start a development server for an STX app or file").option("--port <port>","Port to use for the dev server",{default:3000}).option("--pages <dir>",'Directory containing page templates (default: pagesDir from stx.config.ts, else "pages")').option("--no-watch","Disable file watching and auto-reload").option("--native","Open in a native desktop window using Zyte").option("--titlebar-hidden","Hide the native titlebar but keep the traffic-light buttons (web content draws under a transparent full-size titlebar). Implies --native.").option("--highlight-theme <theme>","Syntax highlighting theme for Markdown code blocks",{default:"github-dark"}).option("--no-highlight","Disable syntax highlighting for Markdown code blocks").option("--no-highlight-unknown","Disable syntax highlighting for unknown languages in Markdown").option("--no-cache","Disable caching of parsed files").option("--no-hmr","Disable HMR / live-reload script injection (useful for clean network traces)").option("--profile","Print per-directive timing for every page render via performanceMonitor").option("--debug-directives","Log directive ordering and intermediate template state during rendering").example("stx dev").example("stx dev --port 8080").example("stx dev --pages src/pages").example("stx dev template.stx").example("stx dev components/hero.stx --port 8080").example("stx dev **/*.stx").example("stx dev docs/guide.md").example("stx dev template.stx --native").action(async(x,b)=>{try{if(b.port!==void 0){let k=h(b.port);if(!k.isValid)S(k);b.port=Number.parseInt(String(b.port),10)}if(b.timeout!==void 0){let k=y(b.timeout);if(!k.isValid)S(k)}let z={syntaxHighlighting:{enabled:b.highlight!==!1,serverSide:!0,defaultTheme:b.highlightTheme||"github-dark",highlightUnknownLanguages:b.highlightUnknown!==!1}};if(!x){if(!await P(".",{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,cache:b.cache!==!1,hotReload:b.hmr!==!1,profile:b.profile===!0,debugDirectives:b.debugDirectives===!0,...b.pages&&{pagesDir:b.pages}}))w.exit(1);return}if(!V(x))try{let k=await import("fs");if(k.existsSync(x)&&k.statSync(x).isDirectory()){if(!await P(x,{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,cache:b.cache!==!1,hotReload:b.hmr!==!1,profile:b.profile===!0,debugDirectives:b.debugDirectives===!0,...b.pages&&{pagesDir:b.pages}}))w.exit(1);return}}catch{}if(V(x)){console.log(`Expanding glob pattern: ${x}`);let k=await A.timeAsync("glob-expansion",async()=>{return Array.fromAsync(new Bun.Glob(x).scan({onlyFiles:!0,absolute:!0}))}),j=x.endsWith(".stx")?k.filter((Y)=>Y.endsWith(".stx")):x.endsWith(".md")?k.filter((Y)=>Y.endsWith(".md")):k.filter((Y)=>Y.endsWith(".stx")||Y.endsWith(".md"));if(j.length===0)console.error(`No STX or Markdown files found matching pattern: ${x}`),console.error("Try using patterns like '*.stx' or 'components/**/*.stx'"),w.exit(1);let W=x.split("*")[0].replace(/\/$/,"")||".",H=$.resolve(W);try{let Y=new Bun.Glob("**/*.stx"),X=(await Array.fromAsync(Y.scan({cwd:H,onlyFiles:!0,absolute:!0}))).filter((_)=>/\[.+\]/.test($.basename(_)));for(let _ of X)if(!j.includes(_))j.push(_)}catch{}if(console.log(`Found ${j.length} ${j.length===1?"file":"files"} matching ${x}`),!await v(j,{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,markdown:z,cache:b.cache!==!1}))w.exit(1)}else{if(!V(x)){let j=d(x);if(!j.isValid)S(j)}if(!await F(x,{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,markdown:z,cache:b.cache!==!1}))w.exit(1)}}catch(z){console.error("Error starting dev server:",z),w.exit(1)}}),E.command("a11y [target]","Scan .stx files for accessibility issues (directory, file, or glob)").option("--no-recursive","Disable recursive scanning of directories").option("--ignore <paths>","Comma-separated paths to ignore",{default:""}).option("--json","Output results as JSON").option("--output <file>","Write results to a file instead of stdout").option("--fix","Automatically fix common accessibility issues").example("stx a11y ./templates").example('stx a11y "resources/**/*.stx"').example("stx a11y resources/emails/welcome.stx").example("stx a11y --json --output a11y-report.json").action(async(x=".",b)=>{try{console.log(`Scanning ${x} for accessibility issues...`);let z=b.ignore?b.ignore.split(",").map((U)=>U.trim()):[],{results:k,scannedFiles:j}=await f(x,{recursive:b.recursive!==!1,ignorePaths:z});if(j.length===0)console.log(`
13
13
  No .stx files matched ${x}
@@ -69,7 +69,7 @@ Total: ${H} issues in ${W} files`),b.output){let U=`
69
69
  File not found: ${x}`),w.exit(1);if(!x.endsWith(".stx"))console.error(`
70
70
  File must have .stx extension: ${x}`),w.exit(1)}let k=$.resolve(b.pages),j=$.resolve(b.out);if(!x&&!L.existsSync(k))console.error(`
71
71
  Pages directory not found: ${k}`),console.log(`
72
- Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),w.exit(1);let{buildApp:W}=await import("./chunk-vnh668fb.js");c();let H=await W({root:x?$.dirname(x):void 0,debug:b.verbose,ssg:{pagesDir:b.pages,outputDir:b.out,domain:b.domain,baseUrl:b.base,sitemap:b.sitemap,rss:b.rss,minify:b.minify,cache:b.cache!==!1,cleanOutput:b.clean,concurrency:Number.parseInt(b.concurrency,10)||10,publicDir:b.public,trailingSlash:b.trailingSlash,generate404:!0,hooks:b.verbose?{onPageStart:(Y)=>console.log(` Generating: ${Y}`),onPageEnd:(Y,Q)=>console.log(` Generated: ${Y} (${Q.length} bytes)`),onError:(Y,Q)=>console.error(` Error in ${Q}: ${Y.message}`)}:void 0},ssr:{outputDir:b.out==="dist"?".output":b.out,debug:b.verbose}}),U=((performance.now()-z)/1000).toFixed(2);if(H.mode==="ssr"&&H.ssr)console.log(`
72
+ Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),w.exit(1);let{buildApp:W}=await import("./chunk-4dtjqc90.js");c();let H=await W({root:x?$.dirname(x):void 0,debug:b.verbose,ssg:{pagesDir:b.pages,outputDir:b.out,domain:b.domain,baseUrl:b.base,sitemap:b.sitemap,rss:b.rss,minify:b.minify,cache:b.cache!==!1,cleanOutput:b.clean,concurrency:Number.parseInt(b.concurrency,10)||10,publicDir:b.public,trailingSlash:b.trailingSlash,generate404:!0,hooks:b.verbose?{onPageStart:(Y)=>console.log(` Generating: ${Y}`),onPageEnd:(Y,Q)=>console.log(` Generated: ${Y} (${Q.length} bytes)`),onError:(Y,Q)=>console.error(` Error in ${Q}: ${Y.message}`)}:void 0},ssr:{outputDir:b.out==="dist"?".output":b.out,debug:b.verbose}}),U=((performance.now()-z)/1000).toFixed(2);if(H.mode==="ssr"&&H.ssr)console.log(`
73
73
  Build complete! (SSR)
74
74
  `),console.log(` Pages compiled: ${H.ssr.pageCount}`),console.log(` Output: ${H.ssr.outputDir}`),console.log(` Duration: ${U}s
75
75
  `);else if(H.ssg){if(console.log(`
@@ -84,8 +84,8 @@ Total: ${H} issues in ${W} files`),b.output){let U=`
84
84
  Build completed with ${H.ssg.failedCount} error(s). Fix the issues above and try again.
85
85
  `),w.exit(1);console.log(" To preview locally:"),console.log(` cd ${b.out||"dist"} && npx serve
86
86
  `)}}catch(z){console.error(`
87
- Build failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(x)=>{try{let b=$.resolve(x.output);if(!L.existsSync($.join(b,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),w.exit(1);let{startProductionServer:z}=await import("./chunk-n0t2at1c.js");await z({outputDir:b,port:Number.parseInt(x.port,10)||3000})}catch(b){console.error(`
88
- Failed to start production server:`,b instanceof Error?b.message:String(b)),w.exit(1)}}),E.command("deploy [directory]","Deploy built site to Netlify").option("--site-id <id>","Netlify site ID (or set NETLIFY_SITE_ID env var)").option("--token <token>","Auth token (or set NETLIFY_AUTH_TOKEN env var)").option("--production","Deploy to production (default: draft preview)").option("--message <msg>","Deploy message/title").option("--no-build","Skip build step before deploy").option("--open","Open deployed URL in browser").option("--dry-run","Preview deployment without uploading").option("--init","Initialize Netlify configuration for this project").example("stx deploy").example("stx deploy --production").example("stx deploy dist --site-id my-site-abc123").example("stx deploy --init").example("stx deploy --dry-run").action(async(x,b)=>{try{let{deploy:z,initNetlify:k,DeployError:j}=await import("./chunk-vhan24as.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${N}\x1B[0m`),b.init){console.log(`
87
+ Build failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(x)=>{try{let b=$.resolve(x.output);if(!L.existsSync($.join(b,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),w.exit(1);let{startProductionServer:z}=await import("./chunk-7v72zj7x.js");await z({outputDir:b,port:Number.parseInt(x.port,10)||3000})}catch(b){console.error(`
88
+ Failed to start production server:`,b instanceof Error?b.message:String(b)),w.exit(1)}}),E.command("deploy [directory]","Deploy built site to Netlify").option("--site-id <id>","Netlify site ID (or set NETLIFY_SITE_ID env var)").option("--token <token>","Auth token (or set NETLIFY_AUTH_TOKEN env var)").option("--production","Deploy to production (default: draft preview)").option("--message <msg>","Deploy message/title").option("--no-build","Skip build step before deploy").option("--open","Open deployed URL in browser").option("--dry-run","Preview deployment without uploading").option("--init","Initialize Netlify configuration for this project").example("stx deploy").example("stx deploy --production").example("stx deploy dist --site-id my-site-abc123").example("stx deploy --init").example("stx deploy --dry-run").action(async(x,b)=>{try{let{deploy:z,initNetlify:k,DeployError:j}=await import("./chunk-373fc0m2.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${N}\x1B[0m`),b.init){console.log(`
89
89
  \uD83D\uDCDD Initializing Netlify configuration...
90
90
  `);let H=await k({directory:x||w.cwd(),siteId:b.siteId});if(console.log(`\u2713 Created ${H.configPath}`),H.siteId)console.log("\u2713 Saved site ID to .env.local");console.log(`
91
91
  You can now deploy with: stx deploy`);return}if(b.build!==!1){if(console.log(`
@@ -97,7 +97,7 @@ You can now deploy with: stx deploy`);return}if(b.build!==!1){if(console.log(`
97
97
  `),console.log(` ${b.dryRun?"Would deploy":"Draft URL"}: ${W.url}`),W.siteUrl)console.log(` Site URL: ${W.siteUrl}`);if(!b.dryRun)console.log(`
98
98
  Deploy ID: ${W.deployId}`),console.log(` Duration: ${(W.duration/1000).toFixed(1)}s`),console.log(` Files: ${W.filesUploaded}`)}}catch(z){if(z instanceof Error&&z.name==="DeployError")console.error(`
99
99
  \u274C ${z.message}`),w.exit(1);console.error(`
100
- \u274C Deploy failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("images <input>","Optimize images for production").option("-o, --output <dir>","Output directory",{default:"dist/images"}).option("-w, --widths <sizes>","Output widths (comma-separated)",{default:"320,640,768,1024,1280,1536,1920"}).option("-f, --formats <types>","Output formats (comma-separated)",{default:"webp,jpeg"}).option("-q, --quality <n>","Output quality (1-100)",{default:"80"}).option("--placeholder <type>","Placeholder type: blur, dominant-color, none",{default:"none"}).option("--dry-run","Preview without processing").option("--verbose","Show detailed output").example("stx images public/images").example("stx images public/images -o dist/images").example("stx images public/images --widths 640,1024,1920").example("stx images public/images --formats webp,avif").example("stx images public/images --quality 85").example("stx images public/images --dry-run").action(async(x,b)=>{try{let{optimizeDirectory:z,isSharpAvailable:k,formatSize:j}=await import("./chunk-b8cteeha.js"),W=await import("fs"),H=await import("path");if(console.log(`\x1B[1mstx images\x1B[0m \x1B[2mv${N}\x1B[0m`),!await k())console.error(`
100
+ \u274C Deploy failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("images <input>","Optimize images for production").option("-o, --output <dir>","Output directory",{default:"dist/images"}).option("-w, --widths <sizes>","Output widths (comma-separated)",{default:"320,640,768,1024,1280,1536,1920"}).option("-f, --formats <types>","Output formats (comma-separated)",{default:"webp,jpeg"}).option("-q, --quality <n>","Output quality (1-100)",{default:"80"}).option("--placeholder <type>","Placeholder type: blur, dominant-color, none",{default:"none"}).option("--dry-run","Preview without processing").option("--verbose","Show detailed output").example("stx images public/images").example("stx images public/images -o dist/images").example("stx images public/images --widths 640,1024,1920").example("stx images public/images --formats webp,avif").example("stx images public/images --quality 85").example("stx images public/images --dry-run").action(async(x,b)=>{try{let{optimizeDirectory:z,isSharpAvailable:k,formatSize:j}=await import("./chunk-pavfpmwj.js"),W=await import("fs"),H=await import("path");if(console.log(`\x1B[1mstx images\x1B[0m \x1B[2mv${N}\x1B[0m`),!await k())console.error(`
101
101
  \u274C sharp is required for image optimization.`),console.log(`
102
102
  Install sharp with:`),console.log(" bun add sharp"),w.exit(1);let Y=b.widths.split(",").map((G)=>Number.parseInt(G.trim(),10)).filter((G)=>!Number.isNaN(G)),Q=b.formats.split(",").map((G)=>G.trim().toLowerCase()),X=Number.parseInt(b.quality,10)||80,_=b.placeholder,q=H.resolve(x);if(!W.existsSync(q))console.error(`
103
103
  \u274C Input directory not found: ${q}`),w.exit(1);if(!W.statSync(q).isDirectory())console.error(`
@@ -110,7 +110,7 @@ Would generate ~${bb} image variants`);return}console.log(`
110
110
  `);let M=await z(q,b.output,{widths:Y,formats:Q,quality:X,placeholder:_,verbose:b.verbose});if(console.log(`
111
111
  \u2713 Optimization complete!
112
112
  `),console.log(` Images processed: ${M.stats.optimizedImages}/${M.stats.totalImages}`),console.log(` Variants created: ${M.stats.variants}`),M.stats.savedBytes>0)console.log(` Estimated savings: ~${j(M.stats.savedBytes)}`)}catch(z){console.error(`
113
- \u274C Image optimization failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("bundle [directory]","Analyze bundle size and composition").option("-o, --output <file>","Output file path").option("--json","Output as JSON").option("--text","Output as text summary").option("--markdown","Output as Markdown").option("--no-open","Do not open HTML report in browser").option("--no-gzip","Do not show gzip sizes").option("--threshold <size>","Fail if total size exceeds threshold (e.g., 500KB, 1MB)").option("--top <n>","Number of top modules to show",{default:"20"}).example("stx bundle").example("stx bundle dist/").example("stx bundle dist/ --json").example("stx bundle dist/ --text").example("stx bundle dist/ --threshold 500KB").example("stx bundle dist/ --no-open").action(async(x,b)=>{try{let{analyze:z,formatBytes:k,parseSize:j}=await import("./chunk-4hk5ewgp.js"),W=await import("path");console.log(`\x1B[1mstx bundle\x1B[0m \x1B[2mv${N}\x1B[0m`);let H=x||"dist",U=W.resolve(H);if(!(await import("fs")).existsSync(U))console.error(`
113
+ \u274C Image optimization failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("bundle [directory]","Analyze bundle size and composition").option("-o, --output <file>","Output file path").option("--json","Output as JSON").option("--text","Output as text summary").option("--markdown","Output as Markdown").option("--no-open","Do not open HTML report in browser").option("--no-gzip","Do not show gzip sizes").option("--threshold <size>","Fail if total size exceeds threshold (e.g., 500KB, 1MB)").option("--top <n>","Number of top modules to show",{default:"20"}).example("stx bundle").example("stx bundle dist/").example("stx bundle dist/ --json").example("stx bundle dist/ --text").example("stx bundle dist/ --threshold 500KB").example("stx bundle dist/ --no-open").action(async(x,b)=>{try{let{analyze:z,formatBytes:k,parseSize:j}=await import("./chunk-gnk0xd8n.js"),W=await import("path");console.log(`\x1B[1mstx bundle\x1B[0m \x1B[2mv${N}\x1B[0m`);let H=x||"dist",U=W.resolve(H);if(!(await import("fs")).existsSync(U))console.error(`
114
114
  \u274C Directory not found: ${U}`),console.log("\nRun `stx build` first to generate build output."),w.exit(1);let Q="html";if(b.json)Q="json";else if(b.text)Q="text";else if(b.markdown)Q="markdown";console.log(`
115
115
  \uD83D\uDCE6 Analyzing: ${U}`);let X=await z({directory:U,output:b.output,format:Q,open:b.open!==!1&&Q==="html",gzip:b.gzip!==!1,threshold:b.threshold,topModules:Number.parseInt(b.top||"20",10),recommendations:!0});if(Q==="html"){if(console.log(`
116
116
  \u2713 Report generated: ${X.outputPath}`),b.open!==!1)console.log(" Opening in browser...")}else console.log(X.report);if(X.exceedsThreshold){let _=b.threshold;console.error(`
@@ -124,7 +124,7 @@ To view it in the development server:`),console.log(` stx dev ${x}
124
124
  \uD83D\uDCDD ${$.relative(w.cwd(),Q)}:`),console.log("--- Original"),console.log("+++ Formatted"),console.log(`@@ Changes in ${$.basename(Q)} @@`),console.log("+ Formatted content would be applied");else await Bun.write(Q,q),console.log(`\u2705 Formatted ${$.relative(w.cwd(),Q)}`),U++}catch(X){console.error(`\u274C Error formatting ${$.relative(w.cwd(),Q)}:`,X),Y++}if(b.check&&Y>0)console.log(`
125
125
  ${Y} files need formatting. Run 'stx format' to fix.`),w.exit(1);else if(!b.check&&!b.diff)console.log(`\u2728 Formatted ${U} files successfully`)}catch(z){console.error("Error formatting files:",z),w.exit(1)}}),E.command("perf [command...]","Show performance statistics for STX operations").option("--clear","Clear performance statistics").option("--json","Output as JSON").example("stx perf").example("stx perf --clear").example("stx perf --json").action(async(x,b)=>{try{if(b.clear){A.clear(),console.log("\u2705 Performance statistics cleared");return}let z=A.getStats();if(Object.keys(z).length===0){if(b.json){console.log(JSON.stringify({},null,2));return}console.log("No performance data available. Run some STX commands first.");return}if(b.json)console.log(JSON.stringify(z,null,2));else{console.log(`
126
126
  \uD83D\uDCCA STX Performance Statistics
127
- `);for(let[k,j]of Object.entries(z))console.log(`\uD83D\uDD27 ${k}:`),console.log(` Count: ${j.count}`),console.log(` Average: ${j.avgTime.toFixed(2)}ms`),console.log(` Total: ${j.totalTime.toFixed(2)}ms`),console.log(` Min: ${j.minTime.toFixed(2)}ms`),console.log(` Max: ${j.maxTime.toFixed(2)}ms`),console.log("")}}catch(z){console.error("Error showing performance stats:",z),w.exit(1)}}),E.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(x,b)=>{let{formatTypecheckDiagnostics:z,typecheckStxFiles:k}=await import("./chunk-8z11nkyk.js"),{resolveStxTargets:j}=await import("./chunk-455m2k1y.js"),W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx"],U=await j(H);if(U.length===0){console.log(`
127
+ `);for(let[k,j]of Object.entries(z))console.log(`\uD83D\uDD27 ${k}:`),console.log(` Count: ${j.count}`),console.log(` Average: ${j.avgTime.toFixed(2)}ms`),console.log(` Total: ${j.totalTime.toFixed(2)}ms`),console.log(` Min: ${j.minTime.toFixed(2)}ms`),console.log(` Max: ${j.maxTime.toFixed(2)}ms`),console.log("")}}catch(z){console.error("Error showing performance stats:",z),w.exit(1)}}),E.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(x,b)=>{let{formatTypecheckDiagnostics:z,typecheckStxFiles:k}=await import("./chunk-48w09pf7.js"),{resolveStxTargets:j}=await import("./chunk-tv2qdq7h.js"),W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx"],U=await j(H);if(U.length===0){console.log(`
128
128
  No .stx files matched ${H.join(", ")}
129
129
  `);return}let Y=m(w.argv,"--lib"),Q=Y.length>0?Y:b.lib?Array.isArray(b.lib)?b.lib:[b.lib]:[],X=await k(U,{client:b.client!==!1,server:b.server!==!1,templates:b.templates!==!1,extraLibs:Q});if(X.failure)console.error(`
130
130
  Type-check did not run.
@@ -135,8 +135,8 @@ ${Y} files need formatting. Run 'stx format' to fix.`),w.exit(1);else if(!b.chec
135
135
  `),w.exit(2);let _=X.diagnostics.filter((q)=>q.category==="error");if(X.diagnostics.length>0)console.error(`
136
136
  ${z(X.diagnostics)}
137
137
  `);if(console.log(` Checked ${X.blockCount} script block(s) and ${X.expressionCount} template expression(s) in ${X.checkedFiles.length} file(s) \u2014 `+`${_.length} error(s), ${X.diagnostics.length-_.length} warning(s)
138
- `),_.length>0)w.exit(1)}),E.command("codemod [patterns...]","Find hand-rolled code that an stx primitive already covers").option("--fix","Write the safe rewrites (default is report-only)").option("--rule <rule>","Run one rule only: confirm | tooltip (rewritable) \xB7 alert | route-params | search-params | navigate | "+"fetch | polling | debounce | click-outside | focus | clipboard | watch (report-only)").example("stx codemod").example("stx codemod --rule route-params").example('stx codemod --fix "resources/views/**/*.stx"').action(async(x,b)=>{let{codemodSource:z,formatCodemodFindings:k}=await import("./chunk-3by4c2g9.js"),j=globalThis.Bun.Glob,W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx","**/*.ts"],U=b.rule?[b.rule]:void 0;if(b.rule&&b.rule!=="confirm"&&b.rule!=="tooltip")console.error(`Unknown rule "${b.rule}". Expected: confirm | tooltip`),w.exit(1);let Y=new Set,Q=[],X=0,_=new Set;try{let q=Bun.spawnSync(["git","ls-files","--others","--ignored","--exclude-standard","-z"],{cwd:w.cwd(),stdout:"pipe",stderr:"pipe"});for(let O of new TextDecoder().decode(q.stdout).split("\x00"))if(O)_.add($.resolve(w.cwd(),O))}catch{}for(let q of H)for await(let O of new j(q).scan({cwd:w.cwd(),absolute:!0})){if(O.includes("/node_modules/")||O.includes("/dist/")||Y.has(O)||_.has(O))continue;Y.add(O);let M=await Bun.file(O).text(),G=z(M,{file:O,rules:U});if(Q.push(...G.findings),b.fix&&G.code!==M)await Bun.write(O,G.code),X++}if(console.error(k(Q,Boolean(b.fix))),b.fix)console.error(`
139
- ${X} file(s) written.`)}),E.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(x)=>{try{let b;try{b=(await import("./chunk-px0hqf1q.js")).generateSignalsRuntime}catch{b=void 0}let z=await s({generateRuntime:b});if(x.json)console.log(JSON.stringify(z,null,2));else console.log(t(z));if(!z.ok)w.exit(1)}catch(b){console.error("Error running doctor:",b),w.exit(1)}}),E.command("debug <file>","Debug STX template processing step by step").option("--step","Step through processing stages interactively").option("--verbose","Show detailed processing information").option("--context <data>","JSON string of context data to use").option("--save-report <file>","Save debug report to file").example("stx debug template.stx").example("stx debug template.stx --step").example(`stx debug template.stx --context '{"name": "John", "items": [1,2,3]}'`).action(async(x,b)=>{try{let z=d(x);if(!z.isValid)S(z);console.log(`\uD83D\uDD0D Debugging stx template: ${x}
138
+ `),_.length>0)w.exit(1)}),E.command("codemod [patterns...]","Find hand-rolled code that an stx primitive already covers").option("--fix","Write the safe rewrites (default is report-only)").option("--rule <rule>","Run one rule only: confirm | tooltip (rewritable) \xB7 alert | route-params | search-params | navigate | "+"fetch | polling | debounce | click-outside | focus | clipboard | watch (report-only)").example("stx codemod").example("stx codemod --rule route-params").example('stx codemod --fix "resources/views/**/*.stx"').action(async(x,b)=>{let{codemodSource:z,formatCodemodFindings:k}=await import("./chunk-tbw7qn8b.js"),j=globalThis.Bun.Glob,W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx","**/*.ts"],U=b.rule?[b.rule]:void 0;if(b.rule&&b.rule!=="confirm"&&b.rule!=="tooltip")console.error(`Unknown rule "${b.rule}". Expected: confirm | tooltip`),w.exit(1);let Y=new Set,Q=[],X=0,_=new Set;try{let q=Bun.spawnSync(["git","ls-files","--others","--ignored","--exclude-standard","-z"],{cwd:w.cwd(),stdout:"pipe",stderr:"pipe"});for(let O of new TextDecoder().decode(q.stdout).split("\x00"))if(O)_.add($.resolve(w.cwd(),O))}catch{}for(let q of H)for await(let O of new j(q).scan({cwd:w.cwd(),absolute:!0})){if(O.includes("/node_modules/")||O.includes("/dist/")||Y.has(O)||_.has(O))continue;Y.add(O);let M=await Bun.file(O).text(),G=z(M,{file:O,rules:U});if(Q.push(...G.findings),b.fix&&G.code!==M)await Bun.write(O,G.code),X++}if(console.error(k(Q,Boolean(b.fix))),b.fix)console.error(`
139
+ ${X} file(s) written.`)}),E.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(x)=>{try{let b;try{b=(await import("./chunk-9whbqxsv.js")).generateSignalsRuntime}catch{b=void 0}let z=await s({generateRuntime:b});if(x.json)console.log(JSON.stringify(z,null,2));else console.log(t(z));if(!z.ok)w.exit(1)}catch(b){console.error("Error running doctor:",b),w.exit(1)}}),E.command("debug <file>","Debug STX template processing step by step").option("--step","Step through processing stages interactively").option("--verbose","Show detailed processing information").option("--context <data>","JSON string of context data to use").option("--save-report <file>","Save debug report to file").example("stx debug template.stx").example("stx debug template.stx --step").example(`stx debug template.stx --context '{"name": "John", "items": [1,2,3]}'`).action(async(x,b)=>{try{let z=d(x);if(!z.isValid)S(z);console.log(`\uD83D\uDD0D Debugging stx template: ${x}
140
140
  `);let k={};if(b.context)try{k=JSON.parse(b.context)}catch(H){console.error("\u274C Invalid JSON in --context option"),w.exit(1)}let j=await Bun.file(x).text();console.log(`\uD83D\uDCC4 Template Content (${j.length} chars):`),console.log("\u2500".repeat(50)),console.log(j.substring(0,500)+(j.length>500?`
141
141
  ...
142
142
  `:"")),console.log("\u2500".repeat(50));let W=j.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(W)console.log(`
@@ -159,12 +159,12 @@ Press Ctrl+C to stop watching...
159
159
  \uD83D\uDCDD ${$.relative(w.cwd(),Q.file)}`),console.log(` Lines: ${Q.metrics.lines} | Complexity: ${Q.metrics.complexity}/10 | Estimated render: ${Q.performance.estimatedRenderTime}ms`),Q.issues.length>0){let X=Q.issues.filter((_)=>j[_.type]>=W);if(X.length>0)console.log(` Issues (${X.length}):`),X.forEach((_)=>{let q=_.type==="error"?"\u274C":_.type==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(console.log(` ${q} ${_.message}`),_.suggestion)console.log(` \uD83D\uDCA1 ${_.suggestion}`)})}if(Q.suggestions.length>0)console.log(` Suggestions (${Q.suggestions.length}):`),Q.suggestions.forEach((X)=>{let _=X.impact==="high"?"\uD83D\uDD25":X.impact==="medium"?"\u26A1":"\uD83D\uDCAB";console.log(` ${_} ${X.message} (${X.impact} impact, ${X.effort} effort)`)})}}else if(Y.length>0&&!b.onlyIssues)console.log(`
160
160
  \uD83D\uDCC4 Files with issues:`),Y.forEach((Q)=>{let X=Q.issues.filter((_)=>j[_.type]>=W).length;if(X>0)console.log(` ${$.relative(w.cwd(),Q.file)} (${X} issues)`)});if(b.saveReport){let Q={summary:U,results:Y,generatedAt:new Date().toISOString(),commandOptions:b};await Bun.write(b.saveReport,JSON.stringify(Q,null,2)),console.log(`
161
161
  \uD83D\uDCCB Analysis report saved to: ${b.saveReport}`)}console.log(`
162
- \u2728 Analysis complete! Use --detailed for more information.`)}catch(z){console.error("Error analyzing templates:",z),w.exit(1)}}),E.command("screenshot [input]","Capture PNG screenshot(s) of page(s) via Bun WebView \u2014 a file, URL, or dist directory").option("--out <dir>","Output directory",{default:"screenshots"}).option("--width <px>","Viewport width",{default:"1440"}).option("--height <px>","Viewport height",{default:"2200"}).option("--wait <ms>","Settle time after navigation before capture",{default:"800"}).option("--timeout <ms>","Hard cap on waiting for navigation",{default:"15000"}).option("--full-page","Capture the entire scrollable page, not just the viewport").option("--wait-selector <sel>","Wait until a CSS selector exists before capturing").option("--format <fmt>","Image format: png | jpeg | webp",{default:"png"}).option("--backend <name>","WebView backend: webkit (macOS, default) | chrome").action(async(x,b)=>{let{captureScreenshots:z}=await import("./chunk-0mnv8pf5.js"),k=x||"dist";try{let j=await z(k,b.out,{width:Number.parseInt(b.width,10),height:Number.parseInt(b.height,10),waitMs:Number.parseInt(b.wait,10),timeoutMs:Number.parseInt(b.timeout,10),fullPage:Boolean(b.fullPage),waitSelector:b.waitSelector,format:b.format,backend:b.backend});for(let W of j)console.log(`\uD83D\uDCF8 ${W.output} (${(W.bytes/1024).toFixed(0)} KB)`);console.log(`
163
- \u2728 Captured ${j.length} screenshot(s) to ${b.out}/ via Bun WebView`)}catch(j){console.error(`Screenshot failed: ${j.message}`),w.exit(1)}}),E.command("version","Show the version of the CLI").action(()=>{console.log(N)}),E.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(x)=>{let{startInteractive:b}=await import("./chunk-9g14542g.js"),z={};if(x.context){let k=$.resolve(x.context);if(L.existsSync(k))try{let j=L.readFileSync(k,"utf-8");z=JSON.parse(j)}catch(j){console.error("Error loading context file:",j),w.exit(1)}else console.error(`Context file not found: ${k}`),w.exit(1)}await b({context:z,cwd:x.cwd?$.resolve(x.cwd):w.cwd(),verbose:x.verbose})}),E.command("build:native <input>","Build stx template into a native desktop/mobile app").option("--output <dir>","Output directory",{default:"dist/native"}).option("--target <platform>","Target platform: macos, windows, linux, ios, android").option("--format <format>","Output format: app, dmg, pkg, msi, zip, deb, rpm, appimage, ipa, apk").option("--name <name>","Application name (defaults to filename)").option("--version <version>","Application version",{default:"1.0.0"}).option("--description <desc>","Application description").option("--author <author>","Author/Maintainer name").option("--bundle-id <id>","Bundle identifier (macOS/iOS)").option("--icon <path>","Path to application icon").option("--width <width>","Window width",{default:"1200"}).option("--height <height>","Window height",{default:"800"}).option("--title <title>","Window title").option("--system-tray","Enable system tray/menubar mode").option("--menubar-only","Run without a dock icon (implied by --system-tray)").option("--category <type>","LSApplicationCategoryType (macOS)").option("--copyright <text>","NSHumanReadableCopyright (macOS)").option("--min-system-version <v>","LSMinimumSystemVersion (macOS)").option("--info-plist <json>","Extra Info.plist keys as a JSON object (macOS)").option("--dev-tools","Enable developer tools").option("--frameless","Create frameless window").option("--always-on-top","Keep window always on top").option("--craft-path <path>","Path to Craft binary").option("--verbose","Show verbose output").example("stx build:native app.stx --target macos").example("stx build:native app.stx --target macos --format dmg").example("stx build:native app.stx --target linux --format appimage").example('stx build:native app.stx --name "My App" --icon icon.png').action(async(x,b)=>{try{let{buildNative:z,getAvailableTargets:k,getAvailableFormats:j}=await import("./chunk-v1j4myd8.js"),W=$.resolve(x);if(!L.existsSync(W))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let H=k();if(b.target&&!["macos","windows","linux","ios","android"].includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${H.join(", ")}`),w.exit(1);let U=b.target||H[0],Y=j(U);if(b.format&&!Y.includes(b.format))console.error(`\u274C Invalid format for ${U}: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${Y.join(", ")}`),w.exit(1);console.log(`
162
+ \u2728 Analysis complete! Use --detailed for more information.`)}catch(z){console.error("Error analyzing templates:",z),w.exit(1)}}),E.command("screenshot [input]","Capture PNG screenshot(s) of page(s) via Bun WebView \u2014 a file, URL, or dist directory").option("--out <dir>","Output directory",{default:"screenshots"}).option("--width <px>","Viewport width",{default:"1440"}).option("--height <px>","Viewport height",{default:"2200"}).option("--wait <ms>","Settle time after navigation before capture",{default:"800"}).option("--timeout <ms>","Hard cap on waiting for navigation",{default:"15000"}).option("--full-page","Capture the entire scrollable page, not just the viewport").option("--wait-selector <sel>","Wait until a CSS selector exists before capturing").option("--format <fmt>","Image format: png | jpeg | webp",{default:"png"}).option("--backend <name>","WebView backend: webkit (macOS, default) | chrome").action(async(x,b)=>{let{captureScreenshots:z}=await import("./chunk-0eydszkp.js"),k=x||"dist";try{let j=await z(k,b.out,{width:Number.parseInt(b.width,10),height:Number.parseInt(b.height,10),waitMs:Number.parseInt(b.wait,10),timeoutMs:Number.parseInt(b.timeout,10),fullPage:Boolean(b.fullPage),waitSelector:b.waitSelector,format:b.format,backend:b.backend});for(let W of j)console.log(`\uD83D\uDCF8 ${W.output} (${(W.bytes/1024).toFixed(0)} KB)`);console.log(`
163
+ \u2728 Captured ${j.length} screenshot(s) to ${b.out}/ via Bun WebView`)}catch(j){console.error(`Screenshot failed: ${j.message}`),w.exit(1)}}),E.command("version","Show the version of the CLI").action(()=>{console.log(N)}),E.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(x)=>{let{startInteractive:b}=await import("./chunk-99yynes4.js"),z={};if(x.context){let k=$.resolve(x.context);if(L.existsSync(k))try{let j=L.readFileSync(k,"utf-8");z=JSON.parse(j)}catch(j){console.error("Error loading context file:",j),w.exit(1)}else console.error(`Context file not found: ${k}`),w.exit(1)}await b({context:z,cwd:x.cwd?$.resolve(x.cwd):w.cwd(),verbose:x.verbose})}),E.command("build:native <input>","Build stx template into a native desktop/mobile app").option("--output <dir>","Output directory",{default:"dist/native"}).option("--target <platform>","Target platform: macos, windows, linux, ios, android").option("--format <format>","Output format: app, dmg, pkg, msi, zip, deb, rpm, appimage, ipa, apk").option("--name <name>","Application name (defaults to filename)").option("--version <version>","Application version",{default:"1.0.0"}).option("--description <desc>","Application description").option("--author <author>","Author/Maintainer name").option("--bundle-id <id>","Bundle identifier (macOS/iOS)").option("--icon <path>","Path to application icon").option("--width <width>","Window width",{default:"1200"}).option("--height <height>","Window height",{default:"800"}).option("--title <title>","Window title").option("--system-tray","Enable system tray/menubar mode").option("--menubar-only","Run without a dock icon (implied by --system-tray)").option("--category <type>","LSApplicationCategoryType (macOS)").option("--copyright <text>","NSHumanReadableCopyright (macOS)").option("--min-system-version <v>","LSMinimumSystemVersion (macOS)").option("--info-plist <json>","Extra Info.plist keys as a JSON object (macOS)").option("--dev-tools","Enable developer tools").option("--frameless","Create frameless window").option("--always-on-top","Keep window always on top").option("--craft-path <path>","Path to Craft binary").option("--verbose","Show verbose output").example("stx build:native app.stx --target macos").example("stx build:native app.stx --target macos --format dmg").example("stx build:native app.stx --target linux --format appimage").example('stx build:native app.stx --name "My App" --icon icon.png').action(async(x,b)=>{try{let{buildNative:z,getAvailableTargets:k,getAvailableFormats:j}=await import("./chunk-jxx9apw6.js"),W=$.resolve(x);if(!L.existsSync(W))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let H=k();if(b.target&&!["macos","windows","linux","ios","android"].includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${H.join(", ")}`),w.exit(1);let U=b.target||H[0],Y=j(U);if(b.format&&!Y.includes(b.format))console.error(`\u274C Invalid format for ${U}: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${Y.join(", ")}`),w.exit(1);console.log(`
164
164
  \uD83D\uDD28 Building native app...`),console.log(` Input: ${x}`),console.log(` Target: ${U}`),console.log(` Format: ${b.format||"default"}`),console.log(` Output: ${b.output}
165
165
  `);let Q=await z({input:W,output:$.resolve(b.output),target:U,format:b.format,name:b.name,version:b.version,description:b.description,author:b.author,bundleId:b.bundleId,icon:b.icon?$.resolve(b.icon):void 0,window:{title:b.title,width:Number.parseInt(b.width,10),height:Number.parseInt(b.height,10),frameless:b.frameless,alwaysOnTop:b.alwaysOnTop},systemTray:b.systemTray,menubarOnly:b.menubarOnly,category:b.category,copyright:b.copyright,minimumSystemVersion:b.minSystemVersion,infoPlist:kb(b.infoPlist),devTools:b.devTools,craftPath:b.craftPath,verbose:b.verbose});if(Q.success){if(console.log("\u2705 Build successful!"),console.log(` Output: ${Q.outputPath}`),Q.duration)console.log(` Duration: ${(Q.duration/1000).toFixed(2)}s`);if(U==="macos"&&Q.format==="app")console.log(`
166
166
  \uD83D\uDCA1 To run: open "${Q.outputPath}"`);else if(U==="linux"&&Q.format==="appimage")console.log(`
167
- \uD83D\uDCA1 To run: chmod +x "${Q.outputPath}" && "${Q.outputPath}"`)}else console.error(`\u274C Build failed: ${Q.error}`),w.exit(1)}catch(z){console.error(`\u274C Build error: ${z.message}`),w.exit(1)}}),E.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(x)=>{try{let{devCommand:b}=await import("./chunk-v02j99gh.js");await b({port:x.port?Number.parseInt(x.port,10):6006,open:x.open,host:x.host})}catch(b){console.error(`\u274C Story error: ${b.message}`),w.exit(1)}}),E.command("story:build","Build static story site").option("-o, --outDir <dir>","Output directory",{default:".stx/dist/story"}).example("stx story:build").example("stx story:build --outDir ./docs/components").action(async(x)=>{try{let{buildCommand:b}=await import("./chunk-7c1qq9zq.js");await b({outDir:x.outDir})}catch(b){console.error(`\u274C Story build error: ${b.message}`),w.exit(1)}}),E.command("story:test","Run visual regression tests").option("-u, --update","Update snapshots",{default:!1}).option("-f, --filter <name>","Filter components by name").example("stx story:test").example("stx story:test --update").example("stx story:test --filter Button").action(async(x)=>{try{let{createContext:b}=await import("./chunk-n43zq50e.js"),{runVisualTests:z,updateSnapshots:k,formatTestResults:j}=await import("./chunk-msmhta0w.js"),W=await b({mode:"build"});if(x.update){let H=await k(W,{filter:x.filter?[x.filter]:void 0});console.log(`Updated ${H} snapshots`)}else{let H=await z(W,{filter:x.filter?[x.filter]:void 0});if(console.log(j(H)),H.failed>0)w.exit(1)}}catch(b){console.error(`\u274C Story test error: ${b.message}`),w.exit(1)}}),E.command("compile <input>","Compile stx template to native Craft component code").option("--target <platform>","Target platform: macos, windows, linux, ios, android, universal",{default:"universal"}).option("--format <format>","Output format: zig, typescript, json",{default:"zig"}).option("--output <path>","Output directory for compiled files",{default:"./dist"}).option("--optimize","Enable optimizations",{default:!0}).option("--tree-shake","Enable tree shaking",{default:!0}).option("--hot-reload","Enable hot reload support",{default:!1}).option("--sourcemaps","Generate source maps",{default:!1}).option("--bundle","Bundle all dependencies",{default:!0}).option("--minify","Minify output",{default:!1}).option("--verbose","Show detailed output",{default:!1}).example("stx compile app.stx").example("stx compile app.stx --target macos --format zig").example("stx compile app.stx --format typescript --output ./native").example("stx compile app.stx --optimize --tree-shake --minify").action(async(x,b)=>{try{let{compileToNative:z}=await import("./chunk-322qz0cj.js"),k=$.resolve(x);if(!L.existsSync(k))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let j=["macos","windows","linux","ios","android","universal"];if(!j.includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error(`\uD83D\uDCA1 Available targets: ${j.join(", ")}`),w.exit(1);let W=["zig","typescript","json"];if(!W.includes(b.format))console.error(`\u274C Invalid format: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${W.join(", ")}`),w.exit(1);console.log(`
167
+ \uD83D\uDCA1 To run: chmod +x "${Q.outputPath}" && "${Q.outputPath}"`)}else console.error(`\u274C Build failed: ${Q.error}`),w.exit(1)}catch(z){console.error(`\u274C Build error: ${z.message}`),w.exit(1)}}),E.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(x)=>{try{let{devCommand:b}=await import("./chunk-cfj7y2tp.js");await b({port:x.port?Number.parseInt(x.port,10):6006,open:x.open,host:x.host})}catch(b){console.error(`\u274C Story error: ${b.message}`),w.exit(1)}}),E.command("story:build","Build static story site").option("-o, --outDir <dir>","Output directory",{default:".stx/dist/story"}).example("stx story:build").example("stx story:build --outDir ./docs/components").action(async(x)=>{try{let{buildCommand:b}=await import("./chunk-g38wktfx.js");await b({outDir:x.outDir})}catch(b){console.error(`\u274C Story build error: ${b.message}`),w.exit(1)}}),E.command("story:test","Run visual regression tests").option("-u, --update","Update snapshots",{default:!1}).option("-f, --filter <name>","Filter components by name").example("stx story:test").example("stx story:test --update").example("stx story:test --filter Button").action(async(x)=>{try{let{createContext:b}=await import("./chunk-mmhdgz5x.js"),{runVisualTests:z,updateSnapshots:k,formatTestResults:j}=await import("./chunk-fs5gwtd9.js"),W=await b({mode:"build"});if(x.update){let H=await k(W,{filter:x.filter?[x.filter]:void 0});console.log(`Updated ${H} snapshots`)}else{let H=await z(W,{filter:x.filter?[x.filter]:void 0});if(console.log(j(H)),H.failed>0)w.exit(1)}}catch(b){console.error(`\u274C Story test error: ${b.message}`),w.exit(1)}}),E.command("compile <input>","Compile stx template to native Craft component code").option("--target <platform>","Target platform: macos, windows, linux, ios, android, universal",{default:"universal"}).option("--format <format>","Output format: zig, typescript, json",{default:"zig"}).option("--output <path>","Output directory for compiled files",{default:"./dist"}).option("--optimize","Enable optimizations",{default:!0}).option("--tree-shake","Enable tree shaking",{default:!0}).option("--hot-reload","Enable hot reload support",{default:!1}).option("--sourcemaps","Generate source maps",{default:!1}).option("--bundle","Bundle all dependencies",{default:!0}).option("--minify","Minify output",{default:!1}).option("--verbose","Show detailed output",{default:!1}).example("stx compile app.stx").example("stx compile app.stx --target macos --format zig").example("stx compile app.stx --format typescript --output ./native").example("stx compile app.stx --optimize --tree-shake --minify").action(async(x,b)=>{try{let{compileToNative:z}=await import("./chunk-6r72pp2t.js"),k=$.resolve(x);if(!L.existsSync(k))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let j=["macos","windows","linux","ios","android","universal"];if(!j.includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error(`\uD83D\uDCA1 Available targets: ${j.join(", ")}`),w.exit(1);let W=["zig","typescript","json"];if(!W.includes(b.format))console.error(`\u274C Invalid format: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${W.join(", ")}`),w.exit(1);console.log(`
168
168
  \uD83D\uDD27 Compiling stx template to native code...`),console.log(` Input: ${x}`),console.log(` Target: ${b.target}`),console.log(` Format: ${b.format}`),console.log(` Output: ${b.output}
169
169
  `);let H=L.readFileSync(k,"utf-8"),U=await z(H,{target:b.target,format:b.format,optimize:b.optimize,treeShake:b.treeShake,hotReload:b.hotReload,debug:b.verbose,sourceMaps:b.sourcemaps,bundle:b.bundle,minify:b.minify}),Y=$.resolve(b.output);if(!L.existsSync(Y))L.mkdirSync(Y,{recursive:!0});let Q=$.basename(x,$.extname(x)),X=b.format==="typescript"?"ts":b.format==="json"?"json":"zig",_=$.join(Y,`${Q}.${X}`);L.writeFileSync(_,U.code);let q=$.join(Y,`${Q}.manifest.json`);if(L.writeFileSync(q,JSON.stringify(U.manifest,null,2)),b.sourcemaps&&U.sourceMaps){let O=$.join(Y,`${Q}.${X}.map`);L.writeFileSync(O,U.sourceMaps)}if(b.target==="universal"&&U.platformCode.size>0)for(let[O,M]of U.platformCode){let G=$.join(Y,`${Q}.${O}.${X}`);L.writeFileSync(G,M)}if(console.log("\u2705 Compilation successful!"),console.log(` Output: ${_}`),console.log(` Manifest: ${q}`),console.log(`
170
170
  \uD83D\uDCCA Statistics:`),console.log(` Compilation time: ${U.stats.compilationTime.toFixed(2)}ms`),console.log(` Total components: ${U.stats.totalComponents}`),console.log(` Native components: ${U.stats.nativeComponents}`),console.log(` Web fallback components: ${U.stats.webComponents}`),console.log(` Bundle size: ${(U.stats.bundleSize/1024).toFixed(2)}KB`),U.stats.warnings.length>0){console.log(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ek as Nj,fk as wj,gk as Aj}from"./chunk-pcvayb2f.js";import{ik as Uj,jk as Xj,kk as Yj,lk as Zj,mk as _j,nk as $j,ok as qj,pk as Fj,qk as Oj,rk as Vj,sk as Ij,tk as Qj,uk as Wj,vk as Kj}from"./chunk-ycgtkfbm.js";import"./chunk-s5wwa0t4.js";import"./chunk-spzbfqjn.js";import"./chunk-raxr83fs.js";import"./chunk-at84gyvf.js";import"./chunk-397rqs12.js";import"./chunk-aqrp68m6.js";import"./chunk-egr5663e.js";import"./chunk-jwnbwemq.js";import"./chunk-ry1key0g.js";import"./chunk-4ee1aaet.js";import"./chunk-wkcnyv6m.js";import"./chunk-18p8dqya.js";import"./chunk-64ttktzc.js";import"./chunk-xcsf7my7.js";import"./chunk-2kv2gnzc.js";import"./chunk-ttny9g8k.js";import"./chunk-bbq82jww.js";import"./chunk-9ebfmdyb.js";import"./chunk-jryjwara.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{ek as Nj,fk as wj,gk as Aj}from"./chunk-pcvayb2f.js";import{ik as Uj,jk as Xj,kk as Yj,lk as Zj,mk as _j,nk as $j,ok as qj,pk as Fj,qk as Oj,rk as Vj,sk as Ij,tk as Qj,uk as Wj,vk as Kj}from"./chunk-jgfkmkpb.js";import"./chunk-akefvpqr.js";import"./chunk-7kk2jb1j.js";import"./chunk-2btrq8sz.js";import"./chunk-z698hwht.js";import"./chunk-70zb3560.js";import"./chunk-zsapb653.js";import"./chunk-hrd56xw7.js";import"./chunk-hhjrtjc9.js";import"./chunk-sb2g9f73.js";import"./chunk-1r3ydhkx.js";import"./chunk-j8bwgnz5.js";import"./chunk-5mdvkpt8.js";import"./chunk-zeqktcby.js";import"./chunk-jtaxnnq3.js";import"./chunk-2925bmqr.js";import"./chunk-sr042pkc.js";import"./chunk-w913decg.js";import"./chunk-sqkz8tf3.js";import"./chunk-cey6rhqw.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{ek as Nj,fk as wj,gk as Aj}from"./chunk-pcvayb2f.js";import{ik as Uj,jk as Xj,kk as Yj,lk as Zj,mk as _j,nk as $j,ok as qj,pk as Fj,qk as Oj,rk as Vj,sk as Ij,tk as Qj,uk as Wj,vk as Kj}from"./chunk-ycgtkfbm.js";import"./chunk-s5wwa0t4.js";import"./chunk-spzbfqjn.js";import"./chunk-raxr83fs.js";import"./chunk-at84gyvf.js";import"./chunk-397rqs12.js";import"./chunk-aqrp68m6.js";import"./chunk-egr5663e.js";import"./chunk-jwnbwemq.js";import"./chunk-ry1key0g.js";import"./chunk-4ee1aaet.js";import"./chunk-wkcnyv6m.js";import"./chunk-18p8dqya.js";import"./chunk-64ttktzc.js";import"./chunk-xcsf7my7.js";import"./chunk-2kv2gnzc.js";import"./chunk-ttny9g8k.js";import"./chunk-bbq82jww.js";import"./chunk-9ebfmdyb.js";import"./chunk-jryjwara.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{ek as Nj,fk as wj,gk as Aj}from"./chunk-pcvayb2f.js";import{ik as Uj,jk as Xj,kk as Yj,lk as Zj,mk as _j,nk as $j,ok as qj,pk as Fj,qk as Oj,rk as Vj,sk as Ij,tk as Qj,uk as Wj,vk as Kj}from"./chunk-jgfkmkpb.js";import"./chunk-akefvpqr.js";import"./chunk-7kk2jb1j.js";import"./chunk-2btrq8sz.js";import"./chunk-z698hwht.js";import"./chunk-70zb3560.js";import"./chunk-zsapb653.js";import"./chunk-hrd56xw7.js";import"./chunk-hhjrtjc9.js";import"./chunk-sb2g9f73.js";import"./chunk-1r3ydhkx.js";import"./chunk-j8bwgnz5.js";import"./chunk-5mdvkpt8.js";import"./chunk-zeqktcby.js";import"./chunk-jtaxnnq3.js";import"./chunk-2925bmqr.js";import"./chunk-sr042pkc.js";import"./chunk-w913decg.js";import"./chunk-sqkz8tf3.js";import"./chunk-cey6rhqw.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{ew as Q}from"./chunk-jryjwara.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{jw as Q}from"./chunk-cey6rhqw.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};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Where the first script that can run sits in a rendered document.
3
+ *
4
+ * The signals runtime has to execute before every other script on the page,
5
+ * so both places that position it -- `injectSignalsRuntime` when it first
6
+ * goes in, and the relocation at the end of `processDirectives` -- insert it
7
+ * at the offset this returns.
8
+ *
9
+ * "First `<script`" is not the same thing as "first script that runs". A
10
+ * script inside a `<template>` is inert: it is template CONTENT, and executes
11
+ * only if something clones it into the document later. A runtime placed there
12
+ * never runs at all, so nothing defines `window.stx` and every page script
13
+ * dies on its first line. That is exactly what a bare layout produced: with no
14
+ * `<head>` script to anchor to, the first `<script` in the document was the
15
+ * one inside a component's `<template :if>`, and the runtime went in beside it
16
+ * (the Stacks `/login` page rendered blank with "Cannot destructure property
17
+ * 'navigate' of 'window.stx'").
18
+ *
19
+ * So a `<template>` is treated as one opaque unit. A script found inside one
20
+ * resolves to the start of the OUTERMOST enclosing template: ahead of that
21
+ * unit, the runtime still precedes everything in it and everything after it,
22
+ * and it is in the live document where it executes.
23
+ */
24
+ export declare function findFirstScriptTag(html: string): number;
@@ -0,0 +1,44 @@
1
+ const STYLE_OPEN_TAG = /<style\b[^>]*>/iy, STYLE_CLOSE_TAG = /<\/style>/gi, SCRIPT_OPEN_TAG = /<script\b[^>]*>/iy, TEMPLATE_OPEN_TAG = /<template(?=[\s>/])[^>]*>/iy, TEMPLATE_CLOSE_TAG = /<\/template\s*>/iy;
2
+ export function findFirstScriptTag(html) {
3
+ let searchFrom = 0, templateDepth = 0, outerTemplateStart = -1;
4
+ while (searchFrom < html.length) {
5
+ const tagStart = html.indexOf("<", searchFrom);
6
+ if (tagStart === -1)
7
+ return -1;
8
+ if (html.startsWith("<!--", tagStart)) {
9
+ const commentEnd = html.indexOf("-->", tagStart + 4);
10
+ searchFrom = commentEnd === -1 ? html.length : commentEnd + 3;
11
+ continue;
12
+ }
13
+ STYLE_OPEN_TAG.lastIndex = tagStart;
14
+ const styleTag = STYLE_OPEN_TAG.exec(html);
15
+ if (styleTag) {
16
+ STYLE_CLOSE_TAG.lastIndex = tagStart + styleTag[0].length;
17
+ const styleEnd = STYLE_CLOSE_TAG.exec(html);
18
+ searchFrom = styleEnd === null ? html.length : styleEnd.index + 8;
19
+ continue;
20
+ }
21
+ TEMPLATE_OPEN_TAG.lastIndex = tagStart;
22
+ const templateTag = TEMPLATE_OPEN_TAG.exec(html);
23
+ if (templateTag) {
24
+ if (templateDepth === 0)
25
+ outerTemplateStart = tagStart;
26
+ templateDepth++;
27
+ searchFrom = tagStart + templateTag[0].length;
28
+ continue;
29
+ }
30
+ TEMPLATE_CLOSE_TAG.lastIndex = tagStart;
31
+ const templateClose = TEMPLATE_CLOSE_TAG.exec(html);
32
+ if (templateClose) {
33
+ if (templateDepth > 0)
34
+ templateDepth--;
35
+ searchFrom = tagStart + templateClose[0].length;
36
+ continue;
37
+ }
38
+ SCRIPT_OPEN_TAG.lastIndex = tagStart;
39
+ if (SCRIPT_OPEN_TAG.test(html))
40
+ return templateDepth > 0 ? outerTemplateStart : tagStart;
41
+ searchFrom = tagStart + 1;
42
+ }
43
+ return -1;
44
+ }
@@ -66,6 +66,8 @@
66
66
  */
67
67
  import type { StxOptions } from './types';
68
68
  import { LRUCache } from './performance-utils';
69
+ /** Forget which partials were warned about, for tests. */
70
+ export declare function resetUnscopedSignalWarnings(): void;
69
71
  export declare const partialsCache: LRUCache<string, string>;
70
72
  export declare const onceStore: Set<string>;
71
73
  /**
package/dist/includes.js CHANGED
@@ -263,6 +263,10 @@ function addScopeToRootElement(html, scopeId) {
263
263
  return { html, mergedIntoExisting: null, stamped: !1, root: null };
264
264
  }
265
265
  let scopeIdCounter = 0;
266
+ const warnedUnscopedSignalPartials = new Set;
267
+ export function resetUnscopedSignalWarnings() {
268
+ warnedUnscopedSignalPartials.clear();
269
+ }
266
270
  function isDataBlockScript(attrs) {
267
271
  return /\btype\s*=\s*["'](?!(?:text\/javascript|application\/javascript|module)["'])[^"']*["']/i.test(attrs);
268
272
  }
@@ -610,7 +614,7 @@ export async function processIncludes(template, context, filePath, options, depe
610
614
  for (const [key, value] of Object.entries(localVars))
611
615
  includeContext[key] = value;
612
616
  const scriptRegex = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi, scriptMatches = [...partialContent.matchAll(scriptRegex)];
613
- let preservedScript = "", signalScopeId = null;
617
+ let preservedScript = "", signalScopeId = null, declaresSignals = !1;
614
618
  for (const scriptMatch of scriptMatches) {
615
619
  const scriptAttrs = scriptMatch[1] || "";
616
620
  let scriptContent = scriptMatch[2] || "";
@@ -653,6 +657,7 @@ export async function processIncludes(template, context, filePath, options, depe
653
657
  }
654
658
  const isSignalScript = hasSignalApis(scriptContent);
655
659
  if (isSignalScript && !isServerScript) {
660
+ declaresSignals = !0;
656
661
  signalScopeId = `stx_scope_${path.basename(includeFilePath, ".stx").replace(/[^a-zA-Z0-9]/g, "_")}_${++scopeIdCounter}`;
657
662
  const resolvedContent = transformStoreImports(scriptContent), transformedScript = transformScopedScript(resolvedContent, signalScopeId);
658
663
  preservedScript += `${vendorStyleTags}<script data-stx-scoped data-stx-run="always" data-stx-owner="${signalScopeId}">${transformedScript}</script>
@@ -689,16 +694,19 @@ export async function processIncludes(template, context, filePath, options, depe
689
694
  const from = signalScopeId, to = scopeResult.mergedIntoExisting;
690
695
  preservedScript = preservedScript.split(`'${from}'`).join(`'${to}'`).split(`"${from}"`).join(`"${to}"`);
691
696
  signalScopeId = to;
692
- } else if (!scopeResult.stamped)
697
+ } else if (!scopeResult.stamped && declaresSignals && !warnedUnscopedSignalPartials.has(includeFilePath)) {
698
+ warnedUnscopedSignalPartials.add(includeFilePath);
693
699
  console.warn(`[stx] ${path.relative(process.cwd(), includeFilePath)} declares signals but has no element to scope them to, so nothing in it will hydrate. Wrap the partial's markup in a single root element.`);
700
+ }
694
701
  const ownsRoot = scopeResult.stamped && scopeResult.root !== null && rendersAsElement(scopeResult.root);
695
702
  preservedScript = keepOwnerStampOf(preservedScript, ownsRoot ? signalScopeId : null);
696
703
  }
697
704
  if (workingContent.includes("@include") || workingContent.includes("@partial"))
698
705
  workingContent = await processIncludes(workingContent, includeContext, includeFilePath, options, dependencies, includeStack);
699
- const { processLoops } = await import("./loops.js");
700
- let processedContent = processLoops(workingContent, includeContext, includeFilePath);
706
+ const { processLoops, reportDeferredLoopWarnings } = await import("./loops.js");
707
+ let processedContent = processLoops(workingContent, includeContext, includeFilePath, void 0, !0);
701
708
  processedContent = processConditionals(processedContent, includeContext, includeFilePath);
709
+ processedContent = reportDeferredLoopWarnings(processedContent);
702
710
  processedContent = processExpressions(processedContent, includeContext, includeFilePath);
703
711
  if (preservedStyle)
704
712
  processedContent += `
package/dist/loops.d.ts CHANGED
@@ -88,4 +88,18 @@ export declare function parseLoopBinding(params: string): {
88
88
  arrayExpr: string;
89
89
  itemVar: string;
90
90
  } | null;
91
- export declare function processLoops(template: string, context: Record<string, any>, filePath: string, options?: StxOptions): string;
91
+ /**
92
+ * Print the "not iterable" warning for every loop still in `html`, and strip
93
+ * the markers. Call it after the conditionals around the loops are decided.
94
+ */
95
+ export declare function reportDeferredLoopWarnings(html: string): string;
96
+ /**
97
+ * Expand `@forelse`, `@foreach`, `@for` and `@while`.
98
+ *
99
+ * `deferWarnings` is for callers that decide the surrounding conditionals
100
+ * afterwards: the "not iterable" warning is then left in the output as a marker
101
+ * for `reportDeferredLoopWarnings`, so a loop in a branch that loses stays
102
+ * quiet. Without it the warning is reported before this returns, still
103
+ * skipping loops whose branch lost inside an enclosing iteration.
104
+ */
105
+ export declare function processLoops(template: string, context: Record<string, any>, filePath: string, options?: StxOptions, deferWarnings?: boolean): string;
package/dist/loops.js CHANGED
@@ -355,7 +355,22 @@ export function parseLoopBinding(params) {
355
355
  const itemVar = inMatch[1].trim().replace(/^\(([\s\S]*)\)$/, "$1").trim(), arrayExpr = inMatch[2].trim();
356
356
  return itemVar && arrayExpr ? { arrayExpr, itemVar } : null;
357
357
  }
358
- export function processLoops(template, context, filePath, options) {
358
+ const NOT_ITERABLE_PREFIX = "<!--stx:foreach-not-iterable:", NOT_ITERABLE_MARK = /<!--stx:foreach-not-iterable:([^|>]*)\|([^>]*?)-->/g;
359
+ function notIterableMark(arrayExpr, filePath) {
360
+ return `${NOT_ITERABLE_PREFIX}${encodeURIComponent(arrayExpr)}|${encodeURIComponent(filePath)}-->`;
361
+ }
362
+ function warnNotIterable(arrayExpr, filePath) {
363
+ console.warn(`[stx] @foreach(${arrayExpr}) in ${filePath}: ${arrayExpr} is not iterable server-side, so the loop rendered nothing. ` + "Values a server loop reads must come from <script server> or the page context \u2014 " + "a plain <script> runs in the browser.");
364
+ }
365
+ export function reportDeferredLoopWarnings(html) {
366
+ if (!html.includes(NOT_ITERABLE_PREFIX))
367
+ return html;
368
+ return html.replace(NOT_ITERABLE_MARK, (_, arrayExpr, filePath) => {
369
+ warnNotIterable(decodeURIComponent(arrayExpr), decodeURIComponent(filePath));
370
+ return "";
371
+ });
372
+ }
373
+ export function processLoops(template, context, filePath, options, deferWarnings = !1) {
359
374
  let output = template;
360
375
  output = processForelse(output, context);
361
376
  function findMatchingForeach(template) {
@@ -432,8 +447,7 @@ export function processLoops(template, context, filePath, options) {
432
447
  array = Object.entries(array);
433
448
  isObjectEntries = !0;
434
449
  } else {
435
- console.warn(`[stx] @foreach(${trimmedArrayExpr}) in ${filePath}: ${trimmedArrayExpr} is not iterable server-side, so the loop rendered nothing. ` + "Values a server loop reads must come from <script server> or the page context \u2014 " + "a plain <script> runs in the browser.");
436
- const errorMsg = inlineError("Foreach", `Error in @foreach: ${trimmedArrayExpr} is not iterable`, ErrorCodes.TYPE_ERROR);
450
+ const errorMsg = notIterableMark(trimmedArrayExpr, filePath) + inlineError("Foreach", `Error in @foreach: ${trimmedArrayExpr} is not iterable`, ErrorCodes.TYPE_ERROR);
437
451
  result = result.substring(0, start) + errorMsg + result.substring(end);
438
452
  continue;
439
453
  }
@@ -529,7 +543,7 @@ export function processLoops(template, context, filePath, options) {
529
543
  output = processForLoops(output, context, filePath, options);
530
544
  const maxWhileIterations = options?.loops?.maxWhileIterations ?? DEFAULT_MAX_WHILE_ITERATIONS;
531
545
  output = processWhileLoops(output, context, maxWhileIterations);
532
- return output;
546
+ return deferWarnings ? output : reportDeferredLoopWarnings(output);
533
547
  }
534
548
  function validateForExpression(expr) {
535
549
  return isForExpressionSafe(expr);