@tdk-landscape/tdk-cli-core 1.3.129 → 1.3.131
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/CHANGELOG.md +20 -0
- package/README.md +1 -0
- package/cli/bin/tdk.js +7 -1
- package/cli/dist/backend-languages/python.js +1 -1
- package/cli/dist-bundle/chunk-6EA4DGCY.js +2 -0
- package/cli/dist-bundle/chunk-BOY5ZP42.js +315 -0
- package/cli/dist-bundle/chunk-OBQS5CYC.js +3 -0
- package/cli/dist-bundle/cli.js +1562 -0
- package/cli/dist-bundle/cold-preflight-GAQ3SIFD.js +2 -0
- package/cli/dist-bundle/devtools-VJJFMAIJ.js +11 -0
- package/cli/dist-bundle/extension-fetch-COIG2KR6.js +2 -0
- package/cli/package.json +9 -8
- package/engine/assets/docker/golden-layers.Dockerfile +3 -3
- package/engine/assets/docker/wake-gateway/Dockerfile +1 -1
- package/package.json +8 -5
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
|
|
2
|
+
import{c as tn}from"./chunk-OBQS5CYC.js";import{execFileSync as xs}from"node:child_process";import{readFileSync as wc}from"node:fs";import{join as vc}from"node:path";import{execFileSync as Wa,execSync as ls}from"node:child_process";import{existsSync as O,readdirSync as Ka,readFileSync as ee}from"node:fs";import{join as w,normalize as Kt,relative as Gt}from"node:path";function nn(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let s=t.length,o=0,i="";do i+=e.slice(o,r)+t+n,o=r+s,r=e.indexOf(t,o);while(r!==-1);return i+=e.slice(o),i}function rn(e,t,n,r){let s=0,o="";do{let i=e[r-1]==="\r";o+=e.slice(s,i?r-1:r)+t+(i?`\r
|
|
3
|
+
`:`
|
|
4
|
+
`)+n,s=r+1,r=e.indexOf(`
|
|
5
|
+
`,s)}while(r!==-1);return o+=e.slice(s),o}var sn=(e=0)=>t=>`\x1B[${t+e}m`,We=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Ke=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,ws=e=>`\x1B[58;5;${e<90?e-30:e-90+8}m`,x={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},Ac=Object.keys(x.modifier),vs=Object.keys(x.color),Ps=Object.keys(x.bgColor),Dc=Object.keys(x.underlineColor),Cc=[...vs,...Ps];function $s(){let e=new Map;for(let[t,n]of Object.entries(x)){for(let[r,s]of Object.entries(n))x[r]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[r]=x[r],e.set(Number.parseInt(s[0],10),s[1]);Object.defineProperty(x,t,{value:n,enumerable:!1})}return Object.defineProperty(x,"codes",{value:e,enumerable:!1}),x.color.close="\x1B[39m",x.bgColor.close="\x1B[49m",x.underlineColor.close="\x1B[59m",x.color.ansi=sn(),x.color.ansi256=We(),x.color.ansi16m=Ke(),x.bgColor.ansi=sn(10),x.bgColor.ansi256=We(10),x.bgColor.ansi16m=Ke(10),x.underlineColor.ansi=ws,x.underlineColor.ansi256=We(20),x.underlineColor.ansi16m=Ke(20),Object.defineProperties(x,{rgbToAnsi256:{value(t,n,r){return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[\da-f]{6}|[\da-f]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(o=>o+o).join(""));let s=Number.parseInt(r,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:t=>x.rgbToAnsi256(...x.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,s;if(t>=232)n=((t-232)*10+8)/255,r=n,s=n;else{t-=16;let a=t%36;n=Math.floor(t/36)/5,r=Math.floor(a/6)/5,s=a%6/5}let o=Math.max(n,r,s)*2;if(o===0)return 30;let i=30+(Math.round(s)<<2|Math.round(r)<<1|Math.round(n));return o===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(t,n,r)=>x.ansi256ToAnsi(x.rgbToAnsi256(t,n,r)),enumerable:!1},hexToAnsi:{value:t=>x.ansi256ToAnsi(x.hexToAnsi256(t)),enumerable:!1}}),x}var Es=$s(),j=Es;import Ge from"node:process";import Rs from"node:os";import on from"node:tty";function A(e,t=globalThis.Deno?globalThis.Deno.args:Ge.argv){let n=e.startsWith("-")?"":e.length===1?"-":"--",r=t.indexOf(n+e),s=t.indexOf("--");return r!==-1&&(s===-1||r<s)}var{env:T}=Ge,be;A("no-color")||A("no-colors")||A("color=false")||A("color=never")?be=0:(A("color")||A("colors")||A("color=true")||A("color=always"))&&(be=1);function cn(){return/^\d+$/.test(T.FORCE_COLOR)}function _s(){if("FORCE_COLOR"in T){if(T.FORCE_COLOR==="false")return 0;if(T.FORCE_COLOR==="true"||T.FORCE_COLOR.length===0)return 1;if(cn())return Math.min(Number.parseInt(T.FORCE_COLOR,10),3)}}function Os(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function As(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=_s();r!==void 0&&(be=r);let s=n?be:r;if(s===0)return 0;if(n){if(A("color=16m")||A("color=full")||A("color=truecolor"))return 3;if(A("color=256"))return 2}if(s!==void 0&&cn())return s;if("TF_BUILD"in T&&"AGENT_NAME"in T)return 1;if(e&&!t&&s===void 0)return 0;let o=s||0;if(T.TERM==="dumb")return o;if(Ge.platform==="win32"){let i=Rs.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in T)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in T)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in T)||T.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in T)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(T.TEAMCITY_VERSION)?1:0;if(T.COLORTERM==="truecolor"||T.TERM==="xterm-kitty"||T.TERM==="xterm-ghostty"||T.TERM==="wezterm")return 3;if("TERM_PROGRAM"in T){let i=Number.parseInt((T.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(T.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(?:color)?$/i.test(T.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(T.TERM)||"COLORTERM"in T?1:o}function an(e,t={}){let n=As(e,{streamIsTTY:e&&e.isTTY,...t});return Os(n)}var Ds={stdout:an({isTTY:on.isatty(1)}),stderr:an({isTTY:on.isatty(2)})},un=Ds;var{stdout:dn,stderr:ln}=un,se=Symbol("GENERATOR"),oe=Symbol("STYLER"),Te=Symbol("IS_EMPTY"),xe=Symbol("LEVEL"),ie=Object.create(null),pn=e=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw new Error("The `level` should be an integer from 0 to 3")},Cs={enumerable:!0,get(){return this[xe]},set(e){pn(e),this[xe]=e}},Ns=(e,t={})=>{t.level!==void 0&&pn(t.level);let n=dn?dn.level:0;e[xe]=t.level===void 0?n:t.level};var js=e=>{let t=(...n)=>n.join(" ");return Ns(t,e),Object.setPrototypeOf(t,ae.prototype),t};function ae(e){return js(e)}Object.setPrototypeOf(ae.prototype,Function.prototype);for(let[e,t]of Object.entries(j))ie[e]={get(){let n=Je(this,fn(t.open,t.close,this[oe]),this[Te]);return Object.defineProperty(this,e,{value:n}),n}};ie.visible={get(){let e=Je(this,this[oe],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var Is=(e,t)=>{let n=j[t];if(e==="rgb"){let s=(i,a,c)=>n.ansi(j.rgbToAnsi(i,a,c));return[s,s,(i,a,c)=>n.ansi256(j.rgbToAnsi256(i,a,c)),n.ansi16m]}if(e==="hex"){let s=i=>n.ansi(j.hexToAnsi(i));return[s,s,i=>n.ansi256(j.hexToAnsi256(i)),i=>n.ansi16m(...j.hexToRgb(i))]}let r=s=>n.ansi(j.ansi256ToAnsi(s));return[r,r,n.ansi256,n.ansi256]},Fs=["rgb","hex","ansi256"];for(let e of Fs){let t=e[0].toUpperCase()+e.slice(1);for(let[n,r]of[[e,"color"],["bg"+t,"bgColor"],["underline"+t,"underlineColor"]]){let{close:s}=j[r],o=Is(e,r);ie[n]={get(){let i=function(a,c,u){let d=o[this.level](a,c,u);return Je(this,fn(d,s,this[oe]),this[Te])};return Object.defineProperty(this,n,{value:i}),i}}}}var Ms=Object.defineProperties(()=>{},{...ie,level:{enumerable:!0,get(){return this[se].level},set(e){this[se].level=e}}}),fn=(e,t,n)=>{let r,s;return n===void 0?(r=e,s=t):(r=n.openAll+e,s=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:s,parent:n}},Je=(e,t,n)=>{let r=(...s)=>s.length===1?qe(r,""+s[0]):s.length===2?qe(r,`${s[0]??""} ${s[1]??""}`):qe(r,s.join(" "));return Object.setPrototypeOf(r,Ms),r[se]=e[se]??e,r[oe]=t,r[Te]=n,r},qe=(e,t)=>{if(e[se][xe]<=0||!t)return e[Te]?"":t;let n=e[oe];if(n===void 0)return t;let{openAll:r,closeAll:s}=n;if(t.includes("\x1B"))for(;n!==void 0;)t=nn(t,n.close,n.open),n=n.parent;let o=t.indexOf(`
|
|
6
|
+
`);return o!==-1&&(t=rn(t,s,r,o)),r+t+s};Object.defineProperties(ae.prototype,{...ie,level:Cs});var Ls=ae(),Hc=ae({level:ln?ln.level:0});var f=Ls;import{Command as Ga}from"commander";import{existsSync as Bs}from"node:fs";var we="docs/agent-hosts.md",ze=`WebContainers cannot run TDK: there is no Docker daemon or Tilt. Run \`tdk up\` on a machine with Docker. See ${we}.`,mn=`Docker is not reachable from this Dev Container. Mount the host Docker socket (-v /var/run/docker.sock:/var/run/docker.sock) or add the docker-outside-of-docker feature to devcontainer.json, then retry. Docker-in-docker is not supported. See ${we}.`;function Us(){return{env:process.env,versions:process.versions,platform:process.platform,fileExists:Bs}}function hn(e=Us()){let{env:t,versions:n,platform:r,fileExists:s}=e;return n.webcontainer?{kind:"webcontainer",canUp:!1}:t.CODESPACES==="true"?{kind:"codespaces",canUp:!0}:t.REMOTE_CONTAINERS||s("/.dockerenv")&&t.DEVCONTAINER?{kind:"devcontainer",canUp:!0}:r==="win32"?{kind:"native-windows",canUp:t.TDK_ALLOW_NATIVE_WINDOWS==="1"}:r==="linux"&&t.WSL_DISTRO_NAME?{kind:"wsl2",canUp:!0}:{kind:"local",canUp:!0}}function gn(e){return e==="devcontainer"||e==="codespaces"}function P(e){return e==="backend"||e==="mcp"}function ve(e){return e.some(t=>P(t.config?.appType)||t.config?.appType==="frontend"||t.config?.appType==="worker")}var Ye=["TILT_TECH_STACK.star","TILT_RESOURCE_DEFAULTS.star","spec.master"],zc=["backend","frontend","library","sdk","worker","migrator","mcp","bring-your-own"],Xe={backend:["dev","build","start"],worker:["dev","build","start"],migrator:["dev","build","start"],mcp:["dev","build","start"],frontend:["dev","build"],library:["dev","build"],sdk:["dev","build"],"bring-your-own":[]};var Ze=["monitoring","elk","debezium","golden_image","verdaccio"],Yc={frontend:{base:3e3,min:3e3,max:3999,range:"3000-3999"},backend:{base:4e3,min:4e3,max:4999,range:"4000-4999"},mcp:{base:4e3,min:4e3,max:5999,range:"4000-5999"},"bring-your-own":{base:4e3,min:4e3,max:5999,range:"4000-5999"},worker:{base:6e3,min:6e3,max:6999,range:"6000-6999"},health:{base:5e3,min:5e3,max:5999,range:"5000-5999"},migrator:{base:7e3,min:7e3,max:7999,range:"7000-7999"}},kn={tiltUi:10350,traefik:8080},Qe="https://tdk-landscape.github.io/tdk-website/docs/quickstart/";var yn=["node_modules",".git",".tilt",".tilt-engine","dist","build",".prisma",".turbo","coverage","tmp","temp","__tests__","test","tests",".github",".vscode","docs"],Sn=["Dockerfile","docker-compose.yml","docker-compose.yaml","Tiltfile","vite.config.ts","tsconfig.json","tsconfig.build.json"],Hs={infra:"\u{1F3D7}\uFE0F",core:"\u{1F527}",api:"\u26A1",app:"\u{1F3A8}",orchestrator:"\u2699\uFE0F"};function Xc(e){let t=e.toLowerCase();for(let[n,r]of Object.entries(Hs))if(t.includes(n))return r;return"\u{1F4E6}"}import{existsSync as Vs,readFileSync as Ws}from"node:fs";import{join as Ks,relative as bn,resolve as xn,sep as Gs}from"node:path";var qs=2,Tn=["services/*/*"];function wn(e){return e.split(Gs).filter(Boolean)}function Js(e,t){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]");return new RegExp(`^${n}$`).test(t)}function zs(e,t){return e.length===t.length&&e.every((n,r)=>Js(n,t[r]))}function et(e){let t=Ks(e,".tdk","project.json");if(!Vs(t))return Tn;try{let n=JSON.parse(Ws(t,"utf-8"))?.discovery?.paths;if(Array.isArray(n)&&n.every(r=>typeof r=="string"))return n}catch{}return Tn}function Pe(e,t,n){let r=wn(bn(e,xn(e,t)));return n.some(s=>{let o=wn(bn(e,xn(e,s)));for(let i=0;i<=qs;i++){let a=r.length-i;if(a>0&&zs(o,r.slice(0,a)))return!0}return!1})}function tu(e,t,n,r){let s=et(e);if(Pe(e,t,s))return{path:t};let o=`services/${n}/${r}`;return Pe(e,o,s)?{path:o,adjustedFrom:t}:{path:t}}async function Pn(e,t){let n=[],r=[],s=o=>{o.status==="fulfilled"?n.push(o.value):r.push({code:"INTERNAL",message:o.reason instanceof Error?o.reason.message:String(o.reason)})};for(let o of await Promise.allSettled(e.map(i=>Promise.resolve().then(i))))s(o);for(let o of t)for(let i of await Promise.allSettled([Promise.resolve().then(o)]))s(i);return{checks:n,errors:r}}function vn(e){let t=e.find(n=>n.name==="Container Runtime");return t?t.didPass:null}function W(e,t,n=[],r,s){return{schemaVersion:1,data:{ready:n.length===0&&e.every(o=>o.didPass||o.isSkipped||o.isWarning),inProject:t,checks:e,...s?{host:{...s,containerRuntimeReachable:vn(e),canUp:s.canUp&&vn(e)!==!1}}:{},...r!==void 0?{ports:{http:{requested:r?.requested.ingressHttp??80,chosen:r?.ingressHttp??null,explicit:r?.explicit.ingressHttp??!!process.env.TDK_HTTP_PORT,reason:r?.reason.ingressHttp??"port planning failed"},https:{requested:r?.requested.ingressHttps??443,chosen:r?.ingressHttps??null,explicit:r?.explicit.ingressHttps??!!process.env.TDK_HTTPS_PORT,reason:r?.reason.ingressHttps??"port planning failed"},postgres:{requested:r?.requested.postgres??5432,chosen:r?.postgres??null,explicit:r?.explicit.postgres??!!process.env.TDK_POSTGRES_PORT,reason:r?.reason.postgres??"port planning failed"}}}:{}},errors:n}}function $n(e){return e.errors.length>0?2:e.data.ready?0:1}import{execFileSync as lr,execSync as me}from"node:child_process";import{existsSync as bt,readdirSync as ri,readFileSync as xt}from"node:fs";import{join as z}from"node:path";function Ys(e,t,n){return e===1?t:n||`${t}s`}function S(e,t,n){return`${e} ${Ys(e,t,n)}`}var Xs={month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};function ou(e){return new Date(e).toLocaleString("en-US",Xs)}function iu(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric"})}var tt={success:{color:"green",icon:"\u2713",chalkFn:f.green},error:{color:"red",icon:"\u2717",chalkFn:f.red},warning:{color:"yellow",icon:"\u25CB",chalkFn:f.yellow},unknown:{color:"gray",icon:"?",chalkFn:f.gray}};function nt(e){if(!e)return"unknown";let t=e.toLowerCase();return t==="ready"||t==="healthy"||t==="active"||t==="running"?"success":t==="error"||t==="failed"||t==="critical"||t==="stopped"?"error":t==="pending"||t==="starting"||t==="building"||t==="degraded"?"warning":"unknown"}function au(e){return tt[nt(e)].color}function cu(e){return tt[nt(e)].icon}function uu(e,t){return tt[nt(t)].chalkFn(e)}var Zs={resources:{singular:"resource",command:"tdk resource <name>",context:`
|
|
7
|
+
To create a resource:`},stacks:{singular:"stack",command:"tdk stack <stack-name>",context:`
|
|
8
|
+
To create a stack, use:`},services:{singular:"service",command:"tdk resource <name>",context:`
|
|
9
|
+
To create a service:`},"stack-services":{singular:"service",command:"tdk resource <name> --stack <stack-name>",context:`
|
|
10
|
+
To add services to this stack:`}};function du(e,t){let n=Zs[e];console.log(t?f.yellow(`No ${n.singular}s found${t}.`):f.yellow(`No ${n.singular}s found.`)),console.log(f.gray(n.context)),console.log(f.gray(` ${n.command}`)),e==="stacks"&&(console.log(f.gray(`
|
|
11
|
+
Or create a new resource with a stack:`)),console.log(f.gray(" tdk resource <name> --stack <stack-name>")))}function lu(e){console.log(f.yellow(e||"Cancelled."))}function pu(e){console.log(f.blue(`TDK ${e}
|
|
12
|
+
`))}function fu(e,t){console.log(f.green(`All ${e} are ${t}!`))}var rt=62;function mu(e="\u2500",t=rt){return e.repeat(t)}function En(e,t=rt-2){let n=Math.max(0,t-e.length),r=Math.floor(n/2),s=n-r;return" ".repeat(r)+e+" ".repeat(s)}function hu(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e.padEnd(t)}function gu(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function ku(e){console.log(f.green(`\u2713 ${e}`))}function yu(e){console.log(f.blue(e))}function Su(e,t=2){console.log(f.gray(`${" ".repeat(t)}${e}`))}function bu(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function xu(e,t,n=rt){let r=n-2,s="\u2500".repeat(r);console.log(),console.log(f.cyan(`\u256D${s}\u256E`)),console.log(f.cyan("\u2502")+f.bold.white(En(e,r))+f.cyan("\u2502")),t&&(console.log(f.cyan(`\u251C${s}\u2524`)),console.log(f.cyan("\u2502")+f.gray(En(t,r))+f.cyan("\u2502"))),console.log(f.cyan(`\u2570${s}\u256F`))}import{existsSync as eo}from"node:fs";import{dirname as to,join as no,resolve as _n}from"node:path";import{cwd as ro}from"node:process";var Rn={name:"tdk-cli-internal",private:!0,version:"1.3.131",description:"TDK CLI \u2014 start services on your laptop.",keywords:["tdk","tilt","cli","local-dev","microservices"],homepage:"https://github.com/tdk-landscape/tdk-cli-core#readme",bugs:{url:"https://github.com/tdk-landscape/tdk-cli-core/issues"},repository:{type:"git",url:"git+https://github.com/tdk-landscape/tdk-cli-core.git",directory:"cli"},license:"MIT",author:"TDK Team",type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",bin:{tdk:"bin/tdk.js","tdk-cli":"bin/tdk.js"},files:["dist","bin","templates","README.md","Tiltfile","engine","discovery","specs","ext","!ext/ide-components/code_executor","shared-platform-engineering/docker-templates"],scripts:{build:"tsc && node scripts/bundle.mjs","build:watch":"tsc --watch",lint:"biome check .","lint:fix":"biome check . --write",typecheck:"tsc --project tsconfig.typecheck.json",clean:"rm -rf dist",dev:"bun run build:watch",test:"vitest run","test:watch":"vitest",prepack:"../scripts/stage-npm-engine.sh && npm run build"},dependencies:{commander:"^15.0.0",handlebars:"^4.7.8"},devDependencies:{"@biomejs/biome":"^2.5.13","@types/node":"^22.0.0","@types/react":"^19.3.0",ajv:"^8.17.1",chalk:"^6.0.1",esbuild:"^0.28.2",ink:"^7.1.1",knip:"^6.38.0",react:"^19.3.0","react-devtools-core":"^8.0.0",typescript:"^7.0.2",vite:"^8.3.1",vitest:"^5.0.0"},engines:{node:">=22.12.0"}};function m(e=ro()){let t=_n(e),n=_n("/");for(;t!==n;){if(eo(no(t,".tdk","project.json")))return t;let r=to(t);if(r===t)break;t=r}return null}var $e=null;function so(){if($e)return $e;let e=Rn;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid package.json: expected object");let t=e;return $e={name:String(t.name??"@tdk-landscape/tdk-cli-core"),version:String(t.version??"0.0.0"),fullPackage:t},$e}function On(){return so().version}import{readFileSync as oo}from"node:fs";import{join as io}from"node:path";function st(){let e=m();if(e)try{let t=oo(io(e,".tdk","project.json"),"utf-8"),n=JSON.parse(t);if(n?.project?.name)return n.project.name}catch{}return"tdk-project"}function ot(e){let t=st(),n=process.env.TDK_SERVICE_BASE_URL??`http://${t}.localhost${e?`:${e}`:""}`;try{let r=new URL(n.includes("://")?n:`http://${n}`),s=r.hostname,o=r.port||(e?String(e):"");if(s==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(s))return{appBase:`${r.protocol}//${s}${o?`:${o}`:""}`,apiBase:`${r.protocol}//${s}${o?`:${o}`:""}`};let i=s.replace(/^(app|api)\./,"");return{appBase:`${r.protocol}//app.${i}${o?`:${o}`:""}`,apiBase:`${r.protocol}//api.${i}${o?`:${o}`:""}`}}catch{return{appBase:`http://app.${t}.localhost`,apiBase:`http://api.${t}.localhost`}}}function ao(e){return`${e.replace(/\/+$/,"")}/health`}function it(e){if(P(e.config?.appType)){let t=e.name.replace(/-api$/,"");return e.config?.apiPath??`/api/${t}`}return e.config?.basePath??`/${e.name}`}function An(e,t){let{appBase:n,apiBase:r}=ot(t);return e.filter(s=>s.config?.appType==="frontend"||P(s.config?.appType)).map(s=>{let o=P(s.config.appType)?r:n;return{name:s.name,appType:s.config.appType,url:`${o}${ao(it(s))}`}})}async function co(e,t){try{let n=await fetch(e.url,{method:"GET",redirect:"manual",signal:AbortSignal.timeout(t)});return{...e,ok:n.ok,status:n.status}}catch(n){let r=n instanceof Error&&n.name==="TimeoutError"?`no response within ${t}ms`:n instanceof Error?n.message:String(n);return{...e,ok:!1,error:r}}}async function Dn(e,t){return Promise.all(e.map(n=>co(n,t)))}import{existsSync as J,readdirSync as nr,readFileSync as rr,statSync as mt}from"node:fs";import{dirname as Jo,join as U}from"node:path";var ce=class{data;options;constructor(t){this.data=new Map,this.options=t}has(t){let n=this.data.get(t);return n?Date.now()-n.timestamp>this.options.ttlMs?(this.data.delete(t),!1):!0:!1}get(t){if(this.has(t))return this.data.get(t)?.value}set(t,n){this.data.set(t,{value:n,timestamp:Date.now()})}delete(t){this.data.delete(t)}clear(){this.data.clear()}keys(){let t=[];for(let n of this.data.keys())this.has(n)&&t.push(n);return t}size(){return this.keys().length}};function Cn(e){let t=0;return{isValid(){return Date.now()-t<e},markUpdated(){t=Date.now()},reset(){t=0}}}import{execFileSync as yo,execSync as So}from"node:child_process";import{existsSync as mo}from"node:fs";import{delimiter as ho,extname as go,join as ko}from"node:path";import{delimiter as Iu,extname as uo}from"node:path";function Ee(){return process.platform==="win32"}function lo(e){return e==="linux"?"linux":e==="darwin"?"darwin":e==="win32"?"windows":null}function po(e){return e==="x64"?"amd64":e==="arm64"?"arm64":null}function fo(e,t){let n=lo(e),r=po(t);if(!n||!r||n==="windows"&&r!=="amd64")return null;let s=`tdk-${n}-${r}`;return n==="windows"?`${s}.exe`:s}function Fu(){return fo(process.platform,process.arch)}function Mu(){return Ee()?"tdk.exe":"tdk"}function Nn(e,t=Ee()){return t?uo(e)?[e]:[e,`${e}.exe`,`${e}.cmd`,`${e}.bat`]:[e]}function $(e){let t=process.env.PATH??process.env.Path??"",n=Ee(),r=Nn(e,n);if(n&&!go(e))for(let s of(process.env.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";")){let o=s.toLowerCase();o&&!r.includes(`${e}${o}`)&&r.push(`${e}${o}`)}for(let s of t.split(ho))if(s)for(let o of r){let i=ko(s,o);if(mo(i))return i}return null}var jn=1e4;function In(){let e=!1;if(process.platform==="win32")try{return yo($("docker")??"docker",["ps"],{stdio:"ignore",timeout:jn,windowsHide:!0}),"running"}catch(t){return t.code==="ETIMEDOUT"?"unresponsive":"missing"}for(let t of["docker ps","colima status","podman ps"])try{return So(t,{stdio:"ignore",timeout:jn}),"running"}catch(n){n.code==="ETIMEDOUT"&&(e=!0)}return e?"unresponsive":"missing"}function bo(e,t){let n=Array.from({length:t.length+1},(r,s)=>s);for(let r=1;r<=e.length;r++){let s=[r];for(let o=1;o<=t.length;o++){let i=e[r-1]===t[o-1]?0:1;s[o]=Math.min(s[o-1]+1,n[o]+1,n[o-1]+i)}n=s}return n[t.length]}function xo(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length-1;n++)if(e[n]!==t[n]&&e[n]===t[n+1]&&e[n+1]===t[n]&&e.slice(0,n)===t.slice(0,n)&&e.slice(n+2)===t.slice(n+2))return!0;return!1}function Fn(e,t){if(e.length<2||t.length===0||t.includes(e))return;let n=e.toLowerCase(),r,s=Number.POSITIVE_INFINITY;for(let o of t){if(o.length===0)continue;let i=o.toLowerCase(),a=xo(n,i)?1:bo(n,i),c=Math.max(1,Math.min(2,Math.floor(Math.max(n.length,i.length)/3)));a>c||(a<s||a===s&&(r===void 0||o<r))&&(r=o,s=a)}return r}import{spawn as To}from"node:child_process";import{join as wo}from"node:path";function vo(e,t=[],n={}){return new Promise((r,s)=>{let o=[e,...t];n.verbose&&console.log(`Executing: tilt ${o.join(" ")}`);let i=To($("tilt")??"tilt",o,{stdio:n.inheritStdio?"inherit":"pipe",shell:!1,windowsHide:process.platform==="win32",timeout:n.timeoutMs}),a="",c="";n.inheritStdio||(i.stdout?.on("data",u=>{a+=u.toString()}),i.stderr?.on("data",u=>{c+=u.toString()})),i.on("close",u=>{r({exitCode:u??1,stdout:a,stderr:c})}),i.on("error",u=>{s(new Error(`Failed to spawn tilt: ${u.message}`))})})}async function Mn(){try{return(await vo("version",[],{inheritStdio:!1,timeoutMs:1e4})).exitCode===0}catch{return!1}}function Po(){let e=m();if(!e)throw I.notInProject();return wo(e,".tdk",".tdk-out","Tiltfile")}function Ln(e){let t=Po();e.push("-f",t)}function Qu(e,t={}){let n=[];return Ln(n),t.focusTargets&&t.focusTargets.length>0&&n.push("--",`--focus=${t.focusTargets.join(",")}`),n.push(...e),t.verbose&&!t.quiet&&n.push("--verbose"),t.watch&&n.push("--watch"),n}function ed(e={}){let t=[];return Ln(t),e.force&&t.push("--force"),e.focusTargets&&e.focusTargets.length>0&&t.push("--",`--focus=${e.focusTargets.join(",")}`),t}function Bn(e){return e instanceof Error?e.message:String(e)}function cd(e,t){if(process.env.TDK_VERBOSE){let n=t!==void 0?`: ${Bn(t)}`:"";console.warn(f.gray(`${e}${n}`))}}var E=class extends Error{suggestions;exitCode;constructor(t,n=[],r=1){super(t),this.name="TdkError",this.suggestions=n,this.exitCode=r}display(){Ro(this.message,void 0,this.suggestions)}exit(){this.display(),process.exit(this.exitCode)}};function at(e,t,n=!1){let r=new Set;for(let s of e){let o=Fn(s,t);o&&r.add(n?`Did you mean "${o}" for "${s}"?`:`Did you mean "${o}"?`)}return[...r]}var I={tiltNotInstalled:()=>new E("Tilt CLI is not installed",["Install Tilt: `brew install tilt` (macOS)","Or download from: https://docs.tilt.dev/install.html","Verify with: `tilt version`",`Setup guide: ${Qe}`]),dockerNotAvailable:()=>new E("Docker (or a compatible container runtime) is not running",["Start Docker Desktop, then verify with: `docker ps`","Or start Colima: `colima start`","Or start the Docker service on Linux: `sudo systemctl start docker`",`Setup guide: ${Qe}`]),dockerNotResponding:()=>new E("Docker is running but not responding (`docker ps` hung for 10s)",["Quit and reopen Docker Desktop, or run `colima restart`","Then verify with: `docker ps`"]),stackNotFound:(e,t=[])=>new E(`Stack "${e}" not found`,[...at([e],t),"Run `tdk stacks` to see available stacks","Run `tdk stack` to assign resources to a stack"]),resourceNotFound:(e,t=[])=>new E(`Resource "${e}" not found`,[...at([e],t),"Run `tdk resources` to list all resources","Check the resource name spelling"]),unknownServices:(e,t)=>{let n=at(e,t,e.length>1);return new E(`Unknown service ${e.join(", ")}. Valid names: ${t.join(", ")}`,n,2)},directoryExists:e=>new E(`Directory already exists: ${e}`,["Use `--path` to specify a different location","Remove the existing directory if no longer needed"]),invalidPath:e=>new E(`Invalid path: ${e}`,["Path must be within the project directory",'Path cannot contain special characters like <>:"|?*']),notInProject:()=>new E("Could not find project root (no .tdk/project.json found)",["Run this from within a TDK project","Run `tdk project --yes` to initialize a new project"])};function ud(){let e=m();return e||I.notInProject().exit()}function $o(e){e instanceof E&&e.exit(),console.error(f.red(`Error: ${Bn(e)}`)),process.exit(1)}async function Eo(e,t){try{return await e()}catch(n){return t?.verbose&&n instanceof Error&&n.stack&&console.error(f.gray(n.stack)),$o(n)}}async function dd(e,t){let n=[],r=In();return r==="unresponsive"?n.push(I.dockerNotResponding()):r==="missing"&&n.push(I.dockerNotAvailable()),await Mn()||n.push(I.tiltNotInstalled()),n.length>0&&(console.error(f.red(`
|
|
13
|
+
TDK can't start - missing prerequisites:
|
|
14
|
+
`)),n.forEach((s,o)=>{o>0&&console.error(""),s.display()}),console.error(f.gray("\nRun `tdk doctor` for a full environment check.")),process.exit(1)),Eo(e,t)}function ld(e,t=1){console.error(f.red(`Error: ${e}`)),process.exit(t)}function Ro(e,t,n){console.error(f.red(`\u274C ${e}`)),t&&console.error(f.gray(` ${t}`)),n&&n.length>0&&(console.error(f.yellow(`
|
|
15
|
+
\u{1F4A1} Suggestions:`)),n.forEach(r=>{console.error(f.cyan(` \u2192 ${r}`))}))}function pd(e,t){console.error(f.red(`
|
|
16
|
+
tilt ${e} failed with exit code ${t}`)),process.exit(t)}import{existsSync as Xn,readFileSync as Zn}from"node:fs";import{copyFileSync as Un,mkdirSync as _o,rmSync as Hn,writeFileSync as Vn}from"node:fs";import{join as q}from"node:path";var Oo=60,Wn=1e3,Kn=1e4,Gn=200,qn=64*1024,Jn=new Set([404,502,503,504]),Ao=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]),Do=new Set(["GET","HEAD","OPTIONS"]);function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Co(e,t){if(Do.has(t))return!0;if(!L(e))return!1;let n=L(e.cause)?e.cause:void 0,r=e.code??n?.code;return typeof r=="string"&&Ao.has(r)}function ut(e){if(!L(e))return['smoke: must be an object with "via" and "steps"'];let t=[];return e.via!=="proxy"&&t.push('smoke.via: only "proxy" is supported (the check must go through the public URL)'),e.timeoutSeconds!==void 0&&!(typeof e.timeoutSeconds=="number"&&e.timeoutSeconds>0)&&t.push("smoke.timeoutSeconds: must be a number greater than 0"),!Array.isArray(e.steps)||e.steps.length===0?(t.push("smoke.steps: needs at least one step"),t):(e.steps.forEach((n,r)=>{let s=`smoke.steps[${r}]`;if(!L(n)){t.push(`${s}: must be an object`);return}let o=n.path;(typeof o!="string"||!o.startsWith("/")||o.startsWith("//"))&&t.push(`${s}.path: must start with "/" and is appended to the public URL; a full URL or relative path would skip the proxy`),n.expect!==void 0&&!(typeof n.expect=="number"&&Number.isInteger(n.expect)&&n.expect>=100&&n.expect<=599)&&t.push(`${s}.expect: must be an HTTP status between 100 and 599`),n.bodyContains!==void 0&&typeof n.bodyContains!="string"&&t.push(`${s}.bodyContains: must be a string`),n.save!==void 0&&(L(n.save)&&Object.values(n.save).every(a=>typeof a=="string"&&a.startsWith("$."))||t.push(`${s}.save: must map names to paths such as "$.id"`))}),t)}function yd(e,t){let{appBase:n,apiBase:r}=ot(t),s=[];for(let o of e){let i=o.config;if(!i?.smoke)continue;let a=i.appType,c=P(a)||a==="bring-your-own";if(!c&&a!=="frontend"||i.exposeViaProxy===!1)continue;let u=c?r:n,d=i.healthCheckPath||(c&&a!=="bring-your-own"?"/health":void 0);s.push({name:o.name,baseUrl:`${u}${it(o).replace(/\/+$/,"")}`,...d?.startsWith("/")?{readyPath:d}:{},smoke:i.smoke})}return s}function No(e,t){let n=t.replace(/^\$\.?/,"").match(/[^.[\]]+/g)??[],r=e;for(let s of n){if(r==null)return;r=r[s]}return r}function zn(e,t){return e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n)}function ct(e,t){return typeof e=="string"?zn(e,t):Array.isArray(e)?e.map(n=>ct(n,t)):L(e)?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,ct(r,t)])):e}function Re(e){let t=e.replace(/\s+/g," ").trim();return t.length>Gn?`${t.slice(0,Gn)}...`:t}function Yn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"step"}function jo(e,t){let n=Yn(t),r=(e.get(n)??0)+1;return e.set(n,r),r===1?n:`${n}-${r}`}function Io(e,t,n,r,s){try{let o=q(e,Yn(n.service),t);_o(o,{recursive:!0});let i=q(o,"latest.json"),a=q(o,"body.txt");return r===void 0?Hn(a,{force:!0}):Vn(a,r),Vn(i,`${JSON.stringify({...n,bodyPath:r===void 0?null:"body.txt"},null,2)}
|
|
17
|
+
`),s&&(Un(i,q(o,"last-success.json")),r===void 0?Hn(q(o,"last-success-body.txt"),{force:!0}):Un(a,q(o,"last-success-body.txt"))),i}catch{return}}function Fo(e){let t=Buffer.from(e,"utf8");if(t.length<=qn)return{body:e,truncated:!1,bytes:t.length};let n=t.subarray(0,qn).toString("utf8").replace(/\uFFFD$/,"");return{body:n,truncated:!0,bytes:Buffer.byteLength(n,"utf8")}}async function Mo(e,t={}){let n=t.fetch??((d,l)=>fetch(d,l)),r=t.now??Date.now,s=t.sleep??(d=>new Promise(l=>setTimeout(l,d))),o=(e.smoke.timeoutSeconds??Oo)*1e3,i=r()+o,a={},c=ut(e.smoke);if(c.length>0)return{name:e.name,ok:!1,failure:`${e.name}: invalid smoke block: ${c.join("; ")}`};if(e.readyPath){let d=`${e.baseUrl}${e.readyPath}`;for(;;){try{let l=await n(d,{method:"GET",signal:AbortSignal.timeout(Kn)});if(await l.text(),!Jn.has(l.status)&&l.status<500)break}catch{}if(r()>=i)break;await s(Wn)}}i=r()+o;let u=new Map;for(let[d,l]of e.smoke.steps.entries()){let h=l.name??`step ${d+1}`,k=(l.method??"GET").toUpperCase(),g=`${e.baseUrl}${zn(l.path,a)}`,p=l.expect??200,y=l.body!==void 0,v,D="",M,Ve;for(;;){M=void 0,Ve=void 0,v=void 0;let C=!1;try{let R=await n(g,{method:k,headers:y?{"content-type":"application/json"}:void 0,body:y?JSON.stringify(ct(l.body,a)):void 0,signal:AbortSignal.timeout(Kn)});v=R.status,D=await R.text()}catch(R){C=Co(R,k),M=R instanceof Error?R.message:String(R);let V=L(R)?R.code??(L(R.cause)?R.cause.code:void 0):void 0;Ve=typeof V=="string"?V:void 0}if(!(M!==void 0&&C||v!==void 0&&v!==p&&Jn.has(v))||r()>=i)break;await s(Wn)}let te=`${e.name}: ${h}: ${k} ${g}`,en;if(t.recordDir){let C=v===void 0?void 0:Fo(D),re=M===void 0&&v===p&&(l.bodyContains===void 0||D.includes(l.bodyContains));en=Io(t.recordDir,jo(u,h),{service:e.name,step:h,method:k,url:g,expectedStatus:p,status:v??null,...M===void 0?{}:{error:Ve??M},truncated:C?.truncated??!1,bodyBytes:C?.bytes??0},C?.body,re)}let ne=C=>({name:e.name,ok:!1,failure:C,recordPath:en});if(M!==void 0)return ne(`${te} never answered (${M})`);if(v!==p)return ne(`${te} returned ${v}, expected ${p}${D?`: ${Re(D)}`:""}`);if(l.bodyContains!==void 0&&!D.includes(l.bodyContains))return ne(`${te} returned ${v} but the body does not contain "${l.bodyContains}": ${Re(D)}`);if(l.save){let C;try{C=JSON.parse(D)}catch{return ne(`${te} returned a body that is not JSON, cannot save: ${Re(D)}`)}for(let[re,R]of Object.entries(l.save)){let V=No(C,R);if(V==null||typeof V=="object")return ne(`${te} response has no ${R} to save as {{${re}}}: ${Re(D)}`);a[re]=String(V)}}}return{name:e.name,ok:!0}}function Sd(e){return`Smoke check failed: ${e.failure}${e.recordPath?` (record: ${e.recordPath})`:""}`}async function bd(e,t={}){return Promise.all(e.map(n=>Mo(n,t)))}var ue=1,vd="https://tdk-landscape.github.io/schema.service.json",Lo={dependencies:"deprecated, use dependsOn (still read for now)",envVars:"deprecated, use params (still read when params is absent)",jwtSecret:"ignored. A secret must not be committed: remove it and set JWT_SECRET in the project .env"},Bo=new Set(["$schema","apiBasePath","apiPath","appName","appType","backendName","basePath","build","buildContext","databaseName","dependencies","dev","dependsOn","dockerfile","enabled","exposeViaProxy","featuresEnabled","framework","healthCheckPath","image","language","name","nats","params","playwright","port","replicas","restart","runtime","sablier","schemaVersion","secrets","smoke","stack","syncs","traefik","type"]),Uo=[{path:["healthCheckPath"],pattern:/^\/[a-z0-9/-]*$/,expected:"a path such as /health"},{path:["traefik","host"],pattern:/^[A-Za-z0-9.-]+$/,expected:"a hostname such as shop.backend.myproject.local"},{path:["traefik","pathPrefix"],pattern:/^\/[a-z0-9/-]*$/,expected:"a path such as /api/v1/shop-management"},{path:["traefik","healthCheck"],pattern:/^\/[a-z0-9/-]*$/,expected:"a path such as /health"},{path:["nats","queueGroup"],pattern:/^[A-Za-z0-9_.-]+$/,expected:"letters, digits, '_', '.' or '-'"},{path:["databaseName"],pattern:/^[A-Za-z0-9_-]+$/,expected:"letters, digits, '_' or '-'"},{path:["stack"],pattern:/^[A-Za-z0-9_-]+$/,expected:"letters, digits, '_' or '-'"},{path:["image"],pattern:/^[A-Za-z0-9._/:@-]+$/,expected:"an image reference such as ghcr.io/acme/app:1.0"}];function _e(e,t){let n=[],r=new Set;for(let{path:s,pattern:o,expected:i}of Uo){let a=e;for(let u of s)a=a&&typeof a=="object"&&!Array.isArray(a)?a[u]:void 0;if(a==null||a==="")continue;let c=`${t}.${s.join(".")}`;(typeof a!="string"||!o.test(a))&&r.add(c),typeof a!="string"?n.push(`${c}: expected a string`):o.test(a)||n.push(`${c}: must be ${i} (no spaces, line breaks or YAML syntax)`)}for(let[s,o]of Ho(e,t))r.has(s)||n.push(`${s}: ${o}`);return n}function dt(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127||n===133||n===8232||n===8233)return!0}return!1}function Ho(e,t){let n=[],r=Object.entries(e).filter(([s])=>s!=="smoke").map(([s,o])=>[o,`${t}.${s}`]);for(let s of Object.keys(e))dt(s)&&n.push([t,"a key contains a line break"]);for(;r.length>0;){let[s,o]=r.pop();if(typeof s=="string")dt(s)&&n.push([o,"must not contain line breaks or control characters"]);else if(Array.isArray(s))for(let[i,a]of s.entries())r.push([a,`${o}[${i}]`]);else if(s&&typeof s=="object")for(let[i,a]of Object.entries(s))dt(i)?n.push([o,"a key contains a line break"]):r.push([a,`${o}.${i}`])}return n.sort(([s],[o])=>s.localeCompare(o))}var Vo=["apiPath","basePath"];function lt(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e;return Vo.filter(n=>n in t&&typeof t[n]!="string")}function pt(e,t){if(!e||typeof e!="object"||Array.isArray(e))return{errors:[`${t}: expected a JSON object`],warnings:[]};let n=e,r=[];for(let a of["appName","appType","stack","schemaVersion"])a in n||r.push(`${t}.${a}: required field is missing`);for(let a of["appName","appType","stack"])a in n&&typeof n[a]!="string"&&r.push(`${t}.${a}: expected a string`);"schemaVersion"in n&&n.schemaVersion!==ue&&r.push(`${t}.schemaVersion: unsupported version ${String(n.schemaVersion)} (supported: ${ue})`);for(let a of lt(n))r.push(`${t}.${a}: expected a string`);let s=n.dev,o=s&&typeof s=="object"&&!Array.isArray(s)?s.liveReload:void 0;if(o!==void 0&&typeof o!="boolean"&&r.push(`${t}.dev.liveReload: expected true or false`),r.push(..._e(n,t)),"smoke"in n)for(let a of ut(n.smoke))r.push(`${t}.${a}`);let i=Object.keys(n).flatMap(a=>{let c=Lo[a];return c?[`${t}.${a}: ${c}`]:Bo.has(a)?[]:[`${t}.${a}: unknown field is preserved`]});return o===!0&&n.language!=="go"&&i.push(`${t}.dev.liveReload: only applies to Go services (language "go"); it is ignored here`),{errors:r,warnings:i,manifest:n}}function Pd(e,t){if(!Xn(e))return[];try{let n=JSON.parse(Zn(e,"utf-8"));return!n||typeof n!="object"||Array.isArray(n)?[]:_e(n,t)}catch{return[]}}function $d(e,t){if(!Xn(e))return{errors:[`${t}: file is missing`],warnings:[]};try{let n=JSON.parse(Zn(e,"utf-8"));return pt(n,t)}catch(n){let r=n instanceof Error?n.message:String(n);return{errors:[`${t}: invalid JSON (${r})`],warnings:[]}}}function Qn(e){if(e.length===0||e.every(n=>n==="unknown"))return"unknown";let t=e.filter(n=>n==="ready").length/e.length;return t>.9?"healthy":t>.5?"degraded":"error"}var Wo=/^[a-z0-9-]+$/;function er(e){return Wo.test(e)}var Ko="Use lowercase letters, numbers, and hyphens only";function tr(e,t){return`${e} "${t}" is not valid. ${Ko}, e.g. "${e==="Resource name"?"my-service":"my-stack"}".`}function Go(e){return e.trim()?er(e)?{valid:!0}:{valid:!1,error:tr("Resource name",e)}:{valid:!1,error:"Resource name is required"}}function qo(e){return e.trim()?er(e)?{valid:!0}:{valid:!1,error:tr("Stack name",e)}:{valid:!1,error:"Stack name is required"}}function Od(e){let t=e==="resource"?Go:qo;return n=>{let r=t(n);return r.valid?!0:r.error??"Invalid name"}}function Ad(e){return ft(Ze,e)?{valid:!0}:{valid:!1,error:`Invalid service. Must be one of: ${Ze.join(", ")}`}}function Dd(e){return Number.isInteger(e)&&e>0&&e<=65535}function Cd(e){return!e.includes("\0")&&!/[<>:"|?*]/.test(e)}function Nd(e,t="_"){return e.replace(/[^a-zA-Z0-9-]/g,t).substring(0,100)}function ft(e,t){return e.includes(t)}var zo="service.json";function yt(e,t=5,n=0){let r=[];if(n>t)return r;let s=nr(e,{withFileTypes:!0});for(let o of s){let i=U(e,o.name);if(o.isDirectory()){if(Yo(o.name))continue;r.push(...yt(i,t,n+1))}else o.isFile()&&o.name===zo&&r.push(i)}return r}function Gd(e){return yt(e)}function Yo(e){return ft(yn,e)||e.startsWith(".")}function Xo(e){if(!e||typeof e!="object")return!1;let t=e,n=typeof t.runtime=="string"||typeof t.appType=="string"||typeof t.type=="string";return typeof t.appName=="string"&&n}var Oe=new Set;var B=class extends Error{reason;constructor(t){super(t),this.reason=t,this.name="InvalidServiceJsonError"}};function ht(e){return e instanceof Error?e.message:String(e)}function Zo(e){let t;try{t=rr(e,"utf-8")}catch(c){throw new B(`could not read file: ${ht(c)}`)}let n;try{n=JSON.parse(t)}catch(c){throw new B(`invalid JSON: ${ht(c)}`)}if(!Xo(n))throw new B("missing required fields (appName, runtime or appType)");let r=lt(n);if(r.length>0)throw new B(r.map(c=>`${c}: expected a string`).join("; "));let s=_e(n,e);if(s.length>0)throw new B(s.join("; "));let o=n;for(let c of pt(n,e).warnings)Oe.has(c)||(Oe.add(c),console.warn(`\u26A0\uFE0F ${c}`));let i={...o,appType:o.appType||o.type},a=Jo(e);return{name:i.appName,path:a,configPath:e,config:i,stack:i.stack,port:i.port,type:i.appType}}function sr(e){let t=yt(e),n=[],r=[];for(let s of t)try{n.push(Zo(s))}catch(o){r.push({path:s,reason:o instanceof B?o.reason:ht(o)})}return{resources:n,problems:r}}function Qo(e){for(let t of e){let n=`skipped ${t.path}: ${t.reason}`;Oe.has(n)||(Oe.add(n),console.warn(`\u26A0\uFE0F ${n}`))}}function b(e){let{resources:t,problems:n}=sr(e);return Qo(n),t}function le(){let e=m();if(!e)throw I.notInProject();return b(e)}function qd(){let e=m();if(!e)throw I.notInProject();let{resources:t,problems:n}=sr(e);if(n.length>0)throw new Error(n.map(r=>`Invalid service.json at ${r.path}: ${r.reason}`).join(`
|
|
18
|
+
`));return t}function Jd(e){let t=b(e),n=new Set;for(let r of t)r.stack&&n.add(r.stack);return Array.from(n).sort()}function zd(e){let t=e||le(),n=new Set;for(let r of t)r.stack&&n.add(r.stack);return Array.from(n).sort()}function Yd(e=le()){let t=new Map;for(let r of e)if(r.stack){let s=t.get(r.stack);s?s.push(r):t.set(r.stack,[r])}let n=[];for(let[r,s]of t)n.push({name:r,description:S(s.length,"resource"),resources:s,resourceCount:s.length});return n.sort((r,s)=>r.name.localeCompare(s.name))}function Xd(e,t){return(t??le()).some(r=>r.stack===e)}var St=5e3,gt=new ce({ttlMs:St}),kt=new ce({ttlMs:St}),de=Cn(St);function Zd(){gt.clear(),kt.clear(),de.reset()}function ei(e,t){if(e==="Dockerfile"||e.startsWith("docker-compose"))return"docker";if(e==="Tiltfile"||e.endsWith(".star"))return"tilt";if(e==="vite.config.ts"||e==="tsconfig.json"||e==="package.json")return"config";if(e==="schema.prisma"||e.includes("migration"))return"prisma";if(t){let n=t.split(`
|
|
19
|
+
`).slice(0,10).join(`
|
|
20
|
+
`);if(n.includes("GENERATED BY TDK")||n.includes("AUTOGENERATED"))return"generated"}return"unknown"}function ti(e){let t=e.configPath;if(de.isValid()){let k=gt.get(t);if(k)return k}let n=e.path,r=mt(e.configPath),s=r.mtime.toISOString(),o=r.mtime.toISOString(),i=ni(n),a=J(U(n,"Dockerfile")),c=J(U(n,"Tiltfile")),u=J(U(n,"docker-compose.yml"))||J(U(n,"docker-compose.yaml")),d=e.config?.appType,l=d||"backend";d||(e.name.includes("frontend")?l="frontend":(e.name.includes("sdk")||e.name.includes("lib")||e.name.includes("infra"))&&(l="library"));let h={name:e.name,stack:e.stack,type:l,port:e.config?.port,createdAt:s,lastModified:o,dependencies:e.config?.dependsOn??[],hasDockerfile:a,hasTiltfile:c,hasDockerCompose:u,autogeneratedFiles:i,status:"unknown"};return gt.set(t,h),de.markUpdated(),h}function ni(e){let t=[];for(let r of Sn){let s=U(e,r);if(J(s)){let o=mt(s),i=rr(s,"utf-8");t.push({name:r,path:s,type:ei(r,i),size:o.size,lastModified:o.mtime.toISOString()})}}let n=U(e,"prisma");if(J(n)){let r=nr(n);for(let s of r)if(s==="schema.prisma"||s.includes("migration")){let o=U(n,s),i=mt(o);t.push({name:`prisma/${s}`,path:o,type:"prisma",size:i.size,lastModified:i.mtime.toISOString()})}}return t.sort((r,s)=>r.name.localeCompare(s.name))}function Qd(e){let t=e.name;if(de.isValid()){let c=kt.get(t);if(c)return c}let n=e.resources.map(c=>ti(c)),r=n.map(c=>new Date(c.createdAt).getTime()),s=Math.min(...r),o=Math.max(...r),i=Qn(n.map(c=>c.status)),a={name:e.name,resourceCount:n.length,createdAt:new Date(s).toISOString(),lastModified:new Date(o).toISOString(),resources:n,overallStatus:i};return kt.set(t,a),de.markUpdated(),a}function or(e,t){return e==="pending"||e==="in_progress"||e==="none"||t==="pending"||t==="none"}var ir="container is running, but its health check is failing";function ar(e){let t=e?.runtimeStatus??"";if(t!=="ok")return t;let n=e?.composeResourceInfo?.healthStatus;return n==="unhealthy"?"error":n==="starting"?"pending":t}var pe=1e4,cr=3e3,si="http://localhost:4873";function pr(e){return`'${e.replace(/'/g,"'\\''")}'`}function fe(e,t,n,r,s){return process.platform==="win32"?lr($(t)??t,n,{...s,windowsHide:!0}):e(r,s)}var oi=[80,443];function ii(e){return e.replace(/-/g,"_")}function ai(e,t){let n=new Set(t),r=[];for(let s of e.split(`
|
|
21
|
+
`)){let o=s.trim();if(!o)continue;let i=o.indexOf(" "),a=i>=0?o.slice(0,i):o,c=i>=0?o.slice(i+1):"",u=[];for(let d of n)(new RegExp(`(?:^|[\\s,])(?:\\d[\\d.]*:|\\[::\\]:|::)?${d}->`).test(c)||c.includes(`:${d}->`))&&u.push(d);u.length>0&&r.push({name:a,ports:c,publishedPorts:u})}return r}function fr(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n===`${r}_traefik`||n.startsWith(`${r}_traefik`)}function ci(e,t){return e.filter(n=>!fr(n.name,t))}function ui(){try{return new Set(le().filter(e=>e.config?.sablier?.enable&&e.config?.sablier?.deferStart).map(e=>e.name))}catch{return new Set}}function di(e,t=new Set){let r=JSON.parse(e).items??[],s=[],o=0,i=0,a=0;for(let c of r){let u=c.metadata?.name??"unknown",d=c.status?.updateStatus??"",l=ar(c.status),h=l==="error"&&c.status?.runtimeStatus==="ok",g=(c.status?.buildHistory?.[0]?.error??"").trim()||(h?ir:"");if(d==="error"||l==="error"){s.push({name:u,updateStatus:d,runtimeStatus:l,error:g.replace(/\s+/g," ").slice(0,800)});continue}if(d==="ok"&&(l==="ok"||l==="not_applicable")){a+=1;continue}u!=="(Tiltfile)"&&or(d,l)&&(t.has(u)?i+=1:o+=1)}return{failures:s,pendingCount:o,deferredCount:i,okCount:a,total:r.length}}var li=/failed to resolve source metadata for docker\.io\/library\/([A-Za-z0-9._-]+-l[1-4](?:-[a-z]+)*)(?::[^\s:]+)?:/i;function Tt(e){let t=e.replace(/\s+/g," ").trim(),n=t.match(/Bind for [^ ]+:(\d+) failed: port is already allocated/i);if(n)return`host port ${n[1]} is already allocated`;if(/port is already allocated/i.test(t))return"a required host port is already allocated";let r=[...t.matchAll(/ConnectionRefused downloading package manifest (@[A-Za-z0-9._/-]+)/gi)].map(a=>a[1]);if(r.length>0){let a=[...new Set(r)],c=a.slice(0,4).join(", "),u=a.length>4?` (+${a.length-4} more)`:"";return`private registry ConnectionRefused for ${c}${u} \u2014 Verdaccio (:4873) is down or unreachable from the build`}let s=t.match(li);if(s)return`base image ${s[1]} was missing when this build started (the golden layers weren't built yet, or golden-layers-build failed) - Tilt does not retry a failed build by itself`;if(/install-deps\.sh/i.test(t)||/bun install(?: --production)?/i.test(t)||/npm (?:ci|install)/i.test(t))return"dependency install failed during ImageBuild \u2014 usually Verdaccio (:4873) unreachable or missing @scoped packages (ConnectionRefused downloading package manifest)";let o=t.match(/No such image:\s*([^\s]+)/i)?.[1]??t.match(/pull access denied for ([^,:\s]+)/i)?.[1]??void 0,i=t.match(/\bup\s+-d\s+--no-build\s+([A-Za-z0-9._-]+)/i)?.[1];if(o||i||/docker compose .*\bup\s+-d\s+--no-build\b/i.test(t)){let a=o??`${i??"service"}:dev`,c=i?` for ${i}`:"";return`compose run failed because image is missing (${a})${c} \u2014 wait for the ImageBuild resource to finish, then re-trigger the *-run-only resource`}return/bun run build/i.test(t)?"ImageBuild failed during `bun run build` (compile/typecheck) \u2014 open the resource logs in Tilt for the TypeScript/build error":(/ImageBuild:/i.test(t)||/^Command "/i.test(t),t.slice(0,220))}function ur(e){return/ConnectionRefused downloading package manifest|Verdaccio|private registry|dependency install failed during ImageBuild|install-deps\.sh|bun install/i.test(e)}function wt(e=m()??process.cwd()){let t=z(e,".tdk","project.json");if(!bt(t))return!1;try{let n=JSON.parse(xt(t,"utf-8"));return n.optional_infra?.verdaccio===!0||Object.values(n.phases??{}).some(r=>(r.enabledStacks??[]).includes("verdaccio"))}catch{return!1}}function mr(e){for(let t of[z(e,".npmrc"),z(e,"package.json")])if(bt(t))try{let n=xt(t,"utf-8");if(/:4873\b/.test(n)||/verdaccio/i.test(n))return!0}catch{}return!1}function pi(e=m()??process.cwd()){return wt(e)||mr(e)}function vt(e=me,t=m()??process.cwd(),n=process.env.VERDACCIO_URL??process.env.NPM_REGISTRY_URL??si,r=!0){if(!r&&!mr(t))return{name:"Private npm registry",didPass:!0,isSkipped:!0,message:"Verdaccio is enabled in the project config but needs a Premium license, so TDK will not start it - skipped"};if(!pi(t))return{name:"Private npm registry",didPass:!0,isSkipped:!0,message:"Private npm registry (Verdaccio) not enabled for this project - skipped"};let s=!1;try{let a=fe(e,"docker",["ps","--format","{{.Names}}"],"docker ps --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:pe});s=/verdaccio/i.test(a)}catch{}let o=!1,i="";try{let a=process.platform==="win32"?lr("curl.exe",["-fsS","-o","NUL","-w","%{http_code}","--max-time","2",n],{stdio:"pipe",encoding:"utf-8",timeout:cr+1e3,windowsHide:!0}).trim():e(`curl -fsS -o /dev/null -w '%{http_code}' --max-time 2 ${pr(n)}`,{stdio:"pipe",encoding:"utf-8",timeout:cr+1e3}).trim();o=/^[23]\d\d$/.test(a),i=`HTTP ${a}`}catch(a){i=a instanceof Error?a.message.slice(0,120):"request failed"}return o?{name:"Private npm registry",didPass:!0,message:`Private npm registry reachable at ${n}${s?" (verdaccio container running)":""}`}:s?{name:"Private npm registry",didPass:!1,message:`Verdaccio container is running but ${n} is not responding (${i}). ImageBuilds that install @scoped packages will fail with ConnectionRefused downloading package manifest.`,fix:"Check `docker logs` for the verdaccio container, confirm port 4873 is published, then re-run `tdk doctor`."}:{name:"Private npm registry",didPass:!1,message:`Private npm registry (Verdaccio) is not reachable at ${n}. Docker ImageBuilds will fail with ConnectionRefused downloading package manifests for @tdk-landscape/* and project-scoped packages.`,fix:"Start the registry with `bun run verdaccio:start` (or `docker compose -f docker-compose.verdaccio.yml up -d`), publish packages with `bun run publish:all` / `scripts/build/publish-to-verdaccio.sh`, then `tilt trigger` failed resources or re-run `tdk up`."}}function Pt(e=me,t=st(),n=oi){let r=ii(t),s="";try{s=fe(e,"docker",["ps","--format","{{.Names}}\\t{{.Ports}}"],"docker ps --format '{{.Names}}\\t{{.Ports}}'",{stdio:"pipe",encoding:"utf-8",timeout:pe})}catch{return{name:"Ingress Ports",didPass:!0,isSkipped:!0,message:"Docker not available - skipped ingress port check"}}let o=ai(s,n),i=ci(o,r);if(i.length===0){let c=o.filter(u=>fr(u.name,r));return c.length>0?{name:"Ingress Ports",didPass:!0,message:`Ingress ports ${n.join("/")} held by this project's Traefik (${c.map(u=>u.name).join(", ")})`}:{name:"Ingress Ports",didPass:!0,message:`Ingress ports ${n.join("/")} are free for Traefik`}}return{name:"Ingress Ports",didPass:!1,message:`Traefik cannot bind ingress ports because another container already owns them:
|
|
22
|
+
${i.map(c=>{let u=c.publishedPorts.join(", ");return`${c.name} (host ports ${u})`}).join(`
|
|
23
|
+
`)}`,fix:`Stop the foreign container(s), e.g. \`docker stop ${i[0]?.name}\`, or shut down the other TDK/Tilt project using that Traefik. Then re-run \`tdk up\`.`}}function fi(e){let{status:t}=e;return t===void 0?e.error??"no response":t===404?"HTTP 404: Traefik is answering but has no route for this URL (container not started yet, or not running)":t===502||t===503||t===504?`HTTP ${t}: Traefik found the route but the container isn't answering (still starting, or unhealthy)`:`HTTP ${t}`}function $t(e){let t=e.filter(o=>o.status!==void 0),n=e.filter(o=>!o.ok);if(t.length===0)return{name:"Service Health",didPass:!0,isSkipped:!0,message:`No services responded - skipped ping of ${S(e.length,"service")} (stack may be down, or Traefik never bound :80)`,fix:"If `tdk up` is already running, check Traefik/port 80 in the Tilt UI. Otherwise start with: tdk up"};if(n.length===0)return{name:"Service Health",didPass:!0,message:`All ${S(e.length,"service")} responding on /health`};let r=n.map(o=>`${o.name} (${fi(o)})
|
|
24
|
+
${o.url}`).join(`
|
|
25
|
+
`),s=n.some(o=>o.status===404);return{name:"Service Health",didPass:!1,message:`${S(n.length,"service")} not healthy (${e.length-n.length}/${e.length} healthy):
|
|
26
|
+
${r}`,fix:s?"If `tdk up` just started, images may still be building: re-run `tdk doctor` in a minute. Otherwise check `docker ps` and the resource in the Tilt UI, and compare `tdk networks` with the URL above.":"Check container state and routing: docker ps, then tdk networks to compare the advertised URLs against Traefik's routers"}}function Et(e=me){let t="";try{t=fe(e,"tilt",["get","uiresources","-o","json"],"tilt get uiresources -o json",{stdio:"pipe",encoding:"utf-8",timeout:pe})}catch{return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"Tilt is not running - skipped resource status check",fix:"Start them with: tdk up"}}let n;try{n=di(t,ui())}catch{return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"Could not parse Tilt resource status - skipped"}}if(n.total===0)return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"No Tilt UIResources found"};if(n.failures.length===0){let y=n.deferredCount>0?`, ${n.deferredCount} deferred`:"";return{name:"Tilt Resources",didPass:!0,message:`Tilt resources healthy (${n.okCount} ok, ${n.pendingCount} pending${y})`}}let r=hi(n.failures),o=r.slice(0,20),i=r.length-o.length,a=o.map(y=>({failure:y,why:ki(y,e)})),c=a.map(({failure:y,why:v})=>`${y.name}: ${v}`).join(`
|
|
27
|
+
`),u=i>0?`
|
|
28
|
+
\u2026and ${S(i,"more failed resource")}`:"",d=n.pendingCount>0?`
|
|
29
|
+
${S(n.pendingCount,"resource")} still pending/not started \u2014 often blocked by the failures above.`:"",l=n.deferredCount>0?`
|
|
30
|
+
${S(n.deferredCount,"resource")} intentionally deferred (sablier.deferStart) \u2014 not started until first request, unrelated to the failures above.`:"",h=r.some(y=>/port is already allocated/i.test(y.error)),k=r.some(y=>ur(y.error)||ur(Tt(y.error))),g=a.some(({why:y})=>/Kafka broker unreachable|kafka:9092/i.test(y)),p="Open the Tilt UI URL printed by tdk up (default port "+kn.tiltUi+" when TILT_PORT is unset), inspect the red resources, fix the listed errors, then `tilt trigger <resource>` or re-run `tdk up`.";return h?p="Free the conflicting host port (usually 80/443): `docker ps --filter publish=80` then `docker stop <other-traefik>`. Re-trigger Traefik in the Tilt UI or run `tdk up` again.":k?p="Start Verdaccio (`bun run verdaccio:start`), ensure packages are published (`bun run publish:all` or `bash scripts/build/publish-to-verdaccio.sh`), confirm `curl http://localhost:4873` works, then `tilt trigger` the failed resources.":g&&(p="Kafka is not running (optional infra). Start it, point the bridge at a real broker, or disable Kafka-dependent resources until Kafka is enabled."),{name:"Tilt Resources",didPass:!1,message:`Tilt reports ${S(n.failures.length,"failed resource")}:
|
|
31
|
+
${c}${u}${d}${l}`,fix:p}}var mi=/^(traefik|postgres|nats|infisical|verdaccio|proxy)([.-]|$)/i;function dr(e){return mi.test(e)}function hi(e){return[...e].sort((t,n)=>{let r=dr(t.name)?0:1,s=dr(n.name)?0:1;return r!==s?r-s:t.name.localeCompare(n.name)})}function gi(e,t=me){try{let n=fe(t,"docker",["ps","-a","--format","{{.Names}}"],"docker ps -a --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:pe}).split(`
|
|
32
|
+
`).map(a=>a.trim()).filter(Boolean),r=n.find(a=>a===e)??n.find(a=>a.includes(e));if(!r)return null;let s=fe(t,"docker",["logs","--tail","120",r],`docker logs --tail 120 ${pr(r)} 2>&1`,{stdio:"pipe",encoding:"utf-8",timeout:pe});if(/getaddrinfo ENOTFOUND/i.test(s)&&/kafka:9092/i.test(s))return"runtime crash: Kafka broker unreachable (getaddrinfo ENOTFOUND kafka:9092)";if(/ECONNREFUSED/i.test(s)&&/kafka/i.test(s))return"runtime crash: Kafka connection refused";let o=s.match(/ConnectionRefused downloading package manifest (@[A-Za-z0-9._/-]+)/i);if(o?.[1])return`runtime/build log: private registry ConnectionRefused for ${o[1]}`;if(/ZodError/i.test(s)){let a=[...s.matchAll(/"path"\s*:\s*\[\s*"([^"]+)"\s*\]/g)].map(u=>u[1]),c=[...new Set(a)].slice(0,6);return c.length>0?`runtime crash: ZodError missing required config/env: ${c.join(", ")}`:"runtime crash: ZodError during config/env validation"}let i=s.match(/error:\s+Failed to [^:\n]+[^\n]{0,120}/i)?.[0]??s.match(/Failed to (?:start|initialize) [^\n]{0,120}/i)?.[0]??s.match(/^\s*error:\s+[^\n]{0,160}/im)?.[0];if(i)return`runtime crash: ${i.replace(/\s+/g," ").trim().slice(0,180)}`}catch{return null}return null}function ki(e,t=me){return e.error?Tt(e.error):e.runtimeStatus==="error"?gi(e.name,t)??"runtime error (container crashed or unhealthy \u2014 check Tilt/docker logs)":e.updateStatus||e.runtimeStatus||"unknown error"}var yi=/\.(ts|tsx|mts|js|mjs|cjs)$/,Si=new Set(["node_modules","dist",".autogenerated","tests","__tests__"]);function hr(e){let t=[];for(let n of ri(e,{withFileTypes:!0}))n.isDirectory()?Si.has(n.name)||t.push(...hr(z(e,n.name))):yi.test(n.name)&&!/\.(test|spec)\./.test(n.name)&&t.push(z(e,n.name));return t}function bi(e){let t=e?.healthCheckPath||"/health";return{container:t,traefik:e?.traefik?.healthCheck||t}}function xi(e){let t=[];for(let n of e){if(!P(n.config?.appType))continue;let r=z(n.path,"src");if(!bt(r))continue;let s=hr(r);if(s.length===0)continue;let o=s.map(u=>xt(u,"utf-8")),{container:i,traefik:a}=bi(n.config),c=i===a?[{path:i,usedBy:"container and Traefik healthchecks"}]:[{path:i,usedBy:"container healthcheck"},{path:a,usedBy:"Traefik healthcheck"}];for(let{path:u,usedBy:d}of c){let l=["'",'"',"`"].map(h=>`${h}${u}${h}`);o.some(h=>l.some(k=>h.includes(k)))||t.push({name:n.name,healthPath:u,usedBy:d})}}return t}function gr(e=m()??process.cwd()){let t=[];try{t=b(e)}catch{return{name:"Health Routes",didPass:!0,isSkipped:!0,message:"Could not read services - skipped health route check"}}let n=t.filter(o=>P(o.config?.appType));if(n.length===0)return{name:"Health Routes",didPass:!0,isSkipped:!0,message:"No backend services to check"};let r=xi(n);return r.length===0?{name:"Health Routes",didPass:!0,message:`All ${S(n.length,"backend")} define their health route`}:{name:"Health Routes",didPass:!1,message:`Backends without a health route (the container never turns healthy, so Traefik returns 404):
|
|
33
|
+
${r.map(o=>`${o.name}: no "${o.healthPath}" route in src/ (probed by the ${o.usedBy})`).join(`
|
|
34
|
+
`)}`,fix:`Add the route, e.g. for Hono: app.get("${r[0]?.healthPath}", (c) => c.json({ status: "ok" })). To use a different path, set "healthCheckPath" (container healthcheck) or "traefik.healthCheck" (Traefik) in its service.json.`}}import{existsSync as _t,readFileSync as kr}from"node:fs";import{dirname as Ti,join as Rt,normalize as wi}from"node:path";function vi(e){let t=new Set,n=/^load\s*\(([\s\S]*?)\)/gm;for(let r of e.matchAll(n)){let s=r[1]??"",o=/["']([^"']+)["']/g,i=Array.from(s.matchAll(o),a=>a[1]);for(let a of i.slice(1))a.startsWith("_")&&t.add(a)}return Array.from(t).sort()}function yr(e,t,n){return t==="ext://tdk-cli"?Rt(n,".tdk",".tdk-out","tdk-cli-ext","Tiltfile"):t.startsWith(".")||!t.includes("://")&&!t.startsWith("@")?wi(Rt(Ti(e),t)):null}function Pi(e,t,n){let r=[],s=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(s)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(!c)continue;let u=yr(e,c,n);u&&(_t(u)||r.push(`${e}: ${c} -> ${u}`))}return r}function $i(e,t,n){let r=[],s=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(s)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(c){let u=yr(e,c,n);u&&r.push(u)}}return r}function Ei(e,t){let n=new Set,r=[e];for(;r.length>0;){let s=r.pop();if(!s||n.has(s)||!_t(s))continue;n.add(s);let o=kr(s,"utf-8");for(let i of $i(s,o,t))n.has(i)||r.push(i)}return Array.from(n).sort()}function Sr(){let e=m()??process.cwd(),t=Rt(e,".tdk",".tdk-out","Tiltfile");if(!_t(t))return{name:"Starlark Load Exports",didPass:!0,isSkipped:!0,message:"No generated Tiltfile to check"};let n=[],r=[],s=Ei(t,e);for(let i of s){let a=kr(i,"utf-8"),c=vi(a);c.length>0&&n.push(`${i}: ${c.join(", ")}`);for(let u of Pi(i,a,e))r.push(u)}if(n.length===0&&r.length===0)return{name:"Starlark Load Exports",didPass:!0,message:`${S(s.length,"reachable Starlark file")} ${s.length===1?"has":"have"} valid load exports and paths`};let o=[];return n.length>0&&o.push(`Private exported symbols:
|
|
35
|
+
${n.join(`
|
|
36
|
+
`)}`),r.length>0&&o.push(`Missing relative load targets:
|
|
37
|
+
${r.join(`
|
|
38
|
+
`)}`),{name:"Starlark Load Exports",didPass:!1,message:`Starlark load() issues will stop Tilt before services start:
|
|
39
|
+
${o.join(`
|
|
40
|
+
|
|
41
|
+
`)}`,fix:"Regenerate with a current TDK (`tdk config regenerate`). If the issue remains, rename loaded symbols without leading underscores and update stale load paths."}}import{execFileSync as Ui,execSync as Hi}from"node:child_process";import{existsSync as Ct,readdirSync as Nr,readFileSync as ge}from"node:fs";import{basename as Vi,dirname as Wi,join as _,relative as he}from"node:path";function Sl(e){return`import { Hono } from 'hono';
|
|
42
|
+
|
|
43
|
+
const app = new Hono();
|
|
44
|
+
|
|
45
|
+
// Health check endpoint (required by TILT_RESOURCE_DEFAULTS.star)
|
|
46
|
+
app.get('/health', (c) => {
|
|
47
|
+
return c.json({ status: 'ok', service: '${e}' });
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
app.get('/health/live', (c) => {
|
|
51
|
+
return c.json({ status: 'alive', timestamp: Date.now() });
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
app.get('/health/ready', async (c) => {
|
|
55
|
+
const dependencies: Record<string, string> = {};
|
|
56
|
+
let allReady = true;
|
|
57
|
+
|
|
58
|
+
// Add dependency checks here (database, cache, etc.)
|
|
59
|
+
// Mark allReady = false if any dependency is unhealthy
|
|
60
|
+
|
|
61
|
+
const status = allReady ? 'ready' : 'not_ready';
|
|
62
|
+
return c.json({ status, dependencies }, allReady ? 200 : 503);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
app.get('/', (c) => {
|
|
66
|
+
return c.json({
|
|
67
|
+
service: '${e}',
|
|
68
|
+
version: '1.0.0',
|
|
69
|
+
endpoints: ['/health', '/health/live', '/health/ready']
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const port = process.env.PORT || 3000;
|
|
74
|
+
console.log('\\n\u{1F680} ${e} running on http://localhost:' + port);
|
|
75
|
+
console.log('\u{1F4CA} Health check: http://localhost:' + port + '/health\\n');
|
|
76
|
+
|
|
77
|
+
export default {
|
|
78
|
+
port,
|
|
79
|
+
fetch: app.fetch,
|
|
80
|
+
};
|
|
81
|
+
`}var br={id:"bun",label:"Bun + Hono",installHint:"bun install"};var Ri="go run .",xr={id:"go",label:"Go 1.23 (net/http)",devCommand:Ri,watch:["**/*.go","go.mod","go.sum"],installHint:"go mod tidy # optional: Docker builds the image for you",createFiles(e){return[{filename:"go.mod",content:`module ${e}
|
|
82
|
+
|
|
83
|
+
go 1.23
|
|
84
|
+
`,description:"Generating go.mod",emoji:"\u{1F4E6}"},{filename:"main.go",content:`package main
|
|
85
|
+
|
|
86
|
+
import (
|
|
87
|
+
"encoding/json"
|
|
88
|
+
"log"
|
|
89
|
+
"net/http"
|
|
90
|
+
"os"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
func writeJSON(w http.ResponseWriter, status int, body any) {
|
|
94
|
+
w.Header().Set("Content-Type", "application/json")
|
|
95
|
+
w.WriteHeader(status)
|
|
96
|
+
_ = json.NewEncoder(w).Encode(body)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
func newMux() *http.ServeMux {
|
|
100
|
+
mux := http.NewServeMux()
|
|
101
|
+
|
|
102
|
+
// Health check endpoint (required by TILT_RESOURCE_DEFAULTS.star)
|
|
103
|
+
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
|
|
104
|
+
writeJSON(w, http.StatusOK, map[string]string{"status": "ok", "service": "${e}"})
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
|
|
108
|
+
writeJSON(w, http.StatusOK, map[string]any{
|
|
109
|
+
"service": "${e}",
|
|
110
|
+
"version": "1.0.0",
|
|
111
|
+
"endpoints": []string{"/health"},
|
|
112
|
+
})
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
return mux
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
func main() {
|
|
119
|
+
port := os.Getenv("PORT")
|
|
120
|
+
if port == "" {
|
|
121
|
+
port = "3000"
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ":" + port listens on every interface, which Traefik needs inside the container network.
|
|
125
|
+
log.Printf("${e} listening on :%s", port)
|
|
126
|
+
log.Fatal(http.ListenAndServe(":"+port, newMux()))
|
|
127
|
+
}
|
|
128
|
+
`,description:"Generating backend source",emoji:"\u{1F4BB}"},{filename:"main_test.go",content:`package main
|
|
129
|
+
|
|
130
|
+
import (
|
|
131
|
+
"net/http"
|
|
132
|
+
"net/http/httptest"
|
|
133
|
+
"testing"
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
func TestHealth(t *testing.T) {
|
|
137
|
+
rec := httptest.NewRecorder()
|
|
138
|
+
newMux().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil))
|
|
139
|
+
|
|
140
|
+
if rec.Code != http.StatusOK {
|
|
141
|
+
t.Fatalf("GET /health = %d, want %d", rec.Code, http.StatusOK)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
`,description:"Generating smoke test",emoji:"\u{1F9EA}"}]}};var _i="uvicorn main:app --app-dir src --host 0.0.0.0 --port ${PORT:-4000} --reload --reload-dir src",Tr={id:"python",label:"Python 3.12 + FastAPI",devCommand:_i,watch:["src/**/*"],installHint:'pip install -e ".[dev]" # optional: Docker builds the image for you',createFiles(e){return[{filename:"pyproject.toml",content:`[project]
|
|
145
|
+
name = "${e}"
|
|
146
|
+
version = "0.0.1"
|
|
147
|
+
requires-python = ">=3.12"
|
|
148
|
+
dependencies = [
|
|
149
|
+
"fastapi==0.115.6",
|
|
150
|
+
"uvicorn[standard]==0.34.0",
|
|
151
|
+
]
|
|
152
|
+
|
|
153
|
+
[project.optional-dependencies]
|
|
154
|
+
dev = [
|
|
155
|
+
"pytest==9.0.3",
|
|
156
|
+
"httpx==0.28.1",
|
|
157
|
+
]
|
|
158
|
+
|
|
159
|
+
[build-system]
|
|
160
|
+
requires = ["setuptools>=68"]
|
|
161
|
+
build-backend = "setuptools.build_meta"
|
|
162
|
+
|
|
163
|
+
# Only the dependencies are installed into the image; the source is synced for live reload.
|
|
164
|
+
[tool.setuptools]
|
|
165
|
+
py-modules = []
|
|
166
|
+
|
|
167
|
+
[tool.pytest.ini_options]
|
|
168
|
+
pythonpath = ["src"]
|
|
169
|
+
testpaths = ["tests"]
|
|
170
|
+
`,description:"Generating pyproject.toml",emoji:"\u{1F4E6}"},{filename:"src/main.py",content:`import os
|
|
171
|
+
|
|
172
|
+
from fastapi import FastAPI
|
|
173
|
+
|
|
174
|
+
app = FastAPI(title="${e}")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@app.get("/health")
|
|
178
|
+
def health() -> dict[str, str]:
|
|
179
|
+
return {"status": "ok", "service": "${e}"}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@app.get("/")
|
|
183
|
+
def root() -> dict[str, object]:
|
|
184
|
+
return {"service": "${e}", "version": "1.0.0", "endpoints": ["/health"]}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
if __name__ == "__main__":
|
|
188
|
+
import uvicorn
|
|
189
|
+
|
|
190
|
+
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "3000")))
|
|
191
|
+
`,description:"Generating backend source",emoji:"\u{1F4BB}"},{filename:"tests/test_health.py",content:`from fastapi.testclient import TestClient
|
|
192
|
+
|
|
193
|
+
from main import app
|
|
194
|
+
|
|
195
|
+
client = TestClient(app)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def test_health() -> None:
|
|
199
|
+
response = client.get("/health")
|
|
200
|
+
assert response.status_code == 200
|
|
201
|
+
assert response.json() == {"status": "ok", "service": "${e}"}
|
|
202
|
+
`,description:"Generating test file",emoji:"\u{1F9EA}"}]}};var Oi="cargo run",wr={id:"rust",label:"Rust (axum)",devCommand:Oi,watch:["src/**/*.rs","Cargo.toml","Cargo.lock"],installHint:"cargo build # optional: Docker builds the image for you",createFiles(e){return[{filename:"Cargo.toml",content:`[package]
|
|
203
|
+
name = "${e}"
|
|
204
|
+
version = "0.1.0"
|
|
205
|
+
edition = "2021"
|
|
206
|
+
|
|
207
|
+
# The image copies the release binary by this fixed name.
|
|
208
|
+
[[bin]]
|
|
209
|
+
name = "app"
|
|
210
|
+
path = "src/main.rs"
|
|
211
|
+
|
|
212
|
+
[dependencies]
|
|
213
|
+
axum = "0.8"
|
|
214
|
+
serde_json = "1"
|
|
215
|
+
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }
|
|
216
|
+
`,description:"Generating Cargo.toml",emoji:"\u{1F4E6}"},{filename:"src/main.rs",content:`use axum::{routing::get, Json, Router};
|
|
217
|
+
use serde_json::{json, Value};
|
|
218
|
+
|
|
219
|
+
fn app() -> Router {
|
|
220
|
+
Router::new()
|
|
221
|
+
.route("/", get(root))
|
|
222
|
+
// Health check endpoint (required by TILT_RESOURCE_DEFAULTS.star)
|
|
223
|
+
.route("/health", get(health))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async fn root() -> Json<Value> {
|
|
227
|
+
Json(json!({ "service": "${e}", "version": "1.0.0", "endpoints": ["/health"] }))
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async fn health() -> Json<Value> {
|
|
231
|
+
Json(json!({ "status": "ok", "service": "${e}" }))
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
#[tokio::main]
|
|
235
|
+
async fn main() {
|
|
236
|
+
let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
|
|
237
|
+
|
|
238
|
+
// 0.0.0.0 listens on every interface, which Traefik needs inside the container network.
|
|
239
|
+
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}"))
|
|
240
|
+
.await
|
|
241
|
+
.expect("failed to bind the port");
|
|
242
|
+
println!("${e} listening on 0.0.0.0:{port}");
|
|
243
|
+
axum::serve(listener, app()).await.expect("server error");
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
#[cfg(test)]
|
|
247
|
+
mod tests {
|
|
248
|
+
use super::*;
|
|
249
|
+
|
|
250
|
+
#[tokio::test]
|
|
251
|
+
async fn health_reports_ok() {
|
|
252
|
+
let Json(body) = health().await;
|
|
253
|
+
assert_eq!(body["status"], "ok");
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
`,description:"Generating backend source and smoke test",emoji:"\u{1F4BB}"}]}};var vr="bun",Y={bun:br,python:Tr,go:xr,rust:wr};function Ai(e){let t=(e??vr).trim().toLowerCase(),n=Object.hasOwn(Y,t)?Y[t]:void 0;if(!n){let r=Object.keys(Y).join(", ");throw new E(`Unknown backend language "${e}". Supported languages: ${r}.`,[`Use one of: ${r}`,`Omit --language to use ${vr}`])}return n}function _l(e,t){if(e!=="backend"){if(t!==void 0)throw new E("--language can only be used with --type backend.",["Add --type backend, or drop --language for this resource type"]);return}return Ai(t)}import{exec as Di,execFile as Ci}from"node:child_process";import{promisify as Pr}from"node:util";var Ni=Pr(Di),N=async(e,t)=>{if(process.platform==="win32"){let r=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)??[],[s,...o]=r.map(c=>c.startsWith('"')||c.startsWith("'")?c.slice(1,-1):c);if(!s)throw new Error("Command is empty");let i=$(s)??s,{stdout:a}=await Pr(Ci)(i,o,{encoding:"utf-8",timeout:t,windowsHide:!0,shell:!1});return a}let{stdout:n}=await Ni(e,{encoding:"utf-8",timeout:t});return n};function $r(e){let t=e;return t?.code==="ETIMEDOUT"||t?.killed===!0}import{existsSync as ji,readFileSync as Er}from"node:fs";import{join as H}from"node:path";var Ot=["database-management","proxy"];var Rr=["postgres","database-management"],_r=["pre_alpha","alpha","beta","out_of_scope"];function Ii(e){return Rr.includes(e)}function Or(e){try{return JSON.parse(Er(H(e,".tdk","project.json"),"utf-8"))}catch{return}}function X(e){try{return ji(e)?Er(e,"utf-8"):void 0}catch{return}}function Ar(e,t){let n=new RegExp(`${t}\\s*=\\s*\\[([^\\]]*)\\]`),r=e.match(n);if(r)return[...r[1].matchAll(/"([^"]+)"|'([^']+)'/g)].map(s=>s[1]??s[2]??"")}function Dr(e){let t=H(e,".tdk",".tdk-out","Tiltfile"),n=X(t);if(n)return Ar(n,"ALWAYS_ENABLED_INFRA")}function Fi(e){let t=H(e,".tdk",".tdk-out","spec.master"),n=X(t);if(n!==void 0)return/"database-management"\s*:\s*True/.test(n)}function Mi(e){let t=H(e,".tdk",".tdk-out"),n=X(H(t,"Tiltfile")),r=X(H(t,"spec.master")),s=X(H(t,"tdk-cli-ext","discovery","config.star")),o=X(H(t,"tdk-cli-ext","engine","topologies","tilt","config","profiles.star"));if(!n||!r||!s||!o)return!1;let i=r.match(/PRE_ALPHA_RESOURCES\s*=\s*\{([^}]*)\}/)?.[1],a=Ar(s,"CORE_INFRA");return/FOCUS_MODE\s*,\s*FOCUS_ENABLED_ALL\s*,\s*FOCUS_ENABLED_RESOURCES\s*=\s*Config\.apply_focus\(cfg\)/.test(n)&&/if FOCUS_MODE and FOCUS_ENABLED_ALL\s*:/.test(n)&&/"[^"]+"\s*:\s*True|'[^']+'\s*:\s*True/.test(i??"")&&(a?.includes("postgres")??!1)&&/["']postgres["']\s*:\s*["']database-management["']/.test(s)&&/for infra in CORE_INFRA_EXPORT\s*:/.test(o)&&/needed\[INFRA_STACK_MAP_EXPORT\[infra\]\]\s*=\s*True/.test(o)}function Li(e){let t=Or(e);if(!t)return!1;let n=t.phases??{};for(let s of _r){let o=n[s]?.enabledStacks;if(Array.isArray(o)&&o.includes("database-management"))return!0}let r=t.always_enabled_infra??Ot;return Array.isArray(r)&&r.includes("database-management")}function Bi(e){let t=new Set;for(let s of Rr)t.add(s);for(let s of b(e))t.add(s.name),s.stack&&t.add(s.stack);let n=Or(e);if(n){let s=n.phases??{};for(let i of _r){let a=s[i]?.enabledStacks;if(Array.isArray(a))for(let c of a)t.add(c)}let o=n.always_enabled_infra??Ot;if(Array.isArray(o))for(let i of o)t.add(i)}let r=Dr(e);if(Array.isArray(r))for(let s of r)t.add(s);return t}function At(e){let t=Li(e),n=Dr(e),r=Array.isArray(n)&&n.includes("database-management"),s=Fi(e)===!0,o=t||r||s,i=!t&&Mi(e),a=Bi(e),c=[],u=[];for(let h of b(e)){let k=h.config?.dependsOn??[],g=!1;for(let p of k){if(Ii(p)){g=!0;continue}a.has(p)||u.push({resource:h.name,name:p})}g&&c.push(h.name)}let d=o||c.length>0,l=o?"feature":c.length>0?"dependsOn":"none";return{featureOn:o,featureOnFromProjectJson:t,featureOnFromTiltfile:r,featureOnFromSpecMaster:s,focusWouldEnableDatabaseManagement:i,dependsOnUsers:c,willStart:d,reason:l,unknownDependsOnNames:u}}var De=1e4,Ki=/\.(?:[cm]?[jt]sx?|vue)$/,Gi=/(?:\.test\.|\.spec\.|\/tests?\/|\/__tests__\/)/,qi=7,Ji=new Set(["node_modules",".autogenerated","dist","tests","__tests__"]);function jr(e){try{let t=JSON.parse(ge(_(e,".tdk","project.json"),"utf-8"));return typeof t?.project?.name=="string"?t.project.name:void 0}catch{return}}function zi(e){try{let t=JSON.parse(ge(e,"utf-8")).params;return t&&typeof t=="object"?t:{}}catch{return{}}}function Dt(e){try{let t=JSON.parse(ge(_(e,"package.json"),"utf-8"));return t&&typeof t=="object"?t:{}}catch{return{}}}function Cr(e){if(typeof e!="string")return;let t=e.match(/(?:^|[^0-9])(\d+)(?:\.|$)/);return t?Number(t[1]):void 0}function Yi(e){let t=Ne(e);if(t===void 0)return["missing prisma/schema.prisma"];let n=t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,""),r=[],s=n.match(/datasource\s+\w+\s*\{([^}]*)\}/)?.[1]??"";return/provider\s*=\s*["']postgresql["']/.test(s)||r.push("schema provider is not postgresql"),/\b(?:url|directUrl)\s*=/.test(n)&&r.push("schema still declares url/directUrl"),r}function Xi(e){let t=_(e,".autogenerated","prisma.config.autogenerated.ts"),r=[_(e,"prisma.config.ts"),t].find(i=>Ct(i));if(!r)return["missing prisma.config.ts or generated Prisma config"];let o=(Ne(r)??"").match(/datasource\s*:\s*\{([^}]*)\}/)?.[1]??"";return/url\s*:\s*(?:env\(["']DATABASE_URL["']\)|process\.env\.DATABASE_URL)\s*,?/.test(o)?[]:['Prisma config datasource.url is not env("DATABASE_URL")']}function Ir(e=m()??process.cwd()){let t=b(e),n=t.filter(o=>o.config?.featuresEnabled?.includes("prisma")),r=[],s=t.filter(o=>o.config?.appType==="migrator");for(let o of t){let i=o.config?.features;Array.isArray(i)&&i.includes("prisma")&&!o.config?.featuresEnabled?.includes("prisma")&&r.push(`${o.name}: use featuresEnabled, not features, for Prisma`)}if(n.length===0)return r.length===0?{name:"Prisma 7 consistency",didPass:!0,isSkipped:!0,message:"No resources enable Prisma; Prisma consistency checks were skipped"}:{name:"Prisma 7 consistency",didPass:!1,message:`${S(r.length,"Prisma consistency error")}:
|
|
257
|
+
${r.join(`
|
|
258
|
+
`)}`,fix:"Use featuresEnabled to opt into the validated Prisma 7 shape"};for(let o of n){let i=Dt(o.path).dependencies,c={...Dt(o.path).devDependencies??{},...i??{}},u=Cr(c.prisma),d=Cr(c["@prisma/client"]);if(u===void 0||d===void 0?r.push(`${o.name}: prisma and @prisma/client are required`):(u!==d||u!==qi)&&r.push(`${o.name}: prisma packages must both be major 7`),r.push(...Yi(_(o.path,"prisma","schema.prisma")).map(h=>`${o.name}: ${h}`)),r.push(...Xi(o.path).map(h=>`${o.name}: ${h}`)),(o.config?.appType??o.type)==="migrator")o.config?.dependsOn?.some(k=>k==="postgres"||k==="database-management")||r.push(`${o.name}: migrator must depend on postgres or database-management`);else{o.config?.dependsOn?.some(p=>s.some(y=>y.name===p))||r.push(`${o.name}: API must depend on its Prisma migrator`);let k=Dt(o.path).scripts;Object.entries(k??{}).some(([p,y])=>Kr.has(p)&&typeof y=="string"&&/prisma\s+migrate/.test(y))&&r.push(`${o.name}: API start script must not run prisma migrate`);let g=_(o.path,o.config?.dockerfile??"Dockerfile");Ae(g,!0)&&r.push(`${o.name}: API image/startup must not run Prisma migrations`)}}return n.length>0&&!At(e).willStart&&r.push("shared platform Postgres will not start for the Prisma resources"),r.length===0?{name:"Prisma 7 consistency",didPass:!0,message:"Prisma resources use the validated Prisma 7 shape"}:{name:"Prisma 7 consistency",didPass:!1,message:`${S(r.length,"Prisma consistency error")}:
|
|
259
|
+
${r.join(`
|
|
260
|
+
`)}`,fix:"Use Prisma 7 packages and config, put migrations in a migrator, and make the API depend on that migrator"}}function Fr(e){let t=new Map;for(let n of e){let r=n.config?.port;P(n.config?.appType)&&typeof r=="number"&&t.set(n.name,r)}return t}function Zi(e){let t=e.config?.language;return typeof t=="string"&&Object.hasOwn(Y,t)&&Y[t].createFiles!==void 0}function Qi(e){return(e.config?.appType??e.type)==="bring-your-own"}function Mr(e=m()??process.cwd()){let t=b(e).filter(n=>!Qi(n)&&!Zi(n)&&!Ct(_(n.path,"package.json"))).map(n=>n.name);return t.length===0?{name:"Resource package.json",didPass:!0,message:"Every resource has a package.json"}:{name:"Resource package.json",didPass:!1,message:`${S(t.length,"resource")} without a package.json: ${t.join(", ")}. The image build stops at "COPY .../package.json: not found"`,fix:"Add a package.json next to each service.json (copy one from a working resource), or delete the folder's service.json if it is not a service"}}function Ce(e=m()??process.cwd()){let t=new Map;for(let s of b(e)){let o=t.get(s.name)??[];o.push(he(e,s.configPath)||s.configPath),t.set(s.name,o)}let n=[...t].filter(([,s])=>s.length>1);if(n.length===0)return{name:"Duplicate resource names",didPass:!0,message:"Every resource has a unique appName"};let r=n.map(([s,o])=>`"${s}" in ${o.join(" and ")}`);return{name:"Duplicate resource names",didPass:!1,message:`${S(n.length,"appName")} used by more than one resource:
|
|
261
|
+
${r.join(`
|
|
262
|
+
`)}`,fix:'Give each resource its own "appName" in its service.json. The name becomes the Compose service and the Traefik router, so two resources with one name collide'}}function ea(e){let t=e.config?.appType;return P(t)?!0:t==="bring-your-own"&&e.config?.exposeViaProxy!==!1}function Lr(e=m()??process.cwd()){let t=new Map;for(let s of b(e)){let o=s.config?.port;if(typeof o!="number"||!ea(s))continue;let i=t.get(o)??[];i.push(s.name),t.set(o,i)}let n=[...t].filter(([,s])=>s.length>1);if(n.length===0)return{name:"Duplicate resource ports",didPass:!0,message:"No two routed resources use the same port"};let r=n.map(([s,o])=>`port ${s}: ${o.join(", ")}`);return{name:"Duplicate resource ports",didPass:!1,isWarning:!0,message:`${S(n.length,"port")} used by more than one routed resource:
|
|
263
|
+
${r.join(`
|
|
264
|
+
`)}`,fix:'Usually a copied service.json. Each container can listen on the same port, but pick distinct "port" values (tdk resource assigns free ones) so URLs like http://<resource>:<port> and localhost checks stay unambiguous'}}var ta=/https?:\/\/([a-z][a-z0-9-]*):(\d+)/g;function Br(e=m()??process.cwd()){let t=b(e),n=Fr(t),r=new Map([...n].map(([o,i])=>[i,o])),s=[];for(let o of t)for(let[i,a]of Object.entries(zi(o.configPath)))for(let[,c,u]of String(a).matchAll(ta)){let d=Number(u),l=n.get(c);l!==void 0&&l!==d?s.push(`${o.name} param ${i}: ${c}:${d}, but ${c} listens on ${l}`):(c==="localhost"||c==="127.0.0.1")&&r.has(d)&&r.get(d)!==o.name&&s.push(`${o.name} param ${i}: localhost:${d} is ${o.name} itself inside its container; ${r.get(d)} is reached as ${r.get(d)}:${d}`)}return s.length===0?{name:"Service URL ports",didPass:!0,message:"Service URLs in params point at the ports the services listen on"}:{name:"Service URL ports",didPass:!1,message:`${S(s.length,"service URL")} in params that cannot connect:
|
|
265
|
+
${s.join(`
|
|
266
|
+
`)}`,fix:'TDK runs each backend on the "port" in its service.json, and containers reach each other by resource name (http://<resource>:<port>). Use that port in the URL'}}function Nt(e){let t=[],n;try{n=Nr(e,{withFileTypes:!0})}catch{return t}for(let r of n){let s=_(e,r.name);r.isDirectory()?Ji.has(r.name)||t.push(...Nt(s)):Ki.test(r.name)&&!Gi.test(s)&&t.push(s)}return t}var na=/(?:localhost|127\.0\.0\.1):(\d{2,5})\b/g,Ur=/^\s*(?:\/\/|\/\*|\*|<!--|#)/;function Hr(e=m()??process.cwd()){let t=new Map;for(let r of b(e)){let s=r.config;if(!(P(s?.appType)||s?.appType==="bring-your-own"&&s.exposeViaProxy!==!1))continue;let i=Wi(r.path),a=s?.stack??Vi(i),c=`${i}\0${a}`,u=t.get(c)??{stack:a,resources:[]};u.resources.push(r),t.set(c,u)}let n=[];for(let{stack:r,resources:s}of t.values()){if(s.length<2)continue;let o=a=>!!(a.config?.traefik?.host||a.config?.traefik?.pathPrefix),i=s.filter(a=>!o(a)).map(a=>a.name);i.length>0&&n.push(`stack "${r}": ${i.sort().join(", ")} lose the shared /api/${r}-management route because ${s.length} backends share the stack; they are routed at /api/<name> only`);for(let a of["host","pathPrefix"]){let c=new Map;for(let u of s){let d=u.config?.traefik?.[a];d&&c.set(d,[...c.get(d)??[],u.name])}for(let[u,d]of c)d.length>1&&n.push(`stack "${r}": ${d.sort().join(" and ")} both set traefik.${a} "${u}", so Traefik cannot tell them apart`)}}return n.length===0?{name:"Stack API routes",didPass:!0,message:"No two backends in one service directory compete for one stack route"}:{name:"Stack API routes",didPass:!1,isWarning:!0,message:n.join(`
|
|
267
|
+
`),fix:'Call each backend at /api/<name>, move one backend to its own stack, or give each its own "traefik.pathPrefix" in service.json'}}function Vr(e=m()??process.cwd()){let t=b(e),n=new Map([...Fr(t)].map(([o,i])=>[i,o])),r=[];for(let o of t.filter(i=>i.config?.appType==="frontend"))for(let i of Nt(_(o.path,"src")))ge(i,"utf-8").split(`
|
|
268
|
+
`).forEach((a,c)=>{if(!Ur.test(a))for(let[,u]of a.matchAll(na)){let d=n.get(Number(u));d&&r.push(`${he(e,i)}:${c+1} calls localhost:${u} (${d})`)}});if(r.length===0)return{name:"Frontend backend URLs",didPass:!0,message:"No frontend calls a backend through a localhost port"};let s=jr(e)??"<project>";return{name:"Frontend backend URLs",didPass:!1,message:`${S(r.length,"frontend call")} to a backend port that TDK does not publish on localhost:
|
|
269
|
+
${r.join(`
|
|
270
|
+
`)}`,fix:`Backends are only reachable through Traefik: http://api.${s}.localhost/api/<name without -api>/... (for example catalog-api is /api/catalog). Use that URL, or the generated .autogenerated/env.ts`}}var Wr=/\b(?:prisma\s+(?:migrate\s+(?:deploy|dev|resolve)|db\s+push)|drizzle-kit\s+(?:migrate|push)|knex\s+migrate:\w+|typeorm\s+migration:run|mikro-orm\s+migration:up|sequelize(?:-cli)?\s+db:migrate|dbmate\s+(?:up|migrate)|atlas\s+migrate\s+apply|alembic\s+upgrade)\b/,Kr=new Set(["start","dev","serve","prestart","predev","preserve"]),ra=/\.(?:sh|bash)$/,sa=/^\s*(?:CMD|ENTRYPOINT)\b/i;function Ne(e){try{return ge(e,"utf-8")}catch{return}}function oa(e){let t=Ne(_(e,"package.json"));if(t===void 0)return[];let n={};try{n=JSON.parse(t)?.scripts??{}}catch{return[]}return Object.entries(n).filter(([r,s])=>Kr.has(r)&&typeof s=="string"&&Wr.test(s)).map(([r])=>`package.json "${r}" script`)}function Ae(e,t){let n=Ne(e);return n===void 0?!1:n.split(`
|
|
271
|
+
`).some(r=>Wr.test(r.replace(/["'`,[\]]+/g," "))&&!Ur.test(r)&&(!t||sa.test(r)))}function Gr(e=m()??process.cwd()){let t=[];for(let n of b(e)){let r=n.config?.appType??n.type;if(r!=="backend"&&r!=="worker")continue;let s=n.path;for(let a of oa(s))t.push(`${n.name}: ${a}`);let o=_(s,n.config?.dockerfile??"Dockerfile");Ae(o,!0)&&t.push(`${n.name}: ${he(e,o)} CMD or ENTRYPOINT`);let i=[];try{i=Nr(s,{withFileTypes:!0})}catch{}for(let a of i){let c=_(s,a.name);a.isFile()&&ra.test(a.name)&&Ae(c,!1)&&t.push(`${n.name}: ${he(e,c)}`)}for(let a of Nt(_(s,"src")))Ae(a,!1)&&t.push(`${n.name}: ${he(e,a)}`)}return t.length===0?{name:"Migrations outside the API",didPass:!0,message:"No backend or worker runs a migration command from its own start-up"}:{name:"Migrations outside the API",didPass:!1,isWarning:!0,message:`${S(t.length,"migration command")} run from a backend or worker's own start-up:
|
|
272
|
+
${t.join(`
|
|
273
|
+
`)}`,fix:"Move the migration into a `migrator` resource (appType migrator) that the service depends on, so it runs once before the service starts instead of on every start and restart"}}function je(e=m()??process.cwd()){let t=b(e).filter(r=>r.config?.featuresEnabled?.includes("nats")).map(r=>r.name);if(t.length===0)return{name:"NATS broker",didPass:!0,message:"No resource enables the nats feature",isSkipped:!0};if(Ct(_(e,"services","platform","messaging","docker-compose.yml")))return{name:"NATS broker",didPass:!0,message:`${S(t.length,"resource")} enable nats and services/platform/messaging/docker-compose.yml is present`};let n=(jr(e)??"project").replace(/-/g,"_");return{name:"NATS broker",didPass:!1,message:`${t.join(", ")} enable the nats feature, but no NATS server will start: TDK only starts one when services/platform/messaging/docker-compose.yml exists, and it does not generate that file`,fix:`Create it with a "nats" service (image nats with -js, container_name ${n}_nats, network ${n}_backend, external) and a "redis" service, which TDK registers alongside it`}}function qr(e=m()??process.cwd()){let t=At(e),n=" (project resource set; tdk up may select a subset and not start Postgres)",r=t.focusWouldEnableDatabaseManagement?" Warning: generated Tiltfile default focus expands CORE_INFRA to database-management while project.json has it off; default tdk up takes the feature path.":"";if(t.unknownDependsOnNames.length>0){let o=t.unknownDependsOnNames.map(({resource:a,name:c})=>`"${c}" (from ${a})`).join(", "),i=t.willStart?` Postgres will start because ${t.reason==="feature"?"database-management is enabled":`resource(s) ${t.dependsOnUsers.join(", ")} depend on postgres/database-management`}${n}`:" Postgres will not start for this project.json/generated Tiltfile state.";return{name:"Shared platform Postgres",didPass:!1,message:`${S(t.unknownDependsOnNames.length,"unknown dependsOn name")}: ${o}. These are not known services or stacks, and are not the shared platform database names (postgres, database-management).${i}${r}`,fix:'Use "postgres" or "database-management" in dependsOn for the shared platform database, or fix the name to match an existing service'}}if(!t.willStart)return{name:"Shared platform Postgres",didPass:!0,isWarning:!!r,isSkipped:!r,message:r?r.trim():"Shared platform Postgres will not start: database-management is off and no resource depends on postgres or database-management."};if(t.reason==="feature"&&t.dependsOnUsers.length===0){let o=t.featureOnFromTiltfile||t.featureOnFromSpecMaster?" (generated Tiltfile/spec.master)":"";return{name:"Shared platform Postgres",didPass:!0,isWarning:!!r,message:`Shared platform Postgres will start because the database-management feature is enabled${o} (project-wide; not a tdk up selection).${r}`}}let s=t.reason==="feature"?`the database-management feature is enabled and resource(s) ${t.dependsOnUsers.join(", ")} depend on postgres/database-management`:`resource(s) ${t.dependsOnUsers.join(", ")} depend on postgres/database-management`;return{name:"Shared platform Postgres",didPass:!0,isWarning:!!r,message:`Shared platform Postgres will start because ${s}${n}${r}`}}function ia(e){let t=[];for(let n of e.split(`
|
|
274
|
+
`)){let r=n.match(/^\s*(\d+)\s+.*\btilt up\b.*?\s-f\s+(\S+)/i);r&&t.push({pid:Number(r[1]),root:r[2].split(/[\\/]\.tdk[\\/]/i)[0]})}return t}function Jr(e=m()??process.cwd(),t=Hi){let n;try{n=process.platform==="win32"?Ui("powershell.exe",["-NoProfile","-Command","Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'tilt.exe' } | ForEach-Object { '{0} {1}' -f $_.ProcessId, $_.CommandLine }"],{encoding:"utf-8",timeout:De,windowsHide:!0}):t("ps -Ao pid=,command=",{encoding:"utf-8",timeout:De})}catch{return{name:"Tilt processes",didPass:!0,isSkipped:!0,message:"Could not list processes"}}let r=ia(n),s=r.filter(i=>i.root===e),o=r.filter(i=>i.root!==e);return s.length>1?{name:"Tilt processes",didPass:!1,message:`${s.length} Tilt processes are running for this project (pids ${s.map(i=>i.pid).join(", ")}). They fight over ports and containers`,fix:`Stop them all, then start one: tdk down && kill ${s.map(i=>i.pid).join(" ")} && tdk up`}:o.length>0?{name:"Tilt processes",didPass:!0,isSkipped:!0,message:`Another project's Tilt is running: ${o.map(a=>`${a.root} (pid ${a.pid})`).join(", ")}`,fix:"tdk up will use the next free Tilt UI port (10351, ...). If it is a leftover, run tdk down in that project"}:{name:"Tilt processes",didPass:!0,message:"No stray Tilt processes"}}async function zr(e=N){let t=`tdk_doctor_probe_${process.pid}`;try{await e(`docker network create ${t}`,De)}catch(n){let r=String(n.stderr??n);return/address pools/i.test(r)?{name:"Docker networks",didPass:!1,message:"Docker cannot create another network: all predefined address pools are in use. Each TDK project needs several",fix:"run tdk down --prune-networks in projects you are not using, or docker network prune (removes all unused networks)"}:{name:"Docker networks",didPass:!0,isSkipped:!0,message:"Could not test network creation"}}try{await e(`docker network rm ${t}`,De)}catch{}return{name:"Docker networks",didPass:!0,message:"Docker can create networks"}}import{randomBytes as Xr}from"node:crypto";import{existsSync as It,readFileSync as Zr,writeFileSync as Qr}from"node:fs";import{join as Ft}from"node:path";import{randomBytes as aa}from"node:crypto";import{closeSync as ca,fchmodSync as ua,fsyncSync as da,openSync as la,renameSync as pa,rmSync as fa,statSync as ma,writeFileSync as ha}from"node:fs";import{basename as ga,dirname as ka,join as ya}from"node:path";function Yr(e,t){let n=ya(ka(e),`.${ga(e)}.${process.pid}.${aa(4).toString("hex")}.tmp`),r;try{r=ma(e).mode&511}catch{r=void 0}try{let s=la(n,"wx");try{r!==void 0&&ua(s,r),ha(s,t,"utf-8"),da(s)}finally{ca(s)}pa(n,e)}catch(s){throw fa(n,{force:!0}),s}}var Z=[{name:"VERDACCIO_URL_DOCKER",description:"Docker-internal URL of the private npm registry (Verdaccio, a paid feature)",required:!1,default:"http://verdaccio:4873",example:"http://verdaccio:4873"},{name:"VERDACCIO_URL",description:"Local URL of the private npm registry (Verdaccio, a paid feature)",required:!1,default:"http://localhost:4873"},{name:"TILT_ENV",description:"Tilt environment name",required:!0,default:"dev",example:"dev",complete:!0},{name:"DATABASE_URL",description:"PostgreSQL connection string (uses the generated DB_PASSWORD below)",required:!1},{name:"DB_PASSWORD",description:"PostgreSQL superuser password (docker-compose POSTGRES_PASSWORD)",required:!0,example:"postgres",complete:!0},{name:"JWT_SECRET",description:"Secret that signs local-jwt tokens (generated once per project; never shared between projects)",required:!1,complete:!0}],es=()=>Xr(16).toString("hex"),Sa=()=>Xr(32).toString("hex");function jt(e,t){return e==="DB_PASSWORD"?t:e==="JWT_SECRET"?Sa():e==="DATABASE_URL"?`postgresql://postgres:${t}@postgres:5432/app_dev`:Z.find(n=>n.name===e)?.default??""}function ba(e){let t=e.trim(),n=t[0];if(n==='"'||n==="'"){let s=!1;for(let o=1;o<t.length;o+=1){let i=t[o];if(s){s=!1;continue}if(i==="\\"){s=!0;continue}if(i===n){let a=t.slice(1,o);if(n==='"'){let c={n:`
|
|
275
|
+
`,r:"\r",t:" ",'"':'"',"\\":"\\",$:"$"};return a.replace(/\\([nrt"\\$])/g,(u,d)=>c[d]??d)}return a.replace(/\\'/g,"'")}}return t}let r=e.search(/\s#/);return(r===-1?e:e.slice(0,r)).trim()}function Q(e){let t=new Map,n=e.startsWith("\uFEFF")?e.slice(1):e;for(let r of n.split(/\r?\n/)){let s=r.trim();if(!s||s.startsWith("#"))continue;let o=s.startsWith("export ")?s.slice(7).trim():s,i=o.indexOf("=");if(i<=0)continue;let a=o.slice(0,i).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(a)&&t.set(a,ba(o.slice(i+1)))}return t}function ts(e){let t=[`# ${e.description}`];return e.required&&t.push("# Required (the value below is a working default)"),e.example&&t.push(`# Example: ${e.example}`),t}function ns(){let e=es(),t=["# \u{1F527} TDK Environment Configuration","# Generated by `tdk project`. The defaults work as-is; edit only to change them.","# Keep this file out of git: it holds a generated database password and JWT secret.","#","# After editing, run: tdk config regenerate && tdk up",""];for(let n of Z)t.push(...ts(n)),t.push(`${n.name}=${jt(n.name,e)}`),t.push("");return t.join(`
|
|
276
|
+
`)}function xa(e){let t=e.match(/^[a-z][a-z0-9+.-]*:\/\/[^:/@\s]+:([^@\s]*)@/i);if(!(!t||t[1].includes("$")))return t[1]}function rs(e){let t=Ft(e,".env"),n={missing:[],invalid:[],warnings:[]};if(!It(t))return{missing:Z.filter(i=>i.required).map(i=>i.name),invalid:[],warnings:[".env file not found - will be auto-generated"]};let r=Q(Zr(t,"utf-8"));for(let i of Z)i.required&&!r.has(i.name)&&n.missing.push(i.name),r.has(i.name)&&!(r.get(i.name)??"").trim()&&n.invalid.push(`${i.name} is set but empty`);let s=r.get("DATABASE_URL"),o=r.get("DB_PASSWORD");if(s&&o){let i=xa(s);i!==void 0&&i!==o&&n.warnings.push("DATABASE_URL carries a different password than DB_PASSWORD; the database container uses DB_PASSWORD")}return n}function Ta(e,t,n){if(!Q(e).has(t))return e;let s=e.indexOf("=");if(s<0)return e;let o=e.slice(s+1),i=o.search(/\s#/),a=i<0?"":o.slice(i);return e.slice(0,s+1)+n+a}function ip(e){let t=Ft(e,".env");if(!It(t))return Qr(t,ns(),{mode:384}),Z.map(l=>l.name);let n=Zr(t,"utf-8"),r=Q(n),s=Z.filter(l=>l.complete?r.has(l.name)?!(r.get(l.name)??"").trim():!0:!1);if(s.length===0)return[];let o=s.filter(l=>!r.has(l.name)),i=s.filter(l=>r.has(l.name)),a=r.get("DB_PASSWORD"),c=a?.trim()?a:es(),u=n.split(/(\r\n|\n|\r)/);for(let l of i){let h=-1;for(let k=0;k<u.length;k+=2)Q(u[k]).has(l.name)&&(h=k);if(h<0)throw new Error(`Could not locate empty .env assignment for ${l.name}`);u[h]=Ta(u[h],l.name,jt(l.name,c))}let d=u.join("");if(o.length>0){let l=["","# Added by TDK: keys this version expects. Existing values above were not changed.",""];for(let k of o)l.push(...ts(k)),l.push(`${k.name}=${jt(k.name,c)}`),l.push("");let h=d.endsWith(`
|
|
277
|
+
`)||d.endsWith("\r")?"":`
|
|
278
|
+
`;d+=h+l.join(`
|
|
279
|
+
`)}return Yr(t,d),s.map(l=>l.name)}function ap(e){let t=Ft(e,".env");return It(t)?!1:(Qr(t,ns(),{mode:384}),!0)}import{execFileSync as Ra}from"node:child_process";import{existsSync as _a,mkdirSync as Oa,readFileSync as os,writeFileSync as Aa}from"node:fs";import{join as ye}from"node:path";import{createServer as va}from"node:net";import{connect as wa}from"node:net";function ss(e,t=500){return new Promise(n=>{let r=wa({port:e,host:"127.0.0.1"}),s=o=>{r.destroy(),n(o)};r.setTimeout(t,()=>s(!1)),r.once("connect",()=>s(!0)),r.once("error",()=>s(!1))})}var Pa={ingressHttp:{start:8080,end:8180},ingressHttps:{start:8443,end:8543},postgres:{start:15432,end:15532}},Ie={ingressHttp:"TDK_HTTP_PORT",ingressHttps:"TDK_HTTPS_PORT",postgres:"TDK_POSTGRES_PORT"},$a={ingressHttp:80,ingressHttps:443,postgres:5432};async function Mt(e){return await ss(e)?!1:new Promise(t=>{let n=va();n.once("error",()=>t(!1)),n.listen(e,"127.0.0.1",()=>n.close(()=>t(!0)))})}function Ea(e,t){let n=Number(t);if(!Number.isInteger(n)||n<1||n>65535)throw new Error(`${e} must be an integer between 1 and 65535 (received ${JSON.stringify(t)})`);return n}async function ke(e={}){let t=e.env??process.env,n=e.isAvailable??Mt,r={ingressHttp:!1,ingressHttps:!1,postgres:!1},s={ingressHttp:"",ingressHttps:"",postgres:""},o={explicit:r},i=new Set;for(let a of["ingressHttp","ingressHttps","postgres"]){let c=t[Ie[a]],u=c!==void 0&&c.trim()!=="",d=e.ranges?.[a]??Pa[a],l=u?[Ea(Ie[a],c)]:Array.from({length:d.end-d.start+1},(k,g)=>d.start+g),h;for(let k of l)if(!i.has(k)){if(await n(k)){h=k;break}if(u)throw new Error(`${Ie[a]}=${k} is already in use. Choose a free host port and retry.`)}if(h===void 0)throw new Error(`No available host port in ${d.start}-${d.end} for ${a}. Set ${Ie[a]} to a free port and retry.`);i.add(h),o[a]=h,r[a]=u,s[a]=u?"explicit override":`selected from fallback range ${d.start}-${d.end}`}return{...o,requested:{...$a},reason:s}}function fp(e){return`Host ports: HTTP ${e.ingressHttp}, HTTPS ${e.ingressHttps}, Postgres ${e.postgres}`}var is=ye(".tdk",".tdk-out","host-ports.json");function Da(e,t,n){return e.split(`
|
|
280
|
+
`).some(r=>{let[s="",o=""]=r.split("|"),i=s.toLowerCase(),a=t.toLowerCase();return(i.startsWith(`${a}_`)||i.startsWith(`${a}-`))&&new RegExp(`:${n}->`).test(o)})}function Ca(e){let t=ye(e,is);if(!_a(t))return null;try{let n=JSON.parse(os(t,"utf-8"));if(!n||typeof n!="object")return null;let r=n;return!Number.isInteger(r.ingressHttp)||!Number.isInteger(r.ingressHttps)||!Number.isInteger(r.postgres)||!r.requested||!r.explicit||!r.reason?null:r}catch{return null}}function Sp(e,t){let n=ye(e,is);Oa(ye(e,".tdk",".tdk-out"),{recursive:!0}),Aa(n,`${JSON.stringify(t,null,2)}
|
|
281
|
+
`,{encoding:"utf-8",mode:384})}function bp(e){process.env.TDK_HTTP_PORT=String(e.ingressHttp),process.env.TDK_HTTPS_PORT=String(e.ingressHttps),process.env.TDK_POSTGRES_PORT=String(e.postgres)}async function Fe(e,t={}){let n=Ca(e),r=["TDK_HTTP_PORT","TDK_HTTPS_PORT","TDK_POSTGRES_PORT"].some(c=>process.env[c]);if(t.inspectDocker===!1&&n&&!r)return n;let s="";try{let c=JSON.parse(os(ye(e,".tdk","project.json"),"utf-8"));s=String(c?.project?.name??"tdk-project").replace(/-/g,"_").toLowerCase()}catch{s="tdk_project"}let o="";if(t.inspectDocker!==!1)try{o=Ra("docker",["ps","--format","{{.Names}}|{{.Ports}}"],{encoding:"utf-8",timeout:5e3})}catch{}let i=c=>Da(o,s,c),a=async c=>await Mt(c)||i(c);if(n&&!r){for(let c of[n.ingressHttp,n.ingressHttps,n.postgres])if(!await a(c))return ke({isAvailable:a});return n}return ke({isAvailable:a})}import{existsSync as Na,readFileSync as ja}from"node:fs";import{join as Ia}from"node:path";var Fa="[REDACTED]",Se=class extends Error{path;constructor(t,n){super(`Could not read ${t}: ${n}`),this.path=t,this.name="EnvUnreadableError"}},Ma=8;function as(e){let t=Ia(e,".env");if(!Na(t))return[];let n;try{n=ja(t,"utf-8")}catch(s){throw new Se(t,s instanceof Error?s.message:String(s))}let r=[...Q(n).values()].filter(s=>s.length>=Ma);return[...new Set(r)].sort((s,o)=>o.length-s.length)}function Lt(e,t){let n=e;for(let r of t)n=n.split(r).join(Fa);return n}function Me(e,t){return t.length===0?e:typeof e=="string"?Lt(e,t):Array.isArray(e)?e.map(n=>Me(n,t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Me(r,t)])):e}import{relative as La}from"node:path";function Le(e,t){return La(e,t.configPath)||t.configPath}function cs(e){let t=e.config?.dependsOn;return t===void 0?[]:Array.isArray(t)&&t.every(n=>typeof n=="string")?t:null}function Ba(e){let t=new Set(e.map(a=>a.name)),n=new Map(e.map(a=>[a.name,(cs(a)??[]).filter(c=>t.has(c))])),r=new Map,s=new Map,o=[],i=a=>{s.set(a,"visiting"),o.push(a);for(let c of n.get(a)??[])if(s.get(c)==="visiting"){let u=o.slice(o.indexOf(c)),d=u.indexOf([...u].sort()[0]??c),l=[...u.slice(d),...u.slice(0,d)];r.set(l.join(">"),[...l,l[0]??c])}else s.has(c)||i(c);o.pop(),s.set(a,"done")};for(let a of[...n.keys()].sort())s.has(a)||i(a);return[...r.values()]}function Bt(e=m()??process.cwd()){let t=b(e).flatMap(n=>cs(n)===null?[`${Le(e,n)} dependsOn ${JSON.stringify(n.config?.dependsOn)}: expected an array of service names`]:[]);return t.length===0?{name:"dependsOn",didPass:!0,message:"Every dependsOn is a list of service names"}:{name:"dependsOn",didPass:!1,message:`${S(t.length,"invalid dependsOn","invalid dependsOn")}:
|
|
282
|
+
${t.join(`
|
|
283
|
+
`)}`,fix:'Write "dependsOn" as an array of service names, for example ["postgres", "api"]'}}function Ut(e=m()??process.cwd()){let t=b(e),n=new Map(t.map(o=>[o.name,o])),r=Ba(t);if(r.length===0)return{name:"Circular dependencies",didPass:!0,message:"No service depends on itself through dependsOn"};let s=r.map(o=>{let i=n.get(o[0]??""),a=o[1]??"";return`${i?Le(e,i):o[0]} dependsOn "${a}": circular dependency ${o.join(" -> ")}`});return{name:"Circular dependencies",didPass:!1,message:`${r.length} ${r.length===1?"circular dependency":"circular dependencies"}:
|
|
284
|
+
${s.join(`
|
|
285
|
+
`)}`,fix:'Remove one "dependsOn" entry in each cycle so the services no longer wait on each other, or move what they share into a third service'}}function Ht(e=m()??process.cwd()){let t=b(e).flatMap(n=>{let r=n.config?.port;return r===void 0?[]:typeof r=="number"&&Number.isInteger(r)&&r>=1&&r<=65535?[]:[`${Le(e,n)} port ${JSON.stringify(r)}: not an integer from 1 to 65535`]});return t.length===0?{name:"Service ports",didPass:!0,message:"Every declared port is valid"}:{name:"Service ports",didPass:!1,message:`${S(t.length,"invalid port")}:
|
|
286
|
+
${t.join(`
|
|
287
|
+
`)}`,fix:'Set "port" to the port the service listens on, an integer from 1 to 65535'}}function Vt(e=m()??process.cwd(),t=!1){let n=[],r=[];for(let o of b(e)){let i=o.config?.schemaVersion;if(i===ue)continue;let a=Le(e,o);i===void 0?n.push(`${a} schemaVersion: missing`):r.push(`${a} schemaVersion ${JSON.stringify(i)}: this tdk supports ${ue}`)}if(n.length===0&&r.length===0)return{name:"schemaVersion",didPass:!0,message:"Every service.json has a supported schemaVersion"};let s=[...n.length>0?["Run `tdk config migrate` to add the missing schemaVersion"]:[],...r.length>0?["A version this tdk does not support cannot be migrated: upgrade tdk"]:[]];return{name:"schemaVersion",didPass:!1,isWarning:!t,message:`${S(n.length+r.length,"service.json file")} without a supported schemaVersion:
|
|
288
|
+
${[...n,...r].join(`
|
|
289
|
+
`)}`,fix:s.join(". ")}}function Cp(e){let t=Vt(e);t.didPass||(console.warn(f.yellow(`\u26A0 ${t.message}`)),t.fix&&console.warn(f.gray(` ${t.fix}`)))}function Np(e,t={},n=process.exit){let r=[Ce(e),Bt(e),Ut(e),Ht(e)].filter(o=>!o.didPass);if(r.length===0)return;let s=r.map(o=>`${o.message}${o.fix?`
|
|
290
|
+
Fix: ${o.fix}`:""}`).join(`
|
|
291
|
+
`);t.onInvalid?.(s);for(let o of r)console.error(f.red(`\u2717 ${o.message}`)),o.fix&&console.error(f.gray(` Fix: ${o.fix}`));n(1)}import{readFileSync as Ua}from"node:fs";import{join as Ha}from"node:path";function us(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function Va(e){try{return JSON.parse(Ua(Ha(e,".tdk","project.json"),"utf-8"))?.minTdkVersion}catch{return}}function ds(e,t){let n=Va(e);if(n===void 0)return{status:"none"};let r=typeof n=="string"?us(n):null;if(!r||!/^\d+\.\d+\.\d+$/.test(String(n).trim()))return{status:"malformed",message:`.tdk/project.json minTdkVersion ${JSON.stringify(n)} is not a version like "1.3.80"`,fix:'Set minTdkVersion to a MAJOR.MINOR.PATCH string, for example "1.3.80".'};let s=us(t),o=s!==null&&(()=>{for(let[a,c]of r.entries()){let u=s[a]??0;if(u!==c)return u>c}return!0})(),i=r.join(".");return o?{status:"ok",required:i}:{status:"too-old",required:i,message:`tdk ${t} is older than the ${i} this project requires (minTdkVersion)`,fix:"Run: tdk upgrade"}}var F=1e4,K={dockerMissing:"See https://docs.docker.com/get-docker/",dockerDaemonDown:"Start Docker Desktop, OrbStack, or Colima, then retry: tdk doctor",tiltMissing:"curl -fsSL https://raw.githubusercontent.com/tilt-dev/tilt/master/scripts/install.sh | bash",bunMissing:"curl -fsSL https://bun.sh/install | bash",port80:"Stop the process bound to port 80, or stop local nginx/caddy. Then: tdk doctor",port5432:"Stop local Postgres or change the host port. Then: tdk doctor",notProject:"tdk project --yes"},ps="WSL2 detected. Use Docker Desktop WSL integration. Guide: docs/wsl2.md",fs="Native Windows landscape boot is unsupported. Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md",Wt=[0,25,0],G=[1,2,0];function Be(e,t){let n=qt(e);return n?Jt(n,t):!1}function qa(e,t,n=process.platform==="linux"&&!!process.env.WSL_DISTRO_NAME){if(!n)return{name:"WSL project location",didPass:!0,isSkipped:!0,message:"Not running in WSL2 - skipped project filesystem check"};let r=e.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase();if(r!=="/mnt/c"&&!r.startsWith("/mnt/c/"))return{name:"WSL project location",didPass:!0,message:`${ps} Project is on the WSL filesystem.`};let s=`${ps} Project is under /mnt/c (${e}); hot reload may be broken. Move it into the WSL filesystem, such as ~/projects.`;return{name:"WSL project location",didPass:!t,isWarning:!t,message:s,fix:"Move the repository under your WSL home directory (for example, ~/projects) and retry tdk doctor."}}function Ja(e){let t=e.replace(/^\[(.*)\]$/,"$1");return t==="0.0.0.0"||/^[0:]*:0\.0\.0\.0$/.test(t)?!0:t.includes(":")&&/^[0:]+$/.test(t)}function za(e=process.env,t=!1){let n=(e.TDK_BIND_ADDRESS??"").trim();return Ja(n)?{name:"Dev Port Bind Address",didPass:!t,isWarning:!t,message:`TDK_BIND_ADDRESS is ${n}: Traefik and Postgres are reachable from other machines on the network.`,fix:"Unset TDK_BIND_ADDRESS to keep dev ports on 127.0.0.1. Keep it only when you test from another device on purpose."}:{name:"Dev Port Bind Address",didPass:!0,message:n?`Dev ports bind to ${n}`:"Dev ports bind to 127.0.0.1 (this machine only)"}}function ms(e){let t=e.filter(r=>!r.didPass&&!r.isSkipped&&!r.isWarning),n=e.filter(r=>r.didPass||r.isSkipped||r.isWarning);return t.sort((r,s)=>{let o=i=>i.name==="Host Ports"&&/\b5432\b/.test(i.message)?0:i.name==="Host Ports"?1:i.name==="Ingress Ports"?2:3;return o(r)-o(s)}),[...t,...n]}function Ya(e,t){return t?e?"Doctor passed. Next: tdk up":"Doctor passed. Next: tdk project example":"Doctor failed. Fix the items above, then run: tdk doctor"}function ks(e){return $r(e)}function Xa(e,t,n,r,s){return async()=>{try{return await N(t,F),{name:e,didPass:!0,message:n}}catch{return{name:e,didPass:!1,message:r,fix:s}}}}async function hs(e){try{return await N(e,F),!0}catch{return!1}}async function Yt(){if(process.platform==="win32")try{return await N("docker ps",F),{name:"Container Runtime",didPass:!0,message:"Docker Desktop Linux container engine is running"}}catch{return{name:"Container Runtime",didPass:!1,message:"Docker is not running",fix:K.dockerDaemonDown}}let e=!!$("docker");try{return await N("docker ps",F),{name:"Container Runtime",didPass:!0,message:"Docker daemon is running"}}catch(t){if(ks(t))return{name:"Container Runtime",didPass:!1,message:"Docker daemon is not responding",fix:K.dockerDaemonDown}}return await hs("colima status")?{name:"Container Runtime",didPass:!0,message:"Colima (Docker runtime) is running"}:$("colima")?{name:"Container Runtime",didPass:!1,message:"Colima is installed but not running",fix:K.dockerDaemonDown}:await hs("podman ps")?{name:"Container Runtime",didPass:!0,message:"Podman is running"}:e?{name:"Container Runtime",didPass:!1,message:"Docker daemon is not running",fix:K.dockerDaemonDown}:{name:"Container Runtime",didPass:!1,message:"Docker is not running",fix:K.dockerMissing}}var Xt=Xa("Docker Compose","docker compose version","Docker Compose plugin available","Docker Compose plugin not found","Install Docker Compose: https://docs.docker.com/compose/install/"),Za=[25,0,0],Qa=[2,20,2];function qt(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function Jt(e,t){for(let[n,r]of t.entries()){let s=e[n]??0;if(s!==r)return s>r}return!0}async function Zt(e=N){let t=async a=>String(await e(a,F)).trim(),n,r;try{[n,r]=await Promise.all([t("docker version --format '{{.Server.Version}}'"),t("docker compose version --short")])}catch{return{name:"Docker Versions",didPass:!0,isSkipped:!0,message:"Could not read Docker Engine/Compose versions - skipped version check"}}let s=qt(n),o=qt(r);if(!s||!o)return{name:"Docker Versions",didPass:!0,isSkipped:!0,message:`Unrecognized Docker version output (engine "${n}", compose "${r}") - skipped version check`};let i=[];return Jt(s,Za)||i.push(`Docker Engine ${n} (need 25.0+)`),Jt(o,Qa)||i.push(`Docker Compose ${r} (need 2.20.2+)`),i.length===0?{name:"Docker Versions",didPass:!0,message:`Docker Engine ${n} and Compose ${r} support generated healthchecks`}:{name:"Docker Versions",didPass:!1,message:`Docker is too old for generated healthchecks (they use start_interval):
|
|
292
|
+
${i.join(`
|
|
293
|
+
`)}`,fix:"Update Docker Desktop, or on Linux update docker-ce and the docker-compose-plugin package"}}async function Qt(e=N){let t;try{t=String(await e("tilt version",F)).trim()}catch{return{name:"Tilt CLI",didPass:!1,message:"Tilt CLI not found",fix:K.tiltMissing}}return Be(t,Wt)?{name:"Tilt CLI",didPass:!0,message:`Tilt ${t} is available`}:{name:"Tilt CLI",didPass:!1,message:`Tilt ${t||"version unknown"} is below the required v${Wt.join(".")} floor`,fix:`Install Tilt v${Wt.join(".")} or newer: https://docs.tilt.dev/install.html`}}async function ec(e=N){let t;try{t=String(await e("docker info --format '{{.OSType}}'",F)).trim().toLowerCase()}catch{return{name:"Docker OS",didPass:!0,isSkipped:!0,message:"Docker OS unavailable - daemon failure reported separately"}}return t!=="linux"?{name:"Docker OS",didPass:!1,message:`Docker is using the ${t||"unknown"} engine; TDK requires Linux containers`,fix:"Switch Docker Desktop to Linux containers, enable WSL2 integration, then retry tdk doctor."}:{name:"Docker OS",didPass:!0,message:"Docker is using Linux containers"}}async function tc(e=N){let t=m();if(!t)return{name:"Bun",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Bun check"};if(!ve(b(t)))return{name:"Bun",didPass:!0,isSkipped:!0,message:"No generated JS services - skipping Bun check"};try{let n=String(await e("bun --version",F)).trim();return Be(n,G)?{name:"Bun",didPass:!0,message:`Bun ${n} is available`}:{name:"Bun",didPass:!1,message:`Bun ${n||"version unknown"} is below the required ${G.join(".")} floor`,fix:`Install Bun ${G.join(".")} or newer: https://bun.sh/install`}}catch{return{name:"Bun",didPass:!1,message:"Bun is not available",fix:K.bunMissing}}}function nc(){let e=m()??process.cwd(),t=rs(e);if(t.missing.length>0)return{name:"Environment Variables",didPass:!1,message:`Missing required env variables: ${t.missing.join(", ")}`,fix:O(w(e,".env"))?`Edit .env and set these values:
|
|
294
|
+
${t.missing.map(r=>`${r}=<value>`).join(`
|
|
295
|
+
`)}`:"No .env file yet. Run `tdk project` to create one with working defaults."};if(t.invalid.length>0)return{name:"Environment Variables",didPass:!1,message:`Invalid env variables: ${t.invalid.join(", ")}`,fix:"Edit .env and provide values for empty variables"};let n=t.warnings.filter(r=>!r.startsWith(".env file not found"));return{name:"Environment Variables",didPass:!0,message:n.length>0?`All required environment variables are set (warning: ${n.join("; ")})`:"All required environment variables are set"}}function rc(){let e=m()??process.cwd(),t=w(e,".tdk",".tdk-out"),n=Ye.filter(r=>!O(w(t,r)));return n.length===0?{name:"Master Configs",didPass:!0,message:`${Ye.join(", ")} found`}:{name:"Master Configs",didPass:!1,message:`Master configs missing: ${n.join(", ")}`,fix:"Run: tdk project"}}function sc(e=On()){let t=m();if(!t)return{name:"TDK version",didPass:!0,isSkipped:!0,message:"Not in a project - skipping TDK version check"};let n=ds(t,e);return n.status==="none"?{name:"TDK version",didPass:!0,isSkipped:!0,message:`tdk ${e} (no minTdkVersion in .tdk/project.json)`}:n.status==="malformed"||n.status==="too-old"?{name:"TDK version",didPass:!1,message:n.message,fix:n.fix}:{name:"TDK version",didPass:!0,message:`tdk ${e} meets minTdkVersion ${n.required}`}}function oc(){let e=m()??process.cwd(),t=et(e),n=b(e).filter(s=>!Pe(e,s.path,t));if(n.length===0)return{name:"Resource Discovery",didPass:!0,message:`All resources are covered by discovery.paths ${JSON.stringify(t)}`};let r=n.map(s=>Kt(Gt(e,s.path))).join(", ");return{name:"Resource Discovery",didPass:!1,message:`${S(n.length,"resource")} outside discovery.paths ${JSON.stringify(t)}: ${r}. \`tdk up\` will not start them`,fix:"Move each under services/<stack>/<name>, or add a matching pattern to discovery.paths in .tdk/project.json and run: tdk config regenerate"}}var ic=["install-deps.sh","bun-hoisted-symlink-fix.sh","prisma-bun-client-link-fix.sh","prisma-normalize-client.sh","infisical-entrypoint.sh"],ac=/shared-platform-engineering\/docker-templates\/([\w.-]+)/g;function cc(e){let t=new Set;for(let n of b(e)){let r=w(n.path,".autogenerated");if(O(r)){for(let s of Ka(r))if(!(!s.startsWith("Dockerfile")||s.endsWith(".dockerignore")))for(let o of ee(w(r,s),"utf-8").matchAll(ac))t.add(o[1])}}return[...t]}function uc(){let e=m()??process.cwd(),t=[];O(w(e,"package.json"))||t.push("package.json (workspace root manifest)");let n=w(e,"shared-platform-engineering","docker-templates"),r=[];try{r=cc(e)}catch{}for(let s of new Set([...ic,...r]))O(w(n,s))||t.push(`shared-platform-engineering/docker-templates/${s}`);return t.length===0?{name:"Generated Runtime Assets",didPass:!0,message:"Generated Docker runtime assets are present"}:{name:"Generated Runtime Assets",didPass:!1,message:`Generated Dockerfiles reference missing project runtime assets:
|
|
296
|
+
${t.join(`
|
|
297
|
+
`)}`,fix:"Run `tdk project --yes` (or `tdk config regenerate`) with an updated TDK. `tdk up` also refreshes these assets before starting Tilt."}}function dc(){let e=m()??process.cwd(),t=b(e),n=[];for(let r of t){let s=w(r.path,"package.json");if(!O(s))continue;let o=r.config?.appType??"backend",i=Xe[o]??Xe.backend,a;try{a=JSON.parse(ee(s,"utf-8")).scripts??{}}catch{n.push(`${r.name} (package.json is invalid JSON)`);continue}let c=i.filter(u=>!a[u]);c.length>0&&n.push(`${r.name}: missing "${c.join('", "')}"`)}return n.length===0?{name:"Startup Scripts",didPass:!0,message:"All services have required package.json scripts"}:{name:"Startup Scripts",didPass:!1,message:`Services missing required package.json scripts:
|
|
298
|
+
${n.join(`
|
|
299
|
+
`)}`,fix:`Add the missing scripts to each service's package.json, e.g.:
|
|
300
|
+
"dev": "bun run src/index.ts",
|
|
301
|
+
"build": "tsc",
|
|
302
|
+
"start": "bun run dist/index.js"`}}function ys(e){if(e.startsWith("@"))return[e.split("/").slice(0,2).join("/")];let t=e.split("/")[0]??e;return[`@types/${t}`,t]}function Ss(e,t,n=0){let r=e[t];if(typeof r!="string"||n>3)return!1;if(/(^|[\s;&|(])tsc(\s|$)/.test(r))return!0;for(let s of r.matchAll(/\b(?:bun|npm|pnpm|yarn)\s+run\s+([\w:.-]+)/g))if(Ss(e,s[1],n+1))return!0;return!1}function gs(e){let t=ys(e);return e.includes("/")||e.startsWith("@")?t[t.length-1]:t[0]}var lc={"@types/bun":"^1.4.2","@types/node":"^20.0.0"};function pc(e,t){return(t.includes("bun")||e.has("@types/bun"))&&!e.has("@types/node")}function fc(){let e=m()??process.cwd(),t=b(e),n=[],r=new Set;for(let o of t){let i=w(o.path,"package.json"),a=w(o.path,".autogenerated","tsconfig.docker.autogenerated.json");if(!O(i)||!O(a))continue;let d=zt(a)?.compilerOptions?.types;if(!Array.isArray(d))continue;let l=zt(i),h=l?.scripts??{};if(!Ss(h,"build"))continue;let k=new Set([...Object.keys(l?.devDependencies??{}),...Object.keys(l?.dependencies??{})]),g=d.filter(p=>typeof p=="string").filter(p=>!ys(p).some(y=>k.has(y)));for(let p of g)r.add(gs(p));if(g.length>0){let p=g.map(y=>`"${y}" (needs ${gs(y)})`).join(", ");n.push(`${o.name}: "types" lists ${p}`)}pc(k,d)&&(r.add("@types/node"),n.push(`${o.name}: uses @types/bun, which references node types internally, but @types/node is not a direct dependency`))}if(n.length===0)return{name:"TypeScript Type Dependencies",didPass:!0,message:`Every service's Docker tsconfig "types" entry has its @types package installed`};let s=[...r].map(o=>{let i=lc[o];return i?`"${o}": "${i}"`:`${o} (bun add -d ${o})`});return{name:"TypeScript Type Dependencies",didPass:!1,message:`\`bun run build\` will fail with TS2688 (Cannot find type definition file) because a @types package it needs is not a direct dependency:
|
|
303
|
+
${n.join(`
|
|
304
|
+
`)}`,fix:`Add to each service's package.json devDependencies: ${s.join(", ")}`}}function zt(e){try{return JSON.parse(ee(e,"utf-8"))}catch{return null}}function mc(e){let n=zt(e)?.compilerOptions;return n?.allowSyntheticDefaultImports===!0||n?.esModuleInterop===!0}function hc(){let e=m()??process.cwd(),t=b(e).filter(r=>r.config?.appType==="frontend");if(t.length===0)return{name:"Frontend Docker Preflight",didPass:!0,isSkipped:!0,message:"No frontend services to check"};let n=[];for(let r of t){O(w(r.path,"public"))||n.push(`${r.name}: no public/ folder, but the Docker build copies it. Create it: mkdir -p ${Kt(Gt(e,w(r.path,"public")))} && touch ${Kt(Gt(e,w(r.path,"public",".gitkeep")))}`);let s=w(r.path,".autogenerated","Dockerfile.app.autogenerated"),o=w(r.path,".autogenerated","tsconfig.docker.autogenerated.json");if(O(s)){let i=ee(s,"utf-8"),a=/\bEXPOSE\s+80\b/.test(i),c=r.config?.stack,u=c?w(e,"services",c,".autogenerated","docker-compose.app.autogenerated.yml"):"";if(a&&u&&O(u)){let d=ee(u,"utf-8"),l=r.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=new RegExp(`traefik\\.http\\.services\\.${l}\\.loadbalancer\\.server\\.port=(\\d+)`),g=d.match(h)?.[1];g&&g!=="80"&&n.push(`${r.name}: nginx runtime exposes 80, but generated Traefik routes to ${g}`)}}if(O(o)&&!mc(o)){let i=w(r.path,"src","main.tsx");if(O(i)){let a=ee(i,"utf-8"),c=[/import\s+\w+\s+from\s+["']react["']/,/import\s+\w+\s+from\s+["']react-dom\/client["']/].filter(u=>u.test(a)).map(u=>u.source.includes("react-dom")?"react-dom/client":"react");c.length>0&&n.push(`${r.name}: Docker tsconfig does not allow synthetic default imports, but src/main.tsx default-imports ${c.join(" and ")}`)}}}return n.length===0?{name:"Frontend Docker Preflight",didPass:!0,message:`${S(t.length,"frontend")} ${t.length===1?"has":"have"} compatible Docker build/routing metadata`}:{name:"Frontend Docker Preflight",didPass:!1,message:`Frontend Docker metadata has issues that will make \`tdk up\` fail or route 404:
|
|
305
|
+
${n.join(`
|
|
306
|
+
`)}`,fix:'Regenerate with a current TDK (`tdk config regenerate`) and ensure frontend nginx runtimes route to port 80. For React entrypoints, prefer named imports: `import { StrictMode } from "react"` and `import { createRoot } from "react-dom/client"`.'}}var gc=90,kc=80;function yc(e){return e.split(`
|
|
307
|
+
`).map(t=>t.trim()).filter(Boolean).map(t=>{let[n,r,s]=t.split(",");return{name:n??"unknown",memPct:Number.parseFloat((r??"").replace("%","")),cpuPct:Number.parseFloat((s??"").replace("%",""))}}).filter(t=>Number.isFinite(t.memPct)&&Number.isFinite(t.cpuPct))}function Sc(){let e;try{e=Wa($("docker")??"docker",["stats","--no-stream","--format","{{.Name}},{{.MemPerc}},{{.CPUPerc}}"],{stdio:"pipe",encoding:"utf-8",timeout:F,windowsHide:process.platform==="win32"})}catch(s){return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:ks(s)?"Docker not responding - skipped container resource check":"Docker not running - skipped container resource check"}}let t=yc(e);if(t.length===0)return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:"No running containers to check"};let n=t.filter(s=>s.memPct>=gc&&s.cpuPct>=kc);if(n.length===0)return{name:"Container Resource Health",didPass:!0,message:`${S(t.length,"container")} within normal resource usage`};let r=n.map(s=>`${s.name} (mem ${s.memPct.toFixed(0)}%, cpu ${s.cpuPct.toFixed(0)}%)`).join(`
|
|
308
|
+
`);return{name:"Container Resource Health",didPass:!1,message:`${S(n.length,"container")} pinned near its memory limit while burning CPU -- likely stuck in a boot-time retry/fetch loop, not a normal crash:
|
|
309
|
+
${r}`,fix:"Check the container's boot logs for a network fetch loop (e.g. `bunx <pkg>` re-downloading a CLI on every start instead of using one already installed): docker logs <container>. If a Prisma auto-migration is the cause, set AUTO_MIGRATE=false in the project's .env as a temporary unblock."}}var bc=5e3;async function xc(e,t){let n=m()??process.cwd(),r=An(b(n),t);return r.length===0?{name:"Service Health",didPass:!0,isSkipped:!0,message:"No routable services to ping"}:$t(await Dn(r,e))}var Tc=new Ga("doctor").description("Check environment readiness for TDK").option("--json","Output a versioned JSON readiness report",!1).exitOverride(e=>{e.exitCode===0&&process.exit(0),Tc.opts().json&&console.log(JSON.stringify(W([],!1,[{code:"USAGE",message:e.message}]))),process.exit(2)}).option("--no-ping","Skip pinging running services' /health endpoints").option("--strict","Fail warnings such as a WSL project under /mnt/c").option("--ping-timeout <ms>","Per-service ping timeout in milliseconds",String(bc)).action(async e=>{let t=Number(e.pingTimeout);if(!/^\d+$/.test(e.pingTimeout)||!Number.isSafeInteger(t)||t<=0){let p="--ping-timeout must be a positive integer number of milliseconds";e.json&&console.log(JSON.stringify(W([],!1,[{code:"USAGE",message:p}]))),console.error(p),process.exit(2);return}e.json||console.log("TDK doctor checks your local Docker + Tilt development environment; it does not check cluster deployments.");let n=hn();if(process.platform==="win32"){if(e.json){let p=null;try{p=await ke()}catch{}console.log(JSON.stringify(W([{name:"Native Windows support",didPass:!1,message:fs,fix:"Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md"}],!!m(),[],p,{...n,canUp:!1})))}console.error(fs),process.exit(1);return}if(n.kind==="webcontainer"){let p=W([{name:"Host",didPass:!1,message:ze,fix:`Use a machine with Docker. Guide: ${we}`}],!!m(),[],void 0,n);e.json&&console.log(JSON.stringify(p)),console.error(ze),process.exit(1);return}e.json||(console.log(`
|
|
310
|
+
${f.bold("\u{1F50D} TDK Doctor")}
|
|
311
|
+
`),console.log(`Checking environment...
|
|
312
|
+
`));let r=m(),s,o;try{s=await Fe(r??process.cwd())}catch(p){s=null,o=p instanceof Error?p.message:String(p)}let i=[()=>s?{name:"Host Ports",didPass:!0,message:`HTTP ${s.ingressHttp}, HTTPS ${s.ingressHttps}, Postgres ${s.postgres}`}:{name:"Host Ports",didPass:!1,message:o??"Could not select host ports",fix:"Set TDK_HTTP_PORT, TDK_HTTPS_PORT, or TDK_POSTGRES_PORT to available host ports."},()=>s?Pt(ls,void 0,[s.ingressHttp,s.ingressHttps]):{name:"Ingress Ports",didPass:!1,message:"Ingress port plan is unavailable"},Yt,ec,Qt,Xt,Zt,tc,()=>qa(m()??process.cwd(),e.strict),()=>za(process.env,e.strict),()=>zr()],a=[()=>sc(),rc,uc,Sr,dc,()=>gr(),fc,hc,oc,()=>Mr(),()=>Ce(),()=>Bt(),()=>Ut(),()=>Ht(),()=>Vt(void 0,e.strict),()=>Lr(),()=>Br(),()=>Vr(),()=>Hr(),()=>je(),()=>Ir(),()=>qr(),()=>Gr(),()=>Jr(),nc,async()=>{let p=m()??process.cwd(),y=wt(p)?await tn(p):!0;return vt(ls,p,void 0,y)},Sc,Et];e.ping&&a.push(()=>xc(t,s?.ingressHttp));let c=!!r,{checks:u,errors:d}=await Pn(i,c?a:[]);if(gn(n.kind))for(let p of u)p.name==="Container Runtime"&&!p.didPass&&(p.fix=mn);let l=W(ms(u),c,d,s,n),h=$n(l),k=l.data.ready;if(e.json){let p;try{p=as(m()??process.cwd())}catch(y){if(!(y instanceof Se))throw y;console.log(JSON.stringify(W([],c,[...d,{code:"ENV_UNREADABLE",message:y.message}]))),console.error(y.message),process.exit(1)}console.log(JSON.stringify(Me(l,p)));for(let y of d)console.error(Lt(y.message,p));h!==0&&process.exit(h);return}for(let p of d)console.error(`${f.red("\u2717")} Doctor check failed: ${p.message}`);for(let p of ms(u))!p.didPass&&!p.isSkipped&&!p.isWarning?(console.log(`${f.red("\u2717")} ${p.message}`),p.fix&&console.log(`${f.blue("\u2139")} Fix: ${p.fix}`)):p.isWarning?(console.log(`${f.yellow("\u26A0")} ${f.yellow(p.message)}`),p.fix&&console.log(`${f.blue("\u2139")} Fix: ${p.fix}`)):p.isSkipped?(console.log(`${f.gray("\u25CB")} ${f.gray(p.message)}`),p.fix&&console.log(`${f.blue("\u2139")} ${p.fix}`)):console.log(`${f.green("\u2713")} ${p.message}`);console.log(""),k&&!c&&(console.log(`${f.gray("\u25CB")} ${f.gray("Not in a TDK project, so project checks were skipped")}`),console.log(""));let g=Ya(c,k);console.log(`${k?f.green(f.bold("\u2713")):f.red(f.bold("\u2717"))} ${g}`),h!==0&&process.exit(h)});function bs(e){return Be(e,G)}var Ue=`${G[0]}.${G[1]}+`;function Pc(e,t){return{id:e,ok:t.didPass||!!t.isSkipped,message:t.message,fix:t.fix}}function Ts(e){let[t=0,n=0]=String(e).split(".").map(r=>Number.parseInt(r,10));return!Number.isFinite(t)||!Number.isFinite(n)||t<22||t===22&&n<12}async function He(e,t,n){try{return Pc(e,await t())}catch{return{id:e,ok:!1,message:n}}}function $c(e){return e.isSkipped?{...e,didPass:!1,isSkipped:!1,message:`Could not verify Docker Engine/Compose minimum versions: ${e.message}`,fix:e.fix??"Start Docker and ensure Docker Engine 25+ and Compose 2.20.2+ are installed."}:e}function Ec(e){try{return b(e).some(t=>t.config?.featuresEnabled?.includes("prisma")??!1)}catch{return!1}}async function Rc(e={}){let t=e.cwd??process.cwd(),n=m(t),r=!!n,s=[],o=process.versions.node;s.push({id:"node",ok:!Ts(o),message:o,fix:Ts(o)?`Install Node.js 22.12+ (current: ${o}). https://nodejs.org`:void 0}),s.push(await He("docker",Yt,"Docker daemon is not running")),s.push(await He("compose",async()=>{let[g,p]=await Promise.all([Xt(),Zt()]);return g.didPass?$c(p):g},"Docker Engine or Compose version check failed")),s.push(await He("tilt",Qt,"Tilt CLI not found"));let i=n?ve(b(n)):!0,a=!1,c=i?$("bun"):void 0;if(c)try{let g=xs(c,["--version"],{encoding:"utf-8",timeout:3e3}).trim();a=bs(g)}catch{}s.push(i?{id:"bun",ok:a,message:a?`Bun ${Ue} is available on PATH`:`Bun ${Ue} not found on PATH`,fix:a?void 0:"curl -fsSL https://bun.sh/install | bash"}:{id:"bun",ok:!0,message:"Bun not needed: no generated JS services"});try{let g=await Fe(n??t);s.push({id:"ports",ok:!0,message:`HTTP ${g.ingressHttp}, HTTPS ${g.ingressHttps}, Postgres ${g.postgres}`})}catch(g){s.push({id:"ports",ok:!1,message:g instanceof Error?g.message:String(g),fix:"Set TDK_HTTP_PORT, TDK_HTTPS_PORT, or TDK_POSTGRES_PORT to available host ports."})}if(n){let g=await He("nats",()=>je(n),"NATS broker check failed");if(g.ok||s.push(g),Ec(n)){let p=!1;try{let y=JSON.parse(wc(vc(n,".tdk","project.json"),"utf-8")),v=String(y?.project?.name??"").replace(/-/g,"_");v&&(p=xs($("docker")??"docker",["ps","--filter",`label=com.docker.compose.project=${v}`,"--filter","label=com.docker.compose.service=postgres","--filter","health=healthy","--format","{{.Names}}"],{encoding:"utf-8",timeout:3e3}).trim().length>0)}catch{}p||s.push({id:"prisma",ok:!1,message:"A Prisma resource is configured, but the project Postgres service is not healthy",fix:"Run `tdk up` to start the bundled Postgres, then check `tdk doctor`."})}}let u=s.filter(g=>!g.ok).slice(0,8),d=u.some(g=>["node","docker","compose","tilt","bun","ports"].includes(g.id)),l=u.some(g=>g.id==="bun"),h=u.length?d?l?`Cold start blocked. Bun ${Ue} must be installed on PATH.
|
|
313
|
+
Prisma/NATS configuration is project-specific and generated after \`tdk project\`. Fix the machine checks below.`:"Cold start blocked. Bun/Prisma/NATS are not the first failure.\nThey are generated after `tdk project`. Fix the machine checks below.":"Machine is ready. Project wiring is not.":"",k=u.length?"":r?"Environment ready for TDK":`This machine is ready for TDK.
|
|
314
|
+
Next: tdk project --yes`;return{ok:u.length===0,inProject:r,items:u,header:h,footer:k}}function _c(e,t={}){let n=[e.header];for(let r of e.items)n.push(`FAIL ${r.id.padEnd(7)} ${r.message}`),r.fix&&n.push(` ${r.fix}`);return e.footer&&(t.includeSuccessFooter??!0)&&n.push(e.footer),n.filter(Boolean).join(`
|
|
315
|
+
`)}async function Ef(){let e=await Rc();e.items.some(n=>["node","docker","compose","tilt","bun","ports"].includes(n.id))&&(console.error(_c(e)),process.exit(1))}export{f as a,Rn as b,Ye as c,zc as d,Yc as e,kn as f,Xc as g,Yr as h,Ot as i,P as j,m as k,On as l,ot as m,ao as n,it as o,yd as p,Sd as q,bd as r,ue as s,vd as t,pt as u,Pd as v,$d as w,Cn as x,Ee as y,Fu as z,Mu as A,$ as B,vo as C,Mn as D,Po as E,Qu as F,ed as G,Bn as H,cd as I,E as J,I as K,ud as L,Eo as M,dd as N,ld as O,pd as P,S as Q,ou as R,iu as S,au as T,cu as U,uu as V,du as W,lu as X,pu as Y,fu as Z,rt as _,mu as $,hu as aa,gu as ba,ku as ca,yu as da,Su as ea,bu as fa,xu as ga,Qn as ha,Go as ia,qo as ja,Od as ka,Ad as la,Dd as ma,Cd as na,Nd as oa,ft as pa,Gd as qa,sr as ra,Qo as sa,b as ta,le as ua,qd as va,Jd as wa,zd as xa,Yd as ya,Xd as za,Zd as Aa,ti as Ba,Qd as Ca,Sl as Da,_l as Ea,At as Fa,Ir as Ga,ze as Ha,mn as Ia,hn as Ja,gn as Ka,et as La,Pe as Ma,tu as Na,or as Oa,ar as Pa,ui as Qa,di as Ra,Tt as Sa,rs as Ta,ip as Ua,ap as Va,ke as Wa,fp as Xa,Ca as Ya,Sp as Za,bp as _a,Fe as $a,Se as ab,as as bb,Lt as cb,Me as db,Cp as eb,Np as fb,ds as gb,Tc as hb,Ts as ib,$c as jb,Rc as kb,_c as lb,Ef as mb};
|