@stacksjs/stx 0.2.422 → 0.2.424
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.
- package/dist/{chunk-ep5jnqdb.js → chunk-02n071n7.js} +6 -6
- package/dist/chunk-03n23sh6.js +2 -0
- package/dist/chunk-07mxghsz.js +2 -0
- package/dist/{chunk-kjkwycce.js → chunk-0bmc75w6.js} +4 -4
- package/dist/{chunk-hyak4dzg.js → chunk-0hhq9hbq.js} +3 -3
- package/dist/{chunk-66k7yxnr.js → chunk-12pvnn1e.js} +4 -4
- package/dist/chunk-1497wcxc.js +2 -0
- package/dist/chunk-17n9e5wk.js +2 -0
- package/dist/chunk-1p8hc1ve.js +2 -0
- package/dist/chunk-1r3ghgsz.js +2 -0
- package/dist/{chunk-681cxw8j.js → chunk-24e7qjb8.js} +2 -2
- package/dist/chunk-259ecbwa.js +2 -0
- package/dist/chunk-26gfsa9w.js +2 -0
- package/dist/{chunk-zp0mg8b2.js → chunk-2bpjq1qz.js} +2 -2
- package/dist/{chunk-11ra3sbc.js → chunk-2x9jd5w0.js} +3 -3
- package/dist/{chunk-k31fwm2w.js → chunk-3hmy75tw.js} +5 -5
- package/dist/{chunk-12b8akfg.js → chunk-3pxp0r0a.js} +3 -3
- package/dist/{chunk-x5ks23vx.js → chunk-3ry9ca1s.js} +2 -2
- package/dist/{chunk-th9s15es.js → chunk-45rfv3a5.js} +2 -2
- package/dist/chunk-47apfsxp.js +2 -0
- package/dist/{chunk-w72p2ak0.js → chunk-48kgnqpk.js} +4 -4
- package/dist/{chunk-rsxvbnp4.js → chunk-4hd5wb8x.js} +3 -3
- package/dist/chunk-535nrr6j.js +2 -0
- package/dist/chunk-5mfhk69g.js +2 -0
- package/dist/{chunk-aync8qmk.js → chunk-5vwg3h5g.js} +2 -2
- package/dist/{chunk-tspmynvh.js → chunk-62chbqev.js} +1 -1
- package/dist/chunk-6c7294j8.js +2 -0
- package/dist/{chunk-qwgdtrhj.js → chunk-6cbvx87h.js} +5 -5
- package/dist/{chunk-q0cehgy2.js → chunk-6fsbny9m.js} +3 -3
- package/dist/chunk-6gh2rvyz.js +2 -0
- package/dist/chunk-6j6gbp0y.js +2 -0
- package/dist/chunk-6jgjmycb.js +2 -0
- package/dist/{chunk-w83djypm.js → chunk-6t278w29.js} +2 -2
- package/dist/{chunk-5vfyxxrp.js → chunk-6t7mxb0b.js} +2 -2
- package/dist/chunk-6wmxrn6x.js +2 -0
- package/dist/chunk-6wweqfg7.js +2 -0
- package/dist/{chunk-ja7znxnz.js → chunk-7a9h7ycs.js} +5 -5
- package/dist/chunk-7pbv9mg7.js +2 -0
- package/dist/{chunk-09hhrjk9.js → chunk-89b2r1q0.js} +6 -6
- package/dist/{chunk-0varh725.js → chunk-8a0r2j8f.js} +3 -3
- package/dist/{chunk-gp8xzbyt.js → chunk-8nsbf2mz.js} +1074 -1074
- package/dist/{chunk-mg13q1kd.js → chunk-8zf5q1m3.js} +2 -2
- package/dist/chunk-9d53d0t6.js +2 -0
- package/dist/chunk-9j72har9.js +2 -0
- package/dist/chunk-9yqz5ge5.js +2 -0
- package/dist/chunk-a5c9n7an.js +2 -0
- package/dist/chunk-a836zn7c.js +2 -0
- package/dist/{chunk-kzkjc12e.js → chunk-a8g6y9kw.js} +5 -5
- package/dist/{chunk-21a7p956.js → chunk-acwgap78.js} +1 -1
- package/dist/{chunk-qx3js9tk.js → chunk-aen2baze.js} +1 -1
- package/dist/chunk-ahgrkva8.js +2 -0
- package/dist/chunk-akbb6j7s.js +2 -0
- package/dist/chunk-avakcrbs.js +2 -0
- package/dist/{chunk-tafebmtg.js → chunk-axydabse.js} +2 -2
- package/dist/{chunk-4n6c5rp5.js → chunk-b7973zvk.js} +2 -2
- package/dist/{chunk-ebkpdc45.js → chunk-bxwe7wxj.js} +10 -10
- package/dist/{chunk-2ewa2sg5.js → chunk-c1dmr865.js} +3 -3
- package/dist/chunk-cenq2n6e.js +2 -0
- package/dist/{chunk-zvh2nnzr.js → chunk-cf6htz63.js} +1 -1
- package/dist/chunk-cnmz9543.js +2 -0
- package/dist/{chunk-h1585jbm.js → chunk-cx2rdew4.js} +13 -13
- package/dist/{chunk-wg1ttvs5.js → chunk-cznsm2n3.js} +2 -2
- package/dist/chunk-d1qzhawc.js +2 -0
- package/dist/chunk-d6hnvwre.js +2 -0
- package/dist/{chunk-7abgzdsm.js → chunk-dcwjxq8n.js} +2 -2
- package/dist/chunk-dhqwg62x.js +2 -0
- package/dist/{chunk-95e3rz88.js → chunk-dmd6yk2x.js} +5 -5
- package/dist/chunk-e18qfegt.js +2 -0
- package/dist/chunk-eej89wkt.js +2 -0
- package/dist/chunk-ekxffxbd.js +2 -0
- package/dist/{chunk-hy9e3ny6.js → chunk-ex0tq6x2.js} +1 -1
- package/dist/{chunk-nqr77pxk.js → chunk-fg5ve6ey.js} +2 -2
- package/dist/{chunk-dejsjk4h.js → chunk-fnt1q1sp.js} +11 -11
- package/dist/chunk-g67gg66e.js +2 -0
- package/dist/chunk-gq16fxc2.js +2 -0
- package/dist/{chunk-5e9zkd65.js → chunk-h3c7z73m.js} +2 -2
- package/dist/chunk-h4avjh3q.js +2 -0
- package/dist/chunk-h7qte7ye.js +2 -0
- package/dist/{chunk-hmdnn9ja.js → chunk-hb9gxad0.js} +3 -3
- package/dist/{chunk-dmxh7zwq.js → chunk-hg4k3nkr.js} +1 -1
- package/dist/{chunk-dhxbjw6k.js → chunk-hnep9jbj.js} +2 -2
- package/dist/chunk-hwycbxg7.js +2 -0
- package/dist/{chunk-34gy5zjm.js → chunk-j1q65enz.js} +2 -2
- package/dist/chunk-j5myfxe8.js +18 -0
- package/dist/{chunk-8jqy69td.js → chunk-j7zywbq0.js} +2 -2
- package/dist/{chunk-788g87ft.js → chunk-jbrdebzs.js} +7 -7
- package/dist/{chunk-wr6b99pw.js → chunk-jj4pyeyj.js} +1 -1
- package/dist/{chunk-g1fxmp9z.js → chunk-k8sqs7j2.js} +4 -4
- package/dist/chunk-mg7jhx5v.js +2 -0
- package/dist/chunk-n16wa755.js +2 -0
- package/dist/chunk-ngv1c807.js +2 -0
- package/dist/{chunk-krr2vb0s.js → chunk-p2x7tjbt.js} +3 -3
- package/dist/{chunk-62r4fa4q.js → chunk-ptjqacjd.js} +2 -2
- package/dist/{chunk-597rfddk.js → chunk-qm1tt8g1.js} +2334 -2334
- package/dist/chunk-r7r5h2eh.js +2 -0
- package/dist/chunk-rhkx17d9.js +2 -0
- package/dist/{chunk-b1fg9vg7.js → chunk-s28eh0jn.js} +2 -2
- package/dist/{chunk-837nb4zv.js → chunk-s295vp9x.js} +3 -3
- package/dist/chunk-sazpw71r.js +4 -0
- package/dist/{chunk-20tdz0zs.js → chunk-sbdzqqr1.js} +6 -6
- package/dist/{chunk-qby6wxat.js → chunk-spx27cs4.js} +2 -2
- package/dist/{chunk-n7jjp08m.js → chunk-stxmwytg.js} +2 -2
- package/dist/{chunk-2tfe2g58.js → chunk-t3wh1jbk.js} +6 -6
- package/dist/{chunk-802pr252.js → chunk-tfexmdkt.js} +2 -2
- package/dist/{chunk-2cn8krpp.js → chunk-tfz95n7j.js} +5 -5
- package/dist/chunk-thdbqsxq.js +2 -0
- package/dist/chunk-tpnfcb83.js +2 -0
- package/dist/chunk-tqkv4th9.js +2 -0
- package/dist/chunk-tznejj9h.js +2 -0
- package/dist/{chunk-ap6fehea.js → chunk-vfk725vm.js} +5 -5
- package/dist/chunk-vsrm9k7p.js +2 -0
- package/dist/chunk-vwms759h.js +2 -0
- package/dist/{chunk-xvzxrt9a.js → chunk-w2085fwx.js} +5 -5
- package/dist/chunk-w252cgnv.js +30 -0
- package/dist/chunk-whdw6dhb.js +2 -0
- package/dist/chunk-wtms9jhs.js +3 -0
- package/dist/chunk-wtqjfar3.js +2 -0
- package/dist/chunk-wx7kfet5.js +2 -0
- package/dist/chunk-wy873fy8.js +2 -0
- package/dist/{chunk-d2z6828s.js → chunk-xa3wsmt5.js} +11 -11
- package/dist/chunk-xrbqf77j.js +2 -0
- package/dist/{chunk-757ec865.js → chunk-yaebdyfr.js} +2 -2
- package/dist/chunk-ycpq3gxc.js +2 -0
- package/dist/chunk-yd50awqp.js +3 -0
- package/dist/{chunk-csjw5esc.js → chunk-ydz7w2mt.js} +2 -2
- package/dist/chunk-yjgbxf26.js +2 -0
- package/dist/{chunk-jjnfj9nf.js → chunk-yqsza22w.js} +2 -2
- package/dist/{chunk-3xm6dyab.js → chunk-zbr333kf.js} +88 -27
- package/dist/chunk-zcyjdcpx.js +33 -0
- package/dist/{chunk-tqnysw0k.js → chunk-zfzcedw4.js} +4 -4
- package/dist/chunk-zm73n103.js +2 -0
- package/dist/cli.js +20 -20
- package/dist/component-renderer.js +54 -2
- package/dist/composables/use-outbox.d.ts +1 -0
- package/dist/composables/use-outbox.js +23 -10
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/database.js +2 -2
- package/dist/native/bridge/protocol.d.ts +5 -0
- package/dist/native/bridge/protocol.js +3 -0
- package/dist/native/cli.js +12 -2
- package/dist/native/compiler/bundle.d.ts +4 -3
- package/dist/native/compiler/bundle.js +46 -51
- package/dist/native/compiler/component-mapping.d.ts +5 -0
- package/dist/native/compiler/component-mapping.js +90 -0
- package/dist/native/compiler/html-to-ir.js +42 -6
- package/dist/native/compiler/ir.d.ts +2 -0
- package/dist/native/compiler/render-screen.d.ts +4 -0
- package/dist/native/compiler/render-screen.js +10 -2
- package/dist/native/compiler/setup-script.d.ts +6 -0
- package/dist/native/compiler/setup-script.js +10 -0
- package/dist/native/components/primitives.d.ts +10 -0
- package/dist/native/index.d.ts +6 -24
- package/dist/native/index.js +1 -17
- package/dist/native/primitives/Button.stx +2 -1
- package/dist/native/primitives/Text.stx +2 -1
- package/dist/native/primitives/TextInput.stx +3 -1
- package/dist/native/prop-names.d.ts +2 -0
- package/dist/native/prop-names.js +71 -0
- package/dist/native/runtime/binding-tree.d.ts +31 -0
- package/dist/native/runtime/binding-tree.js +100 -0
- package/dist/native/runtime/craft-bridge.d.ts +9 -0
- package/dist/native/runtime/craft-bridge.js +231 -0
- package/dist/native/runtime/craft.d.ts +28 -3
- package/dist/native/runtime/jsc-globals.d.ts +16 -0
- package/dist/native/runtime/jsc-globals.js +64 -0
- package/dist/native/runtime/native-host.d.ts +3 -1
- package/dist/native/runtime/native-host.js +183 -33
- package/dist/native/runtime/shared-screen.d.ts +15 -0
- package/dist/native/runtime/shared-screen.js +41 -0
- package/dist/pwa.js +3 -3
- package/dist/signal-processing.d.ts +3 -1
- package/dist/signal-processing.js +4 -3
- package/dist/signals.js +77 -16
- package/dist/ssg.js +28 -28
- package/package.json +5 -5
- package/dist/chunk-10fh9qhe.js +0 -2
- package/dist/chunk-1569v24d.js +0 -2
- package/dist/chunk-18awnp9d.js +0 -2
- package/dist/chunk-1r0c5920.js +0 -30
- package/dist/chunk-2hswgxpb.js +0 -2
- package/dist/chunk-4363reg4.js +0 -2
- package/dist/chunk-48axv7bm.js +0 -2
- package/dist/chunk-50hgr79y.js +0 -2
- package/dist/chunk-54wczcee.js +0 -2
- package/dist/chunk-74gz26zs.js +0 -2
- package/dist/chunk-7906p8zs.js +0 -2
- package/dist/chunk-7dkfjmjw.js +0 -2
- package/dist/chunk-7vr5w75r.js +0 -4
- package/dist/chunk-7zn0yyqk.js +0 -2
- package/dist/chunk-8d2kamh2.js +0 -2
- package/dist/chunk-8ttvazck.js +0 -2
- package/dist/chunk-8y4bqsxz.js +0 -2
- package/dist/chunk-9bpnz431.js +0 -2
- package/dist/chunk-ac033b93.js +0 -2
- package/dist/chunk-aj43359g.js +0 -2
- package/dist/chunk-aj8yq228.js +0 -2
- package/dist/chunk-as72dvvm.js +0 -2
- package/dist/chunk-bfvaxrq0.js +0 -2
- package/dist/chunk-bkaw7sgz.js +0 -2
- package/dist/chunk-d0q2x8e3.js +0 -2
- package/dist/chunk-d2c5727w.js +0 -2
- package/dist/chunk-d5amzers.js +0 -2
- package/dist/chunk-dfchrqw5.js +0 -2
- package/dist/chunk-epv0ahg1.js +0 -2
- package/dist/chunk-f5489ese.js +0 -2
- package/dist/chunk-fqq1w9m1.js +0 -2
- package/dist/chunk-hcgsgnq8.js +0 -2
- package/dist/chunk-hgqcqg1h.js +0 -2
- package/dist/chunk-hjdwf9gp.js +0 -2
- package/dist/chunk-hp7ewdnp.js +0 -2
- package/dist/chunk-jjtzm6dn.js +0 -3
- package/dist/chunk-js79j12f.js +0 -18
- package/dist/chunk-kfsp322p.js +0 -2
- package/dist/chunk-kt557jaj.js +0 -2
- package/dist/chunk-n8kqvzba.js +0 -2
- package/dist/chunk-na70r4sp.js +0 -2
- package/dist/chunk-p083sckk.js +0 -2
- package/dist/chunk-pc178389.js +0 -2
- package/dist/chunk-psqk7932.js +0 -2
- package/dist/chunk-pv5nr9pd.js +0 -2
- package/dist/chunk-q1v0jwr4.js +0 -2
- package/dist/chunk-qeye0901.js +0 -2
- package/dist/chunk-qy59yp2v.js +0 -2
- package/dist/chunk-r5gjb55x.js +0 -2
- package/dist/chunk-tf44jyrh.js +0 -2
- package/dist/chunk-tfypkw4y.js +0 -3
- package/dist/chunk-vv4kkwhn.js +0 -2
- package/dist/chunk-vwhd3h8x.js +0 -2
- package/dist/chunk-vxj8kd2v.js +0 -2
- package/dist/chunk-vzzpvn21.js +0 -2
- package/dist/chunk-w1a2v264.js +0 -2
- package/dist/chunk-wcs7w8wv.js +0 -2
- package/dist/chunk-x6ndnpvr.js +0 -2
- package/dist/chunk-x8rckpyz.js +0 -2
- package/dist/chunk-ya0qecph.js +0 -27
- package/dist/chunk-ykwmqh8z.js +0 -2
- package/dist/chunk-ys71pmrb.js +0 -2
- package/dist/chunk-z5y4qyhg.js +0 -2
- package/dist/chunk-zpcz2kh6.js +0 -2
- package/dist/native/compiler/codegen.d.ts +0 -10
- package/dist/native/compiler/codegen.js +0 -145
- package/dist/native/compiler/parser.d.ts +0 -88
- package/dist/native/compiler/parser.js +0 -753
- package/dist/native/runtime/entry.d.ts +0 -1
- package/dist/native/runtime/entry.js +0 -3
- package/dist/native/runtime/index.d.ts +0 -45
- package/dist/native/runtime/index.js +0 -165
- package/dist/native/runtime/screen.d.ts +0 -43
- package/dist/native/runtime/screen.js +0 -808
package/dist/craft-entry.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Lr,xi,Si}from"./chunk-0hhq9hbq.js";import"./chunk-89b2r1q0.js";import"./chunk-3ry9ca1s.js";import"./chunk-12pvnn1e.js";import"./chunk-yaebdyfr.js";import"./chunk-axydabse.js";import"./chunk-qm1tt8g1.js";import"./chunk-48kgnqpk.js";import"./chunk-jbrdebzs.js";import"./chunk-ptjqacjd.js";import"./chunk-h3c7z73m.js";import"./chunk-b7973zvk.js";import"./chunk-k8sqs7j2.js";import{ou,gi,au,cu,mi,Nr,hi,lu,yi,uu,du,bi,vi,wi}from"./chunk-fnt1q1sp.js";import"./chunk-j5myfxe8.js";import"./chunk-2x9jd5w0.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|
|
6
6
|
`),hydrationData:i,metadata:{renderTime:s,cacheHit:!1,totalSize:a.length,componentCount:t.metadata.componentCount}}}function V(t,e){let n=[],r=[],a=[],i=new Map,s=[];return y(t.tree,(o,c)=>{if(o.type==="component"&&o.componentName){if(T(o.componentName))n.push(o.componentName)}if(o.type==="element"&&o.tag){let p=J(o);if(p)s.push(p);if(o.props){for(let[l,f]of Object.entries(o.props))if(l.startsWith("on")&&typeof f==="string"){let g=`handler_${i.size}`;i.set(g,f)}}}if(o.isStatic&&o.type==="element")r.push(b(o));else if(!o.isStatic&&o.type!=="text")a.push(o.tag||o.componentName||"unknown")}),{nativeComponents:n,staticHTML:r,dynamicParts:a,eventHandlers:i,nativeWidgets:s}}function Y(t,e={}){let n=R(t),r=P(n,e),a=new Map,i=[];return y(n.tree,(s)=>{if(s.type==="component"&&s.componentName){if(T(s.componentName)){i.push(s.componentName);let o=`<!--craft:${s.componentName}:${s.hydrationKey||"default"}-->`;a.set(s.hydrationKey||s.componentName,o)}}}),{staticHTML:r,dynamicPlaceholders:a,craftComponents:i}}function M(t){let e={type:"fragment",children:[]},n=e,r=[e],a=t,i=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);while(a.length>0){let s=a.match(/^<(@?[\w-]+)([^>]*)>/);if(s){let[p,l,f]=s,g=z(f),u=l.startsWith("@craft-"),C=u?l:l.toLowerCase(),S={type:u?"component":"element",tag:C,props:g,children:[],componentName:u?C.slice(1):void 0,isStatic:!v(f),hydrationKey:F()};if(n.children=n.children||[],n.children.push(S),!i.has(C)&&!f.endsWith("/"))r.push(S),n=S;a=a.slice(p.length);continue}let o=a.match(/^<\/(@?[\w-]+)>/);if(o){let[p,l]=o,g=l.startsWith("@craft-")?l:l.toLowerCase();while(r.length>1){let u=r.pop();if(n=r[r.length-1],u.tag===g)break}a=a.slice(p.length);continue}let c=a.match(/^[^<]+/);if(c){let p=c[0];if(p.trim()){let l={type:"text",text:p,isStatic:!v(p)};n.children=n.children||[],n.children.push(l)}a=a.slice(p.length);continue}a=a.slice(1)}return e}function z(t){let e={},n=/([\w-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,r;while((r=n.exec(t))!==null){let[,a,i,s,o]=r,c=i??s??o??!0;e[a]=c}return e}function y(t,e,n=[]){if(e(t,n),t.children)t.children.forEach((r,a)=>{y(r,e,[...n,`${a}`])})}function h(t,e){switch(t.type){case"text":return x(t.text||"",e);case"element":case"component":{let n=t.tag||"div",r=N(t.props||{},e),a=(t.children||[]).map((i)=>h(i,e)).join("");if(!t.children||t.children.length===0){if(["input","br","hr","img","meta","link"].includes(n))return`<${n}${r} />`}return`<${n}${r}>${a}</${n}>`}case"fragment":return(t.children||[]).map((n)=>h(n,e)).join("");case"slot":return`<!--slot:${t.slotName||"default"}-->`;default:return""}}function b(t){if(t.type==="text")return t.text||"";let e=t.tag||"div",n=N(t.props||{},{});return`<${e}${n}></${e}>`}function N(t,e){let n=[];for(let[r,a]of Object.entries(t))if(a===!0)n.push(` ${r}`);else if(a!==!1&&a!==null&&a!==void 0){let i=x(String(a),e);n.push(` ${r}="${k(i)}"`)}return n.join("")}async function H(t,e){return h(t,e)}function P(t,e){let n=[];return y(t.tree,(r)=>{if(r.isStatic)n.push(h(r,e))}),n.join("")}function j(t,e,n){let r={templateId:e.id,context:n,dynamicParts:Array.from(e.dynamicParts.entries())},a=`
|
|
7
7
|
<script data-craft-hydration>
|
|
8
8
|
window.__CRAFT_HYDRATION__ = ${JSON.stringify(r)};
|
|
9
|
-
</script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{
|
|
9
|
+
</script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{ou as CRAFT_BRIDGE_SCRIPT,Nr as CRAFT_COMPONENTS,lu as CRAFT_COMPONENT_RUNTIME,hi as CRAFT_COMPONENT_STYLES,Lr as NATIVE_COMPONENTS,bi as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,xi as compileToNative,Si as createHotReloadServer,gi as generateCraftBridgeScript,V as generateCraftOptimizations,wi as getAvailableFormats,vi as getAvailableTargets,du as getCraftComponents,G as getSSRCacheStats,mi as injectCraftBridge,au as isCraftEnvironment,Y as prerenderForCraft,yi as processCraftComponents,cu as processCraftDirective,uu as registerCraftComponent,Q as renderSSR};
|
package/dist/craft.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Lr,xi,Si}from"./chunk-0hhq9hbq.js";import"./chunk-89b2r1q0.js";import"./chunk-3ry9ca1s.js";import"./chunk-12pvnn1e.js";import"./chunk-yaebdyfr.js";import"./chunk-axydabse.js";import"./chunk-qm1tt8g1.js";import"./chunk-48kgnqpk.js";import"./chunk-jbrdebzs.js";import"./chunk-ptjqacjd.js";import"./chunk-h3c7z73m.js";import"./chunk-b7973zvk.js";import"./chunk-k8sqs7j2.js";import{ou,gi,au,cu,mi,Nr,hi,lu,yi,uu,du,bi,vi,wi}from"./chunk-fnt1q1sp.js";import"./chunk-j5myfxe8.js";import"./chunk-2x9jd5w0.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|
|
6
6
|
`),hydrationData:i,metadata:{renderTime:s,cacheHit:!1,totalSize:a.length,componentCount:t.metadata.componentCount}}}function V(t,e){let n=[],r=[],a=[],i=new Map,s=[];return y(t.tree,(o,c)=>{if(o.type==="component"&&o.componentName){if(T(o.componentName))n.push(o.componentName)}if(o.type==="element"&&o.tag){let p=J(o);if(p)s.push(p);if(o.props){for(let[l,f]of Object.entries(o.props))if(l.startsWith("on")&&typeof f==="string"){let g=`handler_${i.size}`;i.set(g,f)}}}if(o.isStatic&&o.type==="element")r.push(b(o));else if(!o.isStatic&&o.type!=="text")a.push(o.tag||o.componentName||"unknown")}),{nativeComponents:n,staticHTML:r,dynamicParts:a,eventHandlers:i,nativeWidgets:s}}function Y(t,e={}){let n=R(t),r=P(n,e),a=new Map,i=[];return y(n.tree,(s)=>{if(s.type==="component"&&s.componentName){if(T(s.componentName)){i.push(s.componentName);let o=`<!--craft:${s.componentName}:${s.hydrationKey||"default"}-->`;a.set(s.hydrationKey||s.componentName,o)}}}),{staticHTML:r,dynamicPlaceholders:a,craftComponents:i}}function M(t){let e={type:"fragment",children:[]},n=e,r=[e],a=t,i=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);while(a.length>0){let s=a.match(/^<(@?[\w-]+)([^>]*)>/);if(s){let[p,l,f]=s,g=z(f),u=l.startsWith("@craft-"),C=u?l:l.toLowerCase(),S={type:u?"component":"element",tag:C,props:g,children:[],componentName:u?C.slice(1):void 0,isStatic:!v(f),hydrationKey:F()};if(n.children=n.children||[],n.children.push(S),!i.has(C)&&!f.endsWith("/"))r.push(S),n=S;a=a.slice(p.length);continue}let o=a.match(/^<\/(@?[\w-]+)>/);if(o){let[p,l]=o,g=l.startsWith("@craft-")?l:l.toLowerCase();while(r.length>1){let u=r.pop();if(n=r[r.length-1],u.tag===g)break}a=a.slice(p.length);continue}let c=a.match(/^[^<]+/);if(c){let p=c[0];if(p.trim()){let l={type:"text",text:p,isStatic:!v(p)};n.children=n.children||[],n.children.push(l)}a=a.slice(p.length);continue}a=a.slice(1)}return e}function z(t){let e={},n=/([\w-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,r;while((r=n.exec(t))!==null){let[,a,i,s,o]=r,c=i??s??o??!0;e[a]=c}return e}function y(t,e,n=[]){if(e(t,n),t.children)t.children.forEach((r,a)=>{y(r,e,[...n,`${a}`])})}function h(t,e){switch(t.type){case"text":return x(t.text||"",e);case"element":case"component":{let n=t.tag||"div",r=N(t.props||{},e),a=(t.children||[]).map((i)=>h(i,e)).join("");if(!t.children||t.children.length===0){if(["input","br","hr","img","meta","link"].includes(n))return`<${n}${r} />`}return`<${n}${r}>${a}</${n}>`}case"fragment":return(t.children||[]).map((n)=>h(n,e)).join("");case"slot":return`<!--slot:${t.slotName||"default"}-->`;default:return""}}function b(t){if(t.type==="text")return t.text||"";let e=t.tag||"div",n=N(t.props||{},{});return`<${e}${n}></${e}>`}function N(t,e){let n=[];for(let[r,a]of Object.entries(t))if(a===!0)n.push(` ${r}`);else if(a!==!1&&a!==null&&a!==void 0){let i=x(String(a),e);n.push(` ${r}="${k(i)}"`)}return n.join("")}async function H(t,e){return h(t,e)}function P(t,e){let n=[];return y(t.tree,(r)=>{if(r.isStatic)n.push(h(r,e))}),n.join("")}function j(t,e,n){let r={templateId:e.id,context:n,dynamicParts:Array.from(e.dynamicParts.entries())},a=`
|
|
7
7
|
<script data-craft-hydration>
|
|
8
8
|
window.__CRAFT_HYDRATION__ = ${JSON.stringify(r)};
|
|
9
|
-
</script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{
|
|
9
|
+
</script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{ou as CRAFT_BRIDGE_SCRIPT,Nr as CRAFT_COMPONENTS,lu as CRAFT_COMPONENT_RUNTIME,hi as CRAFT_COMPONENT_STYLES,Lr as NATIVE_COMPONENTS,bi as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,xi as compileToNative,Si as createHotReloadServer,gi as generateCraftBridgeScript,V as generateCraftOptimizations,wi as getAvailableFormats,vi as getAvailableTargets,du as getCraftComponents,G as getSSRCacheStats,mi as injectCraftBridge,au as isCraftEnvironment,Y as prerenderForCraft,yi as processCraftComponents,cu as processCraftDirective,uu as registerCraftComponent,Q as renderSSR};
|
package/dist/database.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},k={},C={},f=new Map,P=[];function z(t){u={...u,...t}}function V(){return{...u}}function G(){u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let t of Object.keys(k))delete k[t];f.clear(),P.length=0}function X(t,e){k[t]=e}function g(t){let e=t||u.default;if(k[e])return k[e];let r=u.connections[e];if(!r)throw Error(`Database connection "${e}" not configured`);let s=N(r);return k[e]=s,s}function N(t){switch(t.driver){case"sqlite":return D(t);case"postgres":return S(t);case"mysql":return L(t);default:throw Error(`Unsupported database driver: ${t.driver}`)}}function D(t){let e=null,r=!1;return{async connect(){if(r)return;let{Database:s}=await import("bun:sqlite");e=new s(t.database,{create:!0,readwrite:!0}),r=!0},async disconnect(){if(e)e.close(),e=null,r=!1},async query(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).all(...n);if(u.logging)y(s,n,performance.now()-i);return o}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.lastInsertRowid}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.changes}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!r)await this.connect();e.run("BEGIN TRANSACTION")},async commit(){e.run("COMMIT")},async rollback(){e.run("ROLLBACK")},isConnected(){return r}}}function S(t){let e=!1,r=null;return{async connect(){if(e)return;try{let{Client:s}=await import("pg");r=new s({host:t.host||"localhost",port:t.port||5432,database:t.database,user:t.username,password:t.password,ssl:t.ssl}),await r.connect(),e=!0}catch(s){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rows}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(`${s} RETURNING id`,n);if(u.logging)y(s,n,performance.now()-i);return a.rows[0]?.id}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rowCount||0}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();await r.query("BEGIN")},async commit(){await r.query("COMMIT")},async rollback(){await r.query("ROLLBACK")},isConnected(){return e}}}function L(t){let e=!1,r=null;return{async connect(){if(e)return;try{let s=await import("mysql2/promise");r=s.createPool({host:t.host||"localhost",port:t.port||3306,database:t.database,user:t.username,password:t.password,waitForConnections:!0,connectionLimit:t.poolSize||10,queueLimit:0}),e=!0}catch(s){throw Error(`MySQL connection failed. Install 'mysql2' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.insertId}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.affectedRows||0}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();let s=await r.getConnection();return await s.beginTransaction(),s},async commit(){await r.execute("COMMIT")},async rollback(){await r.execute("ROLLBACK")},isConnected(){return e}}}class x{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(t){if(t)this._table=t}table(t){return this._table=t,this}from(t){return this.table(t)}connection(t){return this._connection=t,this}select(...t){return this._columns=t.length>0?t:["*"],this}addSelect(...t){if(this._columns[0]==="*")this._columns=t;else this._columns.push(...t);return this}distinct(){return this._distinct=!0,this}where(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"and"}),this}orWhere(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"or"}),this}whereIn(t,e){return this._wheres.push({column:t,operator:"in",value:e,boolean:"and"}),this}whereNotIn(t,e){return this._wheres.push({column:t,operator:"not in",value:e,boolean:"and"}),this}whereNull(t){return this._wheres.push({column:t,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(t){return this._wheres.push({column:t,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(t,e,r){return this._wheres.push({column:t,operator:"between",value:[e,r],boolean:"and"}),this}whereLike(t,e){return this._wheres.push({column:t,operator:"like",value:e,boolean:"and"}),this}join(t,e,r,s){return this._joins.push({type:"inner",table:t,first:e,operator:r,second:s}),this}leftJoin(t,e,r,s){return this._joins.push({type:"left",table:t,first:e,operator:r,second:s}),this}rightJoin(t,e,r,s){return this._joins.push({type:"right",table:t,first:e,operator:r,second:s}),this}orderBy(t,e="asc"){return this._orders.push({column:t,direction:e}),this}orderByDesc(t){return this.orderBy(t,"desc")}groupBy(...t){return this._groupBy.push(...t),this}having(t,e,r){return this._having.push({column:t,operator:e,value:r,boolean:"and"}),this}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}async get(){let{sql:t,bindings:e}=this.toSql();if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e),i=Q(n);if(i!==void 0)return i}let s=await g(this._connection).query(t,e);if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e);B(n,s,u.cacheTTL)}return s}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let t=await this.first();if(!t)throw Error("No results found");return t}async find(t,e="id"){return this.where(e,t).first()}async value(t){let e=await this.select(t).first();return e?e[t]:null}async pluck(t){return(await this.select(t).get()).map((r)=>r[t])}async exists(){return(await this.select(_("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(t="*"){let e=await this.select(_(`COUNT(${t}) as count`)).first();return Number(e?.count||0)}async max(t){return(await this.select(_(`MAX(${t}) as max`)).first())?.max}async min(t){return(await this.select(_(`MIN(${t}) as min`)).first())?.min}async sum(t){let e=await this.select(_(`SUM(${t}) as sum`)).first();return Number(e?.sum||0)}async avg(t){return(await this.select(_(`AVG(${t}) as avg`)).first())?.avg}async insert(t){let e=Object.keys(t),r=e.map(()=>"?").join(", "),s=Object.values(t),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES (${r})`,i=g(this._connection);return T(this._table),i.insert(n,s)}async insertAll(t){if(t.length===0)return;let e=Object.keys(t[0]),r=t.map(()=>`(${e.map(()=>"?").join(", ")})`).join(", "),s=t.flatMap((a)=>Object.values(a)),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES ${r}`,i=g(this._connection);T(this._table),await i.execute(n,s)}async update(t){this._bindings=[];let e=this.buildWhereClause(),r=[...this._bindings],s=Object.keys(t).map((o)=>`${o} = ?`).join(", "),n=[...Object.values(t),...r],i=`UPDATE ${this._table} SET ${s}${e}`,a=g(this._connection);return T(this._table),a.execute(i,n)}async increment(t,e=1){this._bindings=[];let r=this.buildWhereClause(),s=`UPDATE ${this._table} SET ${t} = ${t} + ?${r}`,n=g(this._connection);return T(this._table),n.execute(s,[e,...this._bindings])}async decrement(t,e=1){return this.increment(t,-e)}async delete(){this._bindings=[];let t=this.buildWhereClause(),e=`DELETE FROM ${this._table}${t}`,r=g(this._connection);return T(this._table),r.execute(e,this._bindings)}async truncate(){let t=g(this._connection);T(this._table),await t.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let t="SELECT ";if(this._distinct)t+="DISTINCT ";t+=this._columns.map((e)=>{if(typeof e==="object"&&e.__raw)return e.sql;return e}).join(", "),t+=` FROM ${this._table}`;for(let e of this._joins)t+=` ${e.type.toUpperCase()} JOIN ${e.table} ON ${e.first} ${e.operator} ${e.second}`;if(t+=this.buildWhereClause(),this._groupBy.length>0)t+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let e=this._having.map((r,s)=>{let n=s===0?"":` ${r.boolean.toUpperCase()} `;return this._bindings.push(r.value),`${n}${r.column} ${r.operator} ?`});t+=` HAVING ${e.join("")}`}if(this._orders.length>0)t+=` ORDER BY ${this._orders.map((e)=>`${e.column} ${e.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)t+=` LIMIT ${this._limit}`;if(this._offset!==void 0)t+=` OFFSET ${this._offset}`;return{sql:t,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((e,r)=>{let s=r===0?" WHERE ":` ${e.boolean.toUpperCase()} `;switch(e.operator){case"in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} IN (${i})`}case"not in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} NOT IN (${i})`}case"between":{let[n,i]=e.value;return this._bindings.push(n,i),`${s}${e.column} BETWEEN ? AND ?`}case"is null":return`${s}${e.column} IS NULL`;case"is not null":return`${s}${e.column} IS NOT NULL`;default:return this._bindings.push(e.value),`${s}${e.column} ${e.operator} ?`}}).join("")}getCacheKey(t,e){return`${this._table}:${t}:${JSON.stringify(e)}`}clone(){let t=new x(this._table);return t._columns=[...this._columns],t._wheres=[...this._wheres],t._orders=[...this._orders],t._joins=[...this._joins],t._groupBy=[...this._groupBy],t._having=[...this._having],t._limit=this._limit,t._offset=this._offset,t._distinct=this._distinct,t._connection=this._connection,t}}function l(t){return new x(t)}function Y(t){return l(t)}function _(t,e=[]){return{__raw:!0,sql:t,bindings:e}}function H(t,e){let r=e.primaryKey||"id",s={name:t,definition:e,async find(n){let i=await l(e.table).where(r,n).first();return i?b(s,i):null},async findOrFail(n){let i=await this.find(n);if(!i)throw Error(`${t} not found with ${r} = ${n}`);return i},async all(){return(await l(e.table).get()).map((i)=>b(s,i))},async create(n){let i={...e.defaults,...n},a=e.fillable?Object.fromEntries(Object.entries(i).filter(([c])=>e.fillable.includes(c))):i;if(e.timestamps!==!1){let c=new Date().toISOString(),h=typeof e.timestamps==="object"?e.timestamps.createdAt||"created_at":"created_at",m=typeof e.timestamps==="object"?e.timestamps.updatedAt||"updated_at":"updated_at";a[h]=c,a[m]=c}let o=await l(e.table).insert(a);return this.findOrFail(o)},async update(n){return l(e.table).update(n)},async destroy(n){let i=Array.isArray(n)?n:[n];return l(e.table).whereIn(r,i).delete()},query(){return l(e.table)},where(n,i,a){return this.query().where(n,i,a)},async first(){let n=await this.query().first();return n?b(s,n):null},async get(){return(await this.query().get()).map((i)=>b(s,i))},async count(){return this.query().count()}};return C[t]=s,s}function v(t){let e=C[t];if(!e)throw Error(`Model "${t}" not defined. Use defineModel() first.`);return e}function Z(t){return t in C}function b(t,e){let{definition:r}=t,s=r.primaryKey||"id",n={...e},i={...e};if(r.casts){for(let[o,c]of Object.entries(r.casts))if(o in i)i[o]=q(i[o],c)}let a={exists:!0,original:n,attributes:i,get(o){return i[o]},set(o,c){i[o]=c},toJSON(){let o={...i};if(r.hidden)for(let c of r.hidden)delete o[c];return o},async save(){let o={};for(let c of Object.keys(i))if(i[c]!==n[c])o[c]=i[c];if(Object.keys(o).length>0){if(r.timestamps!==!1){let c=typeof r.timestamps==="object"?r.timestamps.updatedAt||"updated_at":"updated_at";o[c]=new Date().toISOString()}await l(r.table).where(s,n[s]).update(o),Object.assign(n,o)}},async delete(){if(r.softDeletes){let o=typeof r.softDeletes==="string"?r.softDeletes:"deleted_at";await l(r.table).where(s,n[s]).update({[o]:new Date().toISOString()})}else await l(r.table).where(s,n[s]).delete();a.exists=!1},async refresh(){let o=await l(r.table).where(s,n[s]).first();if(o)Object.assign(n,o),Object.assign(i,o)},isDirty(o){if(o)return i[o]!==n[o];return Object.keys(i).some((c)=>i[c]!==n[c])}};if(r.relationships)for(let[o,c]of Object.entries(r.relationships))Object.defineProperty(a,o,{value:async()=>j(a,c,t),enumerable:!1});return new Proxy(a,{get(o,c){if(c in o)return o[c];return i[c]},set(o,c,h){if(c in o)o[c]=h;else i[c]=h;return!0}})}async function j(t,e,r){let s=v(e.model),n=r.definition.primaryKey||"id";switch(e.type){case"hasOne":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`,a=await l(s.definition.table).where(i,t.get(n)).first();return a?b(s,a):null}case"hasMany":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`;return(await l(s.definition.table).where(i,t.get(n)).get()).map((o)=>b(s,o))}case"belongsTo":{let i=e.foreignKey||`${e.model.toLowerCase()}_id`,a=e.localKey||"id",o=await l(s.definition.table).where(a,t.get(i)).first();return o?b(s,o):null}case"belongsToMany":{let i=e.pivotTable||[r.name,e.model].sort().join("_").toLowerCase(),a=e.pivotForeignKey||`${r.name.toLowerCase()}_id`,o=e.pivotRelatedKey||`${e.model.toLowerCase()}_id`,c=s.definition.primaryKey||"id";return(await l(s.definition.table).join(i,`${s.definition.table}.${c}`,"=",`${i}.${o}`).where(`${i}.${a}`,t.get(n)).get()).map((m)=>b(s,m))}default:return null}}function q(t,e){if(t===null||t===void 0)return t;switch(e){case"string":return String(t);case"number":return Number(t);case"boolean":return Boolean(t);case"date":return new Date(t);case"json":case"array":return typeof t==="string"?JSON.parse(t):t;default:return t}}async function tt(t,e){let r=g(e);await r.beginTransaction();try{let s=await t();return await r.commit(),s}catch(s){throw await r.rollback(),s}}function Q(t){let e=f.get(t);if(!e)return;if(Date.now()-e.timestamp>e.ttl*1000){f.delete(t);return}return e.result}function B(t,e,r){if(f.size>=(u.maxCacheSize||1000)){let s=f.keys().next().value;if(s)f.delete(s)}f.set(t,{result:e,timestamp:Date.now(),ttl:r})}function T(t){for(let e of f.keys())if(e.startsWith(`${t}:`))f.delete(e)}function et(){f.clear()}function nt(){return{size:f.size,keys:[...f.keys()]}}function y(t,e,r){if(P.push({sql:t,bindings:e,duration:r,timestamp:new Date}),P.length>1000)P.shift()}function rt(){return[...P]}function st(){P.length=0}function it(t=!0){u.logging=t}class p extends Error{sql;bindings;constructor(t,e,r){super(t);this.sql=e;this.bindings=r;this.name="DatabaseError"}}async function K(t,e,r,s){let n=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m]=o;try{let d=await W(h,m),w=`$${h}`;e[w]=d,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- DB Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function U(t,e,r,s){let n=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m]=o;try{let d=v(h),w=await J(d,m),E=`$${h.toLowerCase()}`;e[E]=w,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- Model Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function F(t,e,r,s){let n=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m,d]=o;try{let w=m?JSON.parse(m):[],A=await g().query(h,w);e[`$${d}`]=A,i=i.replace(c,"")}catch(w){i=i.replace(c,`<!-- Query Error: ${w instanceof Error?w.message:String(w)} -->`)}}return i}async function W(t,e){let r=l(t),s=/->(\w+)\(([^)]*)\)/g,n=[...e.matchAll(s)],i=r;for(let[,a,o]of n){let c=O(o);if(typeof i[a]==="function"){if(i=i[a](...c),i instanceof Promise){i=await i;break}}}if(i instanceof x)i=await i.get();return i}async function J(t,e){let r=/->(\w+)\(([^)]*)\)/g,s=[...e.matchAll(r)],n=t;for(let[,i,a]of s){let o=O(a);if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}else if(n instanceof x){if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}}}if(n instanceof x)n=await n.get();return n}function O(t){if(!t.trim())return[];let e=[],r="",s=0,n=!1,i="";for(let a=0;a<t.length;a++){let o=t[a];if(!n&&(o==='"'||o==="'"))n=!0,i=o,r+=o;else if(n&&o===i)n=!1,r+=o;else if(!n&&(o==="["||o==="{"||o==="("))s++,r+=o;else if(!n&&(o==="]"||o==="}"||o===")"))s--,r+=o;else if(!n&&s===0&&o===",")e.push(R(r.trim())),r="";else r+=o}if(r.trim())e.push(R(r.trim()));return e}function R(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let e=Number(t);if(!Number.isNaN(e))return e;try{return JSON.parse(t)}catch{return t}}async function ot(t,e,r,s){let n=t;return n=await F(n,e,r,s),n=await U(n,e,r,s),n=await K(n,e,r,s),n}class I{_connection;connection(t){return this._connection=t,this}async create(t,e){let r=new M(t);e(r);let s=r.toCreateSQL();await g(this._connection).execute(s)}async drop(t){await g(this._connection).execute(`DROP TABLE IF EXISTS ${t}`)}async rename(t,e){await g(this._connection).execute(`ALTER TABLE ${t} RENAME TO ${e}`)}async hasTable(t){let e=g(this._connection);try{return await e.query(`SELECT 1 FROM ${t} LIMIT 1`),!0}catch{return!1}}}class M{table;columns=[];indices=[];constructor(t){this.table=t}id(t="id"){return this.columns.push(`${t} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(t,e=255){return this.columns.push(`${t} VARCHAR(${e})`),this}text(t){return this.columns.push(`${t} TEXT`),this}integer(t){return this.columns.push(`${t} INTEGER`),this}boolean(t){return this.columns.push(`${t} BOOLEAN DEFAULT 0`),this}datetime(t){return this.columns.push(`${t} 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(t){return this.columns.push(`${t} TEXT`),this}foreignId(t){return this.columns.push(`${t} INTEGER`),this}index(t){let e=Array.isArray(t)?t:[t],r=`idx_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}unique(t){let e=Array.isArray(t)?t:[t],r=`uniq_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
|
|
2
|
+
var u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},k={},C={},f=new Map,P=[];function z(t){u={...u,...t}}function V(){return{...u}}function G(){u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let t of Object.keys(k))delete k[t];f.clear(),P.length=0}function X(t,e){k[t]=e}function g(t){let e=t||u.default;if(k[e])return k[e];let r=u.connections[e];if(!r)throw Error(`Database connection "${e}" not configured`);let s=N(r);return k[e]=s,s}function N(t){switch(t.driver){case"sqlite":return D(t);case"postgres":return S(t);case"mysql":return L(t);default:throw Error(`Unsupported database driver: ${t.driver}`)}}function D(t){let e=null,r=!1;return{async connect(){if(r)return;let{Database:s}=await import("bun:sqlite");e=new s(t.database,{create:!0,readwrite:!0}),r=!0},async disconnect(){if(e)e.close(),e=null,r=!1},async query(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).all(...n);if(u.logging)y(s,n,performance.now()-i);return o}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.lastInsertRowid}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.changes}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!r)await this.connect();e.run("BEGIN TRANSACTION")},async commit(){e.run("COMMIT")},async rollback(){e.run("ROLLBACK")},isConnected(){return r}}}function S(t){let e=!1,r=null;return{async connect(){if(e)return;try{let{Client:s}=await import("pg");r=new s({host:t.host||"localhost",port:t.port||5432,database:t.database,user:t.username,password:t.password,ssl:t.ssl}),await r.connect(),e=!0}catch(s){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rows}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(`${s} RETURNING id`,n);if(u.logging)y(s,n,performance.now()-i);return a.rows[0]?.id}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rowCount||0}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();await r.query("BEGIN")},async commit(){await r.query("COMMIT")},async rollback(){await r.query("ROLLBACK")},isConnected(){return e}}}function L(t){let e=!1,r=null;return{async connect(){if(e)return;try{let s=await import("mysql2/promise");r=s.createPool({host:t.host||"localhost",port:t.port||3306,database:t.database,user:t.username,password:t.password,waitForConnections:!0,connectionLimit:t.poolSize||10,queueLimit:0}),e=!0}catch(s){throw Error(`MySQL connection failed. Install 'mysql2' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.insertId}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.affectedRows||0}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();let s=await r.getConnection();return await s.beginTransaction(),s},async commit(){await r.execute("COMMIT")},async rollback(){await r.execute("ROLLBACK")},isConnected(){return e}}}class x{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(t){if(t)this._table=t}table(t){return this._table=t,this}from(t){return this.table(t)}connection(t){return this._connection=t,this}select(...t){return this._columns=t.length>0?t:["*"],this}addSelect(...t){if(this._columns[0]==="*")this._columns=t;else this._columns.push(...t);return this}distinct(){return this._distinct=!0,this}where(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"and"}),this}orWhere(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"or"}),this}whereIn(t,e){return this._wheres.push({column:t,operator:"in",value:e,boolean:"and"}),this}whereNotIn(t,e){return this._wheres.push({column:t,operator:"not in",value:e,boolean:"and"}),this}whereNull(t){return this._wheres.push({column:t,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(t){return this._wheres.push({column:t,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(t,e,r){return this._wheres.push({column:t,operator:"between",value:[e,r],boolean:"and"}),this}whereLike(t,e){return this._wheres.push({column:t,operator:"like",value:e,boolean:"and"}),this}join(t,e,r,s){return this._joins.push({type:"inner",table:t,first:e,operator:r,second:s}),this}leftJoin(t,e,r,s){return this._joins.push({type:"left",table:t,first:e,operator:r,second:s}),this}rightJoin(t,e,r,s){return this._joins.push({type:"right",table:t,first:e,operator:r,second:s}),this}orderBy(t,e="asc"){return this._orders.push({column:t,direction:e}),this}orderByDesc(t){return this.orderBy(t,"desc")}groupBy(...t){return this._groupBy.push(...t),this}having(t,e,r){return this._having.push({column:t,operator:e,value:r,boolean:"and"}),this}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}async get(){let{sql:t,bindings:e}=this.toSql();if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e),i=Q(n);if(i!==void 0)return i}let s=await g(this._connection).query(t,e);if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e);B(n,s,u.cacheTTL)}return s}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let t=await this.first();if(!t)throw Error("No results found");return t}async find(t,e="id"){return this.where(e,t).first()}async value(t){let e=await this.select(t).first();return e?e[t]:null}async pluck(t){return(await this.select(t).get()).map((r)=>r[t])}async exists(){return(await this.select(_("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(t="*"){let e=await this.select(_(`COUNT(${t}) as count`)).first();return Number(e?.count||0)}async max(t){return(await this.select(_(`MAX(${t}) as max`)).first())?.max}async min(t){return(await this.select(_(`MIN(${t}) as min`)).first())?.min}async sum(t){let e=await this.select(_(`SUM(${t}) as sum`)).first();return Number(e?.sum||0)}async avg(t){return(await this.select(_(`AVG(${t}) as avg`)).first())?.avg}async insert(t){let e=Object.keys(t),r=e.map(()=>"?").join(", "),s=Object.values(t),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES (${r})`,i=g(this._connection);return T(this._table),i.insert(n,s)}async insertAll(t){if(t.length===0)return;let e=Object.keys(t[0]),r=t.map(()=>`(${e.map(()=>"?").join(", ")})`).join(", "),s=t.flatMap((a)=>Object.values(a)),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES ${r}`,i=g(this._connection);T(this._table),await i.execute(n,s)}async update(t){this._bindings=[];let e=this.buildWhereClause(),r=[...this._bindings],s=Object.keys(t).map((o)=>`${o} = ?`).join(", "),n=[...Object.values(t),...r],i=`UPDATE ${this._table} SET ${s}${e}`,a=g(this._connection);return T(this._table),a.execute(i,n)}async increment(t,e=1){this._bindings=[];let r=this.buildWhereClause(),s=`UPDATE ${this._table} SET ${t} = ${t} + ?${r}`,n=g(this._connection);return T(this._table),n.execute(s,[e,...this._bindings])}async decrement(t,e=1){return this.increment(t,-e)}async delete(){this._bindings=[];let t=this.buildWhereClause(),e=`DELETE FROM ${this._table}${t}`,r=g(this._connection);return T(this._table),r.execute(e,this._bindings)}async truncate(){let t=g(this._connection);T(this._table),await t.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let t="SELECT ";if(this._distinct)t+="DISTINCT ";t+=this._columns.map((e)=>{if(typeof e==="object"&&e.__raw)return e.sql;return e}).join(", "),t+=` FROM ${this._table}`;for(let e of this._joins)t+=` ${e.type.toUpperCase()} JOIN ${e.table} ON ${e.first} ${e.operator} ${e.second}`;if(t+=this.buildWhereClause(),this._groupBy.length>0)t+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let e=this._having.map((r,s)=>{let n=s===0?"":` ${r.boolean.toUpperCase()} `;return this._bindings.push(r.value),`${n}${r.column} ${r.operator} ?`});t+=` HAVING ${e.join("")}`}if(this._orders.length>0)t+=` ORDER BY ${this._orders.map((e)=>`${e.column} ${e.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)t+=` LIMIT ${this._limit}`;if(this._offset!==void 0)t+=` OFFSET ${this._offset}`;return{sql:t,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((e,r)=>{let s=r===0?" WHERE ":` ${e.boolean.toUpperCase()} `;switch(e.operator){case"in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} IN (${i})`}case"not in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} NOT IN (${i})`}case"between":{let[n,i]=e.value;return this._bindings.push(n,i),`${s}${e.column} BETWEEN ? AND ?`}case"is null":return`${s}${e.column} IS NULL`;case"is not null":return`${s}${e.column} IS NOT NULL`;default:return this._bindings.push(e.value),`${s}${e.column} ${e.operator} ?`}}).join("")}getCacheKey(t,e){return`${this._table}:${t}:${JSON.stringify(e)}`}clone(){let t=new x(this._table);return t._columns=[...this._columns],t._wheres=[...this._wheres],t._orders=[...this._orders],t._joins=[...this._joins],t._groupBy=[...this._groupBy],t._having=[...this._having],t._limit=this._limit,t._offset=this._offset,t._distinct=this._distinct,t._connection=this._connection,t}}function l(t){return new x(t)}function Y(t){return l(t)}function _(t,e=[]){return{__raw:!0,sql:t,bindings:e}}function H(t,e){let r=e.primaryKey||"id",s={name:t,definition:e,async find(n){let i=await l(e.table).where(r,n).first();return i?b(s,i):null},async findOrFail(n){let i=await this.find(n);if(!i)throw Error(`${t} not found with ${r} = ${n}`);return i},async all(){return(await l(e.table).get()).map((i)=>b(s,i))},async create(n){let i={...e.defaults,...n},a=e.fillable?Object.fromEntries(Object.entries(i).filter(([c])=>e.fillable.includes(c))):i;if(e.timestamps!==!1){let c=new Date().toISOString(),h=typeof e.timestamps==="object"?e.timestamps.createdAt||"created_at":"created_at",p=typeof e.timestamps==="object"?e.timestamps.updatedAt||"updated_at":"updated_at";a[h]=c,a[p]=c}let o=await l(e.table).insert(a);return this.findOrFail(o)},async update(n){return l(e.table).update(n)},async destroy(n){let i=Array.isArray(n)?n:[n];return l(e.table).whereIn(r,i).delete()},query(){return l(e.table)},where(n,i,a){return this.query().where(n,i,a)},async first(){let n=await this.query().first();return n?b(s,n):null},async get(){return(await this.query().get()).map((i)=>b(s,i))},async count(){return this.query().count()}};return C[t]=s,s}function v(t){let e=C[t];if(!e)throw Error(`Model "${t}" not defined. Use defineModel() first.`);return e}function Z(t){return t in C}function b(t,e){let{definition:r}=t,s=r.primaryKey||"id",n={...e},i={...e};if(r.casts){for(let[o,c]of Object.entries(r.casts))if(o in i)i[o]=q(i[o],c)}let a={exists:!0,original:n,attributes:i,get(o){return i[o]},set(o,c){i[o]=c},toJSON(){let o={...i};if(r.hidden)for(let c of r.hidden)delete o[c];return o},async save(){let o={};for(let c of Object.keys(i))if(i[c]!==n[c])o[c]=i[c];if(Object.keys(o).length>0){if(r.timestamps!==!1){let c=typeof r.timestamps==="object"?r.timestamps.updatedAt||"updated_at":"updated_at";o[c]=new Date().toISOString()}await l(r.table).where(s,n[s]).update(o),Object.assign(n,o)}},async delete(){if(r.softDeletes){let o=typeof r.softDeletes==="string"?r.softDeletes:"deleted_at";await l(r.table).where(s,n[s]).update({[o]:new Date().toISOString()})}else await l(r.table).where(s,n[s]).delete();a.exists=!1},async refresh(){let o=await l(r.table).where(s,n[s]).first();if(o)Object.assign(n,o),Object.assign(i,o)},isDirty(o){if(o)return i[o]!==n[o];return Object.keys(i).some((c)=>i[c]!==n[c])}};if(r.relationships)for(let[o,c]of Object.entries(r.relationships))Object.defineProperty(a,o,{value:async()=>j(a,c,t),enumerable:!1});return new Proxy(a,{get(o,c){if(c in o)return o[c];return i[c]},set(o,c,h){if(c in o)o[c]=h;else i[c]=h;return!0}})}async function j(t,e,r){let s=v(e.model),n=r.definition.primaryKey||"id";switch(e.type){case"hasOne":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`,a=await l(s.definition.table).where(i,t.get(n)).first();return a?b(s,a):null}case"hasMany":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`;return(await l(s.definition.table).where(i,t.get(n)).get()).map((o)=>b(s,o))}case"belongsTo":{let i=e.foreignKey||`${e.model.toLowerCase()}_id`,a=e.localKey||"id",o=await l(s.definition.table).where(a,t.get(i)).first();return o?b(s,o):null}case"belongsToMany":{let i=e.pivotTable||[r.name,e.model].sort().join("_").toLowerCase(),a=e.pivotForeignKey||`${r.name.toLowerCase()}_id`,o=e.pivotRelatedKey||`${e.model.toLowerCase()}_id`,c=s.definition.primaryKey||"id";return(await l(s.definition.table).join(i,`${s.definition.table}.${c}`,"=",`${i}.${o}`).where(`${i}.${a}`,t.get(n)).get()).map((p)=>b(s,p))}default:return null}}function q(t,e){if(t===null||t===void 0)return t;switch(e){case"string":return String(t);case"number":return Number(t);case"boolean":return Boolean(t);case"date":return new Date(t);case"json":case"array":return typeof t==="string"?JSON.parse(t):t;default:return t}}async function tt(t,e){let r=g(e);await r.beginTransaction();try{let s=await t();return await r.commit(),s}catch(s){throw await r.rollback(),s}}function Q(t){let e=f.get(t);if(!e)return;if(Date.now()-e.timestamp>e.ttl*1000){f.delete(t);return}return e.result}function B(t,e,r){if(f.size>=(u.maxCacheSize||1000)){let s=f.keys().next().value;if(s)f.delete(s)}f.set(t,{result:e,timestamp:Date.now(),ttl:r})}function T(t){for(let e of f.keys())if(e.startsWith(`${t}:`))f.delete(e)}function et(){f.clear()}function nt(){return{size:f.size,keys:[...f.keys()]}}function y(t,e,r){if(P.push({sql:t,bindings:e,duration:r,timestamp:new Date}),P.length>1000)P.shift()}function rt(){return[...P]}function st(){P.length=0}function it(t=!0){u.logging=t}class m extends Error{sql;bindings;constructor(t,e,r){super(t);this.sql=e;this.bindings=r;this.name="DatabaseError"}}async function K(t,e,r,s){let n=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p]=o;try{let d=await W(h,p),w=`$${h}`;e[w]=d,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- DB Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function U(t,e,r,s){let n=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p]=o;try{let d=v(h),w=await J(d,p),E=`$${h.toLowerCase()}`;e[E]=w,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- Model Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function F(t,e,r,s){let n=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p,d]=o;try{let w=p?JSON.parse(p):[],A=await g().query(h,w);e[`$${d}`]=A,i=i.replace(c,"")}catch(w){i=i.replace(c,`<!-- Query Error: ${w instanceof Error?w.message:String(w)} -->`)}}return i}async function W(t,e){let r=l(t),s=/->(\w+)\(([^)]*)\)/g,n=[...e.matchAll(s)],i=r;for(let[,a,o]of n){let c=O(o);if(typeof i[a]==="function"){if(i=i[a](...c),i instanceof Promise){i=await i;break}}}if(i instanceof x)i=await i.get();return i}async function J(t,e){let r=/->(\w+)\(([^)]*)\)/g,s=[...e.matchAll(r)],n=t;for(let[,i,a]of s){let o=O(a);if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}else if(n instanceof x){if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}}}if(n instanceof x)n=await n.get();return n}function O(t){if(!t.trim())return[];let e=[],r="",s=0,n=!1,i="";for(let a=0;a<t.length;a++){let o=t[a];if(!n&&(o==='"'||o==="'"))n=!0,i=o,r+=o;else if(n&&o===i)n=!1,r+=o;else if(!n&&(o==="["||o==="{"||o==="("))s++,r+=o;else if(!n&&(o==="]"||o==="}"||o===")"))s--,r+=o;else if(!n&&s===0&&o===",")e.push(R(r.trim())),r="";else r+=o}if(r.trim())e.push(R(r.trim()));return e}function R(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let e=Number(t);if(!Number.isNaN(e))return e;try{return JSON.parse(t)}catch{return t}}async function ot(t,e,r,s){let n=t;return n=await F(n,e,r,s),n=await U(n,e,r,s),n=await K(n,e,r,s),n}class I{_connection;connection(t){return this._connection=t,this}async create(t,e){let r=new M(t);e(r);let s=r.toCreateSQL();await g(this._connection).execute(s)}async drop(t){await g(this._connection).execute(`DROP TABLE IF EXISTS ${t}`)}async rename(t,e){await g(this._connection).execute(`ALTER TABLE ${t} RENAME TO ${e}`)}async hasTable(t){let e=g(this._connection);try{return await e.query(`SELECT 1 FROM ${t} LIMIT 1`),!0}catch{return!1}}}class M{table;columns=[];indices=[];constructor(t){this.table=t}id(t="id"){return this.columns.push(`${t} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(t,e=255){return this.columns.push(`${t} VARCHAR(${e})`),this}text(t){return this.columns.push(`${t} TEXT`),this}integer(t){return this.columns.push(`${t} INTEGER`),this}boolean(t){return this.columns.push(`${t} BOOLEAN DEFAULT 0`),this}datetime(t){return this.columns.push(`${t} 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(t){return this.columns.push(`${t} TEXT`),this}foreignId(t){return this.columns.push(`${t} INTEGER`),this}index(t){let e=Array.isArray(t)?t:[t],r=`idx_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}unique(t){let e=Array.isArray(t)?t:[t],r=`uniq_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
|
|
3
3
|
${this.columns.join(`,
|
|
4
4
|
`)}
|
|
5
|
-
)`}getIndexSQL(){return this.indices}}function at(){return new I}export{M as Blueprint,
|
|
5
|
+
)`}getIndexSQL(){return this.indices}}function at(){return new I}export{M as Blueprint,m as DatabaseError,x as QueryBuilder,I as SchemaBuilder,et as clearQueryCache,st as clearQueryLog,z as configureDatabase,H as defineModel,it as enableQueryLogging,g as getAdapter,V as getDatabaseConfig,v as getModel,nt as getQueryCacheStats,rt as getQueryLog,Z as hasModel,ot as processDatabaseDirectives,K as processDbDirective,U as processModelDirective,F as processQueryDirective,l as query,_ as raw,X as registerAdapter,G as resetDatabaseConfig,at as schema,Y as table,tt as transaction};
|
|
@@ -243,6 +243,7 @@ export declare interface NativeBridgeInterface {
|
|
|
243
243
|
capabilities?: string[]
|
|
244
244
|
capabilityTimeoutMs?: number
|
|
245
245
|
initialAppState?: 'active' | 'inactive' | 'background'
|
|
246
|
+
colorScheme?: 'light' | 'dark'
|
|
246
247
|
postMessage(message: string): void
|
|
247
248
|
onMessage(callback: (message: string) => void): void
|
|
248
249
|
}
|
|
@@ -268,10 +269,14 @@ export type BridgeMessageType = | 'RENDER' // Render a new componen
|
|
|
268
269
|
| 'NAVIGATE' // Navigate to a new screen
|
|
269
270
|
| 'NAVIGATE_BACK' // Go back
|
|
270
271
|
| 'NAVIGATE_REPLACE' // Replace current screen
|
|
272
|
+
| 'NAVIGATE_OPEN' // Open a native or hybrid app path
|
|
273
|
+
| 'NAVIGATION_SET_OPTIONS' // Update native navigation chrome
|
|
274
|
+
| 'NAV_BUTTON' // Native navigation button pressed
|
|
271
275
|
|
|
272
276
|
// Lifecycle
|
|
273
277
|
| 'APP_STATE' // App foreground/background
|
|
274
278
|
| 'DEEP_LINK' // App opened or resumed through a URL
|
|
279
|
+
| 'APPEARANCE' // Native color scheme changed
|
|
275
280
|
| 'SCREEN_FOCUS' // Screen gained/lost focus
|
|
276
281
|
| 'MEMORY_WARNING' // Low memory warning
|
|
277
282
|
|
|
@@ -15,6 +15,9 @@ export class STXBridge {
|
|
|
15
15
|
defaultTimeout = 30000;
|
|
16
16
|
initialize(nativeBridge) {
|
|
17
17
|
this.nativeBridge = nativeBridge;
|
|
18
|
+
const timeout = Number(nativeBridge.capabilityTimeoutMs);
|
|
19
|
+
if (Number.isFinite(timeout) && timeout > 0)
|
|
20
|
+
this.defaultTimeout = timeout;
|
|
18
21
|
nativeBridge.onMessage((rawMessage) => {
|
|
19
22
|
try {
|
|
20
23
|
const message = JSON.parse(rawMessage);
|
package/dist/native/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { compileNativeBundle, compileScreenBundle } from "./compiler/bundle.js";
|
|
4
|
-
import {
|
|
4
|
+
import { compileScreenFile } from "./compiler/render-screen.js";
|
|
5
5
|
export const NATIVE_CONFIG_FILES = ["native.config.json", "stx-native.config.json"];
|
|
6
6
|
export function loadNativeScreensConfig(cwd = process.cwd(), configFile) {
|
|
7
7
|
const file = configFile ? path.resolve(cwd, configFile) : NATIVE_CONFIG_FILES.map((name) => path.join(cwd, name)).find((candidate) => existsSync(candidate));
|
|
@@ -40,7 +40,17 @@ export async function runNativeCompile(file, options = {}) {
|
|
|
40
40
|
output = bundle.code;
|
|
41
41
|
diagnostics = bundle.diagnostics;
|
|
42
42
|
} else {
|
|
43
|
-
const
|
|
43
|
+
const compile = async (source) => {
|
|
44
|
+
const result = await compileScreenFile(source);
|
|
45
|
+
diagnostics.push(...result.diagnostics.map((diagnostic) => ({
|
|
46
|
+
level: "warning",
|
|
47
|
+
message: [diagnostic.kind, diagnostic.tag, diagnostic.name].filter(Boolean).join(": ")
|
|
48
|
+
})));
|
|
49
|
+
return result.document;
|
|
50
|
+
}, ir = config ? {
|
|
51
|
+
initialScreen: config.initialScreen,
|
|
52
|
+
screens: Object.fromEntries(await Promise.all(Object.entries(config.screens).map(async ([name, source]) => [name, await compile(source)])))
|
|
53
|
+
} : await compile(path.resolve(cwd, file));
|
|
44
54
|
output = JSON.stringify(ir, null, 2);
|
|
45
55
|
}
|
|
46
56
|
if (!options.output)
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { RUNTIME_SPECIFIER } from './codegen';
|
|
2
1
|
/**
|
|
3
2
|
* Build the bundle the host loads as `native-screen.js`.
|
|
4
3
|
*
|
|
@@ -15,8 +14,11 @@ import { RUNTIME_SPECIFIER } from './codegen';
|
|
|
15
14
|
* })
|
|
16
15
|
* ```
|
|
17
16
|
*/
|
|
17
|
+
/** Compile routed screens through stx and run them on the shared signals runtime. */
|
|
18
18
|
export declare function compileNativeBundle(options: CompileNativeBundleOptions): Promise<NativeBundleResult>;
|
|
19
|
-
/**
|
|
19
|
+
/** Compile one screen against stx's shared signals runtime, without the legacy parser/runtime. */
|
|
20
|
+
export declare function compileSharedScreenBundle(file: string, options?: Pick<CompileNativeBundleOptions, 'minify' | 'outFile' | 'root'>): Promise<NativeBundleResult>;
|
|
21
|
+
/** One `.stx` file, as the public single-screen native compiler writes it. */
|
|
20
22
|
export declare function compileScreenBundle(file: string, options?: Pick<CompileNativeBundleOptions, 'minify' | 'outFile' | 'root'>): Promise<NativeBundleResult>;
|
|
21
23
|
export declare interface CompileNativeBundleOptions {
|
|
22
24
|
screens: Record<string, string>
|
|
@@ -38,4 +40,3 @@ export declare interface NativeBundleResult {
|
|
|
38
40
|
}
|
|
39
41
|
/** @deprecated Use `CompileNativeBundleOptions`. */
|
|
40
42
|
export type BundleOptions = CompileNativeBundleOptions;
|
|
41
|
-
export { RUNTIME_SPECIFIER };
|
|
@@ -1,15 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
function runtimeEntry() {
|
|
6
|
-
const candidates = [
|
|
7
|
-
path.join(import.meta.dir, "..", "runtime", "entry.ts"),
|
|
8
|
-
path.join(import.meta.dir, "..", "runtime", "entry.js"),
|
|
9
|
-
path.join(import.meta.dir, "native", "runtime", "entry.js")
|
|
10
|
-
];
|
|
11
|
-
return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
|
|
12
|
-
}
|
|
3
|
+
import { compileScreenFile } from "./render-screen.js";
|
|
4
|
+
import { generateSignalsRuntime } from "../../signals.js";
|
|
13
5
|
async function build(entry, plugins, minify) {
|
|
14
6
|
const result = await Bun.build({
|
|
15
7
|
entrypoints: [entry],
|
|
@@ -27,23 +19,6 @@ ${messages}`);
|
|
|
27
19
|
}
|
|
28
20
|
return (await result.outputs[0].text()).trim();
|
|
29
21
|
}
|
|
30
|
-
function screenPlugin(warnings) {
|
|
31
|
-
return {
|
|
32
|
-
name: "stx-native-screen",
|
|
33
|
-
setup(builder) {
|
|
34
|
-
builder.onResolve({ filter: /^stx:native-runtime$/ }, () => ({ path: "runtime", namespace: "stx-native-runtime" }));
|
|
35
|
-
builder.onLoad({ filter: /.*/, namespace: "stx-native-runtime" }, () => ({
|
|
36
|
-
contents: "export function mount(screen) { return globalThis.__stxNative.mount(screen) }",
|
|
37
|
-
loader: "js"
|
|
38
|
-
}));
|
|
39
|
-
builder.onLoad({ filter: /\.stx$/ }, async (args) => {
|
|
40
|
-
const source = await Bun.file(args.path).text(), module = generateScreenModule(parseSTX(source, args.path));
|
|
41
|
-
warnings.push(...module.warnings);
|
|
42
|
-
return { contents: module.code, loader: "ts" };
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
22
|
export async function compileNativeBundle(options) {
|
|
48
23
|
const names = Object.keys(options.screens);
|
|
49
24
|
if (names.length === 0)
|
|
@@ -51,31 +26,50 @@ export async function compileNativeBundle(options) {
|
|
|
51
26
|
const routed = options.routed ?? !0, initialScreen = options.initialScreen ?? names[0];
|
|
52
27
|
if (!options.screens[initialScreen])
|
|
53
28
|
throw Error(`Initial screen ${initialScreen} is not in screens`);
|
|
54
|
-
const
|
|
55
|
-
var names = ${JSON.stringify(names)};
|
|
56
|
-
var name = globalThis.__stxNativeRoute || ${JSON.stringify(initialScreen)};
|
|
57
|
-
if (names.indexOf(name) === -1) throw new Error(['Unknown native screen:', name].join(' '));
|
|
58
|
-
globalThis.__stxNativeRoute = name;
|
|
59
|
-
globalThis.__stxNativeRuntimeOptions = { routeName: name, routeNames: names };
|
|
60
|
-
})();` : "globalThis.__stxNativeRuntimeOptions = { routeName: 'main', routeNames: ['main'] };", runtime = await build(runtimeEntry(), [], minify), screens = [];
|
|
29
|
+
const root = path.resolve(options.root ?? process.cwd()), compiledScreens = [];
|
|
61
30
|
for (const name of names) {
|
|
62
31
|
const file = path.resolve(root, options.screens[name]);
|
|
63
32
|
if (!file.endsWith(".stx"))
|
|
64
33
|
throw Error(`Screen ${name} must name a .stx file`);
|
|
65
|
-
|
|
66
|
-
screens.push(`// Screen ${name}: ${path.basename(file)}
|
|
67
|
-
if (${guard}) {
|
|
68
|
-
${code}
|
|
69
|
-
}`);
|
|
34
|
+
compiledScreens.push({ name, file, compiled: await compileScreenFile(file, { root }) });
|
|
70
35
|
}
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
`)
|
|
36
|
+
const runtimeGlobals = path.join(import.meta.dir, "..", "runtime", "jsc-globals.ts"), sharedScreen = path.join(import.meta.dir, "..", "runtime", "shared-screen.ts"), route = routed ? `var routeName = g.__stxNativeRoute || ${JSON.stringify(initialScreen)};
|
|
37
|
+
if (routeNames.indexOf(routeName) === -1) throw new Error(['Unknown native screen:', routeName].join(' '));` : "var routeName = 'main';", selections = compiledScreens.map(({ name, compiled }, index) => `${index === 0 ? "if" : "else if"} (routeName === ${JSON.stringify(routed ? name : "main")}) {
|
|
38
|
+
nativeDocument = ${JSON.stringify(compiled.document)};
|
|
39
|
+
manifest = ${JSON.stringify(compiled.manifest)};
|
|
40
|
+
}`).join(`
|
|
41
|
+
`), setups = compiledScreens.map(({ name, compiled }, index) => `${index === 0 ? "if" : "else if"} (routeName === ${JSON.stringify(routed ? name : "main")}) {
|
|
42
|
+
${compiled.setup?.code ?? "g.__stx_latestSetup = null;"}
|
|
43
|
+
}`).join(`
|
|
44
|
+
`), contents = `
|
|
45
|
+
import { installJSCGlobals } from ${JSON.stringify(runtimeGlobals)};
|
|
46
|
+
import { prepareSharedNativeScreen } from ${JSON.stringify(sharedScreen)};
|
|
47
|
+
var g = globalThis;
|
|
48
|
+
installJSCGlobals(g);
|
|
49
|
+
var bridge = g.__stxNativeBridge;
|
|
50
|
+
if (!bridge) throw new Error('Missing __stxNativeBridge');
|
|
51
|
+
var routeNames = ${JSON.stringify(routed ? names : ["main"])};
|
|
52
|
+
${route}
|
|
53
|
+
g.__stxNativeRoute = routeName;
|
|
54
|
+
var nativeDocument;
|
|
55
|
+
var manifest;
|
|
56
|
+
${selections}
|
|
57
|
+
var screen = prepareSharedNativeScreen(nativeDocument, manifest, bridge, { routeName: routeName, routeNames: routeNames });
|
|
58
|
+
g.__stx_host = screen.host;
|
|
59
|
+
g.__stxNativeUnmount = function() { screen.unmount(); };
|
|
60
|
+
${generateSignalsRuntime()}
|
|
61
|
+
${setups}
|
|
62
|
+
screen.mount(g.stx, g.__stx_latestSetup || null);
|
|
63
|
+
`, code = await build("stx:native-shared-screens", [{
|
|
64
|
+
name: "stx-native-shared-screens",
|
|
65
|
+
setup(builder) {
|
|
66
|
+
builder.onResolve({ filter: /^stx:native-shared-screens$/ }, () => ({ path: "entry", namespace: "stx-native-shared-screens" }));
|
|
67
|
+
builder.onLoad({ filter: /.*/, namespace: "stx-native-shared-screens" }, () => ({ contents, loader: "js" }));
|
|
68
|
+
}
|
|
69
|
+
}], options.minify ?? !1), diagnostics = compiledScreens.flatMap(({ compiled }) => compiled.diagnostics).map((diagnostic) => ({
|
|
70
|
+
level: "warning",
|
|
71
|
+
message: [diagnostic.kind, diagnostic.tag, diagnostic.name].filter(Boolean).join(": ")
|
|
72
|
+
}));
|
|
79
73
|
if (!options.outFile)
|
|
80
74
|
return { code, diagnostics };
|
|
81
75
|
const outFile = path.resolve(root, options.outFile);
|
|
@@ -83,8 +77,9 @@ ${code}
|
|
|
83
77
|
await Bun.write(outFile, code);
|
|
84
78
|
return { code, outFile, diagnostics };
|
|
85
79
|
}
|
|
86
|
-
export function
|
|
80
|
+
export async function compileSharedScreenBundle(file, options = {}) {
|
|
87
81
|
return compileNativeBundle({ ...options, screens: { main: file }, routed: !1 });
|
|
88
82
|
}
|
|
89
|
-
|
|
90
|
-
|
|
83
|
+
export function compileScreenBundle(file, options = {}) {
|
|
84
|
+
return compileSharedScreenBundle(file, options);
|
|
85
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { STXComponentType, STXNode } from './ir';
|
|
2
|
+
/** Map rendered HTML and primitive tags to the native IR vocabulary. */
|
|
3
|
+
export declare function mapToNativeComponent(tag: string): STXComponentType | string;
|
|
4
|
+
/** Transform a node tree to use native component types. */
|
|
5
|
+
export declare function transformToNativeComponents(node: STXNode): STXNode;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
const COMPONENT_MAPPING = {
|
|
2
|
+
view: "View",
|
|
3
|
+
text: "Text",
|
|
4
|
+
button: "Button",
|
|
5
|
+
image: "Image",
|
|
6
|
+
img: "Image",
|
|
7
|
+
input: "TextInput",
|
|
8
|
+
textarea: "TextInput",
|
|
9
|
+
scroll: "ScrollView",
|
|
10
|
+
scrollview: "ScrollView",
|
|
11
|
+
list: "FlatList",
|
|
12
|
+
flatlist: "FlatList",
|
|
13
|
+
modal: "Modal",
|
|
14
|
+
switch: "Switch",
|
|
15
|
+
slider: "Slider",
|
|
16
|
+
picker: "Picker",
|
|
17
|
+
select: "Picker",
|
|
18
|
+
loading: "ActivityIndicator",
|
|
19
|
+
spinner: "ActivityIndicator",
|
|
20
|
+
div: "View",
|
|
21
|
+
span: "Text",
|
|
22
|
+
p: "Text",
|
|
23
|
+
h1: "Text",
|
|
24
|
+
h2: "Text",
|
|
25
|
+
h3: "Text",
|
|
26
|
+
h4: "Text",
|
|
27
|
+
h5: "Text",
|
|
28
|
+
h6: "Text",
|
|
29
|
+
a: "TouchableOpacity",
|
|
30
|
+
section: "View",
|
|
31
|
+
article: "View",
|
|
32
|
+
header: "SafeAreaView",
|
|
33
|
+
footer: "View",
|
|
34
|
+
main: "View",
|
|
35
|
+
nav: "View",
|
|
36
|
+
aside: "View",
|
|
37
|
+
form: "View",
|
|
38
|
+
label: "Text",
|
|
39
|
+
fieldset: "View",
|
|
40
|
+
legend: "Text",
|
|
41
|
+
option: "Text",
|
|
42
|
+
dialog: "Modal",
|
|
43
|
+
figure: "View",
|
|
44
|
+
figcaption: "Text",
|
|
45
|
+
picture: "View",
|
|
46
|
+
hr: "View",
|
|
47
|
+
ul: "View",
|
|
48
|
+
ol: "View",
|
|
49
|
+
li: "View",
|
|
50
|
+
dl: "View",
|
|
51
|
+
dt: "Text",
|
|
52
|
+
dd: "Text",
|
|
53
|
+
table: "View",
|
|
54
|
+
thead: "View",
|
|
55
|
+
tbody: "View",
|
|
56
|
+
tfoot: "View",
|
|
57
|
+
tr: "View",
|
|
58
|
+
th: "Text",
|
|
59
|
+
td: "Text",
|
|
60
|
+
caption: "Text",
|
|
61
|
+
strong: "Text",
|
|
62
|
+
b: "Text",
|
|
63
|
+
em: "Text",
|
|
64
|
+
i: "Text",
|
|
65
|
+
u: "Text",
|
|
66
|
+
s: "Text",
|
|
67
|
+
small: "Text",
|
|
68
|
+
mark: "Text",
|
|
69
|
+
abbr: "Text",
|
|
70
|
+
time: "Text",
|
|
71
|
+
code: "Text",
|
|
72
|
+
kbd: "Text",
|
|
73
|
+
samp: "Text",
|
|
74
|
+
pre: "Text",
|
|
75
|
+
blockquote: "Text",
|
|
76
|
+
cite: "Text",
|
|
77
|
+
q: "Text",
|
|
78
|
+
sub: "Text",
|
|
79
|
+
sup: "Text"
|
|
80
|
+
};
|
|
81
|
+
export function mapToNativeComponent(tag) {
|
|
82
|
+
return COMPONENT_MAPPING[tag.toLowerCase()] || tag;
|
|
83
|
+
}
|
|
84
|
+
export function transformToNativeComponents(node) {
|
|
85
|
+
return {
|
|
86
|
+
...node,
|
|
87
|
+
type: mapToNativeComponent(node.type),
|
|
88
|
+
children: node.children.map((child) => typeof child === "string" ? child : transformToNativeComponents(child))
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { nativePropName } from "../prop-names.js";
|
|
2
|
+
import { mapToNativeComponent } from "./component-mapping.js";
|
|
1
3
|
import { compileHeadwindToStyle } from "./headwind-to-style.js";
|
|
2
4
|
import { createDocument, createNode } from "./ir.js";
|
|
3
|
-
import { mapToNativeComponent } from "./parser.js";
|
|
4
5
|
const DROP_SUBTREE = new Set(["script", "style", "head", "meta", "link", "title", "base", "noscript", "svg"]), UNWRAP = new Set(["template", "body", "html", "main", "fragment"]), BOX_ONLY = new Set(["svg"]), EVENT_NAMES = {
|
|
5
6
|
click: "onPress",
|
|
6
7
|
press: "onPress",
|
|
@@ -252,10 +253,11 @@ function readAttributes(tag, attributes, diagnostics) {
|
|
|
252
253
|
props.key = value;
|
|
253
254
|
continue;
|
|
254
255
|
}
|
|
256
|
+
const decoded = decodeEntities(value);
|
|
255
257
|
try {
|
|
256
|
-
props[rawName] = JSON.parse(
|
|
258
|
+
props[nativePropName(rawName)] = JSON.parse(decoded);
|
|
257
259
|
} catch {
|
|
258
|
-
props[rawName] =
|
|
260
|
+
props[nativePropName(rawName)] = decoded;
|
|
259
261
|
}
|
|
260
262
|
}
|
|
261
263
|
const style = { ...classes ? compileHeadwindToStyle(classes) : {}, ...inline };
|
|
@@ -269,8 +271,31 @@ function holdsString(property, value) {
|
|
|
269
271
|
return !0;
|
|
270
272
|
}
|
|
271
273
|
function inlineStyle(tag, css, diagnostics) {
|
|
272
|
-
const style = {};
|
|
273
|
-
|
|
274
|
+
const style = {}, decoded = decodeEntities(css);
|
|
275
|
+
try {
|
|
276
|
+
const object = JSON.parse(decoded);
|
|
277
|
+
if (object && typeof object === "object" && !Array.isArray(object)) {
|
|
278
|
+
for (const [rawProperty, rawValue] of Object.entries(object)) {
|
|
279
|
+
const property = STYLE_KEYS.has(rawProperty) ? rawProperty : camelCase(rawProperty.trim().toLowerCase());
|
|
280
|
+
if (!STYLE_KEYS.has(property)) {
|
|
281
|
+
diagnostics.push({ kind: "unknown-style", tag, name: property });
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (rawValue === null || rawValue === void 0)
|
|
285
|
+
continue;
|
|
286
|
+
const translated = typeof rawValue === "string" ? styleValue(rawValue) : rawValue;
|
|
287
|
+
if (typeof translated !== "string" && typeof translated !== "number")
|
|
288
|
+
continue;
|
|
289
|
+
if (typeof translated === "string" && !holdsString(property, translated)) {
|
|
290
|
+
diagnostics.push({ kind: "non-numeric-style", tag, name: property });
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
style[property] = translated;
|
|
294
|
+
}
|
|
295
|
+
return style;
|
|
296
|
+
}
|
|
297
|
+
} catch {}
|
|
298
|
+
for (const declaration of decoded.split(";")) {
|
|
274
299
|
const colon = declaration.indexOf(":");
|
|
275
300
|
if (colon === -1)
|
|
276
301
|
continue;
|
|
@@ -320,6 +345,14 @@ export async function translateHtmlToIR(html, options = {}) {
|
|
|
320
345
|
parent.node.children.push(node);
|
|
321
346
|
}
|
|
322
347
|
function hoist(frame) {
|
|
348
|
+
if (frame.node.bindings && Object.keys(frame.node.bindings).length > 0) {
|
|
349
|
+
const children = frame.node.children, elements = children.filter((child) => typeof child !== "string"), target = elements.length === 1 && elements.length === children.length ? elements[0] : createNode("View", {}, {}, {}, children);
|
|
350
|
+
target.bindings = { ...frame.node.bindings, ...target.bindings };
|
|
351
|
+
if (target.bindingId === void 0 && frame.node.bindingId !== void 0)
|
|
352
|
+
target.bindingId = frame.node.bindingId;
|
|
353
|
+
attach(target);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
323
356
|
const parent = stack[stack.length - 1];
|
|
324
357
|
for (const child of frame.node.children) {
|
|
325
358
|
if (typeof child === "string") {
|
|
@@ -349,7 +382,10 @@ export async function translateHtmlToIR(html, options = {}) {
|
|
|
349
382
|
seenUnmapped.add(`drop:${tag}`);
|
|
350
383
|
diagnostics.push({ kind: "dropped-subtree", tag });
|
|
351
384
|
}
|
|
352
|
-
const node = createNode(type, props, style, events);
|
|
385
|
+
const node = createNode(type, props, style, events), bindingId = props["data-stx-b"];
|
|
386
|
+
if (typeof bindingId === "number" && Number.isInteger(bindingId))
|
|
387
|
+
node.bindingId = bindingId;
|
|
388
|
+
delete props["data-stx-b"];
|
|
353
389
|
if (classes)
|
|
354
390
|
node._classes = classes;
|
|
355
391
|
if (Object.keys(bindings).length > 0)
|
|
@@ -5,6 +5,8 @@ export declare function createNode(type: STXComponentType | string, props?: Reco
|
|
|
5
5
|
export declare function createDocument(root: STXNode, script: STXDocument['script'], meta?: Partial<STXDocument['meta']>): STXDocument;
|
|
6
6
|
export declare interface STXNode {
|
|
7
7
|
type: STXComponentType | string
|
|
8
|
+
id?: string
|
|
9
|
+
bindingId?: number
|
|
8
10
|
key?: string
|
|
9
11
|
props: Record<string, unknown>
|
|
10
12
|
style: STXStyle
|