@mylasertools/kerfscript 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/libraries.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /*! @mylasertools/kerfscript | (c) MyLaserTools | AGPL-3.0-only or commercial licence, see COMMERCIAL-LICENSE.md. Includes Clipper2 (BSL-1.0), opentype.js, tiny-inflate and string.prototype.codepointat (MIT), see THIRD-PARTY-NOTICES.md. */
2
- import{createHash as L1}from"node:crypto";import{existsSync as I,mkdirSync as b1,readdirSync as Q,readFileSync as T,rmSync as J,statSync as m1,writeFileSync as S}from"node:fs";import{dirname as Y,isAbsolute as E,join as z,relative as w1,resolve as O,sep as A1}from"node:path";import{gunzipSync as C1,gzipSync as H1}from"node:zlib";var p1=(a,c=!0)=>`line ${a.line}${c?`, column ${a.col}`:""}${a.file?` in <${a.file}>`:""}`;var A=class extends Error{constructor(l,e){super(e?`${l} (${p1(e)})`:l);this.echoes=[];this.warnings=[];this.trace=[];this.traceMore=0;this.name="KerfError",this.reason=l,e&&(this.line=e.line,this.col=e.col,this.file=e.file)}addFrame(l,e,n){let t=this.trace.find(h=>h.name===e&&h.line===n.line&&h.col===n.col&&h.file===n.file);t?t.count++:this.trace.length>=50?this.traceMore++:this.trace.push({kind:l,name:e,line:n.line,col:n.col,...n.file&&{file:n.file},count:1})}},g1=["<=",">=","==","!=","&&","||","+","-","*","/","%","^","<",">","!","?",":","=",".",",",";","(",")","[","]","{","}","#"];function s1(a,c){let l=[],e=[],n=0,t=1,h=0,s=()=>({line:t,col:n-h+1,offset:n,...c&&{file:c}}),i=o=>{for(let m=0;m<o;m++)a[n]===`
2
+ import{createHash as b1}from"node:crypto";import{existsSync as I,mkdirSync as w1,readdirSync as Q,readFileSync as T,rmSync as J,statSync as m1,writeFileSync as _}from"node:fs";import{dirname as Y,isAbsolute as E,join as d,relative as L1,resolve as O,sep as A1}from"node:path";import{gunzipSync as y1,gzipSync as C1}from"node:zlib";var p1=(a,c=!0)=>`line ${a.line}${c?`, column ${a.col}`:""}${a.file?` in <${a.file}>`:""}`;var A=class extends Error{constructor(l,e){super(e?`${l} (${p1(e)})`:l);this.echoes=[];this.warnings=[];this.trace=[];this.traceMore=0;this.name="KerfError",this.reason=l,e&&(this.line=e.line,this.col=e.col,this.file=e.file)}addFrame(l,e,n){let t=this.trace.find(h=>h.name===e&&h.line===n.line&&h.col===n.col&&h.file===n.file);t?t.count++:this.trace.length>=50?this.traceMore++:this.trace.push({kind:l,name:e,line:n.line,col:n.col,...n.file&&{file:n.file},count:1})}},g1=["<=",">=","==","!=","&&","||","+","-","*","/","%","^","<",">","!","?",":","=",".",",",";","(",")","[","]","{","}","#"];function s1(a,c){let l=[],e=[],n=0,t=1,h=0,s=()=>({line:t,col:n-h+1,offset:n,...c&&{file:c}}),i=o=>{for(let m=0;m<o;m++)a[n]===`
3
3
  `&&(t++,h=n+1),n++};for(;n<a.length;){let o=a[n];if(o===" "||o===" "||o==="\r"||o===`
4
4
  `){i(1);continue}if(o==="/"&&a[n+1]==="/"){let r=a.indexOf(`
5
5
  `,n),v=r<0?a.length:r,p=/^[ \t]*$/.test(a.slice(a.lastIndexOf(`
6
6
  `,n-1)+1,n));e.push({text:a.slice(n+2,v).trim(),line:t,block:!1,own:p,start:n,end:v}),n=v;continue}if(o==="/"&&a[n+1]==="*"){let r=s(),v=a.indexOf("*/",n+2);if(v<0)throw new A("Unclosed block comment",r);e.push({text:a.slice(n+2,v).trim(),line:r.line,block:!0,own:!0,start:n,end:v+2}),i(v+2-n);continue}let m=s();if(/[0-9]/.test(o)||o==="."&&/[0-9]/.test(a[n+1]??"")){let r=/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?(?:(?:mm|cm|m|in|ft)(?![A-Za-z0-9_]))?/.exec(a.slice(n));l.push({type:"num",value:r[0],pos:m,end:n+r[0].length}),i(r[0].length);continue}if(/[A-Za-z_$]/.test(o)){let r=/^[A-Za-z_$][A-Za-z0-9_]*/.exec(a.slice(n));l.push({type:"id",value:r[0],pos:m,end:n+r[0].length}),i(r[0].length);continue}if(o==='"'){let r="";for(i(1);n<a.length&&a[n]!=='"';){if(a[n]==="\\"){let v=a[n+1];if(v==="n")r+=`
7
7
  `;else if(v==="t")r+=" ";else if(v==="u"){let p=a.slice(n+2,n+6);if(!/^[0-9a-fA-F]{4}$/.test(p))throw new A("Bad \\u escape",s());r+=String.fromCharCode(parseInt(p,16)),i(4)}else r+=v;i(2);continue}if(a[n]===`
8
- `)throw new A("Unclosed string",m);r+=a[n],i(1)}if(n>=a.length)throw new A("Unclosed string",m);i(1),l.push({type:"str",value:r,pos:m,end:n});continue}if(o==="<"&&/^<[A-Za-z0-9_./-]+>/.test(a.slice(n))){let r=l[l.length-1];if(r&&r.type==="id"&&(r.value==="use"||r.value==="include")){let v=/^<([A-Za-z0-9_./-]+)>/.exec(a.slice(n));l.push({type:"str",value:v[1],pos:m,end:n+v[0].length}),i(v[0].length);continue}}let d=g1.find(r=>a.startsWith(r,n));if(!d)throw new A(`Unexpected character "${o}"`,m);l.push({type:"punct",value:d,pos:m,end:n+d.length}),i(d.length)}return l.push({type:"eof",value:"",pos:s(),end:n}),{tokens:l,comments:e}}var D=new Set(["module","function","if","else","for","let","each","use","include","true","false","undef"]);function h1(a,c){let{tokens:l,comments:e}=s1(a,c),n=new N(l),t=[];for(;!n.at("eof");)t.push(...n.statement());return{program:{body:t},comments:e}}var N=class a{constructor(c){this.tokens=c;this.i=0}peek(c=0){return this.tokens[Math.min(this.i+c,this.tokens.length-1)]}at(c,l,e=0){let n=this.peek(e);return n.type===c&&(l===void 0||n.value===l)}isP(c,l=0){return this.at("punct",c,l)}isK(c,l=0){return this.at("id",c,l)}next(){return this.tokens[this.i++]}fail(c,l=this.peek()){let e=l.type==="eof"?"end of file":`"${l.value}"`;throw new A(`${c}, found ${e}`,l.pos)}expectP(c){return this.isP(c)||this.fail(`Expected "${c}"`),this.next()}separator(c){this.isP(c)||(this.isP(",")||this.fail(`Expected "," or "${c}"`),this.next())}ident(){let c=this.peek();return(c.type!=="id"||D.has(c.value))&&this.fail("Expected a name"),this.next()}last(){return this.tokens[this.i-1].end}statement(){let c=this.stmt();for(let l of c)l.end=this.last();return c}stmt(){let c=this.peek();if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let h=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),h.push(...this.statement());return this.next(),[{kind:"block",body:h,pos:c.pos}]}if(this.isK("module")){this.next();let h=this.ident(),s=this.params();return[{kind:"module",name:h.value,params:s,body:this.body(),pos:c.pos,namePos:h.pos}]}if(this.isK("function")&&this.at("id",void 0,1)){this.next();let h=this.ident(),s=this.params();this.expectP("=");let i=this.expr();return this.expectP(";"),[{kind:"function",name:h.value,params:s,body:i,pos:c.pos,namePos:h.pos}]}if(this.isK("use")||this.isK("include")){this.next();let h=this.peek();return h.type!=="str"&&this.fail("Expected a library path like <kerf/box>"),this.next(),this.isP(";")&&this.next(),[{kind:"use",path:h.value,include:c.value==="include",pos:c.pos}]}if(this.isK("for"))return this.next(),[{kind:"for",assigns:this.assigns(),body:this.body(),pos:c.pos}];if(this.isK("if")){this.next(),this.expectP("(");let h=this.expr();this.expectP(")");let s=this.body(),i=[];return this.isK("else")&&(this.next(),i=this.body()),[{kind:"if",cond:h,then:s,else:i,pos:c.pos}]}if(this.isK("let")&&this.isP("(",1))return this.next(),[{kind:"let",assigns:this.assigns(),body:this.body(),pos:c.pos}];if(c.type==="id"&&this.isP("=",1)){let h=this.ident().value;this.next();let s=this.peek().pos.offset,i=this.expr(),o=this.expectP(";").pos.offset;return[{kind:"assign",name:h,value:i,span:[s,o],pos:c.pos}]}let l=null;(this.isP("*")||this.isP("!")||this.isP("#")||this.isP("%"))&&(l=this.next().value);let e=this.peek();(e.type!=="id"||D.has(e.value))&&this.fail("Expected a statement"),this.next();let n=this.args(),t=this.body();return[{kind:"call",name:e.value,args:n,children:t,modifier:l,pos:e.pos}]}body(){if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let c=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),c.push(...this.statement());return this.next(),c}return this.statement()}params(){this.expectP("(");let c=[];for(;!this.isP(")");){let l=this.ident(),e=null;this.isP("=")&&(this.next(),e=this.expr()),c.push({name:l.value,default:e,pos:l.pos}),this.separator(")")}return this.next(),c}args(){this.expectP("(");let c=[];for(;!this.isP(")");){if(this.at("id")&&this.isP("=",1)){let l=this.next();this.next(),c.push({name:l.value,value:this.expr(),pos:l.pos})}else c.push({name:null,value:this.expr()});this.separator(")")}return this.next(),c}assigns(){this.expectP("(");let c=[];for(;!this.isP(")");){let l=this.ident();this.expectP("="),c.push({name:l.value,value:this.expr(),pos:l.pos}),this.separator(")")}return this.next(),c}expr(){let c=this.peek();if(this.isK("function")&&this.isP("(",1)){this.next();let e=this.params(),n=this.expr();return{kind:"lambda",params:e,body:n,pos:c.pos,end:this.last()}}if(this.isK("let")&&this.isP("(",1)){this.next();let e=this.assigns(),n=this.expr();return{kind:"let",assigns:e,body:n,pos:c.pos,end:this.last()}}let l=this.binary(0);if(this.isP("?")){this.next();let e=this.expr();this.expectP(":");let n=this.expr();return{kind:"ternary",cond:l,then:e,else:n,pos:c.pos}}return l}static{this.LEVELS=[["||"],["&&"],["==","!="],["<","<=",">",">="],["+","-"],["*","/","%"]]}binary(c){if(c>=a.LEVELS.length)return this.unary();let l=this.binary(c+1);for(;this.at("punct")&&a.LEVELS[c].includes(this.peek().value);){let e=this.next(),n=this.binary(c+1);l={kind:"binary",op:e.value,left:l,right:n,pos:e.pos}}return l}unary(){if(this.isP("-")||this.isP("!")||this.isP("+")){let c=this.next();return{kind:"unary",op:c.value,arg:this.unary(),pos:c.pos}}return this.power()}power(){let c=this.postfix();if(this.isP("^")){let l=this.next();return{kind:"binary",op:"^",left:c,right:this.unary(),pos:l.pos}}return c}postfix(){let c=this.primary();for(;;){let l=this.peek();if(this.isP("("))c={kind:"call",callee:c,args:this.args(),pos:c.pos};else if(this.isP("[")){this.next();let e=this.expr();this.expectP("]"),c={kind:"index",target:c,index:e,pos:l.pos}}else if(this.isP("."))this.next(),c={kind:"member",target:c,name:this.ident().value,pos:l.pos};else return c}}primary(){let c=this.peek();if(c.type==="num"){this.next();let l=/(mm|cm|m|in|ft)$/.exec(c.value);return l?{kind:"num",value:Number(c.value.slice(0,-l[1].length)),unit:l[1],pos:c.pos}:{kind:"num",value:Number(c.value),pos:c.pos}}if(c.type==="str")return this.next(),{kind:"str",value:c.value,pos:c.pos};if(c.type==="id")return c.value==="true"||c.value==="false"?(this.next(),{kind:"bool",value:c.value==="true",pos:c.pos}):c.value==="undef"?(this.next(),{kind:"undef",pos:c.pos}):(D.has(c.value)&&this.fail("Expected a value"),this.next(),{kind:"var",name:c.value,pos:c.pos});if(this.isP("(")){this.next();let l=this.expr();return this.expectP(")"),l}if(this.isP("["))return this.list();if(this.isP("{"))return this.record();this.fail("Expected a value")}record(){let c=this.expectP("{"),l=[];for(;!this.isP("}");){let e=this.ident();if(l.some(n=>n.name===e.value))throw new A(`Field ${e.value} is given twice`,e.pos);if(this.expectP("="),l.push({name:e.value,value:this.expr(),pos:e.pos}),!this.isP(","))break;this.next()}return this.expectP("}"),{kind:"record",fields:l,pos:c.pos}}list(){let c=this.expectP("[");if(this.isP("]"))return this.next(),{kind:"list",items:[],pos:c.pos};if(!this.isK("for")&&!this.isK("if")&&!this.isK("each")&&!(this.isK("let")&&this.isP("(",1))&&!(this.isP("(")&&(this.isK("for",1)||this.isK("if",1)))){let l=this.expr();if(this.isP(":")){this.next();let n=null,t=this.expr();return this.isP(":")&&(this.next(),n=t,t=this.expr()),this.expectP("]"),{kind:"range",start:l,step:n,end:t,pos:c.pos}}let e=[{kind:"item",expr:l}];return this.listRest(e,c.pos)}return this.listRest([],c.pos)}listRest(c,l){if(c.length){if(this.isP("]"))return this.next(),{kind:"list",items:c,pos:l};this.separator("]")}for(;!this.isP("]");)c.push(this.listItem()),this.separator("]");return this.next(),{kind:"list",items:c,pos:l}}listItem(){let c=this.peek();if(this.isK("for")&&this.isP("(",1)){this.next();let l=this.assigns(),e=this.listItem();return{kind:"for",assigns:l,body:e,pos:c.pos,end:this.last()}}if(this.isK("if")&&this.isP("(",1)){this.next(),this.expectP("(");let l=this.expr();this.expectP(")");let e=this.listItem(),n=null;return this.isK("else")&&(this.next(),n=this.listItem()),{kind:"if",cond:l,then:e,else:n}}if(this.isK("let")&&this.isP("(",1)){this.next();let l=this.assigns(),e=this.listItem();return{kind:"let",assigns:l,body:e,pos:c.pos,end:this.last()}}if(this.isK("each"))return this.next(),{kind:"each",expr:this.expr()};if(this.isP("(")&&(this.isK("for",1)||this.isK("if",1))){this.next();let l=this.listItem();return this.expectP(")"),l}return{kind:"item",expr:this.expr()}}};var i1={"kerf/box":`// kerf/box: finger-jointed boxes.
8
+ `)throw new A("Unclosed string",m);r+=a[n],i(1)}if(n>=a.length)throw new A("Unclosed string",m);i(1),l.push({type:"str",value:r,pos:m,end:n});continue}if(o==="<"&&/^<[A-Za-z0-9_./-]+>/.test(a.slice(n))){let r=l[l.length-1];if(r&&r.type==="id"&&(r.value==="use"||r.value==="include")){let v=/^<([A-Za-z0-9_./-]+)>/.exec(a.slice(n));l.push({type:"str",value:v[1],pos:m,end:n+v[0].length}),i(v[0].length);continue}}let z=g1.find(r=>a.startsWith(r,n));if(!z)throw new A(`Unexpected character "${o}"`,m);l.push({type:"punct",value:z,pos:m,end:n+z.length}),i(z.length)}return l.push({type:"eof",value:"",pos:s(),end:n}),{tokens:l,comments:e}}var D=new Set(["module","function","if","else","for","let","each","use","include","true","false","undef"]);function h1(a,c){let{tokens:l,comments:e}=s1(a,c),n=new N(l),t=[];for(;!n.at("eof");)t.push(...n.statement());return{program:{body:t},comments:e}}var N=class a{constructor(c){this.tokens=c;this.i=0}peek(c=0){return this.tokens[Math.min(this.i+c,this.tokens.length-1)]}at(c,l,e=0){let n=this.peek(e);return n.type===c&&(l===void 0||n.value===l)}isP(c,l=0){return this.at("punct",c,l)}isK(c,l=0){return this.at("id",c,l)}next(){return this.tokens[this.i++]}fail(c,l=this.peek()){let e=l.type==="eof"?"end of file":`"${l.value}"`;throw new A(`${c}, found ${e}`,l.pos)}expectP(c){return this.isP(c)||this.fail(`Expected "${c}"`),this.next()}separator(c){this.isP(c)||(this.isP(",")||this.fail(`Expected "," or "${c}"`),this.next())}ident(){let c=this.peek();return(c.type!=="id"||D.has(c.value))&&this.fail("Expected a name"),this.next()}last(){return this.tokens[this.i-1].end}statement(){let c=this.stmt();for(let l of c)l.end=this.last();return c}stmt(){let c=this.peek();if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let h=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),h.push(...this.statement());return this.next(),[{kind:"block",body:h,pos:c.pos}]}if(this.isK("module")){this.next();let h=this.ident(),s=this.params();return[{kind:"module",name:h.value,params:s,body:this.body(),pos:c.pos,namePos:h.pos}]}if(this.isK("function")&&this.at("id",void 0,1)){this.next();let h=this.ident(),s=this.params();this.expectP("=");let i=this.expr();return this.expectP(";"),[{kind:"function",name:h.value,params:s,body:i,pos:c.pos,namePos:h.pos}]}if(this.isK("use")||this.isK("include")){this.next();let h=this.peek();return h.type!=="str"&&this.fail("Expected a library path like <kerf/box>"),this.next(),this.isP(";")&&this.next(),[{kind:"use",path:h.value,include:c.value==="include",pos:c.pos}]}if(this.isK("for"))return this.next(),[{kind:"for",assigns:this.assigns(),body:this.body(),pos:c.pos}];if(this.isK("if")){this.next(),this.expectP("(");let h=this.expr();this.expectP(")");let s=this.body(),i=[];return this.isK("else")&&(this.next(),i=this.body()),[{kind:"if",cond:h,then:s,else:i,pos:c.pos}]}if(this.isK("let")&&this.isP("(",1))return this.next(),[{kind:"let",assigns:this.assigns(),body:this.body(),pos:c.pos}];if(c.type==="id"&&this.isP("=",1)){let h=this.ident().value;this.next();let s=this.peek().pos.offset,i=this.expr(),o=this.expectP(";").pos.offset;return[{kind:"assign",name:h,value:i,span:[s,o],pos:c.pos}]}let l=null;(this.isP("*")||this.isP("!")||this.isP("#")||this.isP("%"))&&(l=this.next().value);let e=this.peek();(e.type!=="id"||D.has(e.value))&&this.fail("Expected a statement"),this.next();let n=this.args(),t=this.body();return[{kind:"call",name:e.value,args:n,children:t,modifier:l,pos:e.pos}]}body(){if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let c=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),c.push(...this.statement());return this.next(),c}return this.statement()}params(){this.expectP("(");let c=[];for(;!this.isP(")");){let l=this.ident(),e=null;this.isP("=")&&(this.next(),e=this.expr()),c.push({name:l.value,default:e,pos:l.pos}),this.separator(")")}return this.next(),c}args(){this.expectP("(");let c=[];for(;!this.isP(")");){if(this.at("id")&&this.isP("=",1)){let l=this.next();this.next(),c.push({name:l.value,value:this.expr(),pos:l.pos})}else c.push({name:null,value:this.expr()});this.separator(")")}return this.next(),c}assigns(){this.expectP("(");let c=[];for(;!this.isP(")");){let l=this.ident();this.expectP("="),c.push({name:l.value,value:this.expr(),pos:l.pos}),this.separator(")")}return this.next(),c}expr(){let c=this.peek();if(this.isK("function")&&this.isP("(",1)){this.next();let e=this.params(),n=this.expr();return{kind:"lambda",params:e,body:n,pos:c.pos,end:this.last()}}if(this.isK("let")&&this.isP("(",1)){this.next();let e=this.assigns(),n=this.expr();return{kind:"let",assigns:e,body:n,pos:c.pos,end:this.last()}}let l=this.binary(0);if(this.isP("?")){this.next();let e=this.expr();this.expectP(":");let n=this.expr();return{kind:"ternary",cond:l,then:e,else:n,pos:c.pos}}return l}static{this.LEVELS=[["||"],["&&"],["==","!="],["<","<=",">",">="],["+","-"],["*","/","%"]]}binary(c){if(c>=a.LEVELS.length)return this.unary();let l=this.binary(c+1);for(;this.at("punct")&&a.LEVELS[c].includes(this.peek().value);){let e=this.next(),n=this.binary(c+1);l={kind:"binary",op:e.value,left:l,right:n,pos:e.pos}}return l}unary(){if(this.isP("-")||this.isP("!")||this.isP("+")){let c=this.next();return{kind:"unary",op:c.value,arg:this.unary(),pos:c.pos}}return this.power()}power(){let c=this.postfix();if(this.isP("^")){let l=this.next();return{kind:"binary",op:"^",left:c,right:this.unary(),pos:l.pos}}return c}postfix(){let c=this.primary();for(;;){let l=this.peek();if(this.isP("("))c={kind:"call",callee:c,args:this.args(),pos:c.pos};else if(this.isP("[")){this.next();let e=this.expr();this.expectP("]"),c={kind:"index",target:c,index:e,pos:l.pos}}else if(this.isP("."))this.next(),c={kind:"member",target:c,name:this.ident().value,pos:l.pos};else return c}}primary(){let c=this.peek();if(c.type==="num"){this.next();let l=/(mm|cm|m|in|ft)$/.exec(c.value);return l?{kind:"num",value:Number(c.value.slice(0,-l[1].length)),unit:l[1],pos:c.pos}:{kind:"num",value:Number(c.value),pos:c.pos}}if(c.type==="str")return this.next(),{kind:"str",value:c.value,pos:c.pos};if(c.type==="id")return c.value==="true"||c.value==="false"?(this.next(),{kind:"bool",value:c.value==="true",pos:c.pos}):c.value==="undef"?(this.next(),{kind:"undef",pos:c.pos}):(D.has(c.value)&&this.fail("Expected a value"),this.next(),{kind:"var",name:c.value,pos:c.pos});if(this.isP("(")){this.next();let l=this.expr();return this.expectP(")"),l}if(this.isP("["))return this.list();if(this.isP("{"))return this.record();this.fail("Expected a value")}record(){let c=this.expectP("{"),l=[];for(;!this.isP("}");){let e=this.ident();if(l.some(n=>n.name===e.value))throw new A(`Field ${e.value} is given twice`,e.pos);if(this.expectP("="),l.push({name:e.value,value:this.expr(),pos:e.pos}),!this.isP(","))break;this.next()}return this.expectP("}"),{kind:"record",fields:l,pos:c.pos}}list(){let c=this.expectP("[");if(this.isP("]"))return this.next(),{kind:"list",items:[],pos:c.pos};if(!this.isK("for")&&!this.isK("if")&&!this.isK("each")&&!(this.isK("let")&&this.isP("(",1))&&!(this.isP("(")&&(this.isK("for",1)||this.isK("if",1)))){let l=this.expr();if(this.isP(":")){this.next();let n=null,t=this.expr();return this.isP(":")&&(this.next(),n=t,t=this.expr()),this.expectP("]"),{kind:"range",start:l,step:n,end:t,pos:c.pos}}let e=[{kind:"item",expr:l}];return this.listRest(e,c.pos)}return this.listRest([],c.pos)}listRest(c,l){if(c.length){if(this.isP("]"))return this.next(),{kind:"list",items:c,pos:l};this.separator("]")}for(;!this.isP("]");)c.push(this.listItem()),this.separator("]");return this.next(),{kind:"list",items:c,pos:l}}listItem(){let c=this.peek();if(this.isK("for")&&this.isP("(",1)){this.next();let l=this.assigns(),e=this.listItem();return{kind:"for",assigns:l,body:e,pos:c.pos,end:this.last()}}if(this.isK("if")&&this.isP("(",1)){this.next(),this.expectP("(");let l=this.expr();this.expectP(")");let e=this.listItem(),n=null;return this.isK("else")&&(this.next(),n=this.listItem()),{kind:"if",cond:l,then:e,else:n}}if(this.isK("let")&&this.isP("(",1)){this.next();let l=this.assigns(),e=this.listItem();return{kind:"let",assigns:l,body:e,pos:c.pos,end:this.last()}}if(this.isK("each"))return this.next(),{kind:"each",expr:this.expr()};if(this.isP("(")&&(this.isK("for",1)||this.isK("if",1))){this.next();let l=this.listItem();return this.expectP(")"),l}return{kind:"item",expr:this.expr()}}};var i1={"kerf/box":`// kerf/box: finger-jointed boxes.
9
9
  // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
10
10
 
11
11
  // Box from its outer size [width, depth, height] in the current material.
@@ -97,6 +97,62 @@ module joint_test(kerfs = [0.1, 0.15, 0.2], size = [40, 20], finger = undef, lab
97
97
  }
98
98
  }
99
99
  }
100
+ `,"kerf/cones":`// kerf/cones: cones and cut-off cones cut flat, to roll up from thin sheet.
101
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
102
+ //
103
+ // A cone rolled from paper, card, veneer or thin plastic is a ring sector
104
+ // when flat. Gramophone horns, lampshades, funnels and party hats all start
105
+ // as one. The sector's apex is at the origin and it opens from +x
106
+ // anticlockwise; the glue tab runs along its far edge.
107
+
108
+ // The flat pattern of a cone of radius r1 at one end, r2 at the other and h
109
+ // high: [outer radius, inner radius, angle in degrees, slant length]. A
110
+ // cylinder (r1 == r2) has no apex: it gives [undef, undef, 0, h] and is a
111
+ // rectangle 2 * PI * r1 wide.
112
+ function cone_pattern(r1, r2, h) =
113
+ let (
114
+ big = max(r1, r2),
115
+ small = min(r1, r2),
116
+ s = sqrt(h * h + pow(big - small, 2))
117
+ )
118
+ big == small ? [undef, undef, 0, h]
119
+ : [s * big / (big - small), s * small / (big - small), 360 * (big - small) / s, s];
120
+
121
+ // A cone or cut-off cone cut flat: rolled up so the far edge lies on the
122
+ // glue tab, it has radius r1 at one end, r2 at the other, and is h high.
123
+ // \`tab\` adds a glue tab that wide along the far edge, its fold scored; a
124
+ // cylinder becomes a rectangle with the tab on its right.
125
+ module cone_flat(r1, r2, h, tab = 0, steps = 0) {
126
+ p = cone_pattern(r1, r2, h);
127
+ if (is_undef(p[0])) {
128
+ w = 2 * PI * r1;
129
+ rect([w, h]);
130
+ if (tab > 0) {
131
+ polygon([[w, 0], [w + tab, min(tab, h / 4)], [w + tab, h - min(tab, h / 4)], [w, h]]);
132
+ score() line([w, 0], [w, h]);
133
+ }
134
+ } else {
135
+ a = p[2];
136
+ n = steps > 0 ? steps : max(8, ceil(a / 3));
137
+ arc_pts = function(r) [for (i = [0:n]) [r * cos(a * i / n), r * sin(a * i / n)]];
138
+ polygon(concat(arc_pts(p[0]), p[1] > 0 ? reverse(arc_pts(p[1])) : [[0, 0]]));
139
+ if (tab > 0) {
140
+ // The tab beyond the far edge, its ends cut in so it hides when rolled
141
+ ux = cos(a);
142
+ uy = sin(a);
143
+ nx = -uy;
144
+ ny = ux;
145
+ c = min(tab, p[3] / 4);
146
+ polygon([
147
+ [p[1] * ux, p[1] * uy],
148
+ [p[0] * ux, p[0] * uy],
149
+ [(p[0] - c) * ux + tab * nx, (p[0] - c) * uy + tab * ny],
150
+ [(p[1] + (p[1] > 0 ? c : tab)) * ux + tab * nx, (p[1] + (p[1] > 0 ? c : tab)) * uy + tab * ny],
151
+ ]);
152
+ score() line([p[1] * ux, p[1] * uy], [p[0] * ux, p[0] * uy]);
153
+ }
154
+ }
155
+ }
100
156
  `,"kerf/dividers":`// kerf/dividers: dividers that slot into each other like an egg crate.
101
157
  // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
102
158
 
@@ -370,6 +426,209 @@ module tappets(n, r, w = 10, hub = 14, bore = 6, square = false) {
370
426
  if (square) rect([bore, bore], center = true); else circle(d = bore);
371
427
  }
372
428
  }
429
+
430
+ // Cams from a lift curve. The follower rides on the cam's top (+y) and
431
+ // moves straight up and down; turned anticlockwise by \`a\` degrees (rotate =
432
+ // [0, 0, a]), the cam lifts it lift(a) above the base circle. \`lift\` is a
433
+ // function of the angle, 0 to 360, that comes back to where it started.
434
+
435
+ // A smooth rise of \`height\` from angle a0 to a1 (cycloidal: it starts and
436
+ // stops gently): 0 before a0, height after a1. Add and take away rises to
437
+ // make dwells, rises and falls: two pecks then a rest is
438
+ // function(a) cam_rise(a, 0, 40, 8) - cam_rise(a, 40, 80, 8) + cam_rise(a, 100, 140, 8) - cam_rise(a, 140, 180, 8).
439
+ function cam_rise(a, a0, a1, height) =
440
+ a <= a0 ? 0
441
+ : a >= a1 ? height
442
+ : let (u = (a - a0) / (a1 - a0)) height * (u - sin(360 * u) / (2 * PI));
443
+
444
+ // The cam's pitch curve: where the follower's tip (or its roller's centre)
445
+ // sits, in the cam's own turn, \`steps\` points round
446
+ function cam_pitch(lift, base_r, roller_d = 0, steps = 180) =
447
+ [for (i = [0:steps - 1])
448
+ let (f = i * 360 / steps, a = (450 - f) % 360, r = base_r + roller_d / 2 + lift(a))
449
+ [r * cos(f), r * sin(f)]];
450
+
451
+ // How high the follower's tip (or its roller's centre) is above the cam's
452
+ // axle when the cam is turned to \`angle\`, to place the follower
453
+ function cam_follower(lift, base_r, angle, roller_d = 0) =
454
+ base_r + roller_d / 2 + lift(((angle % 360) + 360) % 360);
455
+
456
+ // The steepest pressure angle over a turn, in degrees: how hard the cam
457
+ // pushes the follower sideways. Keep it under about 30, by a bigger base
458
+ // circle or a longer rise.
459
+ function cam_pressure(lift, base_r, roller_d = 0, steps = 360) =
460
+ max([for (i = [0:steps - 1])
461
+ let (
462
+ a = i * 360 / steps,
463
+ r = base_r + roller_d / 2 + lift(a),
464
+ slope = (lift((a + 0.5) % 360) - lift((a + 359.5) % 360)) / (PI / 180)
465
+ )
466
+ atan(abs(slope) / r)]);
467
+
468
+ // A cam that lifts a follower lift(a) at angle a, with a hole for its
469
+ // axle. A "knife" follower rides the pitch curve itself; a "roller" one of
470
+ // diameter roller_d rolls on a profile inside it. Check cam_pressure().
471
+ module cam(lift, base_r, follower = "knife", roller_d = 0, bore = 6, steps = 180, square = false) {
472
+ assert(follower == "knife" || follower == "roller", "follower must be \\"knife\\" or \\"roller\\"");
473
+ assert(follower == "knife" || roller_d > 0, "a roller follower needs roller_d");
474
+ difference() {
475
+ if (follower == "roller") offset(r = -roller_d / 2) polygon(cam_pitch(lift, base_r, roller_d, steps));
476
+ else polygon(cam_pitch(lift, base_r, 0, steps));
477
+ if (square) rect([bore, bore], center = true); else circle(d = bore);
478
+ }
479
+ }
480
+
481
+ // A Geneva drive: a driver turning all the time steps a wheel of \`slots\`
482
+ // slots on by one slot each turn, and locks it between steps. The driver's
483
+ // axle is at the origin and the wheel's at [distance, 0]. Cut the wheel and
484
+ // the locking disc from the same sheet, side by side in one plane, and the
485
+ // crank above them; a dowel pin of pin_d through the crank's outer hole
486
+ // runs in the wheel's slots.
487
+
488
+ // The radius of the circle the driver's pin turns on
489
+ function geneva_pin_radius(slots, distance) = distance * sin(180 / slots);
490
+ // The wheel's outer radius
491
+ function geneva_wheel_radius(slots, distance, pin_d) =
492
+ sqrt(pow(distance * cos(180 / slots), 2) + pow(pin_d / 2, 2));
493
+ // The locking disc's radius
494
+ function geneva_lock_radius(slots, distance, pin_d) = geneva_pin_radius(slots, distance) - pin_d;
495
+
496
+ // How far the wheel has turned when the driver has turned \`angle\`
497
+ // anticlockwise from its pin pointing at the wheel: it turns clockwise,
498
+ // 360 / slots each turn of the driver, and stands still between steps
499
+ function geneva_turn(slots, distance, angle) =
500
+ let (
501
+ k = floor((angle + 180) / 360),
502
+ t = angle - 360 * k,
503
+ rc = geneva_pin_radius(slots, distance),
504
+ on = 90 - 180 / slots,
505
+ step = abs(t) <= on ? atan2(-rc * sin(t), distance - rc * cos(t))
506
+ : t < 0 ? 180 / slots : -180 / slots
507
+ )
508
+ step - k * 360 / slots;
509
+
510
+ // The wheel, centred on the origin, a slot along -x (towards the driver
511
+ // when geneva_turn() is 0)
512
+ module geneva_wheel(slots, distance, pin_d = 6, bore = 6, clearance = 0.2, square = false) {
513
+ rc = geneva_pin_radius(slots, distance);
514
+ ro = geneva_wheel_radius(slots, distance, pin_d);
515
+ rl = geneva_lock_radius(slots, distance, pin_d);
516
+ w = pin_d + clearance;
517
+ inner = distance - rc - clearance;
518
+ assert(rl > 0, "the pin is too thick to leave a locking disc: make the distance longer or the pin thinner");
519
+ assert(inner - w / 2 > bore / 2 + 3, "the slots reach the axle: use more slots, a longer distance or a smaller bore");
520
+ difference() {
521
+ circle(r = ro);
522
+ for (j = [0:slots - 1]) rotate(180 + j * 360 / slots) {
523
+ hull() {
524
+ translate([inner, 0]) circle(d = w);
525
+ translate([ro + 1, -w / 2]) rect([1, w]);
526
+ }
527
+ // The locking arc between this slot and the next
528
+ rotate(180 / slots) translate([distance, 0]) circle(r = rl + clearance);
529
+ }
530
+ if (square) rect([bore, bore], center = true); else circle(d = bore);
531
+ }
532
+ }
533
+
534
+ // The locking disc that turns with the driver, its relief facing the pin's
535
+ // side (+x): cut away wherever the wheel's rim passes while the pin is in a
536
+ // slot, so the wheel turns then
537
+ module geneva_lock(slots, distance, pin_d = 6, bore = 6, clearance = 0.2, square = false) {
538
+ assert(geneva_lock_radius(slots, distance, pin_d) > bore / 2 + 3, "the locking disc is too small for its axle: make the distance longer, the pin thinner or the bore smaller");
539
+ ro = geneva_wheel_radius(slots, distance, pin_d);
540
+ assert(distance - ro - clearance >= bore / 2 + 2, str("the wheel passes within ", round(10 * (distance - ro - clearance)) / 10, " mm of the driver's axle: use a bore of at most ", floor(20 * (distance - ro - clearance - 2)) / 10, " mm or fewer slots"));
541
+ difference() {
542
+ circle(r = geneva_lock_radius(slots, distance, pin_d));
543
+ // Everywhere the wheel's rim passes while the pin is in a slot
544
+ on = 90 - 180 / slots;
545
+ n = max(2, ceil(2 * on / 3));
546
+ for (i = [0:n - 1]) hull() for (t = [-on + 2 * on * i / n, -on + 2 * on * (i + 1) / n])
547
+ translate([distance * cos(t), distance * sin(t)]) circle(r = ro + clearance);
548
+ if (square) rect([bore, bore], center = true); else circle(d = bore);
549
+ }
550
+ }
551
+
552
+ // The crank above the locking disc that carries the pin, along +x
553
+ module geneva_crank(slots, distance, pin_d = 6, bore = 6, width = 0, square = false) {
554
+ rc = geneva_pin_radius(slots, distance);
555
+ w = width > 0 ? width : max(pin_d, bore) + 8;
556
+ difference() {
557
+ hull() {
558
+ circle(d = w);
559
+ translate([rc, 0]) circle(d = pin_d + 8);
560
+ }
561
+ translate([rc, 0]) circle(d = pin_d);
562
+ if (square) rect([bore, bore], center = true); else circle(d = bore);
563
+ }
564
+ }
565
+
566
+ // A ratchet wheel of \`teeth\` teeth, radius r at their tips, \`depth\` deep,
567
+ // centred on the origin with a hole for its axle. It turns anticlockwise
568
+ // freely; a pawl() stops it turning back.
569
+ module ratchet(teeth, r, depth, bore = 6, square = false) {
570
+ p = 360 / teeth;
571
+ difference() {
572
+ polygon([for (k = [0:teeth - 1], j = [0, 1])
573
+ j == 0 ? [r * cos(k * p), r * sin(k * p)]
574
+ : [(r - depth) * cos((k + 1) * p), (r - depth) * sin((k + 1) * p)]]);
575
+ if (square) rect([bore, bore], center = true); else circle(d = bore);
576
+ }
577
+ }
578
+
579
+ // The angle of the tooth face a pawl rests on, nearest \`at\` degrees
580
+ function pawl_face(teeth, at = 90) = round(at / (360 / teeth)) * 360 / teeth;
581
+
582
+ // How far the pawl leans out from the wheel's edge, in degrees: past the
583
+ // teeth's slope, so it clears them
584
+ function pawl_lean(teeth, r, depth) = atan(depth / ((r - depth / 2) * 2 * PI / teeth)) + 15;
585
+
586
+ // The shortest pawl of this width that clears the teeth: its tip edge,
587
+ // along the tooth face, must end before its far end does
588
+ function pawl_min_length(teeth, r, depth, width = 8) =
589
+ width * (0.5 + tan(pawl_lean(teeth, r, depth))) + 2;
590
+
591
+ // The pawl's outline round the wheel's centre: its tip on the root by the
592
+ // tooth face, its far end, and back along the face. Its pivot is the
593
+ // middle of its far end. A length of 0 picks 0.8 * r, or longer if the
594
+ // pawl must be to clear the teeth; pawl() refuses a length given shorter
595
+ // than pawl_min_length().
596
+ function pawl_points(teeth, r, depth, length = 0, width = 8, at = 90, clearance = 0.2) =
597
+ let (
598
+ f = pawl_face(teeth, at),
599
+ g = pawl_lean(teeth, r, depth),
600
+ shortest = pawl_min_length(teeth, r, depth, width),
601
+ L = length > 0 ? length : max(r * 0.8, shortest),
602
+ n = [cos(f), sin(f)],
603
+ tc = [sin(f), -cos(f)],
604
+ u = cos(g) * tc + sin(g) * n,
605
+ v = cos(g) * n - sin(g) * tc,
606
+ T = (r - depth + clearance) * n + clearance * tc
607
+ )
608
+ [T, T + (L - width / 2) * u, T + (L - width / 2) * u + width * v, T + width / cos(g) * n];
609
+
610
+ // Where a pawl()'s pivot is, round the wheel's centre
611
+ function pawl_pivot(teeth, r, depth, length = 0, width = 8, at = 90, clearance = 0.2) =
612
+ let (p = pawl_points(teeth, r, depth, length, width, at, clearance)) (p[1] + p[2]) / 2;
613
+
614
+ // A pawl for a ratchet() of the same sizes, drawn where it works round
615
+ // the wheel's centre: give it the wheel's placement. Its tip rests against
616
+ // the tooth face nearest \`at\` degrees, and it turns on a pin through the
617
+ // hole at pawl_pivot(). Gravity, a rubber band or a spring wire holds it
618
+ // down on the teeth.
619
+ module pawl(teeth, r, depth, length = 0, width = 8, bore = 3, at = 90, clearance = 0.2) {
620
+ shortest = pawl_min_length(teeth, r, depth, width);
621
+ assert(length == 0 || length >= shortest, str("a pawl ", width, " mm wide must be at least ", ceil(2 * shortest) / 2, " mm long to clear the teeth: make it longer or narrower"));
622
+ p = pawl_points(teeth, r, depth, length, width, at, clearance);
623
+ H = (p[1] + p[2]) / 2;
624
+ difference() {
625
+ union() {
626
+ polygon(p);
627
+ translate(H) circle(d = width);
628
+ }
629
+ translate(H) circle(d = bore);
630
+ }
631
+ }
373
632
  `,"kerf/geo":`// kerf/geo: the world's land, for maps, globes and country-shaped pieces.
374
633
  // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
375
634
  // The land data is Natural Earth's 1:110m land (public domain,
@@ -1000,6 +1259,60 @@ module halved_pair(name, at = [0, 0, 0], cap = undef, feet = [], side_feet = und
1000
1259
  }
1001
1260
  }
1002
1261
  }
1262
+ `,"kerf/linkage":`// kerf/linkage: where the joints of a linkage are at a crank angle.
1263
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
1264
+ //
1265
+ // Each function gives the joint points of a linkage drawn flat, so a part
1266
+ // placed on a link and the link's length come from the same numbers. Use
1267
+ // them to place moving parts at a drive angle, and to check a linkage closes
1268
+ // over a whole turn.
1269
+
1270
+ // Where a circle of radius ra round a meets one of radius rb round b: the
1271
+ // point left of the line from a to b (side = 1) or right of it (side = -1).
1272
+ // undef when the circles don't meet: the links are too short or too long.
1273
+ function circle_meet(a, ra, b, rb, side = 1) =
1274
+ let (
1275
+ dx = b[0] - a[0],
1276
+ dy = b[1] - a[1],
1277
+ d = sqrt(dx * dx + dy * dy),
1278
+ along = d > 0 ? (ra * ra - rb * rb + d * d) / (2 * d) : 0,
1279
+ h2 = ra * ra - along * along
1280
+ )
1281
+ d == 0 || h2 < -1e-9 ? undef
1282
+ : let (h = sqrt(max(0, h2)), ux = dx / d, uy = dy / d)
1283
+ [a[0] + along * ux - side * h * uy, a[1] + along * uy + side * h * ux];
1284
+
1285
+ // A crank of radius r turning round the origin drives a slider along the
1286
+ // line y = offset through a connecting rod of length l. At the crank's
1287
+ // angle it gives [crank pin, slider pin]; undef if the rod can't reach.
1288
+ function slider_crank(r, l, angle, offset = 0) =
1289
+ let (
1290
+ pin = [r * cos(angle), r * sin(angle)],
1291
+ dy = offset - pin[1]
1292
+ )
1293
+ abs(dy) > l ? undef : [pin, [pin[0] + sqrt(l * l - dy * dy), offset]];
1294
+
1295
+ // How far the slider of slider_crank() travels from end to end
1296
+ function slider_stroke(r, l, offset = 0) =
1297
+ sqrt(pow(l + r, 2) - offset * offset) - sqrt(pow(l - r, 2) - offset * offset);
1298
+
1299
+ // A four-bar linkage: the crank turns round the origin, the rocker round
1300
+ // [ground, 0], and the coupler joins their ends. At the crank's angle it
1301
+ // gives [crank end, rocker end], the rocker end on the side \`side\` of the
1302
+ // line from the crank end to the rocker's pivot; undef where the links
1303
+ // can't close.
1304
+ function four_bar(ground, crank, coupler, rocker, angle, side = 1) =
1305
+ let (b = [crank * cos(angle), crank * sin(angle)], c = circle_meet(b, coupler, [ground, 0], rocker, side))
1306
+ is_undef(c) ? undef : [b, c];
1307
+
1308
+ // True when the crank of a four-bar linkage turns all the way round
1309
+ // (Grashof's rule, with the crank the shortest link)
1310
+ function four_bar_turns(ground, crank, coupler, rocker) =
1311
+ let (s = min(ground, crank, coupler, rocker), l = max(ground, crank, coupler, rocker))
1312
+ crank == s && s + l <= ground + crank + coupler + rocker - s - l;
1313
+
1314
+ // The angle in degrees of the line from a to b, from +x
1315
+ function link_angle(a, b) = atan2(b[1] - a[1], b[0] - a[0]);
1003
1316
  `,"kerf/lock":`// kerf/lock: a lock with a key, for boxes, diaries, chests and money boxes.
1004
1317
  // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
1005
1318
  //
@@ -1184,11 +1497,20 @@ function card_size(name) = let (s = lookup_size(name, CARD_SIZES))
1184
1497
  is_undef(s) ? assert(false, str("Unknown card size \\"", name, "\\". Known: ", size_names(CARD_SIZES))) : s;
1185
1498
 
1186
1499
  // Photo print sizes as [width, height], landscape: "4x6", "5x7", "8x10",
1187
- // "10x15" (cm), "13x18" (cm), "instax mini", "instax square", "instax wide",
1188
- // "polaroid".
1189
- function photo_size(name) = let (s = lookup_size(name, PHOTO_SIZES))
1500
+ // "10x15" (cm), "13x18" (cm), and instant film: "instant mini", "instant
1501
+ // square", "instant wide" and "instant classic".
1502
+ function photo_size(name) = let (s = lookup_size(lookup_alias(name, PHOTO_ALIASES), PHOTO_SIZES))
1190
1503
  is_undef(s) ? assert(false, str("Unknown photo size \\"", name, "\\". Known: ", size_names(PHOTO_SIZES))) : s;
1191
1504
 
1505
+ // A bought part's sizes by name, as a record: \`body\` [width, depth,
1506
+ // height], and for parts with one, the \`shaft\` diameter, the \`shaft_length\`
1507
+ // it stands out of the body and the \`hole\` to cut for it. Retail sizes vary:
1508
+ // measure yours. "music-18" (an 18-note wind-up music box movement, shaft
1509
+ // the winding key's), "quartz-clock" (a 56 mm quartz clock movement with
1510
+ // the 16.5 mm shaft for dials up to 8 mm thick), "marble-16" and "marble-25".
1511
+ function part_size(name) = let (s = lookup_size(name, PART_SIZES))
1512
+ is_undef(s) ? assert(false, str("Unknown part \\"", name, "\\". Known: ", size_names(PART_SIZES))) : s;
1513
+
1192
1514
  // A size turned to lie wider than tall
1193
1515
  function landscape(size) = size[0] >= size[1] ? size : [size[1], size[0]];
1194
1516
  // A size turned to stand taller than wide
@@ -1210,13 +1532,28 @@ CARD_SIZES = [
1210
1532
  ];
1211
1533
  PHOTO_SIZES = [
1212
1534
  ["4x6", [152.4, 101.6]], ["5x7", [177.8, 127]], ["8x10", [254, 203.2]],
1213
- ["10x15", [150, 100]], ["13x18", [180, 130]], ["instax mini", [54, 86]],
1214
- ["instax square", [72, 86]], ["instax wide", [108, 86]], ["polaroid", [88, 107]]
1535
+ ["10x15", [150, 100]], ["13x18", [180, 130]], ["instant mini", [54, 86]],
1536
+ ["instant square", [72, 86]], ["instant wide", [108, 86]], ["instant classic", [88, 107]]
1537
+ ];
1538
+ // Older names that still work, left out of the list of known names
1539
+ PHOTO_ALIASES = [
1540
+ ["instax mini", "instant mini"], ["instax square", "instant square"],
1541
+ ["instax wide", "instant wide"], ["polaroid", "instant classic"]
1542
+ ];
1543
+ PART_SIZES = [
1544
+ ["music-18", {body = [50, 44, 20], shaft = 3.5, hole = 6}],
1545
+ ["quartz-clock", {body = [56, 56, 16], shaft = 7.6, shaft_length = 16.5, hole = 8, dial = 8}],
1546
+ ["marble-16", {body = [16, 16, 16]}],
1547
+ ["marble-25", {body = [25, 25, 25]}]
1215
1548
  ];
1216
1549
 
1217
1550
  // The size of that name in a table of [name, size], ignoring case
1218
1551
  function lookup_size(name, table) = let (k = lower(name), hit = [for (e = table) if (lower(e[0]) == k) e[1]])
1219
1552
  len(hit) ? hit[0] : undef;
1553
+ // The name an older name stands for in a table of [old, new], or the name
1554
+ // itself
1555
+ function lookup_alias(name, aliases) = let (k = lower(name), hit = [for (e = aliases) if (lower(e[0]) == k) e[1]])
1556
+ len(hit) ? hit[0] : name;
1220
1557
  // The names in a table, for messages
1221
1558
  function size_names(table) = join([for (e = table) e[0]], ", ");
1222
1559
  `,"kerf/symbols":`// kerf/symbols: 867 pictograms by name, for engraving and cutting.
@@ -2219,10 +2556,10 @@ module tab_rect(size, edges = true, count = undef, width = undef) {
2219
2556
  if (e[2]) translate([w, h]) rotate(180) tabs(w, count, width);
2220
2557
  if (e[3]) translate([0, h]) rotate(270) tabs(h, count, width);
2221
2558
  }
2222
- `};var P="0.3";var u="kerf.json",H="kerf.lock",C="kerf_libraries",x=20<<20,R=2e3,X=/^[a-z0-9][a-z0-9_-]{0,63}$/,y1=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/,V1=/^(readme|licen[cs]e|copying|notice|changelog)(\.[a-z]+)?$/i,W=class extends Error{},c1=a=>{try{return m1(a).isFile()}catch{return!1}},y=a=>{try{return m1(a).isDirectory()}catch{return!1}},_=(a,c)=>a&&Object.prototype.hasOwnProperty.call(a,c)?a[c]:void 0,M=a=>{throw new W(a)};function r1(a,c){return(typeof a!="string"||!X.test(a))&&M(`${c} "${a}" is not a library name: use lowercase letters, digits, - and _`),a==="kerf"&&M(`${c}: "kerf" is the standard library's name`),a}function l1(a,c){(!a||typeof a!="object"||Array.isArray(a))&&M(`${c} must hold a JSON object`);let l=a;for(let n of["name","version","description","license","language"])l[n]!==void 0&&typeof l[n]!="string"&&M(`${c}: "${n}" must be a string`);l.name!==void 0&&r1(l.name,`${c}: name`),l.version!==void 0&&!y1.test(l.version)&&M(`${c}: "version" must look like 1.2.0, not "${l.version}"`),l.language!==void 0&&!/^\d+\.\d+$/.test(l.language)&&M(`${c}: "language" must look like ${P}, not "${l.language}"`),l.sheet!==void 0&&!(Array.isArray(l.sheet)&&l.sheet.length===2&&l.sheet.every(n=>typeof n=="number"&&Number.isFinite(n)&&n>0))&&M(`${c}: "sheet" must be [width, height] in mm, like [600, 400]`);let e=l.libraries??{};(!e||typeof e!="object"||Array.isArray(e))&&M(`${c}: "libraries" must be an object of name: source`);for(let[n,t]of Object.entries(e))r1(n,`${c}: library`),typeof t!="string"&&M(`${c}: the source of ${n} must be a string`);return{...l,libraries:{...e}}}function a1(a,c){let l;try{l=T(a,"utf8")}catch{return M(`${c} was not found`)}try{return JSON.parse(l)}catch(e){return M(`${c} is not valid JSON: ${e.message}`)}}function V(a,c=u){return l1(a1(z(a,u),c),c)}function M1(a){if(!I(z(a,H)))return;let c=a1(z(a,H),H);(c?.lockVersion!==1||!c.libraries||typeof c.libraries!="object")&&M(`${H} is not a kerf.lock this kerf can read. Delete it and run kerf install.`);for(let[l,e]of Object.entries(c.libraries))(!e||["source","resolved","integrity"].some(n=>typeof e[n]!="string"))&&M(`${H}: the entry for ${l} is damaged. Remove it and run kerf install.`);return c}function z1(a){for(let c=O(a);;){if(c1(z(c,u)))return c;let l=Y(c);if(l===c)return;c=l}}function n1(a){try{return V(a).name}catch{return}}function k1(a,c,l=c1){let e=(h,s)=>[z(h,s),z(h,s+".kerf")].find(i=>l(i));if(E(c))return[c,c+".kerf"].find(h=>l(h));let n=c.indexOf("/"),t=n>0?z1(a):void 0;if(t){let h=c.slice(0,n);if(h===n1(t))return e(t,c.slice(n+1));if(y(z(t,C,h)))return e(z(t,C),c)}return e(a,c)}function Q1(a){let c=Y(O(a));return l=>{let e=k1(c,l);return e===void 0?void 0:T(e,"utf8")}}function J1(a,c=200){let l=z1(a);if(!l)return[];let e=[],n=(s,i)=>{for(let o of[...d1(s,3)].sort()){if(e.length>=c)return;o.endsWith(".kerf")&&e.push(i+o.slice(0,-5))}},t=n1(l);t&&n(l,t+"/");let h=z(l,C);if(y(h))for(let s of Q(h).sort())X.test(s)&&y(z(h,s))&&n(z(h,s),s+"/");return e}function d1(a,c=1/0){let l=[],e=(n,t,h)=>{let s;try{s=Q(n,{withFileTypes:!0})}catch{return}for(let i of s){if(i.name.startsWith(".")||i.name==="node_modules"||i.name===C)continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?h<c&&e(z(n,i.name),o,h+1):i.isFile()&&(l.push(o),l.length>R&&M(`${a} has more than ${R} files`))}};return e(a,"",0),l}function F(a,c=()=>!0){let l=new Map;for(let e of d1(a))c(e)&&l.set(e,T(z(a,...e.split("/"))));return l}var e1=a=>a===u||a.endsWith(".kerf")||!a.includes("/")&&V1.test(a);function B(a){let c=L1("sha256");for(let l of[...a.keys()].sort()){let e=Buffer.from(a.get(l).toString("utf8").replace(/\r\n/g,`
2223
- `));c.update(`${l}\0${e.length}\0`),c.update(e)}return"sha256-"+c.digest("base64")}function o1(a){return a.kind==="folder"?"folder:"+(process.platform==="win32"?a.path.toLowerCase():a.path):a.kind==="github"?`github:${a.owner}/${a.repo}`.toLowerCase()+`@${a.ref}`:a.url}function Z(a,c){let l=/^github:([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:@(\S+))?$/.exec(a);if(l)return{kind:"github",owner:l[1],repo:l[2],ref:l[3]??"HEAD"};if(/^https?:\/\//i.test(a)){let n;try{n=new URL(a)}catch{return M(`${a} is not a link`)}return n.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(n.hostname)&&M(`Use https:// to download ${a}`),{kind:"url",url:a}}let e=a.startsWith("file:")?a.slice(5):a;return e.startsWith("./")||e.startsWith("../")||E(e)?{kind:"folder",path:O(c,e)}:M(`"${a}" is not a library source. Use github:owner/repo@tag, an https:// link to a .tar.gz, or a folder like ./my-library`)}async function q1(a,c){let l;try{l=await c(a)}catch(s){let i=s;return M(`Could not download ${a}: ${i.cause?.message??i.message}`)}l.ok||M(`Could not download ${a}: HTTP ${l.status}`+(l.status===404?". Check the name and the tag, and that it is public.":""));let e=()=>M(`${a} is larger than ${x>>20} MB`);if(Number(l.headers?.get("content-length"))>x&&e(),!l.body){let s=Buffer.from(await l.arrayBuffer());return s.length>x?e():s}let n=l.body.getReader(),t=[],h=0;for(;;){let{done:s,value:i}=await n.read();if(s||!i)break;h+=i.length,h>x&&(await n.cancel().catch(()=>{}),e()),t.push(i)}return Buffer.concat(t)}function x1(a,c){let l;try{l=C1(a,{maxOutputLength:5*x})}catch{return M(`${c} is not a .tar.gz file`)}let e=new Map,n,t={},h;for(let s=0;s+512<=l.length;){let i=l.subarray(s,s+512);if(i.every(g=>g===0))break;let o=(g,w)=>{let b=i.subarray(g,g+w),k=b.indexOf(0);return b.subarray(0,k<0?w:k).toString("utf8")},m=parseInt(o(124,12).trim()||"0",8);m>=0||M(`${c} is damaged`);let d=o(156,1)||"0",r=l.subarray(s+512,s+512+m);if(s+=512+Math.ceil(m/512)*512,d==="x"||d==="g"){let g=S1(r);d==="g"?n=g.comment??n:t=g;continue}if(d==="L"){h=r.toString("utf8").replace(/\0+$/,"");continue}let v=o(345,155),p=t.path??h??(v?v+"/":"")+o(0,100);t={},h=void 0,(d==="0"||d==="7")&&e.set(p,Buffer.from(r)),e.size>R&&M(`${c} has more than ${R} files`)}return{files:e,commit:n}}function S1(a){let c={};for(let l=0;l<a.length;){let e=a.indexOf(32,l),n=parseInt(a.subarray(l,e).toString(),10);if(!(n>0)||e<0)break;let t=a.subarray(e+1,l+n-1).toString("utf8"),h=t.indexOf("=");h>0&&(c[t.slice(0,h)]=t.slice(h+1)),l+=n}return c}function v1(a,c){let l=new Map;for(let[t,h]of a){let s=t.replace(/^\.\//,""),i=s.split("/");(E(s)||s.includes("\\")||s.includes(":")||i.some(o=>o===".."||o===""))&&M(`${c} holds a file outside its folder: ${t}`),l.set(s,h)}let e="";if(!l.has(u)){let t=new Set([...l.keys()].map(h=>h.split("/")[0]));t.size===1&&(e=[...t][0]+"/")}let n=new Map;for(let[t,h]of l){if(!t.startsWith(e))continue;let s=t.slice(e.length);s.split("/").some(i=>i.startsWith(".")||i===C||i==="node_modules")||e1(s)&&n.set(s,h)}return n.has(u)||M(`${c} has no kerf.json at its top. Is it a KerfScript library?`),n}var _1=(a,c)=>{let[l,e]=a.split(".").map(Number),[n,t]=c.split(".").map(Number);return l>n||l===n&&e>t};async function f1(a,c,l,e,n){let t=Z(a,c),h,s;if(t.kind==="folder")c1(z(t.path,u))||M(`${a}: no kerf.json in ${t.path}. Is it a KerfScript library?`),h=v1(F(t.path,e1),a),s=w1(l,t.path).split(A1).join("/")||".",!s.startsWith(".")&&!E(s)&&(s="./"+s);else{let o=t.kind==="github"?`https://github.com/${t.owner}/${t.repo}/archive/${t.ref}.tar.gz`:t.url,m=n.get(o)??await q1(o,e);n.set(o,m);let d=x1(m,a);h=v1(d.files,a),s=t.kind==="github"&&/^[0-9a-f]{40}$/.test(d.commit??"")?`https://github.com/${t.owner}/${t.repo}/archive/${d.commit}.tar.gz`:o}let i=l1(JSON.parse(h.get(u).toString("utf8")),`the kerf.json of ${a}`);return i.name||M(`${a}: its kerf.json has no "name", so it is not a library`),i.language&&_1(i.language,P)&&M(`${i.name} needs KerfScript language ${i.language} or later, and this kerf has ${P}. Update kerf.`),{manifest:i,files:h,resolved:s,integrity:B(h)}}function T1(a,c){J(a,{recursive:!0,force:!0});for(let[l,e]of c){let n=z(a,...l.split("/"));b1(Y(n),{recursive:!0}),S(n,e)}}var j1=a=>{let c=[...a].sort(([l],[e])=>l<e?-1:1);return JSON.stringify({lockVersion:1,libraries:Object.fromEntries(c)},null,2)+`
2224
- `};async function $1(a,c={}){let l=c.fetch??globalThis.fetch,e=c.log??(()=>{}),n=c.cache??new Map,t=V(a),h=M1(a),s=new Map,i=Object.entries(t.libraries).map(([r,v])=>({name:r,source:v,base:a,from:u})),o=z(a,C);for(;i.length;){let{name:r,source:v,base:p,from:g}=i.shift(),w=Z(v,p),b=w.kind==="folder",k=b?`${v} (${w.path})`:v,j=s.get(r);if(j){j.at!==o1(w)&&!_(t.libraries,r)&&M(`${g} uses ${r} from ${k}, and ${j.from} uses it from ${j.shown}. Add ${r} to kerf.json with the source to use.`);continue}let G=_(h?.libraries,r),L=G?.source===v&&(!b||O(a,G.resolved)===w.path)?G:void 0;c.frozen&&!L&&M(`kerf.lock does not pin ${r} from ${v}. Run kerf install without --frozen.`);let $=z(o,r),q;if(L&&!b&&y($)&&B(F($))===L.integrity)q=L;else{let f=await f1(L&&!b?L.resolved:v,b?p:a,a,l,n);f.manifest.name!==r&&M(`${v} is the library "${f.manifest.name}", so ${g} must call it ${f.manifest.name}, not ${r}`),L&&f.integrity!==L.integrity&&(!b||c.frozen)&&M(b?`${r} in ${v} changed since kerf.lock pinned it. Run kerf install without --frozen.`:`${r} from ${L.resolved} no longer matches kerf.lock. If you trust the change, remove ${r} from kerf.lock and run kerf install again.`),T1($,f.files),q={source:v,...f.manifest.version?{version:f.manifest.version}:{},resolved:f.resolved,integrity:f.integrity},(!L||L.integrity!==f.integrity||!b)&&e(`${L?"Restored":"Installed"} ${r}${q.version?" "+q.version:""} from ${v}`)}s.set(r,{entry:q,at:o1(w),shown:k,from:g});let t1=w.kind==="folder"?w.path:void 0;for(let[f,K]of Object.entries(V($,`${C}/${r}/${u}`).libraries))Z(K,a).kind==="folder"&&!t1&&M(`${r} uses ${f} from the folder ${K}: a published library needs github: or https: sources`),i.push({name:f,source:K,base:t1??a,from:r})}let m=j1(new Map([...s].map(([r,v])=>[r,v.entry]))),d=I(z(a,H))?T(z(a,H),"utf8"):"";if(c.frozen&&m!==d.replace(/\r\n/g,`
2225
- `)&&M("kerf.lock is out of date. Run kerf install without --frozen."),y(o))for(let r of Q(o,{withFileTypes:!0}))r.isDirectory()&&X.test(r.name)&&!s.has(r.name)&&(J(z(o,r.name),{recursive:!0,force:!0}),e(`Removed ${r.name}`));return m!==d.replace(/\r\n/g,`
2226
- `)&&S(z(a,H),m),JSON.parse(m)}function Y1(a){let c=V(a),l=M1(a),e=Object.keys(c.libraries);if(!l)return e.length?["kerf.lock is missing. Run kerf install."]:[];let n=[],t=new Set,h=[...e];for(;h.length;){let s=h.shift();if(t.has(s))continue;t.add(s);let i=_(l.libraries,s);if(!i){n.push(`${s} is not in kerf.lock. Run kerf install.`);continue}e.includes(s)&&i.source!==c.libraries[s]&&n.push(`kerf.json takes ${s} from ${c.libraries[s]}, and kerf.lock from ${i.source}. Run kerf install.`);let o=z(a,C,s);if(!y(o)){n.push(`${s} is not in ${C}. Run kerf install.`);continue}B(F(o))!==i.integrity&&n.push(`The files in ${C}/${s} differ from kerf.lock. Run kerf install.`);try{h.push(...Object.keys(V(o).libraries))}catch(m){n.push(m.message)}}for(let s of Object.keys(l.libraries))t.has(s)||n.push(`kerf.lock pins ${s}, which nothing uses any more.`);return n}function P1(a,c){let l=z(a,u),e=I(l)?a1(l,u):{};l1(e,u);let n={...e.libraries??{}};return c(n),e.libraries=n,{file:l,before:I(l)?T(l,"utf8"):void 0,raw:e}}async function u1(a,c,l){let{file:e,before:n,raw:t}=P1(a,c);S(e,JSON.stringify(t,null,2)+`
2227
- `);try{return await $1(a,l)}catch(h){throw n===void 0?J(e,{force:!0}):S(e,n),h}}async function X1(a,c,l={}){let e=new Map,t=(await f1(c,a,a,l.fetch??globalThis.fetch,e)).manifest.name;t===n1(a)&&M(`This project is the library ${t}; it cannot use itself`);let h=await u1(a,s=>void(s[t]=c),{...l,cache:e});return{name:t,lock:h}}async function c0(a,c,l={}){return u1(a,e=>{_(e,c)===void 0&&M(`kerf.json has no library named ${c}`),delete e[c]},l)}function U(a,c=[]){if(Array.isArray(a))for(let l of a)U(l,c);else if(a&&typeof a=="object"){let l=a;if(l.kind==="use"&&typeof l.path=="string")c.push({path:l.path,line:l.pos.line});else for(let e of Object.values(l))U(e,c)}return c}function I1(a){let c=[];for(let[l,e]of a){let n=Buffer.alloc(512),t=l,h="";if(Buffer.byteLength(t)>100){let i=l.lastIndexOf("/",155);(i<0||Buffer.byteLength(l.slice(i+1))>100)&&M(`${l}: the path is too long to pack`),h=l.slice(0,i),t=l.slice(i+1)}n.write(t,0,100),n.write("0000644\0",100),n.write("0000000\0",108),n.write("0000000\0",116),n.write(e.length.toString(8).padStart(11,"0")+"\0",124),n.write("00000000000\0",136),n.fill(32,148,156),n.write("0",156),n.write("ustar\0",257),n.write("00",263),n.write(h,345,155);let s=0;for(let i of n)s+=i;n.write(s.toString(8).padStart(6,"0")+"\0 ",148),c.push(n,e,Buffer.alloc((512-e.length%512)%512))}return c.push(Buffer.alloc(1024)),H1(Buffer.concat(c),{level:9})}function l0(a,c){let l=V(a),e=l.name??M('kerf.json needs a "name" to pack a library'),n=l.version??M('kerf.json needs a "version", like 1.0.0'),t=F(a,e1),h=[];for(let[m,d]of Object.entries(l.libraries))Z(d,a).kind==="folder"&&h.push(`kerf.json: ${m} comes from a folder; a published library needs github: or https: sources`);let s=m=>t.has(m)||t.has(m+".kerf");for(let[m,d]of t){if(!m.endsWith(".kerf"))continue;let r;try{r=h1(d.toString("utf8"),`${e}/${m}`).program}catch(v){h.push(`${m}: ${v.message}`);continue}for(let v of U(r)){let p=v.path.split("/")[0];Object.prototype.hasOwnProperty.call(i1,v.path)||p===e&&s(v.path.slice(e.length+1))||v.path.includes("/")&&_(l.libraries,p)!==void 0||h.push(`${m}, line ${v.line}: <${v.path}> will not be found once the library is installed`+(s(v.path)?`. Write <${e}/${v.path}> for the library's own file.`:"."))}}[...t.keys()].some(m=>m.endsWith(".kerf"))||h.push("There are no .kerf files to pack"),h.length&&M(h.join(`
2228
- `));let i=[...t.keys()].sort().map(m=>[`${e}/${m}`,t.get(m)]),o=c??z(a,`${e}-${n}.tar.gz`);return S(o,I1(i)),{file:o,name:e,version:n,files:t.size,integrity:B(t)}}export{C as FOLDER,H as LOCK,W as LibraryError,u as MANIFEST,X1 as add,Y1 as check,z1 as findProject,$1 as install,J1 as installedPaths,B as integrity,k1 as libraryFile,l0 as pack,M1 as readLock,V as readManifest,c0 as remove,Q1 as resolver};
2559
+ `};var P="0.3";var u="kerf.json",C="kerf.lock",y="kerf_libraries",x=20<<20,R=2e3,X=/^[a-z0-9][a-z0-9_-]{0,63}$/,H1=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/,k1=/^(readme|licen[cs]e|copying|notice|changelog)(\.[a-z]+)?$/i,W=class extends Error{},c1=a=>{try{return m1(a).isFile()}catch{return!1}},H=a=>{try{return m1(a).isDirectory()}catch{return!1}},S=(a,c)=>a&&Object.prototype.hasOwnProperty.call(a,c)?a[c]:void 0,M=a=>{throw new W(a)};function r1(a,c){return(typeof a!="string"||!X.test(a))&&M(`${c} "${a}" is not a library name: use lowercase letters, digits, - and _`),a==="kerf"&&M(`${c}: "kerf" is the standard library's name`),a}function l1(a,c){(!a||typeof a!="object"||Array.isArray(a))&&M(`${c} must hold a JSON object`);let l=a;for(let n of["name","version","description","license","language"])l[n]!==void 0&&typeof l[n]!="string"&&M(`${c}: "${n}" must be a string`);l.name!==void 0&&r1(l.name,`${c}: name`),l.version!==void 0&&!H1.test(l.version)&&M(`${c}: "version" must look like 1.2.0, not "${l.version}"`),l.language!==void 0&&!/^\d+\.\d+$/.test(l.language)&&M(`${c}: "language" must look like ${P}, not "${l.language}"`),l.sheet!==void 0&&!(Array.isArray(l.sheet)&&l.sheet.length===2&&l.sheet.every(n=>typeof n=="number"&&Number.isFinite(n)&&n>0))&&M(`${c}: "sheet" must be [width, height] in mm, like [600, 400]`);let e=l.libraries??{};(!e||typeof e!="object"||Array.isArray(e))&&M(`${c}: "libraries" must be an object of name: source`);for(let[n,t]of Object.entries(e))r1(n,`${c}: library`),typeof t!="string"&&M(`${c}: the source of ${n} must be a string`);return{...l,libraries:{...e}}}function a1(a,c){let l;try{l=T(a,"utf8")}catch{return M(`${c} was not found`)}try{return JSON.parse(l)}catch(e){return M(`${c} is not valid JSON: ${e.message}`)}}function k(a,c=u){return l1(a1(d(a,u),c),c)}function M1(a){if(!I(d(a,C)))return;let c=a1(d(a,C),C);(c?.lockVersion!==1||!c.libraries||typeof c.libraries!="object")&&M(`${C} is not a kerf.lock this kerf can read. Delete it and run kerf install.`);for(let[l,e]of Object.entries(c.libraries))(!e||["source","resolved","integrity"].some(n=>typeof e[n]!="string"))&&M(`${C}: the entry for ${l} is damaged. Remove it and run kerf install.`);return c}function d1(a){for(let c=O(a);;){if(c1(d(c,u)))return c;let l=Y(c);if(l===c)return;c=l}}function n1(a){try{return k(a).name}catch{return}}function V1(a,c,l=c1){let e=(h,s)=>[d(h,s),d(h,s+".kerf")].find(i=>l(i));if(E(c))return[c,c+".kerf"].find(h=>l(h));let n=c.indexOf("/"),t=n>0?d1(a):void 0;if(t){let h=c.slice(0,n);if(h===n1(t))return e(t,c.slice(n+1));if(H(d(t,y,h)))return e(d(t,y),c)}return e(a,c)}function Q1(a){let c=Y(O(a));return l=>{let e=V1(c,l);return e===void 0?void 0:T(e,"utf8")}}function J1(a,c=200){let l=d1(a);if(!l)return[];let e=[],n=(s,i)=>{for(let o of[...z1(s,3)].sort()){if(e.length>=c)return;o.endsWith(".kerf")&&e.push(i+o.slice(0,-5))}},t=n1(l);t&&n(l,t+"/");let h=d(l,y);if(H(h))for(let s of Q(h).sort())X.test(s)&&H(d(h,s))&&n(d(h,s),s+"/");return e}function z1(a,c=1/0){let l=[],e=(n,t,h)=>{let s;try{s=Q(n,{withFileTypes:!0})}catch{return}for(let i of s){if(i.name.startsWith(".")||i.name==="node_modules"||i.name===y)continue;let o=t?`${t}/${i.name}`:i.name;i.isDirectory()?h<c&&e(d(n,i.name),o,h+1):i.isFile()&&(l.push(o),l.length>R&&M(`${a} has more than ${R} files`))}};return e(a,"",0),l}function G(a,c=()=>!0){let l=new Map;for(let e of z1(a))c(e)&&l.set(e,T(d(a,...e.split("/"))));return l}var e1=a=>a===u||a.endsWith(".kerf")||!a.includes("/")&&k1.test(a);function F(a){let c=b1("sha256");for(let l of[...a.keys()].sort()){let e=Buffer.from(a.get(l).toString("utf8").replace(/\r\n/g,`
2560
+ `));c.update(`${l}\0${e.length}\0`),c.update(e)}return"sha256-"+c.digest("base64")}function o1(a){return a.kind==="folder"?"folder:"+(process.platform==="win32"?a.path.toLowerCase():a.path):a.kind==="github"?`github:${a.owner}/${a.repo}`.toLowerCase()+`@${a.ref}`:a.url}function Z(a,c){let l=/^github:([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:@(\S+))?$/.exec(a);if(l)return{kind:"github",owner:l[1],repo:l[2],ref:l[3]??"HEAD"};if(/^https?:\/\//i.test(a)){let n;try{n=new URL(a)}catch{return M(`${a} is not a link`)}return n.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(n.hostname)&&M(`Use https:// to download ${a}`),{kind:"url",url:a}}let e=a.startsWith("file:")?a.slice(5):a;return e.startsWith("./")||e.startsWith("../")||E(e)?{kind:"folder",path:O(c,e)}:M(`"${a}" is not a library source. Use github:owner/repo@tag, an https:// link to a .tar.gz, or a folder like ./my-library`)}async function q1(a,c){let l;try{l=await c(a)}catch(s){let i=s;return M(`Could not download ${a}: ${i.cause?.message??i.message}`)}l.ok||M(`Could not download ${a}: HTTP ${l.status}`+(l.status===404?". Check the name and the tag, and that it is public.":""));let e=()=>M(`${a} is larger than ${x>>20} MB`);if(Number(l.headers?.get("content-length"))>x&&e(),!l.body){let s=Buffer.from(await l.arrayBuffer());return s.length>x?e():s}let n=l.body.getReader(),t=[],h=0;for(;;){let{done:s,value:i}=await n.read();if(s||!i)break;h+=i.length,h>x&&(await n.cancel().catch(()=>{}),e()),t.push(i)}return Buffer.concat(t)}function x1(a,c){let l;try{l=y1(a,{maxOutputLength:5*x})}catch{return M(`${c} is not a .tar.gz file`)}let e=new Map,n,t={},h;for(let s=0;s+512<=l.length;){let i=l.subarray(s,s+512);if(i.every(g=>g===0))break;let o=(g,L)=>{let w=i.subarray(g,g+L),V=w.indexOf(0);return w.subarray(0,V<0?L:V).toString("utf8")},m=parseInt(o(124,12).trim()||"0",8);m>=0||M(`${c} is damaged`);let z=o(156,1)||"0",r=l.subarray(s+512,s+512+m);if(s+=512+Math.ceil(m/512)*512,z==="x"||z==="g"){let g=_1(r);z==="g"?n=g.comment??n:t=g;continue}if(z==="L"){h=r.toString("utf8").replace(/\0+$/,"");continue}let v=o(345,155),p=t.path??h??(v?v+"/":"")+o(0,100);t={},h=void 0,(z==="0"||z==="7")&&e.set(p,Buffer.from(r)),e.size>R&&M(`${c} has more than ${R} files`)}return{files:e,commit:n}}function _1(a){let c={};for(let l=0;l<a.length;){let e=a.indexOf(32,l),n=parseInt(a.subarray(l,e).toString(),10);if(!(n>0)||e<0)break;let t=a.subarray(e+1,l+n-1).toString("utf8"),h=t.indexOf("=");h>0&&(c[t.slice(0,h)]=t.slice(h+1)),l+=n}return c}function v1(a,c){let l=new Map;for(let[t,h]of a){let s=t.replace(/^\.\//,""),i=s.split("/");(E(s)||s.includes("\\")||s.includes(":")||i.some(o=>o===".."||o===""))&&M(`${c} holds a file outside its folder: ${t}`),l.set(s,h)}let e="";if(!l.has(u)){let t=new Set([...l.keys()].map(h=>h.split("/")[0]));t.size===1&&(e=[...t][0]+"/")}let n=new Map;for(let[t,h]of l){if(!t.startsWith(e))continue;let s=t.slice(e.length);s.split("/").some(i=>i.startsWith(".")||i===y||i==="node_modules")||e1(s)&&n.set(s,h)}return n.has(u)||M(`${c} has no kerf.json at its top. Is it a KerfScript library?`),n}var S1=(a,c)=>{let[l,e]=a.split(".").map(Number),[n,t]=c.split(".").map(Number);return l>n||l===n&&e>t};async function f1(a,c,l,e,n){let t=Z(a,c),h,s;if(t.kind==="folder")c1(d(t.path,u))||M(`${a}: no kerf.json in ${t.path}. Is it a KerfScript library?`),h=v1(G(t.path,e1),a),s=L1(l,t.path).split(A1).join("/")||".",!s.startsWith(".")&&!E(s)&&(s="./"+s);else{let o=t.kind==="github"?`https://github.com/${t.owner}/${t.repo}/archive/${t.ref}.tar.gz`:t.url,m=n.get(o)??await q1(o,e);n.set(o,m);let z=x1(m,a);h=v1(z.files,a),s=t.kind==="github"&&/^[0-9a-f]{40}$/.test(z.commit??"")?`https://github.com/${t.owner}/${t.repo}/archive/${z.commit}.tar.gz`:o}let i=l1(JSON.parse(h.get(u).toString("utf8")),`the kerf.json of ${a}`);return i.name||M(`${a}: its kerf.json has no "name", so it is not a library`),i.language&&S1(i.language,P)&&M(`${i.name} needs KerfScript language ${i.language} or later, and this kerf has ${P}. Update kerf.`),{manifest:i,files:h,resolved:s,integrity:F(h)}}function T1(a,c){J(a,{recursive:!0,force:!0});for(let[l,e]of c){let n=d(a,...l.split("/"));w1(Y(n),{recursive:!0}),_(n,e)}}var j1=a=>{let c=[...a].sort(([l],[e])=>l<e?-1:1);return JSON.stringify({lockVersion:1,libraries:Object.fromEntries(c)},null,2)+`
2561
+ `};async function $1(a,c={}){let l=c.fetch??globalThis.fetch,e=c.log??(()=>{}),n=c.cache??new Map,t=k(a),h=M1(a),s=new Map,i=Object.entries(t.libraries).map(([r,v])=>({name:r,source:v,base:a,from:u})),o=d(a,y);for(;i.length;){let{name:r,source:v,base:p,from:g}=i.shift(),L=Z(v,p),w=L.kind==="folder",V=w?`${v} (${L.path})`:v,j=s.get(r);if(j){j.at!==o1(L)&&!S(t.libraries,r)&&M(`${g} uses ${r} from ${V}, and ${j.from} uses it from ${j.shown}. Add ${r} to kerf.json with the source to use.`);continue}let B=S(h?.libraries,r),b=B?.source===v&&(!w||O(a,B.resolved)===L.path)?B:void 0;c.frozen&&!b&&M(`kerf.lock does not pin ${r} from ${v}. Run kerf install without --frozen.`);let $=d(o,r),q;if(b&&!w&&H($)&&F(G($))===b.integrity)q=b;else{let f=await f1(b&&!w?b.resolved:v,w?p:a,a,l,n);f.manifest.name!==r&&M(`${v} is the library "${f.manifest.name}", so ${g} must call it ${f.manifest.name}, not ${r}`),b&&f.integrity!==b.integrity&&(!w||c.frozen)&&M(w?`${r} in ${v} changed since kerf.lock pinned it. Run kerf install without --frozen.`:`${r} from ${b.resolved} no longer matches kerf.lock. If you trust the change, remove ${r} from kerf.lock and run kerf install again.`),T1($,f.files),q={source:v,...f.manifest.version?{version:f.manifest.version}:{},resolved:f.resolved,integrity:f.integrity},(!b||b.integrity!==f.integrity||!w)&&e(`${b?"Restored":"Installed"} ${r}${q.version?" "+q.version:""} from ${v}`)}s.set(r,{entry:q,at:o1(L),shown:V,from:g});let t1=L.kind==="folder"?L.path:void 0;for(let[f,K]of Object.entries(k($,`${y}/${r}/${u}`).libraries))Z(K,a).kind==="folder"&&!t1&&M(`${r} uses ${f} from the folder ${K}: a published library needs github: or https: sources`),i.push({name:f,source:K,base:t1??a,from:r})}let m=j1(new Map([...s].map(([r,v])=>[r,v.entry]))),z=I(d(a,C))?T(d(a,C),"utf8"):"";if(c.frozen&&m!==z.replace(/\r\n/g,`
2562
+ `)&&M("kerf.lock is out of date. Run kerf install without --frozen."),H(o))for(let r of Q(o,{withFileTypes:!0}))r.isDirectory()&&X.test(r.name)&&!s.has(r.name)&&(J(d(o,r.name),{recursive:!0,force:!0}),e(`Removed ${r.name}`));return m!==z.replace(/\r\n/g,`
2563
+ `)&&_(d(a,C),m),JSON.parse(m)}function Y1(a){let c=k(a),l=M1(a),e=Object.keys(c.libraries);if(!l)return e.length?["kerf.lock is missing. Run kerf install."]:[];let n=[],t=new Set,h=[...e];for(;h.length;){let s=h.shift();if(t.has(s))continue;t.add(s);let i=S(l.libraries,s);if(!i){n.push(`${s} is not in kerf.lock. Run kerf install.`);continue}e.includes(s)&&i.source!==c.libraries[s]&&n.push(`kerf.json takes ${s} from ${c.libraries[s]}, and kerf.lock from ${i.source}. Run kerf install.`);let o=d(a,y,s);if(!H(o)){n.push(`${s} is not in ${y}. Run kerf install.`);continue}F(G(o))!==i.integrity&&n.push(`The files in ${y}/${s} differ from kerf.lock. Run kerf install.`);try{h.push(...Object.keys(k(o).libraries))}catch(m){n.push(m.message)}}for(let s of Object.keys(l.libraries))t.has(s)||n.push(`kerf.lock pins ${s}, which nothing uses any more.`);return n}function P1(a,c){let l=d(a,u),e=I(l)?a1(l,u):{};l1(e,u);let n={...e.libraries??{}};return c(n),e.libraries=n,{file:l,before:I(l)?T(l,"utf8"):void 0,raw:e}}async function u1(a,c,l){let{file:e,before:n,raw:t}=P1(a,c);_(e,JSON.stringify(t,null,2)+`
2564
+ `);try{return await $1(a,l)}catch(h){throw n===void 0?J(e,{force:!0}):_(e,n),h}}async function X1(a,c,l={}){let e=new Map,t=(await f1(c,a,a,l.fetch??globalThis.fetch,e)).manifest.name;t===n1(a)&&M(`This project is the library ${t}; it cannot use itself`);let h=await u1(a,s=>void(s[t]=c),{...l,cache:e});return{name:t,lock:h}}async function c0(a,c,l={}){return u1(a,e=>{S(e,c)===void 0&&M(`kerf.json has no library named ${c}`),delete e[c]},l)}function U(a,c=[]){if(Array.isArray(a))for(let l of a)U(l,c);else if(a&&typeof a=="object"){let l=a;if(l.kind==="use"&&typeof l.path=="string")c.push({path:l.path,line:l.pos.line});else for(let e of Object.values(l))U(e,c)}return c}function I1(a){let c=[];for(let[l,e]of a){let n=Buffer.alloc(512),t=l,h="";if(Buffer.byteLength(t)>100){let i=l.lastIndexOf("/",155);(i<0||Buffer.byteLength(l.slice(i+1))>100)&&M(`${l}: the path is too long to pack`),h=l.slice(0,i),t=l.slice(i+1)}n.write(t,0,100),n.write("0000644\0",100),n.write("0000000\0",108),n.write("0000000\0",116),n.write(e.length.toString(8).padStart(11,"0")+"\0",124),n.write("00000000000\0",136),n.fill(32,148,156),n.write("0",156),n.write("ustar\0",257),n.write("00",263),n.write(h,345,155);let s=0;for(let i of n)s+=i;n.write(s.toString(8).padStart(6,"0")+"\0 ",148),c.push(n,e,Buffer.alloc((512-e.length%512)%512))}return c.push(Buffer.alloc(1024)),C1(Buffer.concat(c),{level:9})}function l0(a,c){let l=k(a),e=l.name??M('kerf.json needs a "name" to pack a library'),n=l.version??M('kerf.json needs a "version", like 1.0.0'),t=G(a,e1),h=[];for(let[m,z]of Object.entries(l.libraries))Z(z,a).kind==="folder"&&h.push(`kerf.json: ${m} comes from a folder; a published library needs github: or https: sources`);let s=m=>t.has(m)||t.has(m+".kerf");for(let[m,z]of t){if(!m.endsWith(".kerf"))continue;let r;try{r=h1(z.toString("utf8"),`${e}/${m}`).program}catch(v){h.push(`${m}: ${v.message}`);continue}for(let v of U(r)){let p=v.path.split("/")[0];Object.prototype.hasOwnProperty.call(i1,v.path)||p===e&&s(v.path.slice(e.length+1))||v.path.includes("/")&&S(l.libraries,p)!==void 0||h.push(`${m}, line ${v.line}: <${v.path}> will not be found once the library is installed`+(s(v.path)?`. Write <${e}/${v.path}> for the library's own file.`:"."))}}[...t.keys()].some(m=>m.endsWith(".kerf"))||h.push("There are no .kerf files to pack"),h.length&&M(h.join(`
2565
+ `));let i=[...t.keys()].sort().map(m=>[`${e}/${m}`,t.get(m)]),o=c??d(a,`${e}-${n}.tar.gz`);return _(o,I1(i)),{file:o,name:e,version:n,files:t.size,integrity:F(t)}}export{y as FOLDER,C as LOCK,W as LibraryError,u as MANIFEST,X1 as add,Y1 as check,d1 as findProject,$1 as install,J1 as installedPaths,F as integrity,V1 as libraryFile,l0 as pack,M1 as readLock,k as readManifest,c0 as remove,Q1 as resolver};
@@ -337,7 +337,7 @@ var SIGNATURES = [
337
337
  params: [p("draw", "Draw the first child too", "false")],
338
338
  children: true,
339
339
  section: "Combining",
340
- doc: "Set $bounds = [x0, y0, x1, y1] of the first child for the children after it"
340
+ doc: "Set $bounds = [x0, y0, x1, y1], $area and $centroid = [x, y] of the first child for the children after it"
341
341
  },
342
342
  {
343
343
  name: "fill_holes",
@@ -445,6 +445,7 @@ var SIGNATURES = [
445
445
  named("rotate", "How the part is turned in the assembled view, [x, y, z] in degrees"),
446
446
  named("stack", "Layers glued in a stack at each placement, one thickness apart", "1"),
447
447
  named("mirror", "Cut the part mirrored left to right, its text still reading", "false"),
448
+ named("material", "The material it is cut from, as material(name = ...) sets it"),
448
449
  named("bend", "Living hinge bends in the assembled view: [x0, x1, angle] or a list"),
449
450
  named("on", "The name of a bent part this one is glued to, to move with it"),
450
451
  named("slots", "Names of parts whose tabs pass through this one: their slots are cut"),
@@ -495,11 +496,12 @@ var SIGNATURES = [
495
496
  kind: "module",
496
497
  params: [
497
498
  p("kind", 'What it is, as "dowel", "screw", "magnet", "elastic" or "paper"', '"dowel"'),
498
- p("from", "One end, [x, y, z]"),
499
- p("to", "The other end, [x, y, z]"),
499
+ p("from", "One end, [x, y, z]; a ball sits midway between from and to"),
500
+ p("to", "The other end, [x, y, z]; a ball may leave it out"),
500
501
  p("size", "Diameter, or [width, height] for a flat section", "6"),
501
502
  named("up", "The direction a [width, height] section's height points"),
502
- named("sides", "Sides of a round section in the 3D view", "24"),
503
+ named("sides", "Sides of a round section in the 3D view; 0 makes a ball", "24"),
504
+ named("shape", '"rod", or "ball" for a bulb, a marble or a bead', '"rod"'),
503
505
  named("label", "The name in the hardware list")
504
506
  ],
505
507
  children: true,
@@ -656,6 +658,18 @@ var SIGNATURES = [
656
658
  section: "Numbers and vectors",
657
659
  doc: "Interpolate between numbers or vectors"
658
660
  },
661
+ {
662
+ name: "train_for",
663
+ kind: "function",
664
+ params: [
665
+ p("ratio", "Turns in for one turn out; under 1 speeds up"),
666
+ p("stages", "Pairs of gears, 1 to 3", "2"),
667
+ p("pinion", "Fewest and most teeth of the small gears", "[10, 20]"),
668
+ p("wheel", "Fewest and most teeth of the big gears", "[20, 80]")
669
+ ],
670
+ section: "Numbers and vectors",
671
+ doc: "Tooth counts for a gear train nearest a ratio: {stages = [[driver, driven], ...], ratio, error}"
672
+ },
659
673
  {
660
674
  name: "norm",
661
675
  kind: "function",
@@ -678,6 +692,17 @@ var SIGNATURES = [
678
692
  section: "Paths and rotations",
679
693
  doc: "The length of the lines through a list of points"
680
694
  },
695
+ {
696
+ name: "offset_path",
697
+ kind: "function",
698
+ params: [
699
+ p("points", "A list of [x, y] points"),
700
+ p("d", "How far to move it: to the left going along it, or the right when less than 0"),
701
+ p("closed", "The path goes round, its last point joined to its first", "false")
702
+ ],
703
+ section: "Paths and rotations",
704
+ doc: "The path moved sideways, each corner mitred: the two edges of a strip along a curve"
705
+ },
681
706
  {
682
707
  name: "point_at",
683
708
  kind: "function",