werkmeister 0.37.0 → 0.38.1

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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # werkmeister
2
2
 
3
- A multi-feature concurrent development orchestrator: run up to 12 isolated
4
- feature environments side by side, each with its own containers, ports, and
5
- ingress hostnames.
3
+ A multi-feature concurrent development orchestrator: run many isolated
4
+ feature environments side by side (12 slots by default, and you can raise it),
5
+ each with its own containers, ports, and ingress hostnames.
6
6
 
7
7
  ## Quick start
8
8
 
package/dist/main.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __sandboxCreateRequire } from "node:module";
3
3
  const require = __sandboxCreateRequire(import.meta.url);
4
- var rV=Object.create;var Gp=Object.defineProperty;var nV=Object.getOwnPropertyDescriptor;var sV=Object.getOwnPropertyNames;var oV=Object.getPrototypeOf,iV=Object.prototype.hasOwnProperty;var i=(e,t)=>Gp(e,"name",{value:t,configurable:!0}),ee=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var $=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ce=(e,t)=>{for(var r in t)Gp(e,r,{get:t[r],enumerable:!0})},aV=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of sV(t))!iV.call(e,s)&&s!==r&&Gp(e,s,{get:()=>t[s],enumerable:!(n=nV(t,s))||n.enumerable});return e};var Ie=(e,t,r)=>(r=e!=null?rV(oV(e)):{},aV(t||!e||!e.__esModule?Gp(r,"default",{value:e,enumerable:!0}):r,e));var S,h=R(()=>{S={sha:"6e095ca031cf5f3869c83d38cc9252de6fc4dea8",dirty:!1}});var bu=$(tw=>{h();var Yp=class extends Error{static{i(this,"CommanderError")}constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},ew=class extends Yp{static{i(this,"InvalidArgumentError")}constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};tw.CommanderError=Yp;tw.InvalidArgumentError=ew});var zp=$(nw=>{h();var{InvalidArgumentError:lV}=bu(),rw=class{static{i(this,"Argument")}constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:r.concat(t)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new lV(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function uV(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}i(uV,"humanReadableArgName");nw.Argument=rw;nw.humanReadableArgName=uV});var iw=$(ow=>{h();var{humanReadableArgName:fV}=zp(),sw=class{static{i(this,"Help")}constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(s=>!s._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,o)=>s.name().localeCompare(o.name())),r}compareOptions(t,r){let n=i(s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,""),"getSortKey");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(s=>!s.hidden),n=t._getHelpOption();if(n&&!n.hidden){let s=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!s&&!o?r.push(n):n.long&&!o?r.push(t.createOption(n.long,n.description)):n.short&&!s&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>fV(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(s)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(s)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let s=t.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];return t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0?`${t.description} (${r.join(", ")})`:t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatHelp(t,r){let n=r.padWidth(t,r),s=r.helpWidth??80;function o(d,p){return r.formatItem(d,n,p,r)}i(o,"callFormatItem");let a=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],c=r.commandDescription(t);c.length>0&&(a=a.concat([r.boxWrap(r.styleCommandDescription(c),s),""]));let l=r.visibleArguments(t).map(d=>o(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));l.length>0&&(a=a.concat([r.styleTitle("Arguments:"),...l,""]));let u=r.visibleOptions(t).map(d=>o(r.styleOptionTerm(r.optionTerm(d)),r.styleOptionDescription(r.optionDescription(d))));if(u.length>0&&(a=a.concat([r.styleTitle("Options:"),...u,""])),r.showGlobalOptions){let d=r.visibleGlobalOptions(t).map(p=>o(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));d.length>0&&(a=a.concat([r.styleTitle("Global Options:"),...d,""]))}let f=r.visibleCommands(t).map(d=>o(r.styleSubcommandTerm(r.subcommandTerm(d)),r.styleSubcommandDescription(r.subcommandDescription(d))));return f.length>0&&(a=a.concat([r.styleTitle("Commands:"),...f,""])),a.join(`
4
+ var rV=Object.create;var Gp=Object.defineProperty;var nV=Object.getOwnPropertyDescriptor;var sV=Object.getOwnPropertyNames;var oV=Object.getPrototypeOf,iV=Object.prototype.hasOwnProperty;var i=(e,t)=>Gp(e,"name",{value:t,configurable:!0}),ee=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var $=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ce=(e,t)=>{for(var r in t)Gp(e,r,{get:t[r],enumerable:!0})},aV=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of sV(t))!iV.call(e,s)&&s!==r&&Gp(e,s,{get:()=>t[s],enumerable:!(n=nV(t,s))||n.enumerable});return e};var Ie=(e,t,r)=>(r=e!=null?rV(oV(e)):{},aV(t||!e||!e.__esModule?Gp(r,"default",{value:e,enumerable:!0}):r,e));var S,h=R(()=>{S={sha:"15e808b1ff2f1f77135fbe2acb276ccf1cc01d20",dirty:!1}});var bu=$(tw=>{h();var Yp=class extends Error{static{i(this,"CommanderError")}constructor(t,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=t,this.nestedError=void 0}},ew=class extends Yp{static{i(this,"InvalidArgumentError")}constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};tw.CommanderError=Yp;tw.InvalidArgumentError=ew});var zp=$(nw=>{h();var{InvalidArgumentError:lV}=bu(),rw=class{static{i(this,"Argument")}constructor(t,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,r){return r===this.defaultValue||!Array.isArray(r)?[t]:r.concat(t)}default(t,r){return this.defaultValue=t,this.defaultValueDescription=r,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new lV(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function uV(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}i(uV,"humanReadableArgName");nw.Argument=rw;nw.humanReadableArgName=uV});var iw=$(ow=>{h();var{humanReadableArgName:fV}=zp(),sw=class{static{i(this,"Help")}constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let r=t.commands.filter(s=>!s._hidden),n=t._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,o)=>s.name().localeCompare(o.name())),r}compareOptions(t,r){let n=i(s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,""),"getSortKey");return n(t).localeCompare(n(r))}visibleOptions(t){let r=t.options.filter(s=>!s.hidden),n=t._getHelpOption();if(n&&!n.hidden){let s=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!s&&!o?r.push(n):n.long&&!o?r.push(t.createOption(n.long,n.description)):n.short&&!s&&r.push(t.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let r=[];for(let n=t.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(r=>{r.description=r.description||t._argsDescription[r.name()]||""}),t.registeredArguments.find(r=>r.description)?t.registeredArguments:[]}subcommandTerm(t){let r=t.registeredArguments.map(n=>fV(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(s)))),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,r){return r.visibleGlobalOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(s)))),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce((n,s)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(s)))),0)}commandUsage(t){let r=t._name;t._aliases[0]&&(r=r+"|"+t._aliases[0]);let n="";for(let s=t.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let r=[];return t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&r.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&r.push(`env: ${t.envVar}`),r.length>0?`${t.description} (${r.join(", ")})`:t.description}argumentDescription(t){let r=[];if(t.argChoices&&r.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatHelp(t,r){let n=r.padWidth(t,r),s=r.helpWidth??80;function o(d,p){return r.formatItem(d,n,p,r)}i(o,"callFormatItem");let a=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(t))}`,""],c=r.commandDescription(t);c.length>0&&(a=a.concat([r.boxWrap(r.styleCommandDescription(c),s),""]));let l=r.visibleArguments(t).map(d=>o(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));l.length>0&&(a=a.concat([r.styleTitle("Arguments:"),...l,""]));let u=r.visibleOptions(t).map(d=>o(r.styleOptionTerm(r.optionTerm(d)),r.styleOptionDescription(r.optionDescription(d))));if(u.length>0&&(a=a.concat([r.styleTitle("Options:"),...u,""])),r.showGlobalOptions){let d=r.visibleGlobalOptions(t).map(p=>o(r.styleOptionTerm(r.optionTerm(p)),r.styleOptionDescription(r.optionDescription(p))));d.length>0&&(a=a.concat([r.styleTitle("Global Options:"),...d,""]))}let f=r.visibleCommands(t).map(d=>o(r.styleSubcommandTerm(r.subcommandTerm(d)),r.styleSubcommandDescription(r.subcommandDescription(d))));return f.length>0&&(a=a.concat([r.styleTitle("Commands:"),...f,""])),a.join(`
5
5
  `)}displayWidth(t){return BO(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,r){return Math.max(r.longestOptionTermLength(t,r),r.longestGlobalOptionTermLength(t,r),r.longestSubcommandTermLength(t,r),r.longestArgumentTermLength(t,r))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,r,n,s){let a=" ".repeat(2);if(!n)return a+t;let c=t.padEnd(r+t.length-s.displayWidth(t)),l=2,f=(this.helpWidth??80)-r-l-2,d;return f<this.minWidthToWrap||s.preformatted(n)?d=n:d=s.boxWrap(n,f).replace(/\n/g,`
6
6
  `+" ".repeat(r+l)),a+c+" ".repeat(l)+d.replace(/\n/g,`
7
7
  ${a}`)}boxWrap(t,r){if(r<this.minWidthToWrap)return t;let n=t.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(a=>{let c=a.match(s);if(c===null){o.push("");return}let l=[c.shift()],u=this.displayWidth(l[0]);c.forEach(f=>{let d=this.displayWidth(f);if(u+d<=r){l.push(f),u+=d;return}o.push(l.join(""));let p=f.trimStart();l=[p],u=this.displayWidth(p)}),o.push(l.join(""))}),o.join(`
@@ -851,7 +851,7 @@ else {`),this._emit("cb()")),this._emitLine("}")},"compileIf"),r.compileIfAsync=
851
851
  # Local subgraphs use the per-feature container network; remote
852
852
  # subgraphs fall through to the shared k8s-forwards container.
853
853
  `;return ge.writeFileSync(u,qt(g,c)+id.stringify(y,{indentSeq:!1,singleQuote:!0})),F(`Generated supergraph config (built-in): ${u}`),u}async function ka(e=null,t=null){let[r,n]=J0(t),s=ze.join(dn(),"proxy");ge.mkdirSync(s,{recursive:!0});let o=ze.join(s,"Caddyfile");return ge.existsSync(o)&&ge.statSync(o).isDirectory()&&ge.rmSync(o,{recursive:!0,force:!0}),m0("caddyfile",async()=>{e==null&&(e=await jt());let a=Object.entries(e).sort(([c],[l])=>c<l?-1:c>l?1:0).filter(([,c])=>Et(c)).map(([c,l])=>({name:c,slot:l.slot??null,services:l.services??[]}));return ge.writeFileSync(ze.join(s,"features.json"),JSON.stringify(a,null,2)+`
854
- `),fie(e,r,n,Ue(),o)})}function cie(e){return`(?:^|;\\s*)X-Feature=${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s*;|\\s*$)`}function lie(e,t){let r=[];for(let[n,s]of Object.entries(wr(t))){if(s.remoteHostname&&s.remoteUpstream&&r.push({hostname:s.remoteHostname,service:n,upstream:s.remoteUpstream}),!s.hostname)continue;let o=t[n]??{},a=Et(o)?o.port_offset??0:0,c=Object.entries(e).filter(([,u])=>Et(u)&&u.slot!==null&&u.slot!==void 0&&(u.services??[]).includes(n)).sort(([u],[f])=>u<f?-1:u>f?1:0).map(([u,f],d)=>({name:u,upstream:`host.docker.internal:${Hr(f.slot)[0]+a}`,matcher:`feat${d}_${u.replace(/[^A-Za-z0-9_]/g,"_")}`,cookie_regexp:cie(u)})),l=s.remoteUpstream??c[0]?.upstream;l&&r.push({hostname:s.hostname,service:n,upstream:l,...c.length?{features:c}:{}})}return r}function uie(e){let t=[];for(let r of e){t.push(`# ${r.service} \u2014 Caddy terminates ${r.hostname} directly`),t.push(`${r.hostname} {`),t.push(" tls internal"),t.push(""),t.push(" # Sandbox feature selector UI (sets/clears the X-Feature cookie)."),t.push(" # /__sandbox is a deprecated alias (SW-8; SW-11 removes it)."),t.push(" @selector_features path /__werkmeister/features.json /__sandbox/features.json"),t.push(" handle @selector_features {"),t.push(" root * /sandbox/proxy/ui"),t.push(" rewrite * /features.json"),t.push(" file_server"),t.push(" }"),t.push(" @selector path /__werkmeister* /__sandbox*"),t.push(" handle @selector {"),t.push(" root * /sandbox/proxy/ui"),t.push(" rewrite * /index.html"),t.push(" file_server"),t.push(" }"),t.push("");let n=r.features??[];if(n.length){for(let s of n)t.push(` # X-Feature=${s.name} -> that workspace's containers.`),t.push(` @${s.matcher} header_regexp Cookie ${s.cookie_regexp}`),t.push(` handle @${s.matcher} {`),t.push(` reverse_proxy ${s.upstream} {`),t.push(` header_up X-Feature ${s.name}`),t.push(" }"),t.push(" }");t.push(" # No cookie, or one naming a feature not serving this service.")}else t.push(" # X-Feature cookie -> X-Feature header (when present), then proxy."),t.push(" @xf header_regexp xf Cookie X-Feature=([^;]+)"),t.push(" handle @xf {"),t.push(` reverse_proxy ${r.upstream} {`),t.push(" header_up X-Feature {re.xf.1}"),t.push(" }"),t.push(" }");t.push(" handle /* {"),t.push(` reverse_proxy ${r.upstream}`),t.push(" }"),t.push("}"),t.push("")}return t}function fie(e,t,r,n,s){let o=lie(e,t),a=X0(),c=Q0(a,"Caddyfile.njk");if(c){let u=c.render(vl({host_routers:o}));return ge.writeFileSync(s,u),F(`Generated Caddyfile (template): ${s}`),s}N("Template 'Caddyfile.njk' not found -- falling back to built-in Caddyfile generation");let l=["# Auto-generated Caddyfile -- do not edit manually","# Regenerate with: sandbox proxy-reload","","{"," admin localhost:2019","}","",...uie(o)];return ge.writeFileSync(s,l.join(`
854
+ `),fie(e,r,n,Ue(),o)})}function cie(e){return`(?:^|;\\s*)X-Feature=${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s*;|\\s*$)`}function lie(e,t){let r=[];for(let[n,s]of Object.entries(wr(t))){if(s.remoteHostname&&s.remoteUpstream&&r.push({hostname:s.remoteHostname,service:n,upstream:s.remoteUpstream}),!s.hostname)continue;let o=t[n]??{},a=Et(o)?o.port_offset??0:0,c=Object.entries(e).filter(([,u])=>Et(u)&&u.slot!==null&&u.slot!==void 0&&(u.services??[]).includes(n)).sort(([u],[f])=>u<f?-1:u>f?1:0).map(([u,f],d)=>({name:u,upstream:`host.docker.internal:${Hr(f.slot)[0]+a}`,matcher:`feat${d}_${u.replace(/[^A-Za-z0-9_]/g,"_")}`,cookie_regexp:cie(u)})),l=s.remoteUpstream??c[0]?.upstream;l&&r.push({hostname:s.hostname,service:n,upstream:l,...c.length?{features:c}:{}})}return r}function uie(e){let t=[];for(let r of e){t.push(`# ${r.service} \u2014 Caddy terminates ${r.hostname} directly`),t.push(`${r.hostname} {`),t.push(" tls internal"),t.push(""),t.push(" # Sandbox feature selector UI (sets/clears the X-Feature cookie)."),t.push(" # /__sandbox is a deprecated alias (SW-8; SW-11 removes it)."),t.push(" @selector_features path /__werkmeister/features.json /__sandbox/features.json"),t.push(" handle @selector_features {"),t.push(" root * /srv"),t.push(" rewrite * /features.json"),t.push(" file_server"),t.push(" }"),t.push(" @selector path /__werkmeister* /__sandbox*"),t.push(" handle @selector {"),t.push(" root * /sandbox/proxy/ui"),t.push(" rewrite * /index.html"),t.push(" file_server"),t.push(" }"),t.push("");let n=r.features??[];if(n.length){for(let s of n)t.push(` # X-Feature=${s.name} -> that workspace's containers.`),t.push(` @${s.matcher} header_regexp Cookie ${s.cookie_regexp}`),t.push(` handle @${s.matcher} {`),t.push(` reverse_proxy ${s.upstream} {`),t.push(` header_up X-Feature ${s.name}`),t.push(" }"),t.push(" }");t.push(" # No cookie, or one naming a feature not serving this service.")}else t.push(" # X-Feature cookie -> X-Feature header (when present), then proxy."),t.push(" @xf header_regexp xf Cookie X-Feature=([^;]+)"),t.push(" handle @xf {"),t.push(` reverse_proxy ${r.upstream} {`),t.push(" header_up X-Feature {re.xf.1}"),t.push(" }"),t.push(" }");t.push(" handle /* {"),t.push(` reverse_proxy ${r.upstream}`),t.push(" }"),t.push("}"),t.push("")}return t}function fie(e,t,r,n,s){let o=lie(e,t),a=X0(),c=Q0(a,"Caddyfile.njk");if(c){let u=c.render(vl({host_routers:o}));return ge.writeFileSync(s,u),F(`Generated Caddyfile (template): ${s}`),s}N("Template 'Caddyfile.njk' not found -- falling back to built-in Caddyfile generation");let l=["# Auto-generated Caddyfile -- do not edit manually","# Regenerate with: sandbox proxy-reload","","{"," admin localhost:2019","}","",...uie(o)];return ge.writeFileSync(s,l.join(`
855
855
  `)),F(`Generated Caddyfile (built-in): ${s}`),s}async function ED(e,t,r,n="",s=[]){vu(r),O(`Generating ${De}...`);let o=le(),a=Dn(),c={services:o,ports:a},l={};for(let[b,E]of Object.entries(o)){if(!Et(E))continue;let k=(E.path??"").replace(/\/+$/,""),T=k.includes("/")?k.slice(k.lastIndexOf("/")+1):k;T!==b&&(l[T]=b)}let u=i(b=>{if(b in o)return b;let E=l[b];return E?(O(` Resolved service alias: ${b} \u2192 ${E}`),E):E??null},"resolve"),f=t.split(",").map(b=>b.trim()).filter(b=>b),d=new Map;for(let b of f)d.set(b,u(b));let p=[...d.values()].filter(b=>b!==null),m=[...d.entries()].filter(([,b])=>b===null).map(([b])=>b);m.length>0&&N(`Unknown services (skipped): ${m.join(", ")}`);let y;try{y=await qf(e,p)}catch(b){let E=b instanceof Error?b.message:String(b);return N(`Could not allocate slot: ${E}`),E.startsWith("Timed out")?N("Retry, or remove the stale lock file if no sandbox process is running."):N("Run 'sandbox down <feature>' to free a slot, then re-run init-workspace."),null}ad(e,y,p,c,r,"sandbox init-workspace"),eg(e,y,p,c,r),rg(e,y,p,c,r);let[g,x]=Hr(y);F(`Compose ready (slot ${y}, ports ${g}-${x})`);let v=JP(e,y,g,x,p,o,n,null,gf(s,fn(),p),vm(r)),_=W(r);return ge.mkdirSync(_,{recursive:!0}),ge.writeFileSync(ze.join(_,"sandbox-context.md"),qt(v,r)),F(`Wrote ${ze.basename(_)}/sandbox-context.md`),y}var _k,id,bk,Zoe,vk,eie,tie,aie,yk,ng=R(()=>{"use strict";h();_k=Ie(lD(),1),id=Ie(st(),1);Fn();sd();Q_();wn();Nn();Q();bs();G_();Ve();fk();Rt();yr();xk();i(Et,"isDict");i(wk,"jinjaTruthy");i(Qr,"setdefault");i(xD,"resolveWorktreeGitdir");i(J0,"resolveServicesAndPorts");bk=class{static{i(this,"DoExtension")}tags=["do"];parse(t,r){let n=t.nextToken(),s=t.parseSignature(null,!0);return t.advanceAfterBlockEnd(n.value),new r.CallExtension(this,"run",s)}run(...t){return""}},Zoe=/(\{%-?\s*(?:el)?if\s+)([\s\S]+?)(\s*-?%\})/g,vk=class extends _k.default.FileSystemLoader{static{i(this,"JinjaCompatLoader")}getSource(t){let r=super.getSource(t);return r&&typeof r.src=="string"&&(r.src=r.src.replace(Zoe,(n,s,o,a)=>`${s}__truthy(${o})${a}`)),r}},eie=i(function(e,t){return e in this?this[e]:t},"_DICT_GET"),tie=i(function(){return Object.entries(this)},"_DICT_ITEMS");i(vl,"jinjaContext");i(rie,"installArrayAppend");i(X0,"getNunjucksEnv");i(Q0,"getTemplateOrNull");i(nie,"composeHeader");i(sie,"resolveComposeOutPath");i(bD,"seedWorkspaceMetadataEnv");i(vD,"preservedEnvMetadata");i(Sa,"k8sPortForService");i(z0,"quoted");i(oie,"resolveServiceRefs");i(_D,"loadWorkspaceDict");i(iie,"loadDevLinks");i(Z0,"loadWorkspaceEnvVars");i(SD,"renderFeatureCompose");i(ad,"generateFeatureCompose");i(kD,"isFeatureComposeStale");aie={_URL:"_BASE_URL",_HOST:"_BASE_HOST",_PORT:"_BASE_PORT"};i(yD,"avoidComposeEnvShadowing");i(eg,"generateFeatureEnv");i(tg,"writeServiceSecretEnvs");i(wD,"writeWorkspaceEnv");yk=new Set(["graphql-subgraph","graphql","subgraph","federation"]);i(rg,"generateSupergraphConfig");i(ka,"generateCaddyfile");i(cie,"featureCookieRegexp");i(lie,"buildHostRouters");i(uie,"hostRouterLines");i(fie,"generateCaddyfileLocked");i(ED,"generateWorkspaceCompose")});import*as vn from"node:fs";import*as $D from"node:http";import*as Sk from"node:net";import*as sg from"node:path";import{setTimeout as die}from"node:timers/promises";async function kk(){return{"k8s-forwards":(await Dt(br,"k8s-forwards",{all:!1})??[]).some(t=>t.health==="healthy"||t.state==="running"&&!t.health)}}function pie(e,t){if(!e)return!0;let r=new Map;for(let n of e){let s=Lr(n.labels,"feature");if(!s)continue;let o=r.get(s)??{local:[],running:!1};o.local.push(n.service),o.running||=n.state==="running",r.set(s,o)}return[...r.values()].some(n=>n.running&&em(n.local,t))}async function og(e){let t;try{t=le()}catch{return!0}return pie(e===void 0?await Dt():e,t)}function hie(e){return vn.existsSync(e)&&vn.statSync(e).isDirectory()}function mie(e){return/server:\s*https:\/\/(127\.0\.0\.1|localhost)\b/.test(e)?e.replace(/(server:\s*https:\/\/)(127\.0\.0\.1|localhost)\b/g,"$1host.docker.internal").replace(/^(\s*)certificate-authority-data:.*$/gm,"$1insecure-skip-tls-verify: true"):e}function Ek(){let e=sg.join(dn(),"k8s-port-forward","kubeconfig");hie(e)&&vn.rmSync(e,{recursive:!0,force:!0}),vn.mkdirSync(sg.dirname(e),{recursive:!0}),O("Refreshing k8s-port-forward/kubeconfig from current context...");try{let t=K(["kubectl","config","view","--raw","--minify","--flatten"],{capture:!0,timeout:10});if(t.status===0){vn.writeFileSync(e,mie(t.stdout));let r=K(["kubectl","--kubeconfig",e,"config","current-context"],{capture:!0,timeout:5}),n=r.status===0?r.stdout.trim():"?";F(`Kubeconfig pinned to context: ${n}`)}else D(`kubectl config view failed: ${t.stderr.trim()}`)}catch(t){if(t instanceof Z&&(t.code==="ENOENT"||t.code==="ETIMEDOUT"))D(`Could not generate kubeconfig: ${t.message}`);else throw t}return vn.existsSync(e)&&vn.statSync(e).isFile()}function gie(){try{return K(["kubectl","--request-timeout=3s","get","--raw","/readyz"],{capture:!0,timeout:20}).status===0}catch(e){if(e instanceof Z)return!1;throw e}}async function ig(){if((await kk())["k8s-forwards"]??!1)return F("k8s port-forwards container is healthy"),"healthy";if(N("k8s port-forwards container is unhealthy \u2014 restarting..."),!Ek())return D("Not restarting k8s-forwards without a kubeconfig file to mount"),"failed";if(!gie())return N("No reachable k8s cluster \u2014 skipping port-forwards; services not run locally are unavailable"),"failed";let{argv:t,env:r,cwd:n}=va();try{let s=K([...t,"up","-d","--force-recreate","k8s-forwards"],{capture:!0,timeout:60,env:r,cwd:n});return s.status!==0?(D(`Failed to restart k8s-forwards: ${s.stderr.trim()}`),"failed"):(F("k8s port-forwards container restarted"),"restarted")}catch(s){if(s instanceof Z)return D(`Failed to restart k8s-forwards: ${s.message}`),"failed";throw s}}async function OD(e=3e4,t=500){let r=Gf();if(!r.length)return;O("Waiting for port-forwards to reconnect...");let n=Date.now()+e;for(;;){if(r=(await Promise.all(r.map(async o=>({spec:o,ok:(await ag(o.listen,o.health)).ok})))).filter(o=>!o.ok).map(o=>o.spec),!r.length){F("k8s port-forwards are carrying traffic");return}if(Date.now()>=n)throw new Y(`k8s port-forwards did not come back within ${Math.round(e/1e3)}s: ${r.map(o=>`${o.name}:${o.listen}`).join(", ")}
856
856
  Check \`docker logs ${Os}\` and your kubeconfig.`,"FORWARDS_NEVER_READY");await die(t)}}function xie(e,t,r=3500){return new Promise(n=>{let s=$D.get({host:"127.0.0.1",port:e,path:t,timeout:r},o=>{o.resume();let a=o.statusCode??0;n({ok:a<500,detail:`HTTP ${a}`})});s.on("timeout",()=>{s.destroy(),n({ok:!1,detail:"timeout"})}),s.on("error",o=>n({ok:!1,detail:o.code??o.message}))})}function yie(e,t,r=3500){return new Promise(n=>{let s=TD[t],o=Sk.connect({host:"127.0.0.1",port:e,timeout:r});o.on("connect",()=>o.write(s.send)),o.once("data",a=>{o.destroy();let c=s.ok(a);n({ok:c,detail:c?`${t} ok`:`${t} bad reply`})}),o.on("timeout",()=>{o.destroy(),n({ok:!1,detail:"timeout (connected, no reply)"})}),o.on("error",a=>n({ok:!1,detail:a.code??a.message})),o.on("close",()=>n({ok:!1,detail:"closed without reply"}))})}function wie(e,t=2500){return new Promise(r=>{let n=Sk.connect({host:"127.0.0.1",port:e,timeout:t});n.on("connect",()=>{n.destroy(),r({ok:!0,detail:"tcp open"})}),n.on("timeout",()=>{n.destroy(),r({ok:!1,detail:"timeout"})}),n.on("error",s=>r({ok:!1,detail:s.code??s.message}))})}function ag(e,t){return t.startsWith("/")?xie(e,t):TD[t]?yie(e,t):t?Promise.resolve({ok:!1,detail:`unknown probe "${t}"`}):wie(e)}async function bie(e,t){return(await ag(e,t)).ok?"alive":"dead"}async function cd(){let e=await h0(Os),t;try{t=Gf()}catch{return[]}let r=e?null:await og()?"container_down":"stopped",n=[];for(let s of t)n.push({name:s.name,listen_port:s.listen,remote_port:s.remote,health_path:s.health,status:r??await bie(s.listen,s.health)});return n}var TD,_l=R(()=>{"use strict";h();ds();_a();Q();Ir();Jt();R0();ft();Ve();Rt();i(kk,"checkPortForwardHealth");i(pie,"clusterNeeded");i(og,"forwarderNeeded");i(hie,"isDir");i(mie,"shimLocalApiServer");i(Ek,"refreshKubeconfig");i(gie,"clusterReachable");i(ig,"ensurePortForwardsHealthy");i(OD,"waitForForwards");i(xie,"checkHttpHealth");TD={redis:{send:Buffer.from(`PING\r
857
857
  `),ok:i(e=>e.toString("latin1").startsWith("+PONG"),"ok")},postgres:{send:Buffer.from([0,0,0,8,4,210,22,47]),ok:i(e=>e[0]===83||e[0]===78,"ok")}};i(yie,"checkWireHealth");i(wie,"checkTcpHealth");i(ag,"checkForwardHealth");i(bie,"classifyForward");i(cd,"getPerServiceStatus")});import*as Sl from"node:fs";import*as cg from"node:os";import*as lg from"node:path";function RD(e){return lg.join(W(e),"starts.json")}function CD(e){try{let t=JSON.parse(Sl.readFileSync(RD(e),"utf8"));return Array.isArray(t)?t:[]}catch{return[]}}function Sie(e,t,r,n=Date.now()){try{let s=RD(e),o=[...CD(e),{by:t,from:new Date(r).toISOString(),to:new Date(n).toISOString()}].slice(-vie);Sl.mkdirSync(lg.dirname(s),{recursive:!0}),Sl.writeFileSync(s,`${JSON.stringify(o,null,2)}
package/dist/mcp.js CHANGED
@@ -644,7 +644,7 @@ ${y?"### Feature missing from `/__werkmeister` selector\n\nThe dropdown is popul
644
644
  # Local subgraphs use the per-feature container network; remote
645
645
  # subgraphs fall through to the shared k8s-forwards container.
646
646
  `;return ze.writeFileSync(u,br(g,c)+ov.stringify(v,{indentSeq:!1,singleQuote:!0})),ee(`Generated supergraph config (built-in): ${u}`),u}s(FS,"generateSupergraphConfig");async function Rd(e=null,t=null){let[r,i]=CS(t),n=xt.join(hi(),"proxy");ze.mkdirSync(n,{recursive:!0});let o=xt.join(n,"Caddyfile");return ze.existsSync(o)&&ze.statSync(o).isDirectory()&&ze.rmSync(o,{recursive:!0,force:!0}),Wk("caddyfile",async()=>{e==null&&(e=await Po());let a=Object.entries(e).sort(([c],[l])=>c<l?-1:c>l?1:0).filter(([,c])=>tr(c)).map(([c,l])=>({name:c,slot:l.slot??null,services:l.services??[]}));return ze.writeFileSync(xt.join(n,"features.json"),JSON.stringify(a,null,2)+`
647
- `),d6e(e,r,i,Ut(),o)})}s(Rd,"generateCaddyfile");function l6e(e){return`(?:^|;\\s*)X-Feature=${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s*;|\\s*$)`}s(l6e,"featureCookieRegexp");function u6e(e,t){let r=[];for(let[i,n]of Object.entries(In(t))){if(n.remoteHostname&&n.remoteUpstream&&r.push({hostname:n.remoteHostname,service:i,upstream:n.remoteUpstream}),!n.hostname)continue;let o=t[i]??{},a=tr(o)?o.port_offset??0:0,c=Object.entries(e).filter(([,u])=>tr(u)&&u.slot!==null&&u.slot!==void 0&&(u.services??[]).includes(i)).sort(([u],[p])=>u<p?-1:u>p?1:0).map(([u,p],d)=>({name:u,upstream:`host.docker.internal:${bi(p.slot)[0]+a}`,matcher:`feat${d}_${u.replace(/[^A-Za-z0-9_]/g,"_")}`,cookie_regexp:l6e(u)})),l=n.remoteUpstream??c[0]?.upstream;l&&r.push({hostname:n.hostname,service:i,upstream:l,...c.length?{features:c}:{}})}return r}s(u6e,"buildHostRouters");function p6e(e){let t=[];for(let r of e){t.push(`# ${r.service} \u2014 Caddy terminates ${r.hostname} directly`),t.push(`${r.hostname} {`),t.push(" tls internal"),t.push(""),t.push(" # Sandbox feature selector UI (sets/clears the X-Feature cookie)."),t.push(" # /__sandbox is a deprecated alias (SW-8; SW-11 removes it)."),t.push(" @selector_features path /__werkmeister/features.json /__sandbox/features.json"),t.push(" handle @selector_features {"),t.push(" root * /sandbox/proxy/ui"),t.push(" rewrite * /features.json"),t.push(" file_server"),t.push(" }"),t.push(" @selector path /__werkmeister* /__sandbox*"),t.push(" handle @selector {"),t.push(" root * /sandbox/proxy/ui"),t.push(" rewrite * /index.html"),t.push(" file_server"),t.push(" }"),t.push("");let i=r.features??[];if(i.length){for(let n of i)t.push(` # X-Feature=${n.name} -> that workspace's containers.`),t.push(` @${n.matcher} header_regexp Cookie ${n.cookie_regexp}`),t.push(` handle @${n.matcher} {`),t.push(` reverse_proxy ${n.upstream} {`),t.push(` header_up X-Feature ${n.name}`),t.push(" }"),t.push(" }");t.push(" # No cookie, or one naming a feature not serving this service.")}else t.push(" # X-Feature cookie -> X-Feature header (when present), then proxy."),t.push(" @xf header_regexp xf Cookie X-Feature=([^;]+)"),t.push(" handle @xf {"),t.push(` reverse_proxy ${r.upstream} {`),t.push(" header_up X-Feature {re.xf.1}"),t.push(" }"),t.push(" }");t.push(" handle /* {"),t.push(` reverse_proxy ${r.upstream}`),t.push(" }"),t.push("}"),t.push("")}return t}s(p6e,"hostRouterLines");function d6e(e,t,r,i,n){let o=u6e(e,t),a=NS(),c=DS(a,"Caddyfile.njk");if(c){let u=c.render(Ad({host_routers:o}));return ze.writeFileSync(n,u),ee(`Generated Caddyfile (template): ${n}`),n}B("Template 'Caddyfile.njk' not found -- falling back to built-in Caddyfile generation");let l=["# Auto-generated Caddyfile -- do not edit manually","# Regenerate with: sandbox proxy-reload","","{"," admin localhost:2019","}","",...p6e(o)];return ze.writeFileSync(n,l.join(`
647
+ `),d6e(e,r,i,Ut(),o)})}s(Rd,"generateCaddyfile");function l6e(e){return`(?:^|;\\s*)X-Feature=${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s*;|\\s*$)`}s(l6e,"featureCookieRegexp");function u6e(e,t){let r=[];for(let[i,n]of Object.entries(In(t))){if(n.remoteHostname&&n.remoteUpstream&&r.push({hostname:n.remoteHostname,service:i,upstream:n.remoteUpstream}),!n.hostname)continue;let o=t[i]??{},a=tr(o)?o.port_offset??0:0,c=Object.entries(e).filter(([,u])=>tr(u)&&u.slot!==null&&u.slot!==void 0&&(u.services??[]).includes(i)).sort(([u],[p])=>u<p?-1:u>p?1:0).map(([u,p],d)=>({name:u,upstream:`host.docker.internal:${bi(p.slot)[0]+a}`,matcher:`feat${d}_${u.replace(/[^A-Za-z0-9_]/g,"_")}`,cookie_regexp:l6e(u)})),l=n.remoteUpstream??c[0]?.upstream;l&&r.push({hostname:n.hostname,service:i,upstream:l,...c.length?{features:c}:{}})}return r}s(u6e,"buildHostRouters");function p6e(e){let t=[];for(let r of e){t.push(`# ${r.service} \u2014 Caddy terminates ${r.hostname} directly`),t.push(`${r.hostname} {`),t.push(" tls internal"),t.push(""),t.push(" # Sandbox feature selector UI (sets/clears the X-Feature cookie)."),t.push(" # /__sandbox is a deprecated alias (SW-8; SW-11 removes it)."),t.push(" @selector_features path /__werkmeister/features.json /__sandbox/features.json"),t.push(" handle @selector_features {"),t.push(" root * /srv"),t.push(" rewrite * /features.json"),t.push(" file_server"),t.push(" }"),t.push(" @selector path /__werkmeister* /__sandbox*"),t.push(" handle @selector {"),t.push(" root * /sandbox/proxy/ui"),t.push(" rewrite * /index.html"),t.push(" file_server"),t.push(" }"),t.push("");let i=r.features??[];if(i.length){for(let n of i)t.push(` # X-Feature=${n.name} -> that workspace's containers.`),t.push(` @${n.matcher} header_regexp Cookie ${n.cookie_regexp}`),t.push(` handle @${n.matcher} {`),t.push(` reverse_proxy ${n.upstream} {`),t.push(` header_up X-Feature ${n.name}`),t.push(" }"),t.push(" }");t.push(" # No cookie, or one naming a feature not serving this service.")}else t.push(" # X-Feature cookie -> X-Feature header (when present), then proxy."),t.push(" @xf header_regexp xf Cookie X-Feature=([^;]+)"),t.push(" handle @xf {"),t.push(` reverse_proxy ${r.upstream} {`),t.push(" header_up X-Feature {re.xf.1}"),t.push(" }"),t.push(" }");t.push(" handle /* {"),t.push(` reverse_proxy ${r.upstream}`),t.push(" }"),t.push("}"),t.push("")}return t}s(p6e,"hostRouterLines");function d6e(e,t,r,i,n){let o=u6e(e,t),a=NS(),c=DS(a,"Caddyfile.njk");if(c){let u=c.render(Ad({host_routers:o}));return ze.writeFileSync(n,u),ee(`Generated Caddyfile (template): ${n}`),n}B("Template 'Caddyfile.njk' not found -- falling back to built-in Caddyfile generation");let l=["# Auto-generated Caddyfile -- do not edit manually","# Regenerate with: sandbox proxy-reload","","{"," admin localhost:2019","}","",...p6e(o)];return ze.writeFileSync(n,l.join(`
648
648
  `)),ee(`Generated Caddyfile (built-in): ${n}`),n}s(d6e,"generateCaddyfileLocked");async function Yre(e,t,r,i="",n=[]){wg(r),C(`Generating ${nt}...`);let o=Ke(),a=Eo(),c={services:o,ports:a},l={};for(let[_,E]of Object.entries(o)){if(!tr(E))continue;let $=(E.path??"").replace(/\/+$/,""),O=$.includes("/")?$.slice($.lastIndexOf("/")+1):$;O!==_&&(l[O]=_)}let u=s(_=>{if(_ in o)return _;let E=l[_];return E?(C(` Resolved service alias: ${_} \u2192 ${E}`),E):E??null},"resolve"),p=t.split(",").map(_=>_.trim()).filter(_=>_),d=new Map;for(let _ of p)d.set(_,u(_));let m=[...d.values()].filter(_=>_!==null),h=[...d.entries()].filter(([,_])=>_===null).map(([_])=>_);h.length>0&&B(`Unknown services (skipped): ${h.join(", ")}`);let v;try{v=await Vk(e,m)}catch(_){let E=_ instanceof Error?_.message:String(_);return B(`Could not allocate slot: ${E}`),E.startsWith("Timed out")?B("Retry, or remove the stale lock file if no sandbox process is running."):B("Run 'sandbox down <feature>' to free a slot, then re-run init-workspace."),null}sv(e,v,m,c,r,"sandbox init-workspace"),zS(e,v,m,c,r),FS(e,v,m,c,r);let[g,y]=bi(v);ee(`Compose ready (slot ${v}, ports ${g}-${y})`);let w=Mre(e,v,g,y,m,o,i,null,Yg(n,Zi(),m),IS(r)),k=Q(r);return ze.mkdirSync(k,{recursive:!0}),ze.writeFileSync(xt.join(k,"sandbox-context.md"),br(w,r)),ee(`Wrote ${xt.basename(k)}/sandbox-context.md`),v}s(Yre,"generateWorkspaceCompose");f();ye();Zt();$t();import*as Xre from"node:fs";import*as Qre from"node:path";var Ds=".githooks";function ene(e){let t=e??Ut();if(!Xre.existsSync(Qre.join(t,".git")))return!1;let r;try{r=te(["git","-C",t,"config","--get","core.hooksPath"],{capture:!0})}catch(n){if(n instanceof be&&n.code==="ENOENT")return B(`git was not found on PATH \u2014 could not check or configure core.hooksPath. The sandbox secret-commit guard (${Ds}/pre-commit) was NOT installed.`),!1;throw n}let i=r.status===0?r.stdout.trim():"";if(i===Ds)return!0;if(i)return B(`core.hooksPath is already set to '${i}' \u2014 leaving it unchanged. The sandbox secret-commit guard (${Ds}/pre-commit) was NOT installed. Run 'git config core.hooksPath ${Ds}' manually if you want to activate it.`),!1;try{te(["git","-C",t,"config","core.hooksPath",Ds],{capture:!0,check:!0})}catch(n){let o=n instanceof be&&n.code===void 0&&n.stderr?n.stderr.trim():String(n instanceof Error?n.message:n);return B(`Could not set core.hooksPath to ${Ds} (${o}). The sandbox secret-commit guard (${Ds}/pre-commit) was NOT installed.`),!1}return C(`Configuring core.hooksPath -> ${Ds} (first-time setup)...`),ee(`core.hooksPath set to ${Ds} (secret-commit guard active)`),!0}s(ene,"configureGitHooksPath");f();xs();import*as $i from"node:fs";import*as tne from"node:http";import*as M2 from"node:net";import*as qS from"node:path";import{setTimeout as f6e}from"node:timers/promises";ye();Ki();On();Zt();$t();Un();async function F2(){return{"k8s-forwards":(await xr(wi,"k8s-forwards",{all:!1})??[]).some(t=>t.health==="healthy"||t.state==="running"&&!t.health)}}s(F2,"checkPortForwardHealth");function m6e(e,t){if(!e)return!0;let r=new Map;for(let i of e){let n=qn(i.labels,"feature");if(!n)continue;let o=r.get(n)??{local:[],running:!1};o.local.push(i.service),o.running||=i.state==="running",r.set(n,o)}return[...r.values()].some(i=>i.running&&sk(i.local,t))}s(m6e,"clusterNeeded");async function US(e){let t;try{t=Ke()}catch{return!0}return m6e(e===void 0?await xr():e,t)}s(US,"forwarderNeeded");function h6e(e){return $i.existsSync(e)&&$i.statSync(e).isDirectory()}s(h6e,"isDir");function g6e(e){return/server:\s*https:\/\/(127\.0\.0\.1|localhost)\b/.test(e)?e.replace(/(server:\s*https:\/\/)(127\.0\.0\.1|localhost)\b/g,"$1host.docker.internal").replace(/^(\s*)certificate-authority-data:.*$/gm,"$1insecure-skip-tls-verify: true"):e}s(g6e,"shimLocalApiServer");function q2(){let e=qS.join(hi(),"k8s-port-forward","kubeconfig");h6e(e)&&$i.rmSync(e,{recursive:!0,force:!0}),$i.mkdirSync(qS.dirname(e),{recursive:!0}),C("Refreshing k8s-port-forward/kubeconfig from current context...");try{let t=te(["kubectl","config","view","--raw","--minify","--flatten"],{capture:!0,timeout:10});if(t.status===0){$i.writeFileSync(e,g6e(t.stdout));let r=te(["kubectl","--kubeconfig",e,"config","current-context"],{capture:!0,timeout:5}),i=r.status===0?r.stdout.trim():"?";ee(`Kubeconfig pinned to context: ${i}`)}else de(`kubectl config view failed: ${t.stderr.trim()}`)}catch(t){if(t instanceof be&&(t.code==="ENOENT"||t.code==="ETIMEDOUT"))de(`Could not generate kubeconfig: ${t.message}`);else throw t}return $i.existsSync(e)&&$i.statSync(e).isFile()}s(q2,"refreshKubeconfig");function v6e(){try{return te(["kubectl","--request-timeout=3s","get","--raw","/readyz"],{capture:!0,timeout:20}).status===0}catch(e){if(e instanceof be)return!1;throw e}}s(v6e,"clusterReachable");async function BS(){if((await F2())["k8s-forwards"]??!1)return ee("k8s port-forwards container is healthy"),"healthy";if(B("k8s port-forwards container is unhealthy \u2014 restarting..."),!q2())return de("Not restarting k8s-forwards without a kubeconfig file to mount"),"failed";if(!v6e())return B("No reachable k8s cluster \u2014 skipping port-forwards; services not run locally are unavailable"),"failed";let{argv:t,env:r,cwd:i}=vd();try{let n=te([...t,"up","-d","--force-recreate","k8s-forwards"],{capture:!0,timeout:60,env:r,cwd:i});return n.status!==0?(de(`Failed to restart k8s-forwards: ${n.stderr.trim()}`),"failed"):(ee("k8s port-forwards container restarted"),"restarted")}catch(n){if(n instanceof be)return de(`Failed to restart k8s-forwards: ${n.message}`),"failed";throw n}}s(BS,"ensurePortForwardsHealthy");async function rne(e=3e4,t=500){let r=qg();if(!r.length)return;C("Waiting for port-forwards to reconnect...");let i=Date.now()+e;for(;;){if(r=(await Promise.all(r.map(async o=>({spec:o,ok:(await ZS(o.listen,o.health)).ok})))).filter(o=>!o.ok).map(o=>o.spec),!r.length){ee("k8s port-forwards are carrying traffic");return}if(Date.now()>=i)throw new le(`k8s port-forwards did not come back within ${Math.round(e/1e3)}s: ${r.map(o=>`${o.name}:${o.listen}`).join(", ")}
649
649
  Check \`docker logs ${Ug}\` and your kubeconfig.`,"FORWARDS_NEVER_READY");await f6e(t)}}s(rne,"waitForForwards");function y6e(e,t,r=3500){return new Promise(i=>{let n=tne.get({host:"127.0.0.1",port:e,path:t,timeout:r},o=>{o.resume();let a=o.statusCode??0;i({ok:a<500,detail:`HTTP ${a}`})});n.on("timeout",()=>{n.destroy(),i({ok:!1,detail:"timeout"})}),n.on("error",o=>i({ok:!1,detail:o.code??o.message}))})}s(y6e,"checkHttpHealth");var nne={redis:{send:Buffer.from(`PING\r
650
650
  `),ok:s(e=>e.toString("latin1").startsWith("+PONG"),"ok")},postgres:{send:Buffer.from([0,0,0,8,4,210,22,47]),ok:s(e=>e[0]===83||e[0]===78,"ok")}};function b6e(e,t,r=3500){return new Promise(i=>{let n=nne[t],o=M2.connect({host:"127.0.0.1",port:e,timeout:r});o.on("connect",()=>o.write(n.send)),o.once("data",a=>{o.destroy();let c=n.ok(a);i({ok:c,detail:c?`${t} ok`:`${t} bad reply`})}),o.on("timeout",()=>{o.destroy(),i({ok:!1,detail:"timeout (connected, no reply)"})}),o.on("error",a=>i({ok:!1,detail:a.code??a.message})),o.on("close",()=>i({ok:!1,detail:"closed without reply"}))})}s(b6e,"checkWireHealth");function x6e(e,t=2500){return new Promise(r=>{let i=M2.connect({host:"127.0.0.1",port:e,timeout:t});i.on("connect",()=>{i.destroy(),r({ok:!0,detail:"tcp open"})}),i.on("timeout",()=>{i.destroy(),r({ok:!1,detail:"timeout"})}),i.on("error",n=>r({ok:!1,detail:n.code??n.message}))})}s(x6e,"checkTcpHealth");function ZS(e,t){return t.startsWith("/")?y6e(e,t):nne[t]?b6e(e,t):t?Promise.resolve({ok:!1,detail:`unknown probe "${t}"`}):x6e(e)}s(ZS,"checkForwardHealth");async function w6e(e,t){return(await ZS(e,t)).ok?"alive":"dead"}s(w6e,"classifyForward");async function ine(){let e=await Hk(Ug),t;try{t=qg()}catch{return[]}let r=e?null:await US()?"container_down":"stopped",i=[];for(let n of t)i.push({name:n.name,listen_port:n.listen,remote_port:n.remote,health_path:n.health,status:r??await w6e(n.listen,n.health)});return i}s(ine,"getPerServiceStatus");Zt();$t();f();ye();Zt();$t();import{spawn as _6e}from"node:child_process";import*as Dt from"node:fs";import*as one from"node:net";import*as sne from"node:os";import*as Mo from"node:path";var Ls={label:"Workspaces dashboard",dir:"werkmeister-dashboard",port:3001,stem:"mcp-server",entry:"dist/main.js",buildRef:"dist/main.js"},k6e={label:"Sandbox MCP server",dir:"werkmeister-mcp",port:3002,stem:"sandbox-mcp",entry:"dist/main.js",buildRef:"dist/main.js",bundled:"dist/mcp.js",env:{HOST:"0.0.0.0"}},S6e=[Ls,k6e];function U2(e){return new Promise(t=>setTimeout(t,e*1e3))}s(U2,"sleep");async function ane(e){let t;try{t=te(["lsof","-ti",`tcp:${e}`,"-sTCP:LISTEN"],{capture:!0,timeout:5}).stdout}catch(i){if(i instanceof be&&(i.code==="ENOENT"||i.code==="ETIMEDOUT"))return;throw i}let r=t.split(/\s+/).map(i=>i.trim()).filter(i=>/^\d+$/.test(i)).map(i=>Number.parseInt(i,10));for(let i of r)try{process.kill(i,"SIGTERM")}catch{}if(r.length!==0){for(let i=0;i<20;i++){if(!await B2(e))return;await U2(.25)}for(let i of r)try{process.kill(i,"SIGKILL")}catch{}}}s(ane,"freePort");function cne(){let e=Q(sne.homedir());return Dt.mkdirSync(e,{recursive:!0}),e}s(cne,"stateDir");function El(e){return Mo.join(cne(),`${e.stem}.pid`)}s(El,"pidFile");function $6e(e){return Mo.join(cne(),`${e.stem}.log`)}s($6e,"logFile");function lne(e){return Mo.join(DJ(),"apps",e.dir)}s(lne,"appDir");function E6e(e,t){let r=t.lastIndexOf("/"),i=r>=0?Mo.join(e,t.slice(0,r)):e,n=r>=0?t.slice(r+1):t,o=new RegExp("^"+n.split("*").map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$"),a;try{a=Dt.readdirSync(i,{withFileTypes:!0})}catch{return[]}return a.filter(c=>o.test(c.name)).map(c=>Mo.join(i,c.name))}s(E6e,"globMatch");function T6e(e){let t=lne(e),r=Mo.join(t,e.buildRef),i;try{let o=Dt.statSync(r);if(!o.isFile())return!0;i=o.mtimeMs}catch{return!0}let n=["*.ts","*.html","package.json","tsconfig*.json","src/*.ts","src/*.css","src/lib/*.ts"];for(let o of n)for(let a of E6e(t,o))try{if(Dt.statSync(a).mtimeMs>i)return!0}catch{}return!1}s(T6e,"distStale");function O6e(e,t){try{return Dt.statSync(t).mtimeMs>Dt.statSync(El(e)).mtimeMs}catch{return!1}}s(O6e,"buildNewerThanRunning");function I6e(e){let t;try{t=Dt.readFileSync(El(e),"utf8")}catch{return null}let r=t.trim();return/^[+-]?\d+$/.test(r)?Number.parseInt(r,10):null}s(I6e,"readPid");function une(e){try{process.kill(e,0)}catch(t){let r=t.code;if(r==="ESRCH")return!1;if(r==="EPERM")return!0;throw t}return!0}s(une,"alive");function B2(e){return new Promise(t=>{let r=one.connect({host:"127.0.0.1",port:e}),i=s(n=>{r.destroy(),t(n)},"done");r.setTimeout(1e3,()=>i(!1)),r.once("connect",()=>i(!0)),r.once("error",()=>i(!1))})}s(B2,"portOpen");function Z2(e=Ls){let t=I6e(e);return t&&une(t)?[!0,t]:[!1,null]}s(Z2,"isRunning");async function H2(e=Ls){let[t,r]=Z2(e);return{running:t,pid:r,port:e.port,url:`http://localhost:${e.port}/`,healthy:t&&await B2(e.port)}}s(H2,"status");async function W2(e=Ls,t=!0,r=!1){let[i,n]=Z2(e);if(i&&n===process.pid)return ee(`${e.label} is this process (pid ${n}); leaving it running`),!0;let o=lne(e),a=e.entry,c=Mo.join(o,e.buildRef);if(!Dt.existsSync(Mo.join(o,"package.json"))){let g=e.bundled?Mo.join(Ut(),e.bundled):null;if(!g||!Dt.existsSync(g))return B(`${e.label} not found at ${o}; skipping`),!1;o=Ut(),a=g,c=g,t=!1}let l=!1;if(t&&T6e(e)){C(`Building ${e.label} (sources changed)...`);let g;try{g=te(["pnpm","run","build"],{cwd:o,capture:!0,timeout:300})}catch(y){if(y instanceof be&&y.code==="ENOENT")return B(`pnpm not found; skipping ${e.label}`),!1;if(y instanceof be&&y.code==="ETIMEDOUT")return de(`${e.label} build timed out; skipping`),!1;throw y}if(g.status!==0){let y=(g.stderr.trim()||g.stdout.trim()).slice(-800);return de(`${e.label} build failed; skipping start:
Binary file
@@ -175,8 +175,9 @@ services:
175
175
  volumes:
176
176
  - ${SANDBOX_STATE_DIR}/proxy/Caddyfile:/etc/caddy/Caddyfile:ro
177
177
  - ../proxy/ui:/sandbox/proxy/ui:ro
178
- # Generated beside the Caddyfile; a file bind over the shipped ui dir.
179
- - ${SANDBOX_STATE_DIR}/proxy/features.json:/sandbox/proxy/ui/features.json:ro
178
+ # Outside the :ro ui bind (SW-100): nesting it there needs a mountpoint file
179
+ # in the shipped ui dir, which fresh clones and npm installs don't have.
180
+ - ${SANDBOX_STATE_DIR}/proxy/features.json:/srv/features.json:ro
180
181
  # Cert location comes from `ingress.certs_dir` in ~/.werkmeister/config.yaml,
181
182
  # exported as SANDBOX_CERTS_DIR by ~/.werkmeister/env.sh. The default keeps
182
183
  # this working for a shell that hasn't sourced env.sh.
@@ -22,12 +22,12 @@
22
22
 
23
23
  # Sandbox feature selector: a static picker UI (mounted at /sandbox/proxy/ui)
24
24
  # that sets/clears the X-Feature cookie client-side. Served on every host so
25
- # `https://<host>/__werkmeister` works. features.json is matched first (it's a
26
- # real file); any other /__werkmeister path returns the picker.
25
+ # `https://<host>/__werkmeister` works. features.json is matched first (the
26
+ # generated file, mounted at /srv); any other /__werkmeister path returns the picker.
27
27
  # /__sandbox is a deprecated alias served identically (SW-8; SW-11 removes it).
28
28
  @selector_features path /__werkmeister/features.json /__sandbox/features.json
29
29
  handle @selector_features {
30
- root * /sandbox/proxy/ui
30
+ root * /srv
31
31
  rewrite * /features.json
32
32
  file_server
33
33
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "werkmeister",
3
- "version": "0.37.0",
3
+ "version": "0.38.1",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Multi-feature concurrent development orchestrator CLI tool",
6
6
  "type": "module",
@@ -55,7 +55,7 @@
55
55
  "typescript": "^5.7.0",
56
56
  "vitest": "^3.0.0",
57
57
  "yaml": "^2.7.0",
58
- "werkmeister-core": "0.37.0"
58
+ "werkmeister-core": "0.38.1"
59
59
  },
60
60
  "scripts": {
61
61
  "build": "node esbuild.mjs",