@stacksjs/tinker 0.75.542 → 0.75.544

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/index.d.ts CHANGED
@@ -65,6 +65,7 @@ export declare interface TinkerConfig {
65
65
  print?: string
66
66
  verbose?: boolean
67
67
  }
68
+ export * from './magic';
68
69
  export * from './protocol';
69
70
  export * from './serialize';
70
71
  export * from './session';
package/dist/index.js CHANGED
@@ -1,42 +1,48 @@
1
1
  // @bun
2
- import{appendFileSync as de,chmodSync as q,existsSync as J,readFileSync as fe,writeFileSync as K,writeSync as pe}from"fs";import{homedir as ge}from"os";import{join as ke,resolve as ye}from"path";import F from"process";import{writeSync as ue}from"fs";import{isAbsolute as ne,resolve as D}from"path";import E from"process";var Y={maxDepth:8,maxItems:200,maxString:20000,maxNodes:50000},G=/^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?\s*$/;function Q(e){if(!e)return[];let r=[];for(let n of e.split(`
3
- `)){let i=G.exec(n);if(!i)continue;r.push({function:i[1]||void 0,file:i[2],line:Number(i[3]),column:Number(i[4])})}return r}function X(e){if(Function.prototype.toString.call(e).startsWith("class"))return"class";let n=e.constructor?.name;if(n==="AsyncFunction"||n==="AsyncGeneratorFunction")return"async";if(n==="GeneratorFunction")return"generator";return"function"}function j(e){let r=Object.getPrototypeOf(e);if(r===null)return"null prototype";let n=r.constructor?.name;return typeof n==="string"&&n&&n!=="Object"?n:void 0}var _=2000000;class A{kind;html;title;text;constructor(e,r,n,i){this.kind=e;this.html=r;this.title=n;this.text=i}}var Z=["hasOne","hasMany","belongsTo","belongsToMany","hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany"];function R(e){let r=[];for(let n of Z){let i=e[n];if(!i)continue;if(Array.isArray(i)){for(let o of i)if(typeof o==="string")r.push({kind:n,model:o});else if(o&&typeof o==="object"&&typeof o.model==="string")r.push({kind:n,model:o.model,...typeof o.relationName==="string"?{name:o.relationName}:{}})}else if(typeof i==="object"){for(let[o,s]of Object.entries(i))if(typeof s==="string")r.push({kind:n,model:s,name:o})}else if(typeof i==="string")r.push({kind:n,model:i})}return r}function ee(e){let r=e._definition;return typeof r==="object"&&r!==null&&typeof r.name==="string"&&typeof e.toJSON==="function"&&typeof e.getAttributes==="function"}function O(e,r={}){let n={...Y,...r.limits},i=r.describers??[],o=new Map,s=0,b=1;function g(a,y){if(s++,a===void 0)return{t:"undefined"};if(a===null)return{t:"null"};switch(typeof a){case"boolean":return{t:"boolean",v:a};case"number":if(Number.isNaN(a))return{t:"number",v:"NaN"};if(a===Number.POSITIVE_INFINITY)return{t:"number",v:"Infinity"};if(a===Number.NEGATIVE_INFINITY)return{t:"number",v:"-Infinity"};if(Object.is(a,-0))return{t:"number",v:"-0"};return{t:"number",v:a};case"bigint":return{t:"bigint",v:a.toString()};case"string":return a.length>n.maxString?{t:"string",v:a.slice(0,n.maxString),truncated:a.length-n.maxString}:{t:"string",v:a};case"symbol":return{t:"symbol",v:a.description??""};case"function":return{t:"function",name:a.name||"(anonymous)",kind:X(a)}}let t=a,d=o.get(t);if(d!==void 0)return{t:"ref",id:d};if(t instanceof Date)return{t:"date",v:Number.isNaN(t.getTime())?null:t.toISOString()};if(t instanceof RegExp)return{t:"regexp",v:t.toString()};if(t instanceof URL)return{t:"url",v:t.href};if(t instanceof Promise)return{t:"promise"};if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer){let c=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return{t:"bytes",ctor:t.constructor?.name??"ArrayBuffer",length:c.byteLength,hex:Buffer.from(c.subarray(0,64)).toString("hex")}}if(y>=n.maxDepth)return{t:"cut",reason:"depth",ctor:j(t)??(Array.isArray(t)?"Array":"Object")};if(s>=n.maxNodes)return{t:"cut",reason:"nodes",ctor:j(t)};let u=b++;o.set(t,u);let l=(c)=>g(c,y+1);if(t instanceof Error)return k(t,l);if(t instanceof A){let c=t.html.length-_;return{t:"html",kind:t.kind,...t.title?{title:t.title}:{},html:c>0?t.html.slice(0,_):t.html,...t.text?{text:t.text.slice(0,n.maxString)}:{},...c>0?{truncated:c}:{}}}if(ee(t))return N(t,u,l);for(let c of i){let p;try{p=c(t,l)}catch{p=void 0}if(p)return p}if(Array.isArray(t)){let c=[],p=Math.min(t.length,n.maxItems);for(let S=0;S<p&&s<n.maxNodes;S++)c.push(l(t[S]));let f=t.length-c.length,m=j(t);return{t:"array",id:u,...m&&m!=="Array"?{ctor:m}:{},length:t.length,items:c,...f>0?{more:f}:{}}}if(t instanceof Map){let c=[];for(let[f,m]of t){if(c.length>=n.maxItems||s>=n.maxNodes)break;c.push([l(f),l(m)])}let p=t.size-c.length;return{t:"map",id:u,size:t.size,entries:c,...p>0?{more:p}:{}}}if(t instanceof Set){let c=[];for(let f of t){if(c.length>=n.maxItems||s>=n.maxNodes)break;c.push(l(f))}let p=t.size-c.length;return{t:"set",id:u,size:t.size,items:c,...p>0?{more:p}:{}}}return V(t,u,l)}function N(a,y,t){let d=a._definition,u={};try{let h=a.toJSON();if(h&&typeof h==="object")u=h}catch{}let l={};try{l=a.getLoadedRelations?.()??{}}catch{l={}}let c=Object.keys(u).filter((h)=>!(h in l)),p=[];for(let h of c){if(p.length>=n.maxItems||s>=n.maxNodes)break;p.push([h,t(u[h])])}let f=Object.keys(a).filter((h)=>!(h in u)),m=[];for(let[h,H]of Object.entries(l)){if(m.length>=n.maxItems||s>=n.maxNodes)break;m.push([h,t(H)])}let S=R(d),w=typeof d.primaryKey==="string"?d.primaryKey:"id",T=c.length-p.length;return{t:"model",id:y,model:d.name,...typeof d.table==="string"?{table:d.table}:{},primaryKey:w,...u[w]!==void 0?{key:t(u[w])}:{},attributes:p,...f.length?{hidden:f}:{},...m.length?{loaded:m}:{},...S.length?{relations:S}:{},...T>0?{more:T}:{}}}function V(a,y,t){let d=j(a),u=a,l=Object.keys(a);if(l.length===0&&d&&typeof a.toJSON==="function")try{let f=a.toJSON();if(Array.isArray(f)){let m=t(f);return m.t==="array"?{...m,ctor:d}:m}if(f&&typeof f==="object")u=f,l=Object.keys(u)}catch{}let c=[];for(let f of l){if(c.length>=n.maxItems||s>=n.maxNodes)break;let m;try{m=u[f]}catch(S){m=S}c.push([f,t(m)])}let p=l.length-c.length;return{t:"object",id:y,...d?{ctor:d}:{},entries:c,...p>0?{more:p}:{}}}function k(a,y){let t={t:"error",name:a.name||"Error",message:String(a.message??"")};if(typeof a.stack==="string"){t.stack=a.stack;let u=Q(a.stack);if(u.length)t.frames=u}if(a.cause!==void 0)t.cause=y(a.cause);let d=[];for(let u of Object.keys(a)){if(u==="name"||u==="message"||u==="stack"||u==="cause")continue;if(d.length>=n.maxItems)break;d.push([u,y(a[u])])}if(d.length)t.entries=d;return t}return g(e,0)}function P(e,r={}){if(e instanceof Error)return O(e,r);return{t:"error",name:"Thrown",message:typeof e==="string"?e:Bun.inspect(e),cause:O(e,r)}}function te(){let e=[],r=new Set;for(let n of Object.getOwnPropertyNames(globalThis)){let i;try{i=globalThis[n]}catch{continue}if(!i||typeof i!=="object"&&typeof i!=="function")continue;let o=i.getDefinition;if(typeof o!=="function")continue;let s;try{s=o.call(i)}catch{continue}if(!s||typeof s.name!=="string"||r.has(s.name))continue;r.add(s.name),e.push({name:s.name,...typeof s.table==="string"?{table:s.table}:{},...typeof s.primaryKey==="string"?{primaryKey:s.primaryKey}:{},attributes:s.attributes&&typeof s.attributes==="object"?Object.keys(s.attributes):[],relations:R(s)})}return e.sort((n,i)=>n.name.localeCompare(i.name))}function re(){return{html(e,r){return new A("html",String(e),r)},async mail(e,r={}){let{templateByName:i}=await import("@stacksjs/email"),o=await i(e,{variables:r});if(!o?.html)throw Error(`No mail template named "${e}" rendered. Templates live in resources/emails.`);return new A("mail",o.html,e,o.text)}}}class I extends Error{constructor(){super("dd");this.name="TinkerHalt"}}var ie=/\bimport\((["'])(\.{1,2}\/[^"']*)\1\)/g;function B(e,r,n="tinker"){return`${new Bun.Transpiler({loader:"ts",replMode:!0}).transformSync(e).replace(ie,(s,b,g)=>`import(${b}${D(r,g)}${b})`)}
4
- //# sourceURL=${n}.ts`}function oe(e){let r=e instanceof AggregateError?e.errors:[e],n=[];for(let i of r){if(!i||typeof i!=="object")continue;let{message:o,position:s}=i;n.push({message:typeof o==="string"?o:String(i),...s?.line!==void 0?{line:s.line}:{},...s?.column!==void 0?{column:s.column}:{},...s?.lineText?{lineText:s.lineText}:{}})}return n}async function se(e){let i=!0;try{let{overridesReady:o}=await import("@stacksjs/config");await o}catch(o){i=!1,e.push(`config not loaded: ${o instanceof Error?o.message:String(o)}`)}try{let{injectGlobalAutoImports:o}=await import("@stacksjs/server");await o()}catch(o){i=!1,e.push(`models and framework globals not injected: ${o instanceof Error?o.message:String(o)}`)}return i}var ae=["log","info","debug","dir","table"],ce=["warn","error","trace"];async function v(e={}){let r=e.cwd?ne(e.cwd)?e.cwd:D(E.cwd(),e.cwd):E.cwd();if(r!==E.cwd())E.chdir(r);let n={limits:e.limits,describers:e.describers},i=[],o=[],s="boot",b,g=(l)=>{b?.push(l);try{e.onFrame?.(l)}catch{}},N=console,V=(l)=>l.map((c)=>typeof c==="string"?c:Bun.inspect(c,{depth:6})).join(" ");for(let[l,c]of[[ae,"stdout"],[ce,"stderr"]])for(let p of l){let f=N[p];N[p]=(...m)=>g({type:c,id:s,text:`${V(m)}
5
- `}),o.push(()=>{N[p]=f})}for(let[l,c]of[[E.stdout,"stdout"],[E.stderr,"stderr"]]){let p=l.write;l.write=(f,...m)=>(g({type:c,id:s,text:typeof f==="string"?f:Buffer.from(f).toString("utf8")}),m.find((w)=>typeof w==="function")?.(),!0),o.push(()=>{l.write=p})}let k=globalThis;if(k.dump=(...l)=>{for(let c of l)g({type:"dump",id:s,value:O(c,n)})},k.dd=(...l)=>{throw k.dump(...l),new I},k.preview=re(),e.globals)Object.assign(k,e.globals);let a=!1;if(typeof e.boot==="function")try{await e.boot(),a=!0}catch(l){i.push(`boot failed: ${l instanceof Error?l.message:String(l)}`)}else if(e.boot!==!1)a=await se(i);if(a&&e.boot!==!1&&typeof e.boot!=="function"){let l=(...f)=>{for(let m of f)g({type:"dump",id:s,value:O(m,n)})};k.dump=l,k.dd=(...f)=>{throw l(...f),new I};let c="@stacksjs/logging",p="@stacksjs/query-builder";try{let{registerTransport:f}=await import(c);o.push(f({name:"tinker",log(m){g({type:"log",id:s,level:m.level,message:m.message,timestamp:m.timestamp,...m.context?{context:O(m.context,n)}:{}})}}))}catch(f){i.push(`log capture unavailable: ${f instanceof Error?f.message:String(f)}`)}try{let{registerPersistentQueryHooks:f}=await import(p);o.push(f({onQueryEnd(m){g({type:"query",id:s,sql:m.sql,...m.params?.length?{params:O(m.params,n)}:{},...m.kind?{kind:m.kind}:{},durationMs:m.durationMs,...m.rowCount!==void 0?{rowCount:m.rowCount}:{}})},onQueryError(m){g({type:"query",id:s,sql:m.sql,...m.params?.length?{params:O(m.params,n)}:{},...m.kind?{kind:m.kind}:{},durationMs:m.durationMs,error:m.error instanceof Error?m.error.message:String(m.error)})}}))}catch(f){i.push(`query capture unavailable: ${f instanceof Error?f.message:String(f)}`)}}let y=eval,t=0,d=Promise.resolve();async function u(l,c){let p=[];b=p,s=c;let f=performance.now(),m=()=>Math.round((performance.now()-f)*100)/100,S;try{S=B(l,r,`tinker-${c}`)}catch(w){let T=m();return g({type:"error",id:c,phase:"parse",error:P(w,n),diagnostics:oe(w),durationMs:T}),g({type:"done",id:c,ok:!1}),b=void 0,{id:c,ok:!1,thrown:w,frames:p,durationMs:T}}try{let T=(await y(S))?.value,h=m();return g({type:"result",id:c,value:O(T,n),durationMs:h}),g({type:"done",id:c,ok:!0}),{id:c,ok:!0,value:T,frames:p,durationMs:h}}catch(w){let T=m();if(w instanceof I)return g({type:"result",id:c,value:{t:"undefined"},durationMs:T}),g({type:"done",id:c,ok:!0}),{id:c,ok:!0,frames:p,durationMs:T};return g({type:"error",id:c,phase:"run",error:P(w,n),durationMs:T}),g({type:"done",id:c,ok:!1}),{id:c,ok:!1,thrown:w,frames:p,durationMs:T}}finally{b=void 0}}return{info:{cwd:r,booted:a,bun:Bun.version,warnings:i},models:te,evaluate(l,c={}){let p=c.id??String(++t),f=d.then(()=>u(l,p));return d=f.catch(()=>{}),f},dispose(){while(o.length)o.pop()?.()}}}var z="\x1E",me=2;function le(e){return`${z}${JSON.stringify(e)}
6
- `}function Ie(){let e="",r=(n)=>{if(n.startsWith(z))try{return{frame:JSON.parse(n.slice(z.length))}}catch{return{stray:n}}return{stray:n}};return{push(n){e+=n;let i=e.split(`
7
- `);return e=i.pop()??"",i.map(r)},flush(){if(!e)return[];let n=e;return e="",[{stray:n}]}}}async function L(e={}){let r=e.write??((d)=>{ue(1,d)}),n=(d)=>r(le(d)),{input:i,write:o,once:s,...b}=e,g=await v({...b,onFrame:n});n({type:"ready",session:g.info,protocol:me});let N=!0,V=!1;if(s!==void 0)return{ok:(await g.evaluate(s)).ok,session:g};let k=new TextDecoder,a="",y=i??Bun.stdin.stream(),t=async(d)=>{if(!d.trim())return!0;let u;try{u=JSON.parse(d)}catch{return n({type:"protocol-error",message:"request is not valid JSON"}),!0}if(u.op==="exit")return!1;if(u.op==="ping")return n({type:"pong",...u.id?{id:u.id}:{}}),!0;if(u.op==="models")return n({type:"models",...u.id?{id:u.id}:{},models:g.models()}),!0;if(u.op==="eval"&&typeof u.code==="string"){if(!(await g.evaluate(u.code,{id:u.id})).ok)N=!1;return!0}return n({type:"protocol-error",message:`unknown request: ${String(u.op)}`}),!0};e:for await(let d of y){a+=typeof d==="string"?d:k.decode(d,{stream:!0});let u=a.indexOf(`
8
- `);while(u!==-1){let l=a.slice(0,u);if(a=a.slice(u+1),!await t(l)){V=!0;break e}u=a.indexOf(`
9
- `)}}if(!V&&a.trim())await t(a);return{ok:N,session:g}}function C(e){return e?.historyFile??ke(ge(),".stacks_tinker_history")}function U(e){let r=C(e);if(!J(r))return[];return fe(r,"utf-8").split(`
10
- `).filter(Boolean)}function be(e,r){let n=C(r),i=!J(n);if(de(n,`${e}
11
- `),i)try{q(n,384)}catch{}let o=r?.historySize??5000,s=U(r);if(s.length>o){let b=s.slice(s.length-o);K(n,b.join(`
2
+ import{appendFileSync as Ce,chmodSync as ne,existsSync as re,readFileSync as ze,writeFileSync as ie,writeSync as Le}from"fs";import{homedir as De}from"os";import{join as qe,resolve as We}from"path";import F from"process";import{writeSync as _e}from"fs";import{isAbsolute as Me,resolve as ee}from"path";import A from"process";var ae=[">>>=","...","===","!==","**=","<<=",">>=",">>>","&&=","||=","??=","=>","==","!=","<=",">=","&&","||","??","?.","++","--","+=","-=","*=","/=","%=","&=","|=","^=","**","<<",">>"],ce=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]),q=new Set(["if","for","while","do","switch","try","function","class","import","export","throw","break","continue","interface","type","enum","declare","namespace"]);function ue(e){return/[\p{L}_$]/u.test(e)}function le(e){return/[\p{L}\p{N}_$]/u.test(e)}function U(e,i){let t=i+1;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`")return t+1;if(n==="$"&&e[t+1]==="{"){t+=2;let r=1;while(t<e.length&&r>0){let o=e[t];if(o==="`"){t=U(e,t);continue}if(o==="'"||o==='"'){t=K(e,t);continue}if(o==="{")r++;else if(o==="}")r--;t++}continue}t++}return e.length}function K(e,i){let t=e[i],n=i+1;while(n<e.length){let r=e[n];if(r==="\\"){n+=2;continue}if(r===t||r===`
3
+ `)return n+1;n++}return e.length}function me(e,i){let t=i+1,n=!1;while(t<e.length){let r=e[t];if(r==="\\"){t+=2;continue}if(r===`
4
+ `)return-1;if(r==="[")n=!0;else if(r==="]")n=!1;else if(r==="/"&&!n){t++;while(t<e.length&&/[a-z]/i.test(e[t]))t++;return t}t++}return-1}function fe(e){let i=[],t=0,n,r=(o,a)=>{let u={type:o,start:t,end:a,text:e.slice(t,a)};if(i.push(u),o!=="ws"&&o!=="nl"&&o!=="comment")n=u;t=a};while(t<e.length){let o=e[t];if(o===`
5
+ `)r("nl",t+1);else if(o===" "||o==="\t"||o==="\r"){let a=t+1;while(a<e.length&&(e[a]===" "||e[a]==="\t"||e[a]==="\r"))a++;r("ws",a)}else if(o==="/"&&e[t+1]==="/"){let a=t+2;while(a<e.length&&e[a]!==`
6
+ `)a++;r("comment",a)}else if(o==="/"&&e[t+1]==="*"){let a=e.indexOf("*/",t+2);r("comment",a===-1?e.length:a+2)}else if(o==="'"||o==='"')r("string",K(e,t));else if(o==="`")r("template",U(e,t));else if(o==="/"){let a=n,k=!a||a.type==="punct"&&a.text!==")"&&a.text!=="]"&&a.text!=="}"||a.type==="word"&&ce.has(a.text)?me(e,t):-1;if(k!==-1)r("regex",k);else r("punct",e[t+1]==="="?t+2:t+1)}else if(/\d/.test(o)||o==="."&&/\d/.test(e[t+1]??"")){let a=t+1;while(a<e.length&&/[\w.]/.test(e[a]))a++;r("number",a)}else if(ue(o)||o==="#"){let a=t+1;while(a<e.length&&le(e[a]))a++;r("word",a)}else{let a=ae.find((u)=>e.startsWith(u,t));r("punct",t+(a?.length??1))}}return i}var de={")":"(","]":"[","}":"{"},J=new Set([")","]","}"]),H=new Set(["(","[","{"]),pe=new Set([".","?.",",","(","[","=","=>","+","-","*","/","%","**","&&","||","??","?",":","<",">","<=",">=","==","===","!=","!==","&","|","^","!","~","+=","-=","*=","/=","??=","||=","&&="]),W=new Set([".","?.",",",")","]","=","=>","+","-","*","/","%","**","&&","||","??","?",":","<",">","<=",">=","==","===","!=","!==","&","|","^"]),ge=new Set(["return","await","typeof","new","in","of","instanceof","yield","void","delete","const","let","var","as"]);function G(e){return Boolean(e)&&e.type!=="ws"&&e.type!=="nl"&&e.type!=="comment"}function v(e,i){for(let t=i;t>=0;t--)if(G(e[t]))return t;return-1}function P(e,i){for(let t=i;t<e.length;t++)if(G(e[t]))return t;return-1}function ye(e,i){let t=0,n=i;for(let r=i;r>=0;r--){let o=e[r];if(o.type==="comment"||o.type==="ws")continue;if(o.type==="nl"){if(t>0)continue;let a=v(e,r-1),u=P(e,r+1);if(a===-1)return n;let k=e[a],w=e[u];if(!(k.type==="punct"&&pe.has(k.text)||k.type==="word"&&ge.has(k.text)||w?.type==="punct"&&W.has(w.text)))return n;continue}if(o.type==="punct"){if(J.has(o.text)){if(t===0&&o.text==="}"){let a=P(e,r+1),u=e.slice(r+1,a===-1?void 0:a).some((w)=>w.type==="nl"),k=a===-1?void 0:e[a];if(r!==i&&u&&!(k?.type==="punct"&&W.has(k.text)))return n}t++,n=r;continue}if(H.has(o.text)){if(t===0)return n;t--,n=r;continue}if(t===0&&(o.text===";"||o.text==="=>"))return n}n=r}return t===0?n:-1}function ke(e,i){let t=v(e,i-1);if(t===-1||t!==i-1)return-1;let n=-1,r=!0;while(t>=0){let a=e[t];if(a.type==="ws"||a.type==="comment")break;if(r){if(a.type==="punct"&&(a.text===")"||a.text==="]")){let u=0,k=t;for(;k>=0;k--){let b=e[k];if(b.type!=="punct")continue;if(b.text===a.text)u++;else if(b.text===de[a.text])u--;if(u===0)break}if(k<0)return-1;n=k,t=k-1;let w=e[t];if(w&&(w.type==="word"||w.type==="punct"&&(w.text===")"||w.text==="]"))){r=!0;continue}r=!1;continue}if(a.type==="word"||a.type==="string"||a.type==="template"||a.type==="number"||a.type==="regex"){n=t,t--,r=!1;continue}return-1}if(a.type==="punct"&&(a.text==="."||a.text==="?.")){t--,r=!0;continue}break}if(n===-1||r)return-1;let o=v(e,n-1);if(o!==-1&&e[o].type==="word"&&(e[o].text==="await"||e[o].text==="new"))n=o;return n}function be(e,i,t){let n=P(e,i+1);if(n===-1||n>t)return;let r=e[n];if(r.type==="word")return r.text;if(r.type!=="punct"||r.text!=="{"&&r.text!=="[")return;let o=[],a=0;for(let u=n;u<=t;u++){let k=e[u];if(k.type==="punct"&&H.has(k.text))a++;else if(k.type==="punct"&&J.has(k.text))a--;else if(k.type==="word"&&a>0){let w=P(e,u+1),b=v(e,u-1),c=w!==-1&&e[w].text===":",x=b!==-1&&e[b].text==="=";if(!c&&!x)o.push(k.text)}if(a===0&&u>n)break}return o.length?`{ ${o.join(", ")} }`:void 0}var Y=/^\/\/\?(\.)?\s*$/,Q=/^\/\*\?(.*)\*\/$/s;function he(e){return e.includes("//?")||e.includes("/*?")}function X(e,i={probe:"__tinkerProbe",time:"__tinkerTime"}){if(!he(e))return{code:e,probes:[]};let t=[],n=e,r=Number.POSITIVE_INFINITY;for(let o=0;o<500;o++){let a=fe(n),u=-1;for(let b=a.length-1;b>=0;b--){let c=a[b];if(c.type==="comment"&&c.start<r&&(Y.test(c.text)||Q.test(c.text))){u=b;break}}if(u===-1)break;let k=a[u],w=xe(n,a,u,i);if(!w){r=k.start;continue}n=n.slice(0,w.start)+w.text+n.slice(k.end),r=w.start+w.text.length,t.unshift({line:w.line,kind:w.kind})}return{code:n,probes:t}}function we(e,i){let t=0;for(let n=0;n<i;n++)if(e.charCodeAt(n)===10)t++;return t}function xe(e,i,t,n){let r=i[t],o=Y.exec(r.text),a=o?null:Q.exec(r.text),u=we(e,r.start),k=a?a[1].trim():"",w=Boolean(o?.[1])||k===".",b=k&&!w?`, __v => __v${k.startsWith(".")||k.startsWith("[")||k.startsWith("?.")?"":"."}${k}`:"",c=v(i,t-1);if(c===-1)return;if(a&&!w&&c===t-1){let l=ke(i,t);if(l===-1)return;let h=e.slice(i[l].start,i[c].end);return{start:i[l].start,text:`${n.probe}(${u}, (${h})${b})`,line:u,kind:"value"}}let x=c;if(i[x].type==="punct"&&i[x].text===";")x=v(i,x-1);if(x===-1)return;let s=i[c].end,d=e.slice(s,r.start).includes(`
7
+ `)?e.slice(s,r.start):"",f=ye(i,x);if(f===-1)return w?{start:s,text:`${d};${n.time}(${u})`,line:u,kind:"time"}:void 0;let y=i[f],m=e.slice(y.start,i[x].end);if(w)return!(y.type==="word"&&(y.text==="const"||y.text==="let"||y.text==="var"||y.text==="return"||q.has(y.text)))?{start:y.start,text:`${n.time}(${u}, (${m}))`,line:u,kind:"time"}:{start:s,text:`${d};${n.time}(${u})`,line:u,kind:"time"};if(y.type==="word"&&(y.text==="const"||y.text==="let"||y.text==="var")){let l=be(i,f,x);return l?{start:s,text:`;${n.probe}(${u}, ${l}${b})`,line:u,kind:"value"}:void 0}if(y.type==="word"&&y.text==="return"){let l=e.slice(y.end,i[x].end).trim();return l?{start:y.start,text:`return ${n.probe}(${u}, (${l})${b})`,line:u,kind:"value"}:void 0}if(y.type==="word"&&q.has(y.text))return;return{start:y.start,text:`${n.probe}(${u}, (${m})${b})`,line:u,kind:"value"}}var Te={maxDepth:8,maxItems:200,maxString:20000,maxNodes:50000},Se=/^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?\s*$/;function $e(e){if(!e)return[];let i=[];for(let t of e.split(`
8
+ `)){let n=Se.exec(t);if(!n)continue;i.push({function:n[1]||void 0,file:n[2],line:Number(n[3]),column:Number(n[4])})}return i}function Oe(e){if(Function.prototype.toString.call(e).startsWith("class"))return"class";let t=e.constructor?.name;if(t==="AsyncFunction"||t==="AsyncGeneratorFunction")return"async";if(t==="GeneratorFunction")return"generator";return"function"}function R(e){let i=Object.getPrototypeOf(e);if(i===null)return"null prototype";let t=i.constructor?.name;return typeof t==="string"&&t&&t!=="Object"?t:void 0}var Z=2000000;class I{kind;html;title;text;constructor(e,i,t,n){this.kind=e;this.html=i;this.title=t;this.text=n}}var Ne=["hasOne","hasMany","belongsTo","belongsToMany","hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany"];function B(e){let i=[];for(let t of Ne){let n=e[t];if(!n)continue;if(Array.isArray(n)){for(let r of n)if(typeof r==="string")i.push({kind:t,model:r});else if(r&&typeof r==="object"&&typeof r.model==="string")i.push({kind:t,model:r.model,...typeof r.relationName==="string"?{name:r.relationName}:{}})}else if(typeof n==="object"){for(let[r,o]of Object.entries(n))if(typeof o==="string")i.push({kind:t,model:o,name:r})}else if(typeof n==="string")i.push({kind:t,model:n})}return i}function Ee(e){let i=e._definition;return typeof i==="object"&&i!==null&&typeof i.name==="string"&&typeof e.toJSON==="function"&&typeof e.getAttributes==="function"}function E(e,i={}){let t={...Te,...i.limits},n=i.describers??[],r=new Map,o=0,a=1;function u(c,x){if(o++,c===void 0)return{t:"undefined"};if(c===null)return{t:"null"};switch(typeof c){case"boolean":return{t:"boolean",v:c};case"number":if(Number.isNaN(c))return{t:"number",v:"NaN"};if(c===Number.POSITIVE_INFINITY)return{t:"number",v:"Infinity"};if(c===Number.NEGATIVE_INFINITY)return{t:"number",v:"-Infinity"};if(Object.is(c,-0))return{t:"number",v:"-0"};return{t:"number",v:c};case"bigint":return{t:"bigint",v:c.toString()};case"string":return c.length>t.maxString?{t:"string",v:c.slice(0,t.maxString),truncated:c.length-t.maxString}:{t:"string",v:c};case"symbol":return{t:"symbol",v:c.description??""};case"function":return{t:"function",name:c.name||"(anonymous)",kind:Oe(c)}}let s=c,d=r.get(s);if(d!==void 0)return{t:"ref",id:d};if(s instanceof Date)return{t:"date",v:Number.isNaN(s.getTime())?null:s.toISOString()};if(s instanceof RegExp)return{t:"regexp",v:s.toString()};if(s instanceof URL)return{t:"url",v:s.href};if(s instanceof Promise)return{t:"promise"};if(ArrayBuffer.isView(s)||s instanceof ArrayBuffer){let m=s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength);return{t:"bytes",ctor:s.constructor?.name??"ArrayBuffer",length:m.byteLength,hex:Buffer.from(m.subarray(0,64)).toString("hex")}}if(x>=t.maxDepth)return{t:"cut",reason:"depth",ctor:R(s)??(Array.isArray(s)?"Array":"Object")};if(o>=t.maxNodes)return{t:"cut",reason:"nodes",ctor:R(s)};let f=a++;r.set(s,f);let y=(m)=>u(m,x+1);if(s instanceof Error)return b(s,y);if(s instanceof I){let m=s.html.length-Z;return{t:"html",kind:s.kind,...s.title?{title:s.title}:{},html:m>0?s.html.slice(0,Z):s.html,...s.text?{text:s.text.slice(0,t.maxString)}:{},...m>0?{truncated:m}:{}}}if(Ee(s))return k(s,f,y);for(let m of n){let l;try{l=m(s,y)}catch{l=void 0}if(l)return l}if(Array.isArray(s)){let m=[],l=Math.min(s.length,t.maxItems);for(let p=0;p<l&&o<t.maxNodes;p++)m.push(y(s[p]));let h=s.length-m.length,g=R(s);return{t:"array",id:f,...g&&g!=="Array"?{ctor:g}:{},length:s.length,items:m,...h>0?{more:h}:{}}}if(s instanceof Map){let m=[];for(let[h,g]of s){if(m.length>=t.maxItems||o>=t.maxNodes)break;m.push([y(h),y(g)])}let l=s.size-m.length;return{t:"map",id:f,size:s.size,entries:m,...l>0?{more:l}:{}}}if(s instanceof Set){let m=[];for(let h of s){if(m.length>=t.maxItems||o>=t.maxNodes)break;m.push(y(h))}let l=s.size-m.length;return{t:"set",id:f,size:s.size,items:m,...l>0?{more:l}:{}}}return w(s,f,y)}function k(c,x,s){let d=c._definition,f={};try{let T=c.toJSON();if(T&&typeof T==="object")f=T}catch{}let y={};try{y=c.getLoadedRelations?.()??{}}catch{y={}}let m=Object.keys(f).filter((T)=>!(T in y)),l=[];for(let T of m){if(l.length>=t.maxItems||o>=t.maxNodes)break;l.push([T,s(f[T])])}let h=Object.keys(c).filter((T)=>!(T in f)),g=[];for(let[T,V]of Object.entries(y)){if(g.length>=t.maxItems||o>=t.maxNodes)break;g.push([T,s(V)])}let p=B(d),S=typeof d.primaryKey==="string"?d.primaryKey:"id",O=m.length-l.length;return{t:"model",id:x,model:d.name,...typeof d.table==="string"?{table:d.table}:{},primaryKey:S,...f[S]!==void 0?{key:s(f[S])}:{},attributes:l,...h.length?{hidden:h}:{},...g.length?{loaded:g}:{},...p.length?{relations:p}:{},...O>0?{more:O}:{}}}function w(c,x,s){let d=R(c),f=c,y=Object.keys(c);if(y.length===0&&d&&typeof c.toJSON==="function")try{let h=c.toJSON();if(Array.isArray(h)){let g=s(h);return g.t==="array"?{...g,ctor:d}:g}if(h&&typeof h==="object")f=h,y=Object.keys(f)}catch{}let m=[];for(let h of y){if(m.length>=t.maxItems||o>=t.maxNodes)break;let g;try{g=f[h]}catch(p){g=p}m.push([h,s(g)])}let l=y.length-m.length;return{t:"object",id:x,...d?{ctor:d}:{},entries:m,...l>0?{more:l}:{}}}function b(c,x){let s={t:"error",name:c.name||"Error",message:String(c.message??"")};if(typeof c.stack==="string"){s.stack=c.stack;let f=$e(c.stack);if(f.length)s.frames=f}if(c.cause!==void 0)s.cause=x(c.cause);let d=[];for(let f of Object.keys(c)){if(f==="name"||f==="message"||f==="stack"||f==="cause")continue;if(d.length>=t.maxItems)break;d.push([f,x(c[f])])}if(d.length)s.entries=d;return s}return u(e,0)}function C(e,i={}){if(e instanceof Error)return E(e,i);return{t:"error",name:"Thrown",message:typeof e==="string"?e:Bun.inspect(e),cause:E(e,i)}}function ve(){let e=[],i=new Set;for(let t of Object.getOwnPropertyNames(globalThis)){let n;try{n=globalThis[t]}catch{continue}if(!n||typeof n!=="object"&&typeof n!=="function")continue;let r=n.getDefinition;if(typeof r!=="function")continue;let o;try{o=r.call(n)}catch{continue}if(!o||typeof o.name!=="string"||i.has(o.name))continue;i.add(o.name),e.push({name:o.name,...typeof o.table==="string"?{table:o.table}:{},...typeof o.primaryKey==="string"?{primaryKey:o.primaryKey}:{},attributes:o.attributes&&typeof o.attributes==="object"?Object.keys(o.attributes):[],relations:B(o)})}return e.sort((t,n)=>t.name.localeCompare(n.name))}function Ae(){return{html(e,i){return new I("html",String(e),i)},async mail(e,i={}){let{templateByName:n}=await import("@stacksjs/email"),r=await n(e,{variables:i});if(!r?.html)throw Error(`No mail template named "${e}" rendered. Templates live in resources/emails.`);return new I("mail",r.html,e,r.text)}}}class j extends Error{constructor(){super("dd");this.name="TinkerHalt"}}var Ie=/\bimport\((["'])(\.{1,2}\/[^"']*)\1\)/g;function z(e,i,t="tinker"){return`${new Bun.Transpiler({loader:"ts",replMode:!0}).transformSync(e).replace(Ie,(o,a,u)=>`import(${a}${ee(i,u)}${a})`)}
9
+ //# sourceURL=${t}.ts`}function Ve(e){let i=e instanceof AggregateError?e.errors:[e],t=[];for(let n of i){if(!n||typeof n!=="object")continue;let{message:r,position:o}=n;t.push({message:typeof r==="string"?r:String(n),...o?.line!==void 0?{line:o.line}:{},...o?.column!==void 0?{column:o.column}:{},...o?.lineText?{lineText:o.lineText}:{}})}return t}async function Pe(e){let n=!0;try{let{overridesReady:r}=await import("@stacksjs/config");await r}catch(r){n=!1,e.push(`config not loaded: ${r instanceof Error?r.message:String(r)}`)}try{let{injectGlobalAutoImports:r}=await import("@stacksjs/server");await r()}catch(r){n=!1,e.push(`models and framework globals not injected: ${r instanceof Error?r.message:String(r)}`)}return n}var Re=["log","info","debug","dir","table"],je=["warn","error","trace"];async function _(e={}){let i=e.cwd?Me(e.cwd)?e.cwd:ee(A.cwd(),e.cwd):A.cwd();if(i!==A.cwd())A.chdir(i);let t={limits:e.limits,describers:e.describers},n=[],r=[],o="boot",a,u=(m)=>{a?.push(m);try{e.onFrame?.(m)}catch{}},k=console,w=(m)=>m.map((l)=>typeof l==="string"?l:Bun.inspect(l,{depth:6})).join(" ");for(let[m,l]of[[Re,"stdout"],[je,"stderr"]])for(let h of m){let g=k[h];k[h]=(...p)=>u({type:l,id:o,text:`${w(p)}
10
+ `}),r.push(()=>{k[h]=g})}for(let[m,l]of[[A.stdout,"stdout"],[A.stderr,"stderr"]]){let h=m.write;m.write=(g,...p)=>(u({type:l,id:o,text:typeof g==="string"?g:Buffer.from(g).toString("utf8")}),p.find((O)=>typeof O==="function")?.(),!0),r.push(()=>{m.write=h})}let b=globalThis;b.dump=(...m)=>{for(let l of m)u({type:"dump",id:o,value:E(l,t)})},b.dd=(...m)=>{throw b.dump(...m),new j},b.preview=Ae();let c=performance.now();if(b.__tinkerProbe=(m,l,h)=>{let g=o,p=(S)=>u({type:"probe",id:g,line:m,kind:"value",value:E(S,t)});if(!h)return p(l),l;try{let S=h(l);if(S instanceof Promise)S.then(p,(O)=>p(O));else p(S)}catch(S){p(S)}return l},b.__tinkerTime=(m,l)=>(u({type:"probe",id:o,line:m,kind:"time",ms:Math.round((performance.now()-c)*100)/100}),l),e.globals)Object.assign(b,e.globals);let x=!1;if(typeof e.boot==="function")try{await e.boot(),x=!0}catch(m){n.push(`boot failed: ${m instanceof Error?m.message:String(m)}`)}else if(e.boot!==!1)x=await Pe(n);if(x&&e.boot!==!1&&typeof e.boot!=="function"){let m=(...g)=>{for(let p of g)u({type:"dump",id:o,value:E(p,t)})};b.dump=m,b.dd=(...g)=>{throw m(...g),new j};let l="@stacksjs/logging",h="@stacksjs/query-builder";try{let{registerTransport:g}=await import(l);r.push(g({name:"tinker",log(p){u({type:"log",id:o,level:p.level,message:p.message,timestamp:p.timestamp,...p.context?{context:E(p.context,t)}:{}})}}))}catch(g){n.push(`log capture unavailable: ${g instanceof Error?g.message:String(g)}`)}try{let{registerPersistentQueryHooks:g}=await import(h);r.push(g({onQueryEnd(p){u({type:"query",id:o,sql:p.sql,...p.params?.length?{params:E(p.params,t)}:{},...p.kind?{kind:p.kind}:{},durationMs:p.durationMs,...p.rowCount!==void 0?{rowCount:p.rowCount}:{}})},onQueryError(p){u({type:"query",id:o,sql:p.sql,...p.params?.length?{params:E(p.params,t)}:{},...p.kind?{kind:p.kind}:{},durationMs:p.durationMs,error:p.error instanceof Error?p.error.message:String(p.error)})}}))}catch(g){n.push(`query capture unavailable: ${g instanceof Error?g.message:String(g)}`)}}let s=eval,d=0,f=Promise.resolve();async function y(m,l){let h=[];a=h,o=l;let g=performance.now();c=g;let p=()=>Math.round((performance.now()-g)*100)/100,S;try{S=z(e.magic===!1?m:X(m).code,i,`tinker-${l}`)}catch(O){let T=p();return u({type:"error",id:l,phase:"parse",error:C(O,t),diagnostics:Ve(O),durationMs:T}),u({type:"done",id:l,ok:!1}),a=void 0,{id:l,ok:!1,thrown:O,frames:h,durationMs:T}}try{let T=(await s(S))?.value,V=p();return u({type:"result",id:l,value:E(T,t),durationMs:V}),u({type:"done",id:l,ok:!0}),{id:l,ok:!0,value:T,frames:h,durationMs:V}}catch(O){let T=p();if(O instanceof j)return u({type:"result",id:l,value:{t:"undefined"},durationMs:T}),u({type:"done",id:l,ok:!0}),{id:l,ok:!0,frames:h,durationMs:T};return u({type:"error",id:l,phase:"run",error:C(O,t),durationMs:T}),u({type:"done",id:l,ok:!1}),{id:l,ok:!1,thrown:O,frames:h,durationMs:T}}finally{a=void 0}}return{info:{cwd:i,booted:x,bun:Bun.version,warnings:n},models:ve,evaluate(m,l={}){let h=l.id??String(++d),g=f.then(()=>y(m,h));return f=g.catch(()=>{}),g},dispose(){while(r.length)r.pop()?.()}}}var L="\x1E",Fe=2;function Be(e){return`${L}${JSON.stringify(e)}
11
+ `}function at(){let e="",i=(t)=>{if(t.startsWith(L))try{return{frame:JSON.parse(t.slice(L.length))}}catch{return{stray:t}}return{stray:t}};return{push(t){e+=t;let n=e.split(`
12
+ `);return e=n.pop()??"",n.map(i)},flush(){if(!e)return[];let t=e;return e="",[{stray:t}]}}}async function te(e={}){let i=e.write??((d)=>{_e(1,d)}),t=(d)=>i(Be(d)),{input:n,write:r,once:o,...a}=e,u=await _({...a,onFrame:t});t({type:"ready",session:u.info,protocol:Fe});let k=!0,w=!1;if(o!==void 0)return{ok:(await u.evaluate(o)).ok,session:u};let b=new TextDecoder,c="",x=n??Bun.stdin.stream(),s=async(d)=>{if(!d.trim())return!0;let f;try{f=JSON.parse(d)}catch{return t({type:"protocol-error",message:"request is not valid JSON"}),!0}if(f.op==="exit")return!1;if(f.op==="ping")return t({type:"pong",...f.id?{id:f.id}:{}}),!0;if(f.op==="models")return t({type:"models",...f.id?{id:f.id}:{},models:u.models()}),!0;if(f.op==="eval"&&typeof f.code==="string"){if(!(await u.evaluate(f.code,{id:f.id})).ok)k=!1;return!0}return t({type:"protocol-error",message:`unknown request: ${String(f.op)}`}),!0};e:for await(let d of x){c+=typeof d==="string"?d:b.decode(d,{stream:!0});let f=c.indexOf(`
13
+ `);while(f!==-1){let y=c.slice(0,f);if(c=c.slice(f+1),!await s(y)){w=!0;break e}f=c.indexOf(`
14
+ `)}}if(!w&&c.trim())await s(c);return{ok:k,session:u}}function D(e){return e?.historyFile??qe(De(),".stacks_tinker_history")}function oe(e){let i=D(e);if(!re(i))return[];return ze(i,"utf-8").split(`
15
+ `).filter(Boolean)}function Ue(e,i){let t=D(i),n=!re(t);if(Ce(t,`${e}
16
+ `),n)try{ne(t,384)}catch{}let r=i?.historySize??5000,o=oe(i);if(o.length>r){let a=o.slice(o.length-r);ie(t,a.join(`
12
17
  `)+`
13
- `);try{q(n,384)}catch{}}}function he(e){let r=C(e);K(r,"")}function we(e){let r=["",` \x1B[36mStacks Tinker\x1B[0m (Bun v${e.bun})`,e.booted?" Your app is booted: models, jobs, config and framework helpers are globals.":" Bare session: the app context is not booted."];for(let n of e.warnings)r.push(` \x1B[33m${n}\x1B[0m`);return r.push(""," \x1B[2mDeclarations persist between lines. dump(value) inspects, dd(value) inspects and stops."," .help for commands, .exit or Ctrl+D to leave.\x1B[0m","",""),r.join(`
14
- `)}function x(e,r=1){pe(r,e)}function M(e,r=""){let n=`${r} `;switch(e.t){case"undefined":return"undefined";case"null":return"null";case"boolean":return String(e.v);case"number":return String(e.v);case"bigint":return`${e.v}n`;case"string":return JSON.stringify(e.v)+(e.truncated?` ... ${e.truncated} more characters`:"");case"symbol":return`Symbol(${e.v})`;case"function":return`[${e.kind==="class"?"class":"Function"}: ${e.name}]`;case"date":return e.v??"Invalid Date";case"regexp":return e.v;case"url":return e.v;case"promise":return"Promise {}";case"bytes":return`${e.ctor}(${e.length}) <${e.hex}${e.length>64?" ...":""}>`;case"ref":return`[Circular *${e.id}]`;case"cut":return`[${e.ctor??"Object"}]`;case"error":return e.stack??`${e.name}: ${e.message}`;case"array":{if(!e.items.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}[]`;let i=e.items.map((o)=>`${n}${M(o,n)}`);if(e.more)i.push(`${n}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}[
15
- ${i.join(`,
18
+ `);try{ne(t,384)}catch{}}}function Ke(e){let i=D(e);ie(i,"")}function Je(e){let i=["",` \x1B[36mStacks Tinker\x1B[0m (Bun v${e.bun})`,e.booted?" Your app is booted: models, jobs, config and framework helpers are globals.":" Bare session: the app context is not booted."];for(let t of e.warnings)i.push(` \x1B[33m${t}\x1B[0m`);return i.push(""," \x1B[2mDeclarations persist between lines. dump(value) inspects, dd(value) inspects and stops."," .help for commands, .exit or Ctrl+D to leave.\x1B[0m","",""),i.join(`
19
+ `)}function N(e,i=1){Le(i,e)}function M(e,i=""){let t=`${i} `;switch(e.t){case"undefined":return"undefined";case"null":return"null";case"boolean":return String(e.v);case"number":return String(e.v);case"bigint":return`${e.v}n`;case"string":return JSON.stringify(e.v)+(e.truncated?` ... ${e.truncated} more characters`:"");case"symbol":return`Symbol(${e.v})`;case"function":return`[${e.kind==="class"?"class":"Function"}: ${e.name}]`;case"date":return e.v??"Invalid Date";case"regexp":return e.v;case"url":return e.v;case"promise":return"Promise {}";case"bytes":return`${e.ctor}(${e.length}) <${e.hex}${e.length>64?" ...":""}>`;case"ref":return`[Circular *${e.id}]`;case"cut":return`[${e.ctor??"Object"}]`;case"error":return e.stack??`${e.name}: ${e.message}`;case"array":{if(!e.items.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}[]`;let n=e.items.map((r)=>`${t}${M(r,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}[
20
+ ${n.join(`,
16
21
  `)}
17
- ${r}]`}case"set":{let i=e.items.map((o)=>`${n}${M(o,n)}`);if(e.more)i.push(`${n}... ${e.more} more`);return i.length?`Set(${e.size}) {
18
- ${i.join(`,
22
+ ${i}]`}case"set":{let n=e.items.map((r)=>`${t}${M(r,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return n.length?`Set(${e.size}) {
23
+ ${n.join(`,
19
24
  `)}
20
- ${r}}`:"Set(0) {}"}case"map":{let i=e.entries.map(([o,s])=>`${n}${M(o,n)} => ${M(s,n)}`);if(e.more)i.push(`${n}... ${e.more} more`);return i.length?`Map(${e.size}) {
21
- ${i.join(`,
25
+ ${i}}`:"Set(0) {}"}case"map":{let n=e.entries.map(([r,o])=>`${t}${M(r,t)} => ${M(o,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return n.length?`Map(${e.size}) {
26
+ ${n.join(`,
22
27
  `)}
23
- ${r}}`:"Map(0) {}"}case"html":return`[${e.kind}${e.title?` ${e.title}`:""}: ${e.html.length} characters of markup]`;case"model":{let i=e.attributes.map(([o,s])=>`${n}${o}: ${M(s,n)}`);for(let o of e.hidden??[])i.push(`${n}${o}: [hidden]`);for(let[o,s]of e.loaded??[])i.push(`${n}${o}: ${M(s,n)}`);if(e.more)i.push(`${n}... ${e.more} more`);return`${e.model} {
24
- ${i.join(`,
28
+ ${i}}`:"Map(0) {}"}case"html":return`[${e.kind}${e.title?` ${e.title}`:""}: ${e.html.length} characters of markup]`;case"model":{let n=e.attributes.map(([r,o])=>`${t}${r}: ${M(o,t)}`);for(let r of e.hidden??[])n.push(`${t}${r}: [hidden]`);for(let[r,o]of e.loaded??[])n.push(`${t}${r}: ${M(o,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.model} {
29
+ ${n.join(`,
25
30
  `)}
26
- ${r}}`}case"object":{if(!e.entries.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}{}`;let i=e.entries.map(([o,s])=>`${n}${o}: ${M(s,n)}`);if(e.more)i.push(`${n}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}{
27
- ${i.join(`,
31
+ ${i}}`}case"object":{if(!e.entries.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}{}`;let n=e.entries.map(([r,o])=>`${t}${r}: ${M(o,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}{
32
+ ${n.join(`,
28
33
  `)}
29
- ${r}}`}}}function Te(e,r){switch(e.type){case"stdout":x(e.text);break;case"stderr":x(e.text,2);break;case"dump":x(`${M(e.value)}
30
- `);break;case"query":if(r)x(`\x1B[2m ${e.durationMs??"?"}ms ${e.sql}\x1B[0m
31
- `,2);break;case"log":if(r)x(`\x1B[2m [${e.level}] ${e.message}\x1B[0m
32
- `,2);break}}async function xe(e,r){let n=[];for(let i of e??[]){let o=i.replace(/[@/\-.]/g,"_").replace(/^_+/,"");try{let s=i.startsWith(".")?ye(r,i):i;globalThis[o]=await import(s)}catch(s){n.push(`${i}: ${s instanceof Error?s.message:String(s)}`)}}return n}var Se=/Unexpected end of file|Unterminated|Expected "\}" but found end of file|Expected "\)" but found end of file|Expected "\]" but found end of file/;function $e(e,r){try{return B(e,r),!1}catch(n){return(n instanceof AggregateError?n.errors.map((o)=>String(o?.message??o)):[String(n?.message??n)]).some((o)=>Se.test(o))}}async function W(e={}){let r=e.cwd??F.cwd(),n=e.stacksPreload!==!1;if(e.serve){let t=e.eval??e.print,{ok:d}=await L({cwd:r,boot:n,...t!==void 0?{once:t}:{}});return{exitCode:d?0:1}}let i=e.verbose===!0,o=await v({cwd:r,boot:n,onFrame:(t)=>Te(t,i)});for(let t of await xe(e.preload,o.info.cwd))x(`\x1B[33mpreload failed: ${t}\x1B[0m
33
- `,2);let s=(t,d)=>{if(!t.ok){let u=t.thrown;x(`${u instanceof Error?Bun.inspect(u,{colors:Boolean(F.stderr.isTTY)}):`Uncaught ${Bun.inspect(u)}`}
34
- `,2);return}if(d&&t.value!==void 0)x(`${M(O(t.value))}
35
- `)};if(e.eval!==void 0||e.print!==void 0){for(let d of o.info.warnings)x(`\x1B[33m${d}\x1B[0m
36
- `,2);let t=await o.evaluate(e.print??e.eval??"");return s(t,e.print!==void 0),o.dispose(),{exitCode:t.ok?0:1}}if(e.banner!==!1)x(we(o.info));let{createInterface:b}=await import("readline"),{Writable:g}=await import("stream"),N=new g({write(t,d,u){x(typeof t==="string"?t:Buffer.from(t).toString("utf8")),u()}}),V=e.historySize??5000,k=b({input:F.stdin,output:N,terminal:Boolean(F.stdin.isTTY),history:U(e).slice(-V).reverse(),historySize:V,prompt:"> "}),a="",y=0;k.prompt();try{for await(let t of k){let d=t.trim();if(!a&&d.startsWith(".")){if(d===".exit")break;if(d===".help")x(` .exit leave
34
+ ${i}}`}}}function He(e,i){switch(e.type){case"stdout":N(e.text);break;case"stderr":N(e.text,2);break;case"dump":N(`${M(e.value)}
35
+ `);break;case"probe":N(`\x1B[2m line ${e.line+1}:\x1B[0m ${e.kind==="time"?`${e.ms} ms`:M(e.value," ")}
36
+ `);break;case"query":if(i)N(`\x1B[2m ${e.durationMs??"?"}ms ${e.sql}\x1B[0m
37
+ `,2);break;case"log":if(i)N(`\x1B[2m [${e.level}] ${e.message}\x1B[0m
38
+ `,2);break}}async function Ge(e,i){let t=[];for(let n of e??[]){let r=n.replace(/[@/\-.]/g,"_").replace(/^_+/,"");try{let o=n.startsWith(".")?We(i,n):n;globalThis[r]=await import(o)}catch(o){t.push(`${n}: ${o instanceof Error?o.message:String(o)}`)}}return t}var Ye=/Unexpected end of file|Unterminated|Expected "\}" but found end of file|Expected "\)" but found end of file|Expected "\]" but found end of file/;function Qe(e,i){try{return z(e,i),!1}catch(t){return(t instanceof AggregateError?t.errors.map((r)=>String(r?.message??r)):[String(t?.message??t)]).some((r)=>Ye.test(r))}}async function se(e={}){let i=e.cwd??F.cwd(),t=e.stacksPreload!==!1;if(e.serve){let s=e.eval??e.print,{ok:d}=await te({cwd:i,boot:t,...s!==void 0?{once:s}:{}});return{exitCode:d?0:1}}let n=e.verbose===!0,r=await _({cwd:i,boot:t,onFrame:(s)=>He(s,n)});for(let s of await Ge(e.preload,r.info.cwd))N(`\x1B[33mpreload failed: ${s}\x1B[0m
39
+ `,2);let o=(s,d)=>{if(!s.ok){let f=s.thrown;N(`${f instanceof Error?Bun.inspect(f,{colors:Boolean(F.stderr.isTTY)}):`Uncaught ${Bun.inspect(f)}`}
40
+ `,2);return}if(d&&s.value!==void 0)N(`${M(E(s.value))}
41
+ `)};if(e.eval!==void 0||e.print!==void 0){for(let d of r.info.warnings)N(`\x1B[33m${d}\x1B[0m
42
+ `,2);let s=await r.evaluate(e.print??e.eval??"");return o(s,e.print!==void 0),r.dispose(),{exitCode:s.ok?0:1}}if(e.banner!==!1)N(Je(r.info));let{createInterface:a}=await import("readline"),{Writable:u}=await import("stream"),k=new u({write(s,d,f){N(typeof s==="string"?s:Buffer.from(s).toString("utf8")),f()}}),w=e.historySize??5000,b=a({input:F.stdin,output:k,terminal:Boolean(F.stdin.isTTY),history:oe(e).slice(-w).reverse(),historySize:w,prompt:"> "}),c="",x=0;b.prompt();try{for await(let s of b){let d=s.trim();if(!c&&d.startsWith(".")){if(d===".exit")break;if(d===".help")N(` .exit leave
37
43
  .clear forget the history file
38
44
  .help this list
39
45
  dump(v), dd(v) inspect a value; dd also stops the line
40
- `);else if(d===".clear")he(e);else x(` unknown command ${d}
41
- `);k.prompt();continue}if(a=a?`${a}
42
- ${t}`:t,!a.trim()){a="",k.prompt();continue}if($e(a,o.info.cwd)){k.setPrompt("... "),k.prompt();continue}let u=a;a="";try{be(u.replace(/\n/g," "),e)}catch{}let l=await o.evaluate(u);s(l,!0),y=l.ok?0:y,k.setPrompt("> "),k.prompt()}}finally{k.close(),o.dispose()}return{exitCode:y}}async function De(e,r={}){return W({...r,eval:e})}async function Le(e,r={}){return W({...r,print:e})}export{z as FRAME_MARKER,me as PROTOCOL_VERSION,A as TinkerPreview,be as appendHistory,he as clearHistory,B as compileSnippet,Ie as createFrameReader,v as createTinkerSession,Y as defaultSerializeLimits,le as encodeFrame,C as getHistoryPath,$e as isIncompleteSnippet,ee as isModelInstance,te as listModels,Q as parseStack,U as readHistory,R as relationsOf,M as renderValue,O as serialize,P as serializeThrown,L as serveTinker,W as startTinker,De as tinkerEval,Le as tinkerPrint};
46
+ `);else if(d===".clear")Ke(e);else N(` unknown command ${d}
47
+ `);b.prompt();continue}if(c=c?`${c}
48
+ ${s}`:s,!c.trim()){c="",b.prompt();continue}if(Qe(c,r.info.cwd)){b.setPrompt("... "),b.prompt();continue}let f=c;c="";try{Ue(f.replace(/\n/g," "),e)}catch{}let y=await r.evaluate(f);o(y,!0),x=y.ok?0:x,b.setPrompt("> "),b.prompt()}}finally{b.close(),r.dispose()}return{exitCode:x}}async function yt(e,i={}){return se({...i,eval:e})}async function kt(e,i={}){return se({...i,print:e})}export{L as FRAME_MARKER,Fe as PROTOCOL_VERSION,I as TinkerPreview,Ue as appendHistory,Ke as clearHistory,z as compileSnippet,at as createFrameReader,_ as createTinkerSession,Te as defaultSerializeLimits,Be as encodeFrame,D as getHistoryPath,he as hasMagicComments,X as instrumentMagicComments,Qe as isIncompleteSnippet,Ee as isModelInstance,ve as listModels,$e as parseStack,oe as readHistory,B as relationsOf,M as renderValue,E as serialize,C as serializeThrown,te as serveTinker,se as startTinker,yt as tinkerEval,kt as tinkerPrint,fe as tokenize};
@@ -0,0 +1,32 @@
1
+ export declare function tokenize(code: string): Token[];
2
+ /** Whether a snippet has anything for the transform to do. A cheap test before tokenizing. */
3
+ export declare function hasMagicComments(code: string): boolean;
4
+ /**
5
+ * Rewrite magic comments into probe calls. `probe` and `time` name the
6
+ * functions the session provides.
7
+ */
8
+ export declare function instrumentMagicComments(code: string, names?: { probe: string, time: string }): Instrumented;
9
+ /*?.*\/` at the end of a statement) shows the milliseconds
10
+ * since the run began.
11
+ *
12
+ * The transform rewrites the source in place and never adds or removes a line,
13
+ * so every line number an error or a probe reports is the one the user sees.
14
+ * It works from tokens, not a syntax tree, which is a deliberate limit: a
15
+ * comment it cannot place with certainty is left alone as an ordinary comment
16
+ * rather than guessed at.
17
+ */
18
+ declare interface Token {
19
+ type: 'ws' | 'nl' | 'comment' | 'string' | 'template' | 'regex' | 'number' | 'word' | 'punct'
20
+ start: number
21
+ end: number
22
+ text: string
23
+ }
24
+ export declare interface MagicProbe {
25
+ line: number
26
+ kind: 'value' | 'time'
27
+ }
28
+ export declare interface Instrumented {
29
+ code: string
30
+ probes: MagicProbe[]
31
+ }
32
+ export {};
package/dist/session.d.ts CHANGED
@@ -30,6 +30,7 @@ export declare interface TinkerSessionOptions extends SerializeOptions {
30
30
  cwd?: string
31
31
  boot?: boolean | (() => Promise<void> | void)
32
32
  globals?: Record<string, unknown>
33
+ magic?: boolean
33
34
  onFrame?: (frame: TinkerFrame) => void
34
35
  }
35
36
  export declare interface TinkerEvaluation {
@@ -69,6 +70,9 @@ export type TinkerFrame = | { type: 'stdout' | 'stderr', id: string, text: strin
69
70
  | { type: 'log', id: string, level: string, message: string, timestamp: string, context?: TinkerValue }
70
71
  | { type: 'query', id: string, sql: string, params?: TinkerValue, kind?: string, durationMs?: number, rowCount?: number, error?: string }
71
72
  | { type: 'dump', id: string, value: TinkerValue }
73
+ /** A magic comment's answer: the value at that line, or the milliseconds the run had taken when it got there. */
74
+ | { type: 'probe', id: string, line: number, kind: 'value', value: TinkerValue }
75
+ | { type: 'probe', id: string, line: number, kind: 'time', ms: number }
72
76
  | { type: 'result', id: string, value: TinkerValue, durationMs: number }
73
77
  | { type: 'error', id: string, error: TinkerErrorValue, phase: 'parse' | 'run', diagnostics?: TinkerDiagnostic[], durationMs: number }
74
78
  | { type: 'done', id: string, ok: boolean }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/tinker",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.542",
5
+ "version": "0.75.544",
6
6
  "description": "Interactive REPL with Stacks framework preloaded.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [