@mylasertools/kerfscript 0.4.0 → 0.5.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/LANGUAGE.md +26 -11
  3. package/README.md +65 -2
  4. package/dist/ast.d.cts +13 -1
  5. package/dist/ast.d.ts +13 -1
  6. package/dist/cli.js +4734 -1405
  7. package/dist/diagnostics.d.cts +6 -0
  8. package/dist/diagnostics.d.ts +6 -0
  9. package/dist/evaluator.d.cts +12 -0
  10. package/dist/evaluator.d.ts +12 -0
  11. package/dist/format.d.cts +4 -0
  12. package/dist/format.d.ts +4 -0
  13. package/dist/highlight.cjs +151 -0
  14. package/dist/highlight.d.cts +13 -0
  15. package/dist/highlight.d.ts +13 -0
  16. package/dist/highlight.js +131 -0
  17. package/dist/index.cjs +357 -13
  18. package/dist/index.d.cts +6 -3
  19. package/dist/index.d.ts +6 -3
  20. package/dist/index.js +357 -13
  21. package/dist/language.cjs +417 -0
  22. package/dist/language.d.cts +143 -0
  23. package/dist/language.d.ts +143 -0
  24. package/dist/language.js +417 -0
  25. package/dist/lexer.d.cts +17 -0
  26. package/dist/lexer.d.ts +17 -0
  27. package/dist/libraries.cjs +380 -0
  28. package/dist/libraries.d.cts +112 -0
  29. package/dist/libraries.d.ts +112 -0
  30. package/dist/libraries.js +380 -0
  31. package/dist/lsp.d.cts +12 -0
  32. package/dist/lsp.d.ts +12 -0
  33. package/dist/signatures.cjs +675 -0
  34. package/dist/signatures.d.cts +20 -0
  35. package/dist/signatures.d.ts +20 -0
  36. package/dist/signatures.js +655 -0
  37. package/docs/cli.md +45 -2
  38. package/docs/desktop.md +5 -0
  39. package/docs/editors.md +121 -0
  40. package/docs/javascript.md +146 -10
  41. package/docs/kerf.md +10 -0
  42. package/docs/library/box.svg +11 -0
  43. package/docs/library/calibration.svg +11 -0
  44. package/docs/library/dividers.svg +11 -0
  45. package/docs/library/enclosure.svg +11 -0
  46. package/docs/library/hanging.svg +11 -0
  47. package/docs/library/hinge.svg +11 -0
  48. package/docs/library/tabs.svg +11 -0
  49. package/docs/library.md +339 -0
  50. package/docs/openscad.md +1 -1
  51. package/docs/shared-libraries.md +229 -0
  52. package/docs/specification.md +529 -0
  53. package/docs/versions.md +2 -2
  54. package/package.json +51 -4
package/dist/lexer.d.cts CHANGED
@@ -10,20 +10,37 @@ export interface Token {
10
10
  type: TokenType;
11
11
  value: string;
12
12
  pos: Pos;
13
+ end: number;
13
14
  }
14
15
  export interface Comment {
15
16
  text: string;
16
17
  line: number;
17
18
  block: boolean;
18
19
  own: boolean;
20
+ start: number;
21
+ end: number;
22
+ }
23
+ export interface TraceFrame {
24
+ kind: 'module' | 'function';
25
+ name: string;
26
+ line: number;
27
+ col: number;
28
+ file?: string;
29
+ count: number;
19
30
  }
20
31
  export declare class KerfError extends Error {
21
32
  line?: number;
22
33
  col?: number;
23
34
  echoes: string[];
35
+ warnings: string[];
24
36
  missingFonts?: string[];
25
37
  file?: string;
38
+ reason: string;
39
+ trace: TraceFrame[];
40
+ traceMore: number;
41
+ call?: string;
26
42
  constructor(message: string, pos?: Pos);
43
+ addFrame(kind: TraceFrame['kind'], name: string, pos: Pos): void;
27
44
  }
28
45
  export declare function tokenize(src: string, file?: string): {
29
46
  tokens: Token[];
package/dist/lexer.d.ts CHANGED
@@ -10,20 +10,37 @@ export interface Token {
10
10
  type: TokenType;
11
11
  value: string;
12
12
  pos: Pos;
13
+ end: number;
13
14
  }
14
15
  export interface Comment {
15
16
  text: string;
16
17
  line: number;
17
18
  block: boolean;
18
19
  own: boolean;
20
+ start: number;
21
+ end: number;
22
+ }
23
+ export interface TraceFrame {
24
+ kind: 'module' | 'function';
25
+ name: string;
26
+ line: number;
27
+ col: number;
28
+ file?: string;
29
+ count: number;
19
30
  }
20
31
  export declare class KerfError extends Error {
21
32
  line?: number;
22
33
  col?: number;
23
34
  echoes: string[];
35
+ warnings: string[];
24
36
  missingFonts?: string[];
25
37
  file?: string;
38
+ reason: string;
39
+ trace: TraceFrame[];
40
+ traceMore: number;
41
+ call?: string;
26
42
  constructor(message: string, pos?: Pos);
43
+ addFrame(kind: TraceFrame['kind'], name: string, pos: Pos): void;
27
44
  }
28
45
  export declare function tokenize(src: string, file?: string): {
29
46
  tokens: Token[];
@@ -0,0 +1,380 @@
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
+ "use strict";var G=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var be=Object.prototype.hasOwnProperty;var ke=(n,e)=>{for(var t in e)G(n,t,{get:e[t],enumerable:!0})},we=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of me(e))!be.call(n,s)&&s!==t&&G(n,s,{get:()=>e[s],enumerable:!(i=ge(e,s))||i.enumerable});return n};var ye=n=>we(G({},"__esModule",{value:!0}),n);var Ke={};ke(Ke,{FOLDER:()=>v,LOCK:()=>_,LibraryError:()=>B,MANIFEST:()=>b,add:()=>Fe,check:()=>Re,findProject:()=>Q,install:()=>ue,installedPaths:()=>_e,integrity:()=>R,libraryFile:()=>ce,pack:()=>Be,readLock:()=>Y,readManifest:()=>L,remove:()=>Oe,resolver:()=>ze});module.exports=ye(Ke);var he=require("node:crypto"),g=require("node:fs"),d=require("node:path"),C=require("node:zlib");var xe=(n,e=!0)=>`line ${n.line}${e?`, column ${n.col}`:""}${n.file?` in <${n.file}>`:""}`;var z=class extends Error{constructor(t,i){super(i?`${t} (${xe(i)})`:t);this.echoes=[];this.warnings=[];this.trace=[];this.traceMore=0;this.name="KerfError",this.reason=t,i&&(this.line=i.line,this.col=i.col,this.file=i.file)}addFrame(t,i,s){let r=this.trace.find(a=>a.name===i&&a.line===s.line&&a.col===s.col&&a.file===s.file);r?r.count++:this.trace.length>=50?this.traceMore++:this.trace.push({kind:t,name:i,line:s.line,col:s.col,...s.file&&{file:s.file},count:1})}},$e=["<=",">=","==","!=","&&","||","+","-","*","/","%","^","<",">","!","?",":","=",".",",",";","(",")","[","]","{","}","#"];function se(n,e){let t=[],i=[],s=0,r=1,a=0,o=()=>({line:r,col:s-a+1,offset:s,...e&&{file:e}}),l=c=>{for(let u=0;u<c;u++)n[s]===`
3
+ `&&(r++,a=s+1),s++};for(;s<n.length;){let c=n[s];if(c===" "||c===" "||c==="\r"||c===`
4
+ `){l(1);continue}if(c==="/"&&n[s+1]==="/"){let h=n.indexOf(`
5
+ `,s),f=h<0?n.length:h,w=/^[ \t]*$/.test(n.slice(n.lastIndexOf(`
6
+ `,s-1)+1,s));i.push({text:n.slice(s+2,f).trim(),line:r,block:!1,own:w,start:s,end:f}),s=f;continue}if(c==="/"&&n[s+1]==="*"){let h=o(),f=n.indexOf("*/",s+2);if(f<0)throw new z("Unclosed block comment",h);i.push({text:n.slice(s+2,f).trim(),line:h.line,block:!0,own:!0,start:s,end:f+2}),l(f+2-s);continue}let u=o();if(/[0-9]/.test(c)||c==="."&&/[0-9]/.test(n[s+1]??"")){let h=/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(n.slice(s));t.push({type:"num",value:h[0],pos:u,end:s+h[0].length}),l(h[0].length);continue}if(/[A-Za-z_$]/.test(c)){let h=/^[A-Za-z_$][A-Za-z0-9_]*/.exec(n.slice(s));t.push({type:"id",value:h[0],pos:u,end:s+h[0].length}),l(h[0].length);continue}if(c==='"'){let h="";for(l(1);s<n.length&&n[s]!=='"';){if(n[s]==="\\"){let f=n[s+1];if(f==="n")h+=`
7
+ `;else if(f==="t")h+=" ";else if(f==="u"){let w=n.slice(s+2,s+6);if(!/^[0-9a-fA-F]{4}$/.test(w))throw new z("Bad \\u escape",o());h+=String.fromCharCode(parseInt(w,16)),l(4)}else h+=f;l(2);continue}if(n[s]===`
8
+ `)throw new z("Unclosed string",u);h+=n[s],l(1)}if(s>=n.length)throw new z("Unclosed string",u);l(1),t.push({type:"str",value:h,pos:u,end:s});continue}if(c==="<"&&/^<[A-Za-z0-9_./-]+>/.test(n.slice(s))){let h=t[t.length-1];if(h&&h.type==="id"&&(h.value==="use"||h.value==="include")){let f=/^<([A-Za-z0-9_./-]+)>/.exec(n.slice(s));t.push({type:"str",value:f[1],pos:u,end:s+f[0].length}),l(f[0].length);continue}}let m=$e.find(h=>n.startsWith(h,s));if(!m)throw new z(`Unexpected character "${c}"`,u);t.push({type:"punct",value:m,pos:u,end:s+m.length}),l(m.length)}return t.push({type:"eof",value:"",pos:o(),end:s}),{tokens:t,comments:i}}var D=new Set(["module","function","if","else","for","let","each","use","include","true","false","undef"]);function ie(n,e){let{tokens:t,comments:i}=se(n,e),s=new V(t),r=[];for(;!s.at("eof");)r.push(...s.statement());return{program:{body:r},comments:i}}var V=class n{constructor(e){this.tokens=e;this.i=0}peek(e=0){return this.tokens[Math.min(this.i+e,this.tokens.length-1)]}at(e,t,i=0){let s=this.peek(i);return s.type===e&&(t===void 0||s.value===t)}isP(e,t=0){return this.at("punct",e,t)}isK(e,t=0){return this.at("id",e,t)}next(){return this.tokens[this.i++]}fail(e,t=this.peek()){let i=t.type==="eof"?"end of file":`"${t.value}"`;throw new z(`${e}, found ${i}`,t.pos)}expectP(e){return this.isP(e)||this.fail(`Expected "${e}"`),this.next()}separator(e){this.isP(e)||(this.isP(",")||this.fail(`Expected "," or "${e}"`),this.next())}ident(){let e=this.peek();return(e.type!=="id"||D.has(e.value))&&this.fail("Expected a name"),this.next()}last(){return this.tokens[this.i-1].end}statement(){let e=this.stmt();for(let t of e)t.end=this.last();return e}stmt(){let e=this.peek();if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let a=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),a.push(...this.statement());return this.next(),[{kind:"block",body:a,pos:e.pos}]}if(this.isK("module")){this.next();let a=this.ident(),o=this.params();return[{kind:"module",name:a.value,params:o,body:this.body(),pos:e.pos,namePos:a.pos}]}if(this.isK("function")&&this.at("id",void 0,1)){this.next();let a=this.ident(),o=this.params();this.expectP("=");let l=this.expr();return this.expectP(";"),[{kind:"function",name:a.value,params:o,body:l,pos:e.pos,namePos:a.pos}]}if(this.isK("use")||this.isK("include")){this.next();let a=this.peek();return a.type!=="str"&&this.fail("Expected a library path like <kerf/box>"),this.next(),this.isP(";")&&this.next(),[{kind:"use",path:a.value,include:e.value==="include",pos:e.pos}]}if(this.isK("for"))return this.next(),[{kind:"for",assigns:this.assigns(),body:this.body(),pos:e.pos}];if(this.isK("if")){this.next(),this.expectP("(");let a=this.expr();this.expectP(")");let o=this.body(),l=[];return this.isK("else")&&(this.next(),l=this.body()),[{kind:"if",cond:a,then:o,else:l,pos:e.pos}]}if(this.isK("let")&&this.isP("(",1))return this.next(),[{kind:"let",assigns:this.assigns(),body:this.body(),pos:e.pos}];if(e.type==="id"&&this.isP("=",1)){let a=this.ident().value;this.next();let o=this.peek().pos.offset,l=this.expr(),c=this.expectP(";").pos.offset;return[{kind:"assign",name:a,value:l,span:[o,c],pos:e.pos}]}let t=null;(this.isP("*")||this.isP("!")||this.isP("#")||this.isP("%"))&&(t=this.next().value);let i=this.peek();(i.type!=="id"||D.has(i.value))&&this.fail("Expected a statement"),this.next();let s=this.args(),r=this.body();return[{kind:"call",name:i.value,args:s,children:r,modifier:t,pos:i.pos}]}body(){if(this.isP(";"))return this.next(),[];if(this.isP("{")){this.next();let e=[];for(;!this.isP("}");)this.at("eof")&&this.fail('Expected "}"'),e.push(...this.statement());return this.next(),e}return this.statement()}params(){this.expectP("(");let e=[];for(;!this.isP(")");){let t=this.ident(),i=null;this.isP("=")&&(this.next(),i=this.expr()),e.push({name:t.value,default:i,pos:t.pos}),this.separator(")")}return this.next(),e}args(){this.expectP("(");let e=[];for(;!this.isP(")");){if(this.at("id")&&this.isP("=",1)){let t=this.next();this.next(),e.push({name:t.value,value:this.expr(),pos:t.pos})}else e.push({name:null,value:this.expr()});this.separator(")")}return this.next(),e}assigns(){this.expectP("(");let e=[];for(;!this.isP(")");){let t=this.ident();this.expectP("="),e.push({name:t.value,value:this.expr(),pos:t.pos}),this.separator(")")}return this.next(),e}expr(){let e=this.peek();if(this.isK("function")&&this.isP("(",1)){this.next();let i=this.params(),s=this.expr();return{kind:"lambda",params:i,body:s,pos:e.pos,end:this.last()}}if(this.isK("let")&&this.isP("(",1)){this.next();let i=this.assigns(),s=this.expr();return{kind:"let",assigns:i,body:s,pos:e.pos,end:this.last()}}let t=this.binary(0);if(this.isP("?")){this.next();let i=this.expr();this.expectP(":");let s=this.expr();return{kind:"ternary",cond:t,then:i,else:s,pos:e.pos}}return t}static{this.LEVELS=[["||"],["&&"],["==","!="],["<","<=",">",">="],["+","-"],["*","/","%"]]}binary(e){if(e>=n.LEVELS.length)return this.unary();let t=this.binary(e+1);for(;this.at("punct")&&n.LEVELS[e].includes(this.peek().value);){let i=this.next(),s=this.binary(e+1);t={kind:"binary",op:i.value,left:t,right:s,pos:i.pos}}return t}unary(){if(this.isP("-")||this.isP("!")||this.isP("+")){let e=this.next();return{kind:"unary",op:e.value,arg:this.unary(),pos:e.pos}}return this.power()}power(){let e=this.postfix();if(this.isP("^")){let t=this.next();return{kind:"binary",op:"^",left:e,right:this.unary(),pos:t.pos}}return e}postfix(){let e=this.primary();for(;;){let t=this.peek();if(this.isP("("))e={kind:"call",callee:e,args:this.args(),pos:e.pos};else if(this.isP("[")){this.next();let i=this.expr();this.expectP("]"),e={kind:"index",target:e,index:i,pos:t.pos}}else if(this.isP("."))this.next(),e={kind:"member",target:e,name:this.ident().value,pos:t.pos};else return e}}primary(){let e=this.peek();if(e.type==="num")return this.next(),{kind:"num",value:Number(e.value),pos:e.pos};if(e.type==="str")return this.next(),{kind:"str",value:e.value,pos:e.pos};if(e.type==="id")return e.value==="true"||e.value==="false"?(this.next(),{kind:"bool",value:e.value==="true",pos:e.pos}):e.value==="undef"?(this.next(),{kind:"undef",pos:e.pos}):(D.has(e.value)&&this.fail("Expected a value"),this.next(),{kind:"var",name:e.value,pos:e.pos});if(this.isP("(")){this.next();let t=this.expr();return this.expectP(")"),t}if(this.isP("["))return this.list();this.fail("Expected a value")}list(){let e=this.expectP("[");if(this.isP("]"))return this.next(),{kind:"list",items:[],pos:e.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 t=this.expr();if(this.isP(":")){this.next();let s=null,r=this.expr();return this.isP(":")&&(this.next(),s=r,r=this.expr()),this.expectP("]"),{kind:"range",start:t,step:s,end:r,pos:e.pos}}let i=[{kind:"item",expr:t}];return this.listRest(i,e.pos)}return this.listRest([],e.pos)}listRest(e,t){if(e.length){if(this.isP("]"))return this.next(),{kind:"list",items:e,pos:t};this.separator("]")}for(;!this.isP("]");)e.push(this.listItem()),this.separator("]");return this.next(),{kind:"list",items:e,pos:t}}listItem(){let e=this.peek();if(this.isK("for")&&this.isP("(",1)){this.next();let t=this.assigns(),i=this.listItem();return{kind:"for",assigns:t,body:i,pos:e.pos,end:this.last()}}if(this.isK("if")&&this.isP("(",1)){this.next(),this.expectP("(");let t=this.expr();this.expectP(")");let i=this.listItem(),s=null;return this.isK("else")&&(this.next(),s=this.listItem()),{kind:"if",cond:t,then:i,else:s}}if(this.isK("let")&&this.isP("(",1)){this.next();let t=this.assigns(),i=this.listItem();return{kind:"let",assigns:t,body:i,pos:e.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 t=this.listItem();return this.expectP(")"),t}return{kind:"item",expr:this.expr()}}};var re={"kerf/box":`// kerf/box: finger-jointed boxes.
9
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
10
+
11
+ // Box from its outer size [width, depth, height] in the current material.
12
+ // Edges pair "out" with "in", and the bottom owns every bottom corner,
13
+ // so the six panels interlock without gaps.
14
+ module box(size, lid = false, finger = undef) {
15
+ w = size[0];
16
+ d = size[1];
17
+ h = size[2];
18
+ t = $thickness;
19
+ top = lid ? "in" : "flat";
20
+ part("bottom", at = [0, 0, 0]) finger_rect([w, d], "out", finger = finger);
21
+ if (lid) part("lid", at = [0, 0, h - t]) finger_rect([w, d], "out", finger = finger);
22
+ part("front", at = [0, t, 0], rotate = [90, 0, 0])
23
+ finger_rect([w, h], ["in", "out", top, "out"], finger = finger);
24
+ part("back", at = [0, d, 0], rotate = [90, 0, 0])
25
+ finger_rect([w, h], ["in", "out", top, "out"], finger = finger);
26
+ part("left", rotate = [90, 0, 90])
27
+ finger_rect([d, h], ["in", "in", top, "in"], finger = finger);
28
+ part("right", at = [w - t, 0, 0], rotate = [90, 0, 90])
29
+ finger_rect([d, h], ["in", "in", top, "in"], finger = finger);
30
+ }
31
+
32
+ // Divider that slides between two walls: tabs on both sides drop into
33
+ // finger_holes() cut in the walls.
34
+ module divider(size, finger = undef) {
35
+ finger_rect(size, ["flat", "out", "flat", "out"], finger = finger);
36
+ }
37
+ `,"kerf/calibration":`// kerf/calibration: test pieces that measure your laser and your sheet,
38
+ // before you cut a design that depends on them. The labels are text, so
39
+ // they need a font; turn them off with labels = false.
40
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
41
+
42
+ // Kerf gauge: a frame and \`strips\` strips inside it, all separated by
43
+ // single cuts, which kerf compensation does not move. Push the strips to
44
+ // one side and measure the gap they leave: the kerf is the gap divided by
45
+ // strips + 1. \`size\` is the window the strips fill.
46
+ module kerf_gauge(strips = 10, size = [60, 25], labels = true) {
47
+ foot = labels ? 12 : 6;
48
+ w = size[0] + 12;
49
+ rect([w, size[1] + 6 + foot], r = 2);
50
+ translate([6, foot]) {
51
+ outline() rect(size);
52
+ for (i = [1:strips - 1]) line([size[0] * i / strips, 0], [size[0] * i / strips, size[1]]);
53
+ }
54
+ if (labels)
55
+ engrave() translate([w / 2, 4]) text(str("kerf = gap / ", strips + 1), size = 3.5, halign = "center");
56
+ }
57
+
58
+ // Slot gauge: \`steps\` slots \`depth\` deep, from narrower than $thickness
59
+ // to wider by \`step\` each, labelled with the difference. Try a scrap of
60
+ // the same sheet in each: the one that fits as you want is the clearance
61
+ // to add to slots.
62
+ module slot_gauge(steps = 7, step = 0.1, depth = 15, labels = true) {
63
+ pitch = $thickness + 8;
64
+ deltas = [for (i = [0:steps - 1]) round((i - (steps - 1) / 2) * step * 100) / 100];
65
+ difference() {
66
+ rect([steps * pitch + 4, depth + 12], r = 2);
67
+ for (i = [0:steps - 1])
68
+ translate([pitch / 2 + 2 + i * pitch - ($thickness + deltas[i]) / 2, 12])
69
+ rect([$thickness + deltas[i], depth + 1]);
70
+ }
71
+ if (labels)
72
+ engrave() for (i = [0:steps - 1])
73
+ translate([pitch / 2 + 2 + i * pitch, 4])
74
+ text(str(deltas[i] > 0 ? "+" : "", deltas[i]), size = 3.5, halign = "center");
75
+ }
76
+
77
+ // Finger joint test: a pair of pieces for each kerf in \`kerfs\`, cut with
78
+ // that kerf compensation, as parts "joint <kerf> out" and "joint <kerf>
79
+ // in". Push each pair together: the kerf of the pair that holds without
80
+ // glue and without forcing is the one to set for this sheet.
81
+ module joint_test(kerfs = [0.1, 0.15, 0.2], size = [40, 20], finger = undef, labels = true) {
82
+ for (k = kerfs) {
83
+ $kerf = k;
84
+ for (edge = ["out", "in"])
85
+ part(str("joint ", k, " ", edge)) {
86
+ finger_rect(size, [edge, "flat", "flat", "flat"], finger = finger);
87
+ if (labels)
88
+ engrave() translate([size[0] / 2, (size[1] + $thickness) / 2])
89
+ text(str(k), size = 4, halign = "center", valign = "center");
90
+ }
91
+ }
92
+ }
93
+ `,"kerf/dividers":`// kerf/dividers: dividers that slot into each other like an egg crate.
94
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
95
+
96
+ // A divider \`length\` long and \`height\` tall, with a slot half its height
97
+ // at each x in \`at\` for a divider that crosses it: from the top, or from
98
+ // the bottom with from = "bottom". Two crossing dividers take one of
99
+ // each. \`scoops\` dips in the top edge, evenly spaced, make room for a
100
+ // finger; \`clearance\` is added to the slot width.
101
+ module slotted_divider(length, height, at = [], from = "top", clearance = 0.15, scoops = 0) {
102
+ s = $thickness + clearance;
103
+ difference() {
104
+ rect([length, height], r = 1);
105
+ if (scoops > 0)
106
+ for (k = [0:scoops - 1])
107
+ translate([length * (k + 0.5) / scoops, height])
108
+ ellipse([min(length / scoops * 0.3, 30), height * 0.35], $fn = 64);
109
+ for (x = at) translate([x - s / 2, from == "top" ? height / 2 : -1]) rect([s, height / 2 + 1]);
110
+ }
111
+ }
112
+
113
+ // A grid of dividers for the inside of a box or drawer, \`size\` =
114
+ // [width, depth, height], making \`cols\` compartments across and \`rows\`
115
+ // front to back. The parts "long divider" run left to right and "cross
116
+ // divider" front to back. They stop \`gap\` short of the walls, and stand
117
+ // in the assembly with the inside's front left bottom corner at \`at\`.
118
+ module grid_dividers(size, cols = 2, rows = 2, clearance = 0.15, gap = 0.5, scoops = false, at = [0, 0, 0]) {
119
+ t = $thickness;
120
+ w = size[0];
121
+ d = size[1];
122
+ h = size[2];
123
+ if (rows > 1)
124
+ part("long divider", qty = rows - 1, rotate = [90, 0, 0],
125
+ at = [for (i = [1:rows - 1]) at + [gap, d * i / rows + t / 2, 0]])
126
+ slotted_divider(w - 2 * gap, h, cols > 1 ? [for (j = [1:cols - 1]) w * j / cols - gap] : [],
127
+ "top", clearance, scoops ? cols : 0);
128
+ if (cols > 1)
129
+ part("cross divider", qty = cols - 1, rotate = [90, 0, 90],
130
+ at = [for (j = [1:cols - 1]) at + [w * j / cols - t / 2, gap, 0]])
131
+ slotted_divider(d - 2 * gap, h, rows > 1 ? [for (i = [1:rows - 1]) d * i / rows - gap] : [],
132
+ "bottom", clearance, scoops ? rows : 0);
133
+ }
134
+ `,"kerf/enclosure":`// kerf/enclosure: boxes with a screwed-on lid, for electronics and parts
135
+ // you need to get back to.
136
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
137
+
138
+ // Box with a lid held by screws. The walls and the bottom are finger
139
+ // jointed, as box() in kerf/box; the lid lies on the walls and overhangs
140
+ // them by \`lip\`, and each screw goes through it into the top of the front
141
+ // or back wall, into a nut in a T-slot. \`size\` is the outside [width,
142
+ // depth, height], lid included. \`screw\` is the diameter and
143
+ // \`screw_length\` the length under the head; \`nut\` is [width, height] of
144
+ // the nut's slot. \`cutouts\` lists holes in the panels, see
145
+ // enclosure_cutouts().
146
+ module enclosure(size, screw = 3, screw_length = 12, nut = undef, lip = undef, cutouts = [], finger = undef) {
147
+ t = $thickness;
148
+ o = is_undef(lip) ? screw : lip;
149
+ // The box under the lid
150
+ w = size[0] - 2 * o;
151
+ d = size[1] - 2 * o;
152
+ h = size[2] - t;
153
+ into = screw_length - t;
154
+ nut_slot = is_undef(nut) ? [screw * 1.9, screw * 0.9] : nut;
155
+ assert(into > nut_slot[1], "screw_length is too short for the lid and the nut");
156
+ assert(h > into + 2 * t, "the walls are too low for the screws");
157
+ // Two screws on the front and the back, and one more for every 80 mm
158
+ n = max(2, round(w / 80));
159
+ xs = [for (i = [0:n - 1]) w * (i + 0.5) / n];
160
+ part("bottom", at = [o, o, 0]) difference() {
161
+ finger_rect([w, d], "out", finger = finger);
162
+ enclosure_cutouts("bottom", cutouts);
163
+ }
164
+ part("lid", at = [0, 0, h]) difference() {
165
+ rect([w + 2 * o, d + 2 * o]);
166
+ for (x = xs, y = [t / 2, d - t / 2]) translate([o + x, o + y]) circle(d = screw + 0.3, $fn = 24);
167
+ enclosure_cutouts("lid", cutouts);
168
+ }
169
+ part("front", at = [o, o + t, 0], rotate = [90, 0, 0]) difference() {
170
+ finger_rect([w, h], ["in", "out", "flat", "out"], finger = finger);
171
+ for (x = xs) translate([x, h]) rotate(180) tslot(screw, into, nut_slot);
172
+ enclosure_cutouts("front", cutouts);
173
+ }
174
+ part("back", at = [o, o + d, 0], rotate = [90, 0, 0]) difference() {
175
+ finger_rect([w, h], ["in", "out", "flat", "out"], finger = finger);
176
+ for (x = xs) translate([x, h]) rotate(180) tslot(screw, into, nut_slot);
177
+ enclosure_cutouts("back", cutouts);
178
+ }
179
+ part("left", at = [o, o, 0], rotate = [90, 0, 90]) difference() {
180
+ finger_rect([d, h], ["in", "in", "flat", "in"], finger = finger);
181
+ enclosure_cutouts("left", cutouts);
182
+ }
183
+ part("right", at = [o + w - t, o, 0], rotate = [90, 0, 90]) difference() {
184
+ finger_rect([d, h], ["in", "in", "flat", "in"], finger = finger);
185
+ enclosure_cutouts("right", cutouts);
186
+ }
187
+ }
188
+
189
+ // The holes listed in \`cutouts\` for one panel. Each is [side, [x, y],
190
+ // size]: side is "front", "back", "left", "right", "lid" or "bottom";
191
+ // [x, y] is the hole's centre on the panel as it is drawn, from its
192
+ // bottom left corner; a number size is a round hole of that diameter, and
193
+ // [width, height] a rectangle. Add "vents" after the size for vents()
194
+ // filling that rectangle.
195
+ module enclosure_cutouts(side, cutouts) {
196
+ for (c = cutouts)
197
+ if (c[0] == side) translate(c[1]) {
198
+ if (c[3] == "vents") vents(c[2]);
199
+ else if (is_list(c[2])) rect(c[2], center = true);
200
+ else circle(d = c[2]);
201
+ }
202
+ }
203
+
204
+ // Ventilation slots across [width, height], centred on the origin:
205
+ // upright slots \`slot\` wide with round ends, \`pitch\` apart.
206
+ module vents(size, slot = 3, pitch = 6) {
207
+ n = max(1, floor((size[0] - slot) / pitch) + 1);
208
+ ends = max(0, size[1] - slot) / 2;
209
+ for (i = [0:n - 1])
210
+ translate([(i - (n - 1) / 2) * pitch, 0]) hull() {
211
+ translate([0, -ends]) circle(d = slot, $fn = 24);
212
+ translate([0, ends]) circle(d = slot, $fn = 24);
213
+ }
214
+ }
215
+ `,"kerf/hanging":`// kerf/hanging: holes, keyholes and loops for hanging things on a wall.
216
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
217
+ //
218
+ // Each module cuts its hole out of the shapes it is given, as in
219
+ // keyhole([0, 40]) rect([100, 50]). Given nothing, it makes the hole
220
+ // itself, to subtract in a difference() of your own.
221
+
222
+ // A keyhole for hanging on a screw: the head goes through the round hole,
223
+ // then the panel drops \`drop\` mm so the screw rests at \`at\`, at the top of
224
+ // the slot. \`head\` and \`shank\` are the hole and slot widths; measure the
225
+ // screw and add a little.
226
+ module keyhole(at = [0, 0], head = 9, shank = 4.5, drop = 10) {
227
+ assert(drop >= (head + shank) / 2, "drop must be at least (head + shank) / 2");
228
+ module hole() translate(at) {
229
+ translate([0, -drop]) circle(d = head);
230
+ hull() {
231
+ circle(d = shank);
232
+ translate([0, -drop]) circle(d = shank);
233
+ }
234
+ }
235
+ if ($children > 0) difference() { children(); hole(); } else hole();
236
+ }
237
+
238
+ // Two keyholes \`spacing\` apart, centred on \`at\`, for a panel that hangs
239
+ // level and does not turn.
240
+ module keyholes(spacing, at = [0, 0], head = 9, shank = 4.5, drop = 10) {
241
+ module holes() for (x = [-spacing / 2, spacing / 2]) keyhole(at + [x, 0], head, shank, drop);
242
+ if ($children > 0) difference() { children(); holes(); } else holes();
243
+ }
244
+
245
+ // A round hole of diameter \`d\` at \`at\`, for a nail, a hook or a cord.
246
+ // Give \`spacing\` for two holes that far apart, centred on \`at\`.
247
+ module hanging_hole(at = [0, 0], d = 5, spacing = 0) {
248
+ module holes() for (x = spacing > 0 ? [-spacing / 2, spacing / 2] : [0])
249
+ translate(at + [x, 0]) circle(d = d);
250
+ if ($children > 0) difference() { children(); holes(); } else holes();
251
+ }
252
+
253
+ // A ring around a hole of diameter \`d\` at \`at\`, \`wall\` wide, joined to the
254
+ // shapes it is given: put it on the edge of an ornament or a tag, and the
255
+ // hole stays open even where the ring overlaps the shape.
256
+ module hanging_loop(at = [0, 0], d = 4, wall = 3) {
257
+ difference() {
258
+ union() {
259
+ children();
260
+ translate(at) circle(d = d + 2 * wall);
261
+ }
262
+ translate(at) circle(d = d);
263
+ }
264
+ }
265
+ `,"kerf/hinge":`// kerf/hinge: living hinges, for bending flat sheet around a corner.
266
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
267
+
268
+ use <kerf/tabs>
269
+
270
+ // Length of living hinge that bends \`angle\` degrees around an inside
271
+ // radius \`r\`: the arc along the middle of the sheet.
272
+ function bend_length(r, angle = 90) = PI * (r + $thickness / 2) * angle / 180;
273
+
274
+ // A rectangle that bends: a living hinge across its full height at each x
275
+ // in \`bends\`, centred there and \`width\` wide. The width defaults to a
276
+ // 90\xB0 bend around three thicknesses; \`r\` rounds the corners.
277
+ module flex_rect(size, bends, width = undef, spacing = 1.5, bridge = 3, r = 0) {
278
+ w = is_undef(width) ? bend_length(3 * $thickness) : width;
279
+ rect(size, r = r);
280
+ for (x = bends)
281
+ translate([x - w / 2, 0]) living_hinge([w, size[1]], spacing = spacing, bridge = bridge);
282
+ }
283
+
284
+ // Box with rounded corners whose four sides are one strip, bent at the
285
+ // corners by living hinges. The bottom's tabs go through slots in the
286
+ // strip; the lid rests on top, kept in place by an insert glued under it.
287
+ // \`size\` is the outside [width, depth, height], lid included, and \`r\` the
288
+ // outside corner radius, more than two thicknesses.
289
+ module flex_box(size, r = 15, lid = true, clearance = 0.1, spacing = 1.5, bridge = 3) {
290
+ t = $thickness;
291
+ w = size[0];
292
+ d = size[1];
293
+ h = lid ? size[2] - t : size[2];
294
+ assert(r > 2 * t, "r must be more than two thicknesses");
295
+ assert(w >= 2 * r && d >= 2 * r, "width and depth must be at least 2 * r");
296
+ // Straight runs and the bends at the corners, measured along the strip
297
+ sw = w - 2 * r;
298
+ sd = d - 2 * r;
299
+ b = bend_length(r - t);
300
+ L = 2 * sw + 2 * sd + 4 * b;
301
+ // The strip starts in the middle of the front and goes round
302
+ // anticlockwise seen from above: where each run starts, and its length
303
+ runs = [[-sw / 2, sw], [sw / 2 + b, sd], [sw / 2 + 2 * b + sd, sw], [1.5 * sw + 3 * b + sd, sd]];
304
+ bends = [sw / 2 + b / 2, sw / 2 + 1.5 * b + sd, 1.5 * sw + 2.5 * b + sd, 1.5 * sw + 3.5 * b + 2 * sd];
305
+ part("side") difference() {
306
+ flex_rect([L, h], bends, width = b, spacing = spacing, bridge = bridge);
307
+ // The front run crosses the ends: its slots are cut at both
308
+ for (run = runs, o = [0, L])
309
+ if (run[1] > 0) translate([run[0] + o, 1.5 * t]) slots(run[1], clearance = clearance);
310
+ }
311
+ part("bottom") flex_panel([w - 2 * t, d - 2 * t], r - t, sw, sd);
312
+ if (lid) {
313
+ part("lid") rect([w, d], r = r);
314
+ part("lid insert")
315
+ offset(delta = -clearance) rect([w - 2 * t, d - 2 * t], r = r - t);
316
+ }
317
+ }
318
+
319
+ // The bottom of flex_box(): a rounded rectangle with tabs on its straight
320
+ // runs, \`sw\` long on the front and back and \`sd\` on the sides.
321
+ module flex_panel(size, r, sw, sd) {
322
+ rect(size, r = r);
323
+ if (sw > 0) {
324
+ translate([r, 0]) tabs(sw);
325
+ translate([r + sw, size[1]]) rotate(180) tabs(sw);
326
+ }
327
+ if (sd > 0) {
328
+ translate([size[0], r]) rotate(90) tabs(sd);
329
+ translate([0, r + sd]) rotate(270) tabs(sd);
330
+ }
331
+ }
332
+ `,"kerf/tabs":`// kerf/tabs: tab and slot joints, for one panel standing on another.
333
+ // Copyright (c) 2026 MyLaserTools. AGPL-3.0-only or MyLaserTools commercial licence.
334
+
335
+ // Centres of \`count\` tabs spread evenly along an edge \`length\` long.
336
+ // Without a count, one tab for every 50 mm, and at least one.
337
+ function tab_positions(length, count = undef) =
338
+ let (n = is_undef(count) ? max(1, round(length / 50)) : count)
339
+ n < 1 ? assert(false, "count must be at least 1") :
340
+ [for (i = [0:n - 1]) length * (i + 0.5) / n];
341
+
342
+ // Tabs along x from 0 to \`length\`, hanging \`depth\` below y = 0: join them
343
+ // to the bottom edge of a panel, and cut slots() where they go through.
344
+ // Each tab is \`width\` wide, half the space between tabs by default, and
345
+ // \`depth\` defaults to $thickness, flush with the far side.
346
+ module tabs(length, count = undef, width = undef, depth = undef) {
347
+ at = tab_positions(length, count);
348
+ w = is_undef(width) ? length / (2 * len(at)) : width;
349
+ h = is_undef(depth) ? $thickness : depth;
350
+ for (x = at) translate([x - w / 2, -h]) rect([w, h]);
351
+ }
352
+
353
+ // The slots that tabs() with the same length, count and width go
354
+ // through, centred on y = 0. \`clearance\` is added to the width and to
355
+ // $thickness, so the tabs slide in.
356
+ module slots(length, count = undef, width = undef, clearance = 0.1) {
357
+ at = tab_positions(length, count);
358
+ w = is_undef(width) ? length / (2 * len(at)) : width;
359
+ for (x = at) translate([x, 0]) rect([w + clearance, $thickness + clearance], center = true);
360
+ }
361
+
362
+ // A rectangle with tabs on some of its edges, outside \`size\`. \`edges\` is
363
+ // true or false for all four, or [bottom, right, top, left].
364
+ module tab_rect(size, edges = true, count = undef, width = undef) {
365
+ e = is_list(edges) ? edges : [edges, edges, edges, edges];
366
+ w = size[0];
367
+ h = size[1];
368
+ rect([w, h]);
369
+ if (e[0]) tabs(w, count, width);
370
+ if (e[1]) translate([w, 0]) rotate(90) tabs(h, count, width);
371
+ if (e[2]) translate([w, h]) rotate(180) tabs(w, count, width);
372
+ if (e[3]) translate([0, h]) rotate(270) tabs(h, count, width);
373
+ }
374
+ `};var O="0.2";var b="kerf.json",_="kerf.lock",v="kerf_libraries",A=20<<20,I=2e3,Z=/^[a-z0-9][a-z0-9_-]{0,63}$/,ve=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/,Pe=/^(readme|licen[cs]e|copying|notice|changelog)(\.[a-z]+)?$/i,B=class extends Error{},q=n=>{try{return(0,g.statSync)(n).isFile()}catch{return!1}},T=n=>{try{return(0,g.statSync)(n).isDirectory()}catch{return!1}},j=(n,e)=>n&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0,p=n=>{throw new B(n)};function oe(n,e){return(typeof n!="string"||!Z.test(n))&&p(`${e} "${n}" is not a library name: use lowercase letters, digits, - and _`),n==="kerf"&&p(`${e}: "kerf" is the standard library's name`),n}function X(n,e){(!n||typeof n!="object"||Array.isArray(n))&&p(`${e} must hold a JSON object`);let t=n;for(let s of["name","version","description","license","language"])t[s]!==void 0&&typeof t[s]!="string"&&p(`${e}: "${s}" must be a string`);t.name!==void 0&&oe(t.name,`${e}: name`),t.version!==void 0&&!ve.test(t.version)&&p(`${e}: "version" must look like 1.2.0, not "${t.version}"`),t.language!==void 0&&!/^\d+\.\d+$/.test(t.language)&&p(`${e}: "language" must look like ${O}, not "${t.language}"`);let i=t.libraries??{};(!i||typeof i!="object"||Array.isArray(i))&&p(`${e}: "libraries" must be an object of name: source`);for(let[s,r]of Object.entries(i))oe(s,`${e}: library`),typeof r!="string"&&p(`${e}: the source of ${s} must be a string`);return{...t,libraries:{...i}}}function H(n,e){let t;try{t=(0,g.readFileSync)(n,"utf8")}catch{return p(`${e} was not found`)}try{return JSON.parse(t)}catch(i){return p(`${e} is not valid JSON: ${i.message}`)}}function L(n,e=b){return X(H((0,d.join)(n,b),e),e)}function Y(n){if(!(0,g.existsSync)((0,d.join)(n,_)))return;let e=H((0,d.join)(n,_),_);(e?.lockVersion!==1||!e.libraries||typeof e.libraries!="object")&&p(`${_} is not a kerf.lock this kerf can read. Delete it and run kerf install.`);for(let[t,i]of Object.entries(e.libraries))(!i||["source","resolved","integrity"].some(s=>typeof i[s]!="string"))&&p(`${_}: the entry for ${t} is damaged. Remove it and run kerf install.`);return e}function Q(n){for(let e=(0,d.resolve)(n);;){if(q((0,d.join)(e,b)))return e;let t=(0,d.dirname)(e);if(t===e)return;e=t}}function ee(n){try{return L(n).name}catch{return}}function ce(n,e,t=q){let i=(a,o)=>[(0,d.join)(a,o),(0,d.join)(a,o+".kerf")].find(l=>t(l)),s=e.indexOf("/"),r=s>0?Q(n):void 0;if(r){let a=e.slice(0,s);if(a===ee(r))return i(r,e.slice(s+1));if(T((0,d.join)(r,v,a)))return i((0,d.join)(r,v),e)}return i(n,e)}function ze(n){let e=(0,d.dirname)((0,d.resolve)(n));return t=>{let i=ce(e,t);return i===void 0?void 0:(0,g.readFileSync)(i,"utf8")}}function _e(n,e=200){let t=Q(n);if(!t)return[];let i=[],s=(o,l)=>{for(let c of[...fe(o,3)].sort()){if(i.length>=e)return;c.endsWith(".kerf")&&i.push(l+c.slice(0,-5))}},r=ee(t);r&&s(t,r+"/");let a=(0,d.join)(t,v);if(T(a))for(let o of(0,g.readdirSync)(a).sort())Z.test(o)&&T((0,d.join)(a,o))&&s((0,d.join)(a,o),o+"/");return i}function fe(n,e=1/0){let t=[],i=(s,r,a)=>{let o;try{o=(0,g.readdirSync)(s,{withFileTypes:!0})}catch{return}for(let l of o){if(l.name.startsWith(".")||l.name==="node_modules"||l.name===v)continue;let c=r?`${r}/${l.name}`:l.name;l.isDirectory()?a<e&&i((0,d.join)(s,l.name),c,a+1):l.isFile()&&(t.push(c),t.length>I&&p(`${n} has more than ${I} files`))}};return i(n,"",0),t}function N(n,e=()=>!0){let t=new Map;for(let i of fe(n))e(i)&&t.set(i,(0,g.readFileSync)((0,d.join)(n,...i.split("/"))));return t}var te=n=>n===b||n.endsWith(".kerf")||!n.includes("/")&&Pe.test(n);function R(n){let e=(0,he.createHash)("sha256");for(let t of[...n.keys()].sort()){let i=Buffer.from(n.get(t).toString("utf8").replace(/\r\n/g,`
375
+ `));e.update(`${t}\0${i.length}\0`),e.update(i)}return"sha256-"+e.digest("base64")}function ae(n){return n.kind==="folder"?"folder:"+(process.platform==="win32"?n.path.toLowerCase():n.path):n.kind==="github"?`github:${n.owner}/${n.repo}`.toLowerCase()+`@${n.ref}`:n.url}function K(n,e){let t=/^github:([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:@(\S+))?$/.exec(n);if(t)return{kind:"github",owner:t[1],repo:t[2],ref:t[3]??"HEAD"};if(/^https?:\/\//i.test(n)){let s;try{s=new URL(n)}catch{return p(`${n} is not a link`)}return s.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(s.hostname)&&p(`Use https:// to download ${n}`),{kind:"url",url:n}}let i=n.startsWith("file:")?n.slice(5):n;return i.startsWith("./")||i.startsWith("../")||(0,d.isAbsolute)(i)?{kind:"folder",path:(0,d.resolve)(e,i)}:p(`"${n}" 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 Le(n,e){let t;try{t=await e(n)}catch(o){let l=o;return p(`Could not download ${n}: ${l.cause?.message??l.message}`)}t.ok||p(`Could not download ${n}: HTTP ${t.status}`+(t.status===404?". Check the name and the tag, and that it is public.":""));let i=()=>p(`${n} is larger than ${A>>20} MB`);if(Number(t.headers?.get("content-length"))>A&&i(),!t.body){let o=Buffer.from(await t.arrayBuffer());return o.length>A?i():o}let s=t.body.getReader(),r=[],a=0;for(;;){let{done:o,value:l}=await s.read();if(o||!l)break;a+=l.length,a>A&&(await s.cancel().catch(()=>{}),i()),r.push(l)}return Buffer.concat(r)}function Te(n,e){let t;try{t=(0,C.gunzipSync)(n,{maxOutputLength:5*A})}catch{return p(`${e} is not a .tar.gz file`)}let i=new Map,s,r={},a;for(let o=0;o+512<=t.length;){let l=t.subarray(o,o+512);if(l.every(y=>y===0))break;let c=(y,P)=>{let $=l.subarray(y,y+P),S=$.indexOf(0);return $.subarray(0,S<0?P:S).toString("utf8")},u=parseInt(c(124,12).trim()||"0",8);u>=0||p(`${e} is damaged`);let m=c(156,1)||"0",h=t.subarray(o+512,o+512+u);if(o+=512+Math.ceil(u/512)*512,m==="x"||m==="g"){let y=Se(h);m==="g"?s=y.comment??s:r=y;continue}if(m==="L"){a=h.toString("utf8").replace(/\0+$/,"");continue}let f=c(345,155),w=r.path??a??(f?f+"/":"")+c(0,100);r={},a=void 0,(m==="0"||m==="7")&&i.set(w,Buffer.from(h)),i.size>I&&p(`${e} has more than ${I} files`)}return{files:i,commit:s}}function Se(n){let e={};for(let t=0;t<n.length;){let i=n.indexOf(32,t),s=parseInt(n.subarray(t,i).toString(),10);if(!(s>0)||i<0)break;let r=n.subarray(i+1,t+s-1).toString("utf8"),a=r.indexOf("=");a>0&&(e[r.slice(0,a)]=r.slice(a+1)),t+=s}return e}function le(n,e){let t=new Map;for(let[r,a]of n){let o=r.replace(/^\.\//,""),l=o.split("/");((0,d.isAbsolute)(o)||o.includes("\\")||o.includes(":")||l.some(c=>c===".."||c===""))&&p(`${e} holds a file outside its folder: ${r}`),t.set(o,a)}let i="";if(!t.has(b)){let r=new Set([...t.keys()].map(a=>a.split("/")[0]));r.size===1&&(i=[...r][0]+"/")}let s=new Map;for(let[r,a]of t){if(!r.startsWith(i))continue;let o=r.slice(i.length);o.split("/").some(l=>l.startsWith(".")||l===v||l==="node_modules")||te(o)&&s.set(o,a)}return s.has(b)||p(`${e} has no kerf.json at its top. Is it a KerfScript library?`),s}var Ee=(n,e)=>{let[t,i]=n.split(".").map(Number),[s,r]=e.split(".").map(Number);return t>s||t===s&&i>r};async function de(n,e,t,i,s){let r=K(n,e),a,o;if(r.kind==="folder")q((0,d.join)(r.path,b))||p(`${n}: no kerf.json in ${r.path}. Is it a KerfScript library?`),a=le(N(r.path,te),n),o=(0,d.relative)(t,r.path).split(d.sep).join("/")||".",!o.startsWith(".")&&!(0,d.isAbsolute)(o)&&(o="./"+o);else{let c=r.kind==="github"?`https://github.com/${r.owner}/${r.repo}/archive/${r.ref}.tar.gz`:r.url,u=s.get(c)??await Le(c,i);s.set(c,u);let m=Te(u,n);a=le(m.files,n),o=r.kind==="github"&&/^[0-9a-f]{40}$/.test(m.commit??"")?`https://github.com/${r.owner}/${r.repo}/archive/${m.commit}.tar.gz`:c}let l=X(JSON.parse(a.get(b).toString("utf8")),`the kerf.json of ${n}`);return l.name||p(`${n}: its kerf.json has no "name", so it is not a library`),l.language&&Ee(l.language,O)&&p(`${l.name} needs KerfScript language ${l.language} or later, and this kerf has ${O}. Update kerf.`),{manifest:l,files:a,resolved:o,integrity:R(a)}}function Ae(n,e){(0,g.rmSync)(n,{recursive:!0,force:!0});for(let[t,i]of e){let s=(0,d.join)(n,...t.split("/"));(0,g.mkdirSync)((0,d.dirname)(s),{recursive:!0}),(0,g.writeFileSync)(s,i)}}var je=n=>{let e=[...n].sort(([t],[i])=>t<i?-1:1);return JSON.stringify({lockVersion:1,libraries:Object.fromEntries(e)},null,2)+`
376
+ `};async function ue(n,e={}){let t=e.fetch??globalThis.fetch,i=e.log??(()=>{}),s=e.cache??new Map,r=L(n),a=Y(n),o=new Map,l=Object.entries(r.libraries).map(([h,f])=>({name:h,source:f,base:n,from:b})),c=(0,d.join)(n,v);for(;l.length;){let{name:h,source:f,base:w,from:y}=l.shift(),P=K(f,w),$=P.kind==="folder",S=$?`${f} (${P.path})`:f,M=o.get(h);if(M){M.at!==ae(P)&&!j(r.libraries,h)&&p(`${y} uses ${h} from ${S}, and ${M.from} uses it from ${M.shown}. Add ${h} to kerf.json with the source to use.`);continue}let U=j(a?.libraries,h),x=U?.source===f&&(!$||(0,d.resolve)(n,U.resolved)===P.path)?U:void 0;e.frozen&&!x&&p(`kerf.lock does not pin ${h} from ${f}. Run kerf install without --frozen.`);let F=(0,d.join)(c,h),E;if(x&&!$&&T(F)&&R(N(F))===x.integrity)E=x;else{let k=await de(x&&!$?x.resolved:f,$?w:n,n,t,s);k.manifest.name!==h&&p(`${f} is the library "${k.manifest.name}", so ${y} must call it ${k.manifest.name}, not ${h}`),x&&k.integrity!==x.integrity&&(!$||e.frozen)&&p($?`${h} in ${f} changed since kerf.lock pinned it. Run kerf install without --frozen.`:`${h} from ${x.resolved} no longer matches kerf.lock. If you trust the change, remove ${h} from kerf.lock and run kerf install again.`),Ae(F,k.files),E={source:f,...k.manifest.version?{version:k.manifest.version}:{},resolved:k.resolved,integrity:k.integrity},(!x||x.integrity!==k.integrity||!$)&&i(`${x?"Restored":"Installed"} ${h}${E.version?" "+E.version:""} from ${f}`)}o.set(h,{entry:E,at:ae(P),shown:S,from:y});let ne=P.kind==="folder"?P.path:void 0;for(let[k,W]of Object.entries(L(F,`${v}/${h}/${b}`).libraries))K(W,n).kind==="folder"&&!ne&&p(`${h} uses ${k} from the folder ${W}: a published library needs github: or https: sources`),l.push({name:k,source:W,base:ne??n,from:h})}let u=je(new Map([...o].map(([h,f])=>[h,f.entry]))),m=(0,g.existsSync)((0,d.join)(n,_))?(0,g.readFileSync)((0,d.join)(n,_),"utf8"):"";if(e.frozen&&u!==m.replace(/\r\n/g,`
377
+ `)&&p("kerf.lock is out of date. Run kerf install without --frozen."),T(c))for(let h of(0,g.readdirSync)(c,{withFileTypes:!0}))h.isDirectory()&&Z.test(h.name)&&!o.has(h.name)&&((0,g.rmSync)((0,d.join)(c,h.name),{recursive:!0,force:!0}),i(`Removed ${h.name}`));return u!==m.replace(/\r\n/g,`
378
+ `)&&(0,g.writeFileSync)((0,d.join)(n,_),u),JSON.parse(u)}function Re(n){let e=L(n),t=Y(n),i=Object.keys(e.libraries);if(!t)return i.length?["kerf.lock is missing. Run kerf install."]:[];let s=[],r=new Set,a=[...i];for(;a.length;){let o=a.shift();if(r.has(o))continue;r.add(o);let l=j(t.libraries,o);if(!l){s.push(`${o} is not in kerf.lock. Run kerf install.`);continue}i.includes(o)&&l.source!==e.libraries[o]&&s.push(`kerf.json takes ${o} from ${e.libraries[o]}, and kerf.lock from ${l.source}. Run kerf install.`);let c=(0,d.join)(n,v,o);if(!T(c)){s.push(`${o} is not in ${v}. Run kerf install.`);continue}R(N(c))!==l.integrity&&s.push(`The files in ${v}/${o} differ from kerf.lock. Run kerf install.`);try{a.push(...Object.keys(L(c).libraries))}catch(u){s.push(u.message)}}for(let o of Object.keys(t.libraries))r.has(o)||s.push(`kerf.lock pins ${o}, which nothing uses any more.`);return s}function Me(n,e){let t=(0,d.join)(n,b),i=(0,g.existsSync)(t)?H(t,b):{};X(i,b);let s={...i.libraries??{}};return e(s),i.libraries=s,{file:t,before:(0,g.existsSync)(t)?(0,g.readFileSync)(t,"utf8"):void 0,raw:i}}async function pe(n,e,t){let{file:i,before:s,raw:r}=Me(n,e);(0,g.writeFileSync)(i,JSON.stringify(r,null,2)+`
379
+ `);try{return await ue(n,t)}catch(a){throw s===void 0?(0,g.rmSync)(i,{force:!0}):(0,g.writeFileSync)(i,s),a}}async function Fe(n,e,t={}){let i=new Map,r=(await de(e,n,n,t.fetch??globalThis.fetch,i)).manifest.name;r===ee(n)&&p(`This project is the library ${r}; it cannot use itself`);let a=await pe(n,o=>void(o[r]=e),{...t,cache:i});return{name:r,lock:a}}async function Oe(n,e,t={}){return pe(n,i=>{j(i,e)===void 0&&p(`kerf.json has no library named ${e}`),delete i[e]},t)}function J(n,e=[]){if(Array.isArray(n))for(let t of n)J(t,e);else if(n&&typeof n=="object"){let t=n;if(t.kind==="use"&&typeof t.path=="string")e.push({path:t.path,line:t.pos.line});else for(let i of Object.values(t))J(i,e)}return e}function Ie(n){let e=[];for(let[t,i]of n){let s=Buffer.alloc(512),r=t,a="";if(Buffer.byteLength(r)>100){let l=t.lastIndexOf("/",155);(l<0||Buffer.byteLength(t.slice(l+1))>100)&&p(`${t}: the path is too long to pack`),a=t.slice(0,l),r=t.slice(l+1)}s.write(r,0,100),s.write("0000644\0",100),s.write("0000000\0",108),s.write("0000000\0",116),s.write(i.length.toString(8).padStart(11,"0")+"\0",124),s.write("00000000000\0",136),s.fill(32,148,156),s.write("0",156),s.write("ustar\0",257),s.write("00",263),s.write(a,345,155);let o=0;for(let l of s)o+=l;s.write(o.toString(8).padStart(6,"0")+"\0 ",148),e.push(s,i,Buffer.alloc((512-i.length%512)%512))}return e.push(Buffer.alloc(1024)),(0,C.gzipSync)(Buffer.concat(e),{level:9})}function Be(n,e){let t=L(n),i=t.name??p('kerf.json needs a "name" to pack a library'),s=t.version??p('kerf.json needs a "version", like 1.0.0'),r=N(n,te),a=[];for(let[u,m]of Object.entries(t.libraries))K(m,n).kind==="folder"&&a.push(`kerf.json: ${u} comes from a folder; a published library needs github: or https: sources`);let o=u=>r.has(u)||r.has(u+".kerf");for(let[u,m]of r){if(!u.endsWith(".kerf"))continue;let h;try{h=ie(m.toString("utf8"),`${i}/${u}`).program}catch(f){a.push(`${u}: ${f.message}`);continue}for(let f of J(h)){let w=f.path.split("/")[0];Object.prototype.hasOwnProperty.call(re,f.path)||w===i&&o(f.path.slice(i.length+1))||f.path.includes("/")&&j(t.libraries,w)!==void 0||a.push(`${u}, line ${f.line}: <${f.path}> will not be found once the library is installed`+(o(f.path)?`. Write <${i}/${f.path}> for the library's own file.`:"."))}}[...r.keys()].some(u=>u.endsWith(".kerf"))||a.push("There are no .kerf files to pack"),a.length&&p(a.join(`
380
+ `));let l=[...r.keys()].sort().map(u=>[`${i}/${u}`,r.get(u)]),c=e??(0,d.join)(n,`${i}-${s}.tar.gz`);return(0,g.writeFileSync)(c,Ie(l)),{file:c,name:i,version:s,files:r.size,integrity:R(r)}}0&&(module.exports={FOLDER,LOCK,LibraryError,MANIFEST,add,check,findProject,install,installedPaths,integrity,libraryFile,pack,readLock,readManifest,remove,resolver});
@@ -0,0 +1,112 @@
1
+ export declare const MANIFEST = "kerf.json";
2
+ export declare const LOCK = "kerf.lock";
3
+ export declare const FOLDER = "kerf_libraries";
4
+ /** A problem with a project's libraries, shown to the user as it is. */
5
+ export declare class LibraryError extends Error {
6
+ }
7
+ /** A kerf.json: a library's name and version, and the libraries it uses. */
8
+ export interface Manifest {
9
+ name?: string;
10
+ version?: string;
11
+ description?: string;
12
+ license?: string;
13
+ /** The oldest KerfScript language version the library works with */
14
+ language?: string;
15
+ /** Library name to source: github:owner/repo@tag, an https link to a
16
+ * .tar.gz, or a folder */
17
+ libraries: Record<string, string>;
18
+ }
19
+ /** One library pinned in kerf.lock. */
20
+ export interface Locked {
21
+ /** The source as kerf.json gives it */
22
+ source: string;
23
+ version?: string;
24
+ /** Where the exact files came from: a link to one commit, or the folder */
25
+ resolved: string;
26
+ /** sha256 of the library's files */
27
+ integrity: string;
28
+ }
29
+ export interface Lock {
30
+ lockVersion: 1;
31
+ libraries: Record<string, Locked>;
32
+ }
33
+ /** A download, as the global fetch makes one. When the response has a
34
+ * body stream, it is read a piece at a time and stopped at the size limit. */
35
+ export type Fetch = (url: string) => Promise<{
36
+ ok: boolean;
37
+ status: number;
38
+ headers?: {
39
+ get(name: string): string | null;
40
+ };
41
+ body?: {
42
+ getReader(): {
43
+ read(): Promise<{
44
+ done: boolean;
45
+ value?: Uint8Array;
46
+ }>;
47
+ cancel(): Promise<void>;
48
+ };
49
+ } | null;
50
+ arrayBuffer(): Promise<ArrayBuffer>;
51
+ }>;
52
+ export interface InstallOptions {
53
+ /** Downloads a link; the global fetch by default */
54
+ fetch?: Fetch;
55
+ /** Fail instead of changing kerf.lock, as in CI */
56
+ frozen?: boolean;
57
+ /** Called with a line for each library installed or removed */
58
+ log?: (line: string) => void;
59
+ }
60
+ type Files = Map<string, Buffer>;
61
+ /** Reads and checks the kerf.json in a folder. */
62
+ export declare function readManifest(dir: string, label?: string): Manifest;
63
+ /** Reads kerf.lock in a project folder, or undefined when there is none. */
64
+ export declare function readLock(root: string): Lock | undefined;
65
+ /** The project a design belongs to: the nearest folder at or above `dir`
66
+ * with a kerf.json. */
67
+ export declare function findProject(dir: string): string | undefined;
68
+ /** The file that `use <path>` names, outside the standard library, for a
69
+ * design in folder `base`. A path that starts with the project's own name
70
+ * is a file of the project; one that starts with the name of a library in
71
+ * kerf_libraries is that library's; any other is next to the design. Each
72
+ * is tried as written and with .kerf added. */
73
+ export declare function libraryFile(base: string, path: string, exists?: (file: string) => boolean): string | undefined;
74
+ /** A render() resolve option for a design file: finds its libraries as
75
+ * `kerf render` does. */
76
+ export declare function resolver(designFile: string): (path: string) => string | undefined;
77
+ /** The `use <...>` paths of the installed libraries and of the project's own
78
+ * files, for completion in editors. */
79
+ export declare function installedPaths(base: string, limit?: number): string[];
80
+ /** A hash of a library's files, the same whatever line endings git gives
81
+ * them. */
82
+ export declare function integrity(files: Files): string;
83
+ /** Makes kerf_libraries/ match kerf.json, with the libraries those
84
+ * libraries use, and writes kerf.lock. A library kerf.lock pins is
85
+ * downloaded from the exact link it records and must have the same files. */
86
+ export declare function install(root: string, options?: InstallOptions & {
87
+ cache?: Map<string, Buffer>;
88
+ }): Promise<Lock>;
89
+ /** Problems with a project's libraries, found without downloading: kerf.json
90
+ * and kerf.lock disagree, or kerf_libraries/ differs from kerf.lock. */
91
+ export declare function check(root: string): string[];
92
+ /** Adds a library to kerf.json, under the name its own kerf.json gives, and
93
+ * installs it. Makes kerf.json if the folder has none. */
94
+ export declare function add(root: string, source: string, options?: InstallOptions): Promise<{
95
+ name: string;
96
+ lock: Lock;
97
+ }>;
98
+ /** Removes a library from kerf.json, and from kerf_libraries/ and kerf.lock
99
+ * unless another library uses it. */
100
+ export declare function remove(root: string, name: string, options?: InstallOptions): Promise<Lock>;
101
+ /** Checks a library and writes it as name-version.tar.gz in its folder, or
102
+ * to `out`, ready to attach to a release. Every .kerf file must parse, and
103
+ * every `use <...>` must name the standard library, the library's own files
104
+ * as <name/...>, or a library its kerf.json names. */
105
+ export declare function pack(root: string, out?: string): {
106
+ file: string;
107
+ name: string;
108
+ version: string;
109
+ files: number;
110
+ integrity: string;
111
+ };
112
+ export {};