@takodotid/circuit 0.34.3 → 0.35.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 (240) hide show
  1. package/README.md +13 -14
  2. package/dist/chunks/index-20kcjxjg.js +174 -0
  3. package/dist/chunks/index-2r4bbhac.js +977 -0
  4. package/dist/chunks/index-n7w3tg5y.js +149 -0
  5. package/dist/chunks/new-w3zys5y4.js +172 -0
  6. package/dist/chunks/server-gzsf5me5.js +259 -0
  7. package/dist/cli/index.js +11345 -9024
  8. package/dist/helpers/index.js +594 -0
  9. package/dist/index.js +9 -28
  10. package/dist/types/core/{addresses.d.ts → address-space.d.ts} +23 -7
  11. package/dist/types/core/address.d.ts +44 -0
  12. package/dist/types/core/cabling.d.ts +41 -0
  13. package/dist/types/core/cross-checks.d.ts +28 -0
  14. package/dist/types/core/define.d.ts +25 -3
  15. package/dist/types/core/project-files.d.ts +12 -0
  16. package/dist/types/core/schema-docs.d.ts +13 -4
  17. package/dist/types/core/secrets.d.ts +62 -21
  18. package/dist/types/core/{graph.d.ts → topology.d.ts} +32 -12
  19. package/dist/types/core/utils.d.ts +8 -0
  20. package/dist/types/core/validator.d.ts +19 -0
  21. package/dist/types/helpers/bgp.d.ts +97 -0
  22. package/dist/types/helpers/checks.d.ts +32 -0
  23. package/dist/types/helpers/exchange.d.ts +49 -0
  24. package/dist/types/helpers/filters.d.ts +51 -0
  25. package/dist/types/helpers/index.d.ts +10 -0
  26. package/dist/types/helpers/route-server.d.ts +52 -0
  27. package/dist/types/index.d.ts +5 -3
  28. package/dist/types/integrations/librenms.d.ts +60 -0
  29. package/dist/types/integrations/netbox.d.ts +89 -0
  30. package/dist/types/integrations/peeringdb.d.ts +24 -0
  31. package/dist/types/integrations/prometheus.d.ts +24 -0
  32. package/dist/types/integrations/registries.d.ts +8 -0
  33. package/dist/types/platforms/bgp-wait.d.ts +18 -0
  34. package/dist/types/platforms/catalog.d.ts +109 -0
  35. package/dist/types/platforms/derive.d.ts +17 -0
  36. package/dist/types/platforms/fortios/firewall.d.ts +45 -0
  37. package/dist/types/platforms/fortios/index.d.ts +134 -0
  38. package/dist/types/platforms/fortios/names.d.ts +52 -0
  39. package/dist/types/platforms/fortios/plan.d.ts +104 -0
  40. package/dist/types/platforms/fortios/render.d.ts +75 -0
  41. package/dist/types/platforms/fortios/routing.d.ts +56 -0
  42. package/dist/types/platforms/fortios/tree.d.ts +37 -0
  43. package/dist/types/platforms/index.d.ts +13 -0
  44. package/dist/types/platforms/junos/bgp.d.ts +44 -0
  45. package/dist/types/platforms/junos/index.d.ts +114 -0
  46. package/dist/types/platforms/junos/render.d.ts +154 -0
  47. package/dist/types/platforms/line-diff.d.ts +67 -0
  48. package/dist/types/platforms/platform.d.ts +120 -0
  49. package/dist/types/platforms/raisecom-ros/index.d.ts +71 -0
  50. package/dist/types/platforms/raisecom-ros/render.d.ts +41 -0
  51. package/dist/types/platforms/routeros/export.d.ts +59 -0
  52. package/dist/types/platforms/routeros/index.d.ts +96 -0
  53. package/dist/types/{adapters/devices → platforms}/routeros/models.d.ts +4 -0
  54. package/dist/types/platforms/routeros/plan.d.ts +54 -0
  55. package/dist/types/platforms/routeros/render.d.ts +240 -0
  56. package/dist/types/platforms/vrp/index.d.ts +83 -0
  57. package/dist/types/platforms/vrp/render.d.ts +96 -0
  58. package/dist/types/schema/common.d.ts +12 -6
  59. package/dist/types/schema/index.d.ts +1 -0
  60. package/dist/types/schema/interfaces.d.ts +14 -6
  61. package/dist/types/schema/policy.d.ts +18 -10
  62. package/dist/types/schema/routing.d.ts +14 -1
  63. package/dist/types/schema/system.d.ts +16 -6
  64. package/dist/types/schema/time-zones.d.ts +2 -0
  65. package/dist/types/transport/console.d.ts +79 -23
  66. package/dist/types/transport/path-check.d.ts +32 -0
  67. package/dist/types/transport/ssh.d.ts +17 -15
  68. package/package.json +17 -11
  69. package/src/cli/graph-format.ts +91 -0
  70. package/src/cli/index.ts +1074 -484
  71. package/src/cli/new.ts +208 -175
  72. package/src/cli/rename.ts +97 -91
  73. package/src/core/address-space.ts +320 -0
  74. package/src/core/address.ts +202 -0
  75. package/src/core/cabling.ts +154 -0
  76. package/src/core/cross-checks.ts +364 -0
  77. package/src/core/define.ts +26 -3
  78. package/src/core/project-files.ts +35 -0
  79. package/src/core/schema-docs.ts +138 -130
  80. package/src/core/secrets.ts +170 -76
  81. package/src/core/topology.ts +656 -0
  82. package/src/core/utils.ts +37 -0
  83. package/src/core/validator.ts +407 -0
  84. package/src/helpers/bgp.ts +301 -0
  85. package/src/helpers/checks.ts +178 -0
  86. package/src/helpers/exchange.ts +117 -0
  87. package/src/helpers/filters.ts +107 -0
  88. package/src/helpers/index.ts +12 -0
  89. package/src/helpers/route-server.ts +212 -0
  90. package/src/index.ts +6 -3
  91. package/src/integrations/librenms.ts +291 -0
  92. package/src/integrations/netbox.ts +620 -0
  93. package/src/integrations/peeringdb.ts +173 -0
  94. package/src/integrations/prometheus.ts +90 -0
  95. package/src/integrations/registries.ts +25 -0
  96. package/src/platforms/bgp-wait.ts +41 -0
  97. package/src/platforms/catalog.ts +69 -0
  98. package/src/platforms/derive.ts +117 -0
  99. package/src/{adapters/devices → platforms}/fortios/TRAPS.md +6 -0
  100. package/src/platforms/fortios/firewall.ts +377 -0
  101. package/src/platforms/fortios/index.ts +1060 -0
  102. package/src/platforms/fortios/names.ts +130 -0
  103. package/src/platforms/fortios/plan.ts +929 -0
  104. package/src/platforms/fortios/render.ts +779 -0
  105. package/src/platforms/fortios/routing.ts +476 -0
  106. package/src/platforms/fortios/tree.ts +129 -0
  107. package/src/platforms/index.ts +36 -0
  108. package/src/{adapters/devices → platforms}/junos/TRAPS.md +8 -0
  109. package/src/platforms/junos/bgp.ts +293 -0
  110. package/src/platforms/junos/index.ts +1006 -0
  111. package/src/platforms/junos/render.ts +967 -0
  112. package/src/platforms/line-diff.ts +244 -0
  113. package/src/platforms/platform.ts +122 -0
  114. package/src/platforms/raisecom-ros/TRAPS.md +40 -0
  115. package/src/platforms/raisecom-ros/index.ts +731 -0
  116. package/src/platforms/raisecom-ros/render.ts +328 -0
  117. package/src/{adapters/devices → platforms}/routeros/TRAPS.md +16 -2
  118. package/src/platforms/routeros/export.ts +342 -0
  119. package/src/platforms/routeros/index.ts +636 -0
  120. package/src/{adapters/devices → platforms}/routeros/models.ts +2 -0
  121. package/src/platforms/routeros/plan.ts +444 -0
  122. package/src/platforms/routeros/render.ts +1483 -0
  123. package/src/platforms/vrp/TRAPS.md +45 -0
  124. package/src/platforms/vrp/index.ts +652 -0
  125. package/src/platforms/vrp/render.ts +615 -0
  126. package/src/schema/common.ts +15 -6
  127. package/src/schema/index.ts +1 -0
  128. package/src/schema/interfaces.ts +15 -5
  129. package/src/schema/policy.ts +22 -10
  130. package/src/schema/routing.ts +16 -1
  131. package/src/schema/system.ts +16 -6
  132. package/src/schema/time-zones.ts +482 -0
  133. package/src/studio/data.ts +172 -168
  134. package/src/studio/git.ts +95 -90
  135. package/src/studio/public/app.js +161 -150
  136. package/src/studio/public/compare.js +219 -212
  137. package/src/studio/public/diff.js +77 -75
  138. package/src/studio/public/dom.js +118 -108
  139. package/src/studio/public/evaluate.js +584 -545
  140. package/src/studio/public/export.js +120 -118
  141. package/src/studio/public/graph.js +1343 -1266
  142. package/src/studio/public/net.js +115 -109
  143. package/src/studio/public/tables.js +1135 -1083
  144. package/src/studio/public/tools.js +561 -529
  145. package/src/studio/server.ts +202 -196
  146. package/src/transport/console.ts +363 -271
  147. package/src/transport/path-check.ts +91 -0
  148. package/src/transport/ssh.ts +98 -94
  149. package/templates/colocation/checks.ts +11 -6
  150. package/templates/colocation/edge-01.ts +9 -9
  151. package/templates/colocation/routing.ts +2 -2
  152. package/templates/colocation/tenancy.ts +3 -3
  153. package/templates/colocation/tor-01.ts +3 -3
  154. package/templates/edge-router/checks.ts +4 -4
  155. package/templates/edge-router/edge-01.ts +5 -5
  156. package/templates/edge-router/routing.ts +2 -2
  157. package/templates/project/AGENTS.md +5 -1
  158. package/templates/single-site/checks.ts +2 -2
  159. package/dist/chunks/index-47debt16.js +0 -956
  160. package/dist/chunks/index-v8zgr7wm.js +0 -128
  161. package/dist/chunks/new-ny89s7y7.js +0 -166
  162. package/dist/chunks/server-tjbb3rqc.js +0 -251
  163. package/dist/presets/index.js +0 -394
  164. package/dist/types/adapters/devices/catalog.d.ts +0 -86
  165. package/dist/types/adapters/devices/derive.d.ts +0 -7
  166. package/dist/types/adapters/devices/fortios/firewall.d.ts +0 -23
  167. package/dist/types/adapters/devices/fortios/index.d.ts +0 -58
  168. package/dist/types/adapters/devices/fortios/names.d.ts +0 -48
  169. package/dist/types/adapters/devices/fortios/plan.d.ts +0 -28
  170. package/dist/types/adapters/devices/fortios/render.d.ts +0 -38
  171. package/dist/types/adapters/devices/fortios/routing.d.ts +0 -32
  172. package/dist/types/adapters/devices/fortios/tree.d.ts +0 -33
  173. package/dist/types/adapters/devices/index.d.ts +0 -3
  174. package/dist/types/adapters/devices/junos/bgp.d.ts +0 -11
  175. package/dist/types/adapters/devices/junos/index.d.ts +0 -42
  176. package/dist/types/adapters/devices/junos/render.d.ts +0 -52
  177. package/dist/types/adapters/devices/lines.d.ts +0 -56
  178. package/dist/types/adapters/devices/raisecom-ros/index.d.ts +0 -28
  179. package/dist/types/adapters/devices/routeros/export.d.ts +0 -39
  180. package/dist/types/adapters/devices/routeros/index.d.ts +0 -30
  181. package/dist/types/adapters/devices/routeros/plan.d.ts +0 -4
  182. package/dist/types/adapters/devices/routeros/render.d.ts +0 -100
  183. package/dist/types/adapters/devices/types.d.ts +0 -40
  184. package/dist/types/adapters/devices/vrp/index.d.ts +0 -27
  185. package/dist/types/adapters/registries/index.d.ts +0 -3
  186. package/dist/types/adapters/registries/librenms.d.ts +0 -15
  187. package/dist/types/adapters/registries/peeringdb.d.ts +0 -16
  188. package/dist/types/adapters/registries/prometheus.d.ts +0 -16
  189. package/dist/types/core/across.d.ts +0 -4
  190. package/dist/types/core/addr.d.ts +0 -34
  191. package/dist/types/core/files.d.ts +0 -6
  192. package/dist/types/core/merge.d.ts +0 -4
  193. package/dist/types/core/time.d.ts +0 -2
  194. package/dist/types/core/validate.d.ts +0 -2
  195. package/dist/types/presets/index.d.ts +0 -183
  196. package/src/adapters/devices/catalog.ts +0 -41
  197. package/src/adapters/devices/derive.ts +0 -59
  198. package/src/adapters/devices/fortios/firewall.ts +0 -362
  199. package/src/adapters/devices/fortios/index.ts +0 -923
  200. package/src/adapters/devices/fortios/names.ts +0 -115
  201. package/src/adapters/devices/fortios/plan.ts +0 -888
  202. package/src/adapters/devices/fortios/render.ts +0 -768
  203. package/src/adapters/devices/fortios/routing.ts +0 -444
  204. package/src/adapters/devices/fortios/tree.ts +0 -121
  205. package/src/adapters/devices/index.ts +0 -9
  206. package/src/adapters/devices/junos/bgp.ts +0 -269
  207. package/src/adapters/devices/junos/index.ts +0 -862
  208. package/src/adapters/devices/junos/render.ts +0 -872
  209. package/src/adapters/devices/lines.ts +0 -212
  210. package/src/adapters/devices/raisecom-ros/TRAPS.md +0 -26
  211. package/src/adapters/devices/raisecom-ros/index.ts +0 -700
  212. package/src/adapters/devices/routeros/export.ts +0 -321
  213. package/src/adapters/devices/routeros/index.ts +0 -346
  214. package/src/adapters/devices/routeros/plan.ts +0 -398
  215. package/src/adapters/devices/routeros/render.ts +0 -1490
  216. package/src/adapters/devices/types.ts +0 -38
  217. package/src/adapters/devices/vrp/TRAPS.md +0 -26
  218. package/src/adapters/devices/vrp/index.ts +0 -865
  219. package/src/adapters/registries/index.ts +0 -19
  220. package/src/adapters/registries/librenms.ts +0 -92
  221. package/src/adapters/registries/peeringdb.ts +0 -169
  222. package/src/adapters/registries/prometheus.ts +0 -71
  223. package/src/cli/graph.ts +0 -89
  224. package/src/core/across.ts +0 -350
  225. package/src/core/addr.ts +0 -174
  226. package/src/core/addresses.ts +0 -316
  227. package/src/core/files.ts +0 -32
  228. package/src/core/graph.ts +0 -640
  229. package/src/core/merge.ts +0 -19
  230. package/src/core/time.ts +0 -15
  231. package/src/core/validate.ts +0 -348
  232. package/src/presets/index.ts +0 -579
  233. /package/dist/types/{adapters/devices → platforms}/fortios/models.d.ts +0 -0
  234. /package/dist/types/{adapters/devices → platforms}/junos/models.d.ts +0 -0
  235. /package/dist/types/{adapters/devices → platforms}/raisecom-ros/models.d.ts +0 -0
  236. /package/dist/types/{adapters/devices → platforms}/vrp/models.d.ts +0 -0
  237. /package/src/{adapters/devices → platforms}/fortios/models.ts +0 -0
  238. /package/src/{adapters/devices → platforms}/junos/models.ts +0 -0
  239. /package/src/{adapters/devices → platforms}/raisecom-ros/models.ts +0 -0
  240. /package/src/{adapters/devices → platforms}/vrp/models.ts +0 -0
@@ -0,0 +1,149 @@
1
+ // src/core/address.ts
2
+ class Address2 {
3
+ static NOT_GLOBAL_V4 = [
4
+ "0.0.0.0/8",
5
+ "10.0.0.0/8",
6
+ "100.64.0.0/10",
7
+ "127.0.0.0/8",
8
+ "169.254.0.0/16",
9
+ "172.16.0.0/12",
10
+ "192.0.2.0/24",
11
+ "192.168.0.0/16",
12
+ "198.18.0.0/15",
13
+ "198.51.100.0/24",
14
+ "203.0.113.0/24"
15
+ ];
16
+ static family(address) {
17
+ return address.includes(":") ? "ipv6" : "ipv4";
18
+ }
19
+ static bits(family) {
20
+ return family === "ipv4" ? 32 : 128;
21
+ }
22
+ static toNumber(address) {
23
+ if (!address.includes(":")) {
24
+ const octets = address.split(".");
25
+ const valid = octets.length === 4 && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255);
26
+ if (!valid)
27
+ return null;
28
+ return octets.reduce((value, octet) => value << 8n | BigInt(octet), 0n);
29
+ }
30
+ const [before, after, extra] = address.split("::");
31
+ if (extra !== undefined)
32
+ return null;
33
+ const groupsOf = (text) => text ? text.split(":") : [];
34
+ const leading = groupsOf(before);
35
+ const trailing = groupsOf(after);
36
+ const zeros = after === undefined ? 0 : 8 - leading.length - trailing.length;
37
+ const groups = [...leading, ...Array(zeros).fill("0"), ...trailing];
38
+ const valid = groups.length === 8 && groups.every((group) => /^[0-9a-fA-F]{1,4}$/.test(group));
39
+ if (!valid)
40
+ return null;
41
+ return groups.reduce((value, group) => value << 16n | BigInt(parseInt(group, 16)), 0n);
42
+ }
43
+ static split(cidr) {
44
+ const [address, lengthText] = cidr.split("/");
45
+ const family = Address2.family(address);
46
+ const length = Number(lengthText);
47
+ const valid = Address2.toNumber(address) !== null && lengthText !== undefined && Number.isInteger(length) && length >= 0 && length <= Address2.bits(family);
48
+ if (!valid)
49
+ throw new Error(`'${cidr}' is not an address with a length`);
50
+ return { addr: address, len: length, family };
51
+ }
52
+ static isValid(text) {
53
+ return Address2.toNumber(text) !== null;
54
+ }
55
+ static isCidr(text) {
56
+ try {
57
+ Address2.split(text);
58
+ return true;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+ static mask(length, family) {
64
+ const all = (1n << BigInt(Address2.bits(family))) - 1n;
65
+ const hostBits = (1n << BigInt(Address2.bits(family) - length)) - 1n;
66
+ return all ^ hostBits;
67
+ }
68
+ static fromNumber(value, family) {
69
+ if (family === "ipv4") {
70
+ return [24n, 16n, 8n, 0n].map((shift) => String(value >> shift & 255n)).join(".");
71
+ }
72
+ const groups = Array.from({ length: 8 }, (_, index) => (value >> BigInt(112 - index * 16) & 0xffffn).toString(16));
73
+ let longestStart = -1;
74
+ let longestLength = 0;
75
+ for (let start = 0;start < 8; ) {
76
+ let end = start;
77
+ while (end < 8 && groups[end] === "0")
78
+ end++;
79
+ const runLength = end - start;
80
+ if (runLength > longestLength && runLength > 1) {
81
+ longestStart = start;
82
+ longestLength = runLength;
83
+ }
84
+ start = end === start ? start + 1 : end;
85
+ }
86
+ if (longestStart < 0)
87
+ return groups.join(":");
88
+ const head = groups.slice(0, longestStart).join(":");
89
+ const tail = groups.slice(longestStart + longestLength).join(":");
90
+ return `${head}::${tail}`;
91
+ }
92
+ static canonical(text) {
93
+ const [address, length] = text.split("/");
94
+ const value = Address2.toNumber(address);
95
+ if (value === null)
96
+ return text;
97
+ const spelled = Address2.fromNumber(value, Address2.family(address));
98
+ return length === undefined ? spelled : `${spelled}/${length}`;
99
+ }
100
+ static prefixOf(cidr) {
101
+ const { addr, len, family } = Address2.split(cidr);
102
+ return `${Address2.fromNumber(Address2.toNumber(addr) & Address2.mask(len, family), family)}/${len}`;
103
+ }
104
+ static contains(outer, inner) {
105
+ const outerParts = Address2.split(outer);
106
+ const [innerAddress, innerLengthText] = inner.split("/");
107
+ if (Address2.family(innerAddress) !== outerParts.family)
108
+ return false;
109
+ const innerLength = innerLengthText === undefined ? Address2.bits(outerParts.family) : Number(innerLengthText);
110
+ if (innerLength < outerParts.len)
111
+ return false;
112
+ const outerMask = Address2.mask(outerParts.len, outerParts.family);
113
+ return (Address2.toNumber(innerAddress) & outerMask) === (Address2.toNumber(outerParts.addr) & outerMask);
114
+ }
115
+ static range(cidr) {
116
+ const { addr, len, family } = Address2.split(cidr);
117
+ const hostBits = Address2.mask(len, family) ^ (1n << BigInt(Address2.bits(family))) - 1n;
118
+ const first = Address2.toNumber(addr) & Address2.mask(len, family);
119
+ return { first, last: first | hostBits, family };
120
+ }
121
+ static prefixesBetween(first, last, family) {
122
+ const bits = Address2.bits(family);
123
+ const prefixes = [];
124
+ for (let start = first;start <= last; ) {
125
+ let size = 0;
126
+ while (size < bits && start % (1n << BigInt(size + 1)) === 0n && start + (1n << BigInt(size + 1)) - 1n <= last)
127
+ size++;
128
+ prefixes.push(`${Address2.fromNumber(start, family)}/${bits - size}`);
129
+ start += 1n << BigInt(size);
130
+ }
131
+ return prefixes;
132
+ }
133
+ static netmask(length) {
134
+ return Address2.fromNumber(Address2.mask(length, "ipv4"), "ipv4");
135
+ }
136
+ static wildcard(length) {
137
+ return Address2.fromNumber(Address2.mask(length, "ipv4") ^ 0xffffffffn, "ipv4");
138
+ }
139
+ static host(cidr) {
140
+ return cidr.split("/")[0];
141
+ }
142
+ static isGlobal(address) {
143
+ if (Address2.family(address) === "ipv6")
144
+ return Address2.contains("2000::/3", address) && !Address2.contains("2001:db8::/32", address);
145
+ return !Address2.NOT_GLOBAL_V4.some((prefix) => Address2.contains(prefix, address));
146
+ }
147
+ }
148
+
149
+ export { Address2 };
@@ -0,0 +1,172 @@
1
+ // src/cli/new.ts
2
+ import { spawnSync } from "node:child_process";
3
+ import { cpSync, existsSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import * as prompts from "@clack/prompts";
7
+
8
+ class Scaffold {
9
+ static ROOT = Scaffold.packageRoot();
10
+ static TEMPLATES = join(Scaffold.ROOT, "templates");
11
+ static CIRCUIT = JSON.parse(readFileSync(join(Scaffold.ROOT, "package.json"), "utf8"));
12
+ static MANAGERS = {
13
+ npm: { install: "npm install", run: "npx circuit", types: "node" },
14
+ pnpm: { install: "pnpm install", run: "pnpm circuit", types: "node" },
15
+ bun: { install: "bun install", run: "bun circuit", types: "bun" }
16
+ };
17
+ static PATTERNS = {
18
+ "single-site": {
19
+ title: "A single site",
20
+ fits: "a home, an office or an internal network: a router and a switch, no BGP",
21
+ asn: false
22
+ },
23
+ "edge-router": { title: "An edge router", fits: "your own AS number, with an IP transit and an internet exchange", asn: true },
24
+ colocation: {
25
+ title: "Colocation with tenants",
26
+ fits: "a provider whose customers each get their own VLANs, addresses and ports",
27
+ asn: true
28
+ }
29
+ };
30
+ static EXAMPLE_ASN = "64500";
31
+ static packageRoot() {
32
+ let directory = dirname(fileURLToPath(import.meta.url));
33
+ while (!existsSync(join(directory, "templates"))) {
34
+ const parent = dirname(directory);
35
+ if (parent === directory)
36
+ throw new Error("Circuit's templates are missing from its package");
37
+ directory = parent;
38
+ }
39
+ return directory;
40
+ }
41
+ static detectManager() {
42
+ const agent = process.env.npm_config_user_agent ?? "";
43
+ if (agent.startsWith("pnpm/"))
44
+ return "pnpm";
45
+ if (agent.startsWith("bun/") || process.versions.bun)
46
+ return "bun";
47
+ return "npm";
48
+ }
49
+ static fail(message) {
50
+ console.error(message);
51
+ process.exit(1);
52
+ }
53
+ static filesIn(directory) {
54
+ return readdirSync(directory, { recursive: true, withFileTypes: true }).filter((entry) => entry.isFile()).map((entry) => relative(directory, join(entry.parentPath, entry.name)));
55
+ }
56
+ static notEmpty(directory) {
57
+ const target = resolve(process.cwd(), directory);
58
+ return existsSync(target) && readdirSync(target).length ? `${target} is not empty` : undefined;
59
+ }
60
+ static async ask(question, fallback) {
61
+ if (process.stdin.isTTY !== true)
62
+ return fallback;
63
+ const answer = await question();
64
+ if (prompts.isCancel(answer)) {
65
+ prompts.cancel("Nothing created.");
66
+ process.exit(1);
67
+ }
68
+ return answer;
69
+ }
70
+ static async create(directoryArgument, options) {
71
+ const directory = directoryArgument ?? await Scaffold.ask(() => prompts.text({
72
+ message: "Directory for the project",
73
+ placeholder: "my-network",
74
+ defaultValue: "my-network",
75
+ validate: (value) => Scaffold.notEmpty(value || "my-network")
76
+ }), "my-network");
77
+ const notEmpty = Scaffold.notEmpty(directory);
78
+ if (notEmpty)
79
+ Scaffold.fail(notEmpty);
80
+ const target = resolve(process.cwd(), directory);
81
+ const names = Object.keys(Scaffold.PATTERNS);
82
+ const pattern = options.pattern ?? await Scaffold.ask(() => prompts.select({
83
+ message: "Which is closest to your network?",
84
+ options: names.map((name) => ({
85
+ value: name,
86
+ label: Scaffold.PATTERNS[name].title,
87
+ hint: Scaffold.PATTERNS[name].fits
88
+ }))
89
+ }), names[0]);
90
+ if (!Object.hasOwn(Scaffold.PATTERNS, pattern))
91
+ Scaffold.fail(`no pattern ${pattern}; there are ${names.join(", ")}`);
92
+ const chosen = Scaffold.PATTERNS[pattern];
93
+ let asn = options.asn;
94
+ if (!asn && chosen.asn) {
95
+ asn = await Scaffold.ask(() => prompts.text({
96
+ message: "Your AS number, or press enter to keep the documentation example",
97
+ placeholder: Scaffold.EXAMPLE_ASN,
98
+ defaultValue: Scaffold.EXAMPLE_ASN,
99
+ validate: (value) => !value || /^\d+$/.test(value) ? undefined : `${value} is not an AS number`
100
+ }), Scaffold.EXAMPLE_ASN);
101
+ }
102
+ if (asn && !/^\d+$/.test(asn))
103
+ Scaffold.fail(`${asn} is not an AS number`);
104
+ const manager = options.use ?? Scaffold.detectManager();
105
+ if (!Object.hasOwn(Scaffold.MANAGERS, manager)) {
106
+ Scaffold.fail(`no package manager ${manager}; there are ${Object.keys(Scaffold.MANAGERS).join(", ")}`);
107
+ }
108
+ const { install, run, types } = Scaffold.MANAGERS[manager];
109
+ const onePassword = options.onePassword || await Scaffold.ask(() => prompts.confirm({ message: "Keep the secrets in 1Password?", initialValue: false }), false);
110
+ cpSync(join(Scaffold.TEMPLATES, pattern), target, { recursive: true });
111
+ cpSync(join(Scaffold.TEMPLATES, "project"), target, { recursive: true });
112
+ renameSync(join(target, "gitignore"), join(target, ".gitignore"));
113
+ for (const file of ["AGENTS.md", "README.md", "tsconfig.json"]) {
114
+ const path = join(target, file);
115
+ const text = readFileSync(path, "utf8").replaceAll("npx circuit", run).replaceAll("npm install", install).replaceAll('"types": ["node"]', `"types": ["${types}"]`);
116
+ writeFileSync(path, text);
117
+ }
118
+ const sources = Scaffold.filesIn(target).filter((file) => file.endsWith(".ts"));
119
+ const secrets = new Set;
120
+ for (const file of sources) {
121
+ const path = join(target, file);
122
+ let text = readFileSync(path, "utf8");
123
+ if (asn && asn !== Scaffold.EXAMPLE_ASN)
124
+ text = text.replaceAll(new RegExp(`\\b${Scaffold.EXAMPLE_ASN}\\b`, "g"), asn);
125
+ for (const [, name] of text.matchAll(/secret\("([A-Z0-9_]+)"\)/g))
126
+ secrets.add(name);
127
+ writeFileSync(path, text);
128
+ }
129
+ const env = [
130
+ "# Secrets for Circuit. Never commit this file.",
131
+ "# A value is the secret itself, or a 1Password reference, op://vault/item/field, read with the 1Password CLI.",
132
+ "# Put quotes around a value that has a # in it: without them, # starts a comment.",
133
+ ...[...secrets].sort().map((name) => onePassword ? `${name}=op://Network/${name}/password` : `${name}=`),
134
+ ""
135
+ ];
136
+ writeFileSync(join(target, ".env"), env.join(`
137
+ `));
138
+ const name = basename(target).toLowerCase().replace(/[^a-z0-9-]+/g, "-");
139
+ const packageJson = {
140
+ name,
141
+ private: true,
142
+ type: "module",
143
+ dependencies: { "@takodotid/circuit": Scaffold.CIRCUIT.version },
144
+ devDependencies: { [`@types/${types}`]: Scaffold.CIRCUIT.devDependencies[`@types/${types}`] }
145
+ };
146
+ writeFileSync(join(target, "package.json"), JSON.stringify(packageJson, null, 4) + `
147
+ `);
148
+ if (options.install) {
149
+ const result = spawnSync(install, { cwd: target, stdio: "inherit", shell: true });
150
+ if (result.status !== 0)
151
+ console.log(`${install} failed; run it again in the project.`);
152
+ }
153
+ const steps = [
154
+ `cd ${directory}`,
155
+ onePassword ? `Point each line of .env at the item that holds it in 1Password, then run: ${run} secrets` : `Fill in each password in .env, then run: ${run} secrets`,
156
+ "Change the names, addresses and ports in the device files to your own.",
157
+ ...chosen.asn && (!asn || asn === Scaffold.EXAMPLE_ASN) ? ["Put your own AS number in routing.ts."] : [],
158
+ `${run} validate`,
159
+ `${run} snapshot, then ${run} diff, to see what would change on each device`
160
+ ];
161
+ console.log(`
162
+ Created ${directory} from the pattern "${chosen.title}".
163
+
164
+ Next:`);
165
+ steps.forEach((step, index) => console.log(` ${index + 1}. ${step}`));
166
+ console.log(`
167
+ What each file does: https://circuit.tako.id/patterns/${pattern}`);
168
+ }
169
+ }
170
+ export {
171
+ Scaffold
172
+ };
@@ -0,0 +1,259 @@
1
+ import {
2
+ StudioModel
3
+ } from "./index-2r4bbhac.js";
4
+
5
+ // src/studio/server.ts
6
+ import { execFile as execFile2, spawn } from "node:child_process";
7
+ import { existsSync, readFileSync, watch } from "node:fs";
8
+ import { createServer } from "node:http";
9
+ import { extname, join as join2 } from "node:path";
10
+
11
+ // src/studio/git.ts
12
+ import { execFile } from "node:child_process";
13
+ import { mkdirSync, writeFileSync } from "node:fs";
14
+ import { basename, join } from "node:path";
15
+
16
+ class Git {
17
+ static FORMAT = "--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s";
18
+ static environment() {
19
+ return Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")));
20
+ }
21
+ static run(cwd, args) {
22
+ return new Promise((done, fail) => {
23
+ execFile("git", args, { cwd, env: Git.environment(), maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
24
+ if (error)
25
+ fail(new Error((stderr || error.message).trim()));
26
+ else
27
+ done(stdout);
28
+ });
29
+ });
30
+ }
31
+ static commitsOf(text) {
32
+ return text.split(`
33
+ `).filter(Boolean).map((line) => {
34
+ const [commit = "", short = "", author = "", date = "", subject = ""] = line.split("\x1F");
35
+ return { commit, short, author, date, subject };
36
+ });
37
+ }
38
+ static async top(directory) {
39
+ try {
40
+ return (await Git.run(directory, ["rev-parse", "--show-toplevel"])).trim();
41
+ } catch {
42
+ return;
43
+ }
44
+ }
45
+ static async history(directory, files, limit = 50) {
46
+ if (!files.length)
47
+ return [];
48
+ return Git.commitsOf(await Git.run(directory, ["log", `-n${limit}`, Git.FORMAT, "--", ...files]));
49
+ }
50
+ static async references(directory) {
51
+ const names = (await Git.run(directory, [
52
+ "for-each-ref",
53
+ "--count=100",
54
+ "--sort=-committerdate",
55
+ "--format=%(refname:short)",
56
+ "refs/heads",
57
+ "refs/remotes",
58
+ "refs/tags"
59
+ ])).split(`
60
+ `).filter((name) => name && !name.endsWith("/HEAD"));
61
+ return { names, commits: Git.commitsOf(await Git.run(directory, ["log", "-n30", Git.FORMAT])) };
62
+ }
63
+ static async commitOf(directory, name) {
64
+ if (!/^[A-Za-z0-9][\w./@^~-]*$/.test(name))
65
+ return;
66
+ try {
67
+ const [commit] = Git.commitsOf(await Git.run(directory, ["log", "-n1", Git.FORMAT, `${name}^{commit}`, "--"]));
68
+ return commit;
69
+ } catch {
70
+ return;
71
+ }
72
+ }
73
+ static async networkAt(configDirectory, configPath, commit, gather) {
74
+ const top = await Git.top(configDirectory);
75
+ if (!top)
76
+ throw new Error("the config is not in a git repository");
77
+ const cache = join(configDirectory, ".circuit", "cache");
78
+ mkdirSync(cache, { recursive: true });
79
+ writeFileSync(join(cache, ".gitignore"), `# Written by Circuit Studio: checkouts of other commits, removed once read.
80
+ *
81
+ `);
82
+ await Git.run(top, ["worktree", "prune"]);
83
+ const checkout = join(cache, commit.slice(0, 12));
84
+ await Git.run(top, ["-c", "core.longpaths=true", "worktree", "add", "--detach", "--force", checkout, commit]);
85
+ try {
86
+ const prefix = (await Git.run(configDirectory, ["rev-parse", "--show-prefix"])).trim();
87
+ return await gather(join(checkout, prefix, basename(configPath)));
88
+ } finally {
89
+ await Git.run(top, ["-c", "core.longpaths=true", "worktree", "remove", "--force", checkout]).catch(() => {});
90
+ }
91
+ }
92
+ }
93
+
94
+ // src/studio/server.ts
95
+ class StudioServer {
96
+ static IGNORED = /(^|[\\/])(node_modules|\.git|\.circuit[\\/]cache)([\\/]|$)/;
97
+ static CONTENT_TYPES = {
98
+ ".html": "text/html; charset=utf-8",
99
+ ".css": "text/css; charset=utf-8",
100
+ ".js": "text/javascript; charset=utf-8",
101
+ ".svg": "image/svg+xml",
102
+ ".woff2": "font/woff2"
103
+ };
104
+ static isLoopback(host) {
105
+ return host === "localhost" || host === "::1" || /^127\.\d+\.\d+\.\d+$/.test(host);
106
+ }
107
+ static hostAllowed(header, port, allowHosts) {
108
+ if (!header)
109
+ return false;
110
+ if (header === `127.0.0.1:${port}` || header === `localhost:${port}` || header === `[::1]:${port}`)
111
+ return true;
112
+ const name = header.replace(/:\d+$/, "").toLowerCase();
113
+ return allowHosts.some((allowed) => {
114
+ const wanted = allowed.toLowerCase();
115
+ return wanted === header.toLowerCase() || wanted === name;
116
+ });
117
+ }
118
+ static gather(configPath) {
119
+ const cli = process.argv[1];
120
+ const args = [...process.execArgv, cli, "studio", "--json", `--config=${configPath}`];
121
+ return new Promise((done) => {
122
+ execFile2(process.execPath, args, { maxBuffer: 256 * 1024 * 1024 }, (error, stdout, stderr) => {
123
+ if (!error)
124
+ return done(stdout);
125
+ const message = (stderr || error.message).trim();
126
+ done(JSON.stringify({ error: message }));
127
+ });
128
+ });
129
+ }
130
+ static openBrowser(url) {
131
+ const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
132
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
133
+ child.on("error", () => {});
134
+ child.unref();
135
+ }
136
+ static async start(options) {
137
+ const { configPath, root, port } = options;
138
+ const installed = StudioModel.packageRoot();
139
+ if (!installed)
140
+ throw new Error("cannot find where Circuit is installed, so Studio has no page to serve");
141
+ const pages = join2(installed, "src", "studio", "public");
142
+ let data = await StudioServer.gather(configPath);
143
+ const past = new Map;
144
+ const answer = async (response, work) => {
145
+ let body;
146
+ try {
147
+ const result = await work();
148
+ body = typeof result === "string" ? result : JSON.stringify(result);
149
+ } catch (error) {
150
+ body = JSON.stringify({ error: error.message });
151
+ }
152
+ response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(body);
153
+ };
154
+ const listeners = new Set;
155
+ const tell = (message) => {
156
+ for (const listener of listeners)
157
+ listener.write(`data: ${message}
158
+
159
+ `);
160
+ };
161
+ const server = createServer((request, response) => {
162
+ response.setHeader("x-robots-tag", "noindex, nofollow, noarchive");
163
+ if (!StudioServer.hostAllowed(request.headers.host, port, options.allowHosts)) {
164
+ response.writeHead(403).end();
165
+ return;
166
+ }
167
+ const url = new URL(request.url ?? "/", "http://studio");
168
+ const path = url.pathname;
169
+ if (path === "/history") {
170
+ answer(response, async () => {
171
+ const name = url.searchParams.get("device") ?? "";
172
+ const files = JSON.parse(data).files?.[name];
173
+ if (!files)
174
+ throw new Error(`no device ${name}`);
175
+ return Git.history(root, [files.source, files.snapshot].filter((file) => Boolean(file)));
176
+ });
177
+ return;
178
+ }
179
+ if (path === "/refs") {
180
+ answer(response, () => Git.references(root));
181
+ return;
182
+ }
183
+ if (path === "/compare") {
184
+ answer(response, async () => {
185
+ const asked = url.searchParams.get("ref") ?? "";
186
+ const commit = await Git.commitOf(root, asked);
187
+ if (!commit)
188
+ throw new Error(`${asked} names no commit here`);
189
+ if (!past.has(commit.commit))
190
+ past.set(commit.commit, Git.networkAt(root, configPath, commit.commit, StudioServer.gather));
191
+ const network = await past.get(commit.commit);
192
+ if (network.startsWith('{"error"'))
193
+ past.delete(commit.commit);
194
+ return `{"commit":${JSON.stringify(commit)},"network":${network}}`;
195
+ });
196
+ return;
197
+ }
198
+ if (path === "/robots.txt") {
199
+ response.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end(`User-agent: *
200
+ Disallow: /
201
+ `);
202
+ return;
203
+ }
204
+ if (path === "/data") {
205
+ response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(data);
206
+ return;
207
+ }
208
+ if (path === "/events") {
209
+ response.writeHead(200, {
210
+ "content-type": "text/event-stream",
211
+ "cache-control": "no-store",
212
+ connection: "keep-alive",
213
+ "x-accel-buffering": "no"
214
+ });
215
+ response.write(`: connected
216
+
217
+ `);
218
+ listeners.add(response);
219
+ request.on("close", () => listeners.delete(response));
220
+ return;
221
+ }
222
+ const name = path === "/" ? "index.html" : path.slice(1);
223
+ const type = StudioServer.CONTENT_TYPES[extname(name)];
224
+ const file = join2(pages, name);
225
+ if (!/^[a-z-]+\.[a-z0-9]+$/.test(name) || !type || !existsSync(file)) {
226
+ response.writeHead(404).end();
227
+ return;
228
+ }
229
+ response.writeHead(200, { "content-type": type, "cache-control": "no-store" }).end(readFileSync(file));
230
+ });
231
+ let timer;
232
+ watch(root, { recursive: true }, (_event, filename) => {
233
+ if (filename && StudioServer.IGNORED.test(filename))
234
+ return;
235
+ clearTimeout(timer);
236
+ timer = setTimeout(async () => {
237
+ data = await StudioServer.gather(configPath);
238
+ tell("changed");
239
+ console.log(`${new Date().toLocaleTimeString()} ${filename ?? "a file"} changed, read again`);
240
+ }, 300);
241
+ });
242
+ watch(pages, () => tell("page"));
243
+ server.on("error", (error) => {
244
+ const message = error.code === "EADDRINUSE" ? `port ${port} is in use; choose another with --port=N` : error.message;
245
+ console.error(message);
246
+ process.exit(1);
247
+ });
248
+ server.listen(port, options.host, () => {
249
+ const local = StudioServer.isLoopback(options.host);
250
+ const url = local ? `http://127.0.0.1:${port}` : `http://${options.allowHosts[0] ?? options.host}`;
251
+ console.log(`Circuit Studio at ${url}, listening on ${options.host}:${port}, watching ${root}. Stop it with Ctrl+C.`);
252
+ if (options.open && local)
253
+ StudioServer.openBrowser(url);
254
+ });
255
+ }
256
+ }
257
+ export {
258
+ StudioServer
259
+ };