@takodotid/circuit 0.18.5 → 0.20.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 (47) hide show
  1. package/README.md +18 -0
  2. package/dist/chunks/index-jtzfw679.js +936 -0
  3. package/dist/chunks/{index-ex1wcst7.js → index-xm9nma2t.js} +20 -1
  4. package/dist/chunks/server-5shmsmse.js +246 -0
  5. package/dist/cli/index.js +701 -106
  6. package/dist/index.js +1 -1
  7. package/dist/presets/index.js +1 -1
  8. package/dist/types/adapters/devices/derive.d.ts +2 -0
  9. package/dist/types/core/across.d.ts +4 -0
  10. package/dist/types/core/addr.d.ts +10 -0
  11. package/dist/types/core/addresses.d.ts +46 -0
  12. package/dist/types/core/files.d.ts +6 -0
  13. package/dist/types/core/graph.d.ts +74 -0
  14. package/dist/types/core/schema-docs.d.ts +16 -0
  15. package/package.json +1 -1
  16. package/src/adapters/devices/derive.ts +32 -0
  17. package/src/adapters/devices/raisecom-ros/index.ts +23 -3
  18. package/src/adapters/devices/routeros/index.ts +10 -0
  19. package/src/adapters/devices/vrp/index.ts +10 -1
  20. package/src/cli/graph.ts +89 -0
  21. package/src/cli/index.ts +205 -2
  22. package/src/cli/rename.ts +129 -0
  23. package/src/core/across.ts +322 -0
  24. package/src/core/addr.ts +29 -0
  25. package/src/core/addresses.ts +316 -0
  26. package/src/core/files.ts +30 -0
  27. package/src/core/graph.ts +634 -0
  28. package/src/core/schema-docs.ts +166 -0
  29. package/src/core/validate.ts +2 -52
  30. package/src/studio/data.ts +255 -0
  31. package/src/studio/git.ts +119 -0
  32. package/src/studio/public/app.js +147 -0
  33. package/src/studio/public/compare.js +243 -0
  34. package/src/studio/public/diff.js +97 -0
  35. package/src/studio/public/dom.js +108 -0
  36. package/src/studio/public/evaluate.js +648 -0
  37. package/src/studio/public/export.js +122 -0
  38. package/src/studio/public/favicon.svg +6 -0
  39. package/src/studio/public/graph.js +914 -0
  40. package/src/studio/public/index.html +67 -0
  41. package/src/studio/public/net.js +128 -0
  42. package/src/studio/public/style.css +693 -0
  43. package/src/studio/public/tables.js +1223 -0
  44. package/src/studio/public/tools.js +578 -0
  45. package/src/studio/server.ts +218 -0
  46. package/templates/project/AGENTS.md +12 -9
  47. package/templates/project/README.md +1 -0
@@ -84,6 +84,25 @@ function contains(outer, inner) {
84
84
  const outerMask = mask(outerParts.len, outerParts.family);
85
85
  return (parse(innerAddress) & outerMask) === (parse(outerParts.addr) & outerMask);
86
86
  }
87
+ var formatAddress = (value, family) => format(value, family);
88
+ function rangeOf(cidr) {
89
+ const { addr, len, family } = split(cidr);
90
+ const hostBits = mask(len, family) ^ (1n << BigInt(bitsOf(family))) - 1n;
91
+ const first = parse(addr) & mask(len, family);
92
+ return { first, last: first | hostBits, family };
93
+ }
94
+ function prefixesBetween(first, last, family) {
95
+ const bits = bitsOf(family);
96
+ const prefixes = [];
97
+ for (let start = first;start <= last; ) {
98
+ let size = 0;
99
+ while (size < bits && start % (1n << BigInt(size + 1)) === 0n && start + (1n << BigInt(size + 1)) - 1n <= last)
100
+ size++;
101
+ prefixes.push(`${format(start, family)}/${bits - size}`);
102
+ start += 1n << BigInt(size);
103
+ }
104
+ return prefixes;
105
+ }
87
106
  var netmask = (length) => format(mask(length, "ipv4"), "ipv4");
88
107
  var wildcard = (length) => format(mask(length, "ipv4") ^ 0xffffffffn, "ipv4");
89
108
  var host = (cidr) => cidr.split("/")[0];
@@ -106,4 +125,4 @@ function isGlobal(address) {
106
125
  return !NOT_GLOBAL_V4.some((prefix) => contains(prefix, address));
107
126
  }
108
127
 
109
- export { familyOf, split, isAddress, isCidr, network, contains, netmask, wildcard, host, isGlobal };
128
+ export { familyOf, parse, split, isAddress, isCidr, network, contains, formatAddress, rangeOf, prefixesBetween, netmask, wildcard, host, isGlobal };
@@ -0,0 +1,246 @@
1
+ import {
2
+ packageRoot
3
+ } from "./index-jtzfw679.js";
4
+ import"./index-xm9nma2t.js";
5
+ import"./index-fq57hya4.js";
6
+
7
+ // src/studio/server.ts
8
+ import { execFile as execFile2, spawn } from "node:child_process";
9
+ import { existsSync, readFileSync, watch } from "node:fs";
10
+ import { createServer } from "node:http";
11
+ import { extname, join as join2 } from "node:path";
12
+
13
+ // src/studio/git.ts
14
+ import { execFile } from "node:child_process";
15
+ import { mkdirSync, writeFileSync } from "node:fs";
16
+ import { basename, join } from "node:path";
17
+ var environment = () => Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")));
18
+ function git(cwd, args) {
19
+ return new Promise((done, fail) => {
20
+ execFile("git", args, { cwd, env: environment(), maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
21
+ if (error)
22
+ fail(new Error((stderr || error.message).trim()));
23
+ else
24
+ done(stdout);
25
+ });
26
+ });
27
+ }
28
+ var FORMAT = "--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s";
29
+ function commitsOf(text) {
30
+ return text.split(`
31
+ `).filter(Boolean).map((line) => {
32
+ const [commit = "", short = "", author = "", date = "", subject = ""] = line.split("\x1F");
33
+ return { commit, short, author, date, subject };
34
+ });
35
+ }
36
+ async function gitTop(directory) {
37
+ try {
38
+ return (await git(directory, ["rev-parse", "--show-toplevel"])).trim();
39
+ } catch {
40
+ return;
41
+ }
42
+ }
43
+ async function history(directory, files, limit = 50) {
44
+ if (!files.length)
45
+ return [];
46
+ return commitsOf(await git(directory, ["log", `-n${limit}`, FORMAT, "--", ...files]));
47
+ }
48
+ async function references(directory) {
49
+ const names = (await git(directory, [
50
+ "for-each-ref",
51
+ "--count=100",
52
+ "--sort=-committerdate",
53
+ "--format=%(refname:short)",
54
+ "refs/heads",
55
+ "refs/remotes",
56
+ "refs/tags"
57
+ ])).split(`
58
+ `).filter((name) => name && !name.endsWith("/HEAD"));
59
+ return { names, commits: commitsOf(await git(directory, ["log", "-n30", FORMAT])) };
60
+ }
61
+ async function commitOf(directory, name) {
62
+ if (!/^[A-Za-z0-9][\w./@^~-]*$/.test(name))
63
+ return;
64
+ try {
65
+ const [commit] = commitsOf(await git(directory, ["log", "-n1", FORMAT, `${name}^{commit}`, "--"]));
66
+ return commit;
67
+ } catch {
68
+ return;
69
+ }
70
+ }
71
+ async function networkAt(configDirectory, configPath, commit, gather) {
72
+ const top = await gitTop(configDirectory);
73
+ if (!top)
74
+ throw new Error("the config is not in a git repository");
75
+ const cache = join(configDirectory, ".circuit", "cache");
76
+ mkdirSync(cache, { recursive: true });
77
+ writeFileSync(join(cache, ".gitignore"), `# Written by Circuit Studio: checkouts of other commits, removed once read.
78
+ *
79
+ `);
80
+ await git(top, ["worktree", "prune"]);
81
+ const checkout = join(cache, commit.slice(0, 12));
82
+ await git(top, ["worktree", "add", "--detach", "--force", checkout, commit]);
83
+ try {
84
+ const prefix = (await git(configDirectory, ["rev-parse", "--show-prefix"])).trim();
85
+ return await gather(join(checkout, prefix, basename(configPath)));
86
+ } finally {
87
+ await git(top, ["worktree", "remove", "--force", checkout]).catch(() => {});
88
+ }
89
+ }
90
+
91
+ // src/studio/server.ts
92
+ var isLoopback = (host) => host === "localhost" || host === "::1" || /^127\.\d+\.\d+\.\d+$/.test(host);
93
+ function hostAllowed(header, port, allowHosts) {
94
+ if (!header)
95
+ return false;
96
+ if (header === `127.0.0.1:${port}` || header === `localhost:${port}` || header === `[::1]:${port}`)
97
+ return true;
98
+ const name = header.replace(/:\d+$/, "").toLowerCase();
99
+ return allowHosts.some((allowed) => {
100
+ const wanted = allowed.toLowerCase();
101
+ return wanted === header.toLowerCase() || wanted === name;
102
+ });
103
+ }
104
+ var IGNORED = /(^|[\\/])(node_modules|\.git|\.circuit[\\/]cache)([\\/]|$)/;
105
+ var CONTENT_TYPES = {
106
+ ".html": "text/html; charset=utf-8",
107
+ ".css": "text/css; charset=utf-8",
108
+ ".js": "text/javascript; charset=utf-8",
109
+ ".svg": "image/svg+xml"
110
+ };
111
+ function gather(configPath) {
112
+ const cli = process.argv[1];
113
+ const args = [...process.execArgv, cli, "studio", "--json", `--config=${configPath}`];
114
+ return new Promise((done) => {
115
+ execFile2(process.execPath, args, { maxBuffer: 256 * 1024 * 1024 }, (error, stdout, stderr) => {
116
+ if (!error)
117
+ return done(stdout);
118
+ const message = (stderr || error.message).trim();
119
+ done(JSON.stringify({ error: message }));
120
+ });
121
+ });
122
+ }
123
+ function openBrowser(url) {
124
+ const [command, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
125
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
126
+ child.on("error", () => {});
127
+ child.unref();
128
+ }
129
+ async function studio(options) {
130
+ const { configPath, root, port } = options;
131
+ const installed = packageRoot();
132
+ if (!installed)
133
+ throw new Error("cannot find where Circuit is installed, so Studio has no page to serve");
134
+ const pages = join2(installed, "src", "studio", "public");
135
+ let data = await gather(configPath);
136
+ const past = new Map;
137
+ const answer = async (response, work) => {
138
+ let body;
139
+ try {
140
+ const result = await work();
141
+ body = typeof result === "string" ? result : JSON.stringify(result);
142
+ } catch (error) {
143
+ body = JSON.stringify({ error: error.message });
144
+ }
145
+ response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(body);
146
+ };
147
+ const listeners = new Set;
148
+ const tell = (message) => {
149
+ for (const listener of listeners)
150
+ listener.write(`data: ${message}
151
+
152
+ `);
153
+ };
154
+ const server = createServer((request, response) => {
155
+ if (!hostAllowed(request.headers.host, port, options.allowHosts)) {
156
+ response.writeHead(403).end();
157
+ return;
158
+ }
159
+ const url = new URL(request.url ?? "/", "http://studio");
160
+ const path = url.pathname;
161
+ if (path === "/history") {
162
+ answer(response, async () => {
163
+ const name2 = url.searchParams.get("device") ?? "";
164
+ const files = JSON.parse(data).files?.[name2];
165
+ if (!files)
166
+ throw new Error(`no device ${name2}`);
167
+ return history(root, [files.source, files.snapshot].filter((file2) => Boolean(file2)));
168
+ });
169
+ return;
170
+ }
171
+ if (path === "/refs") {
172
+ answer(response, () => references(root));
173
+ return;
174
+ }
175
+ if (path === "/compare") {
176
+ answer(response, async () => {
177
+ const asked = url.searchParams.get("ref") ?? "";
178
+ const commit = await commitOf(root, asked);
179
+ if (!commit)
180
+ throw new Error(`${asked} names no commit here`);
181
+ if (!past.has(commit.commit))
182
+ past.set(commit.commit, networkAt(root, configPath, commit.commit, gather));
183
+ const network = await past.get(commit.commit);
184
+ if (network.startsWith('{"error"'))
185
+ past.delete(commit.commit);
186
+ return `{"commit":${JSON.stringify(commit)},"network":${network}}`;
187
+ });
188
+ return;
189
+ }
190
+ if (path === "/data") {
191
+ response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(data);
192
+ return;
193
+ }
194
+ if (path === "/events") {
195
+ response.writeHead(200, {
196
+ "content-type": "text/event-stream",
197
+ "cache-control": "no-store",
198
+ connection: "keep-alive",
199
+ "x-accel-buffering": "no"
200
+ });
201
+ response.write(`: connected
202
+
203
+ `);
204
+ listeners.add(response);
205
+ request.on("close", () => listeners.delete(response));
206
+ return;
207
+ }
208
+ const name = path === "/" ? "index.html" : path.slice(1);
209
+ const type = CONTENT_TYPES[extname(name)];
210
+ const file = join2(pages, name);
211
+ if (!/^[a-z-]+\.[a-z]+$/.test(name) || !type || !existsSync(file)) {
212
+ response.writeHead(404).end();
213
+ return;
214
+ }
215
+ response.writeHead(200, { "content-type": type, "cache-control": "no-store" }).end(readFileSync(file));
216
+ });
217
+ let timer;
218
+ watch(root, { recursive: true }, (_event, filename) => {
219
+ if (filename && IGNORED.test(filename))
220
+ return;
221
+ clearTimeout(timer);
222
+ timer = setTimeout(async () => {
223
+ data = await gather(configPath);
224
+ tell("changed");
225
+ console.log(`${new Date().toLocaleTimeString()} ${filename ?? "a file"} changed, read again`);
226
+ }, 300);
227
+ });
228
+ watch(pages, () => tell("page"));
229
+ server.on("error", (error) => {
230
+ const message = error.code === "EADDRINUSE" ? `port ${port} is in use; choose another with --port=N` : error.message;
231
+ console.error(message);
232
+ process.exit(1);
233
+ });
234
+ server.listen(port, options.host, () => {
235
+ const local = isLoopback(options.host);
236
+ const url = local ? `http://127.0.0.1:${port}` : `http://${options.allowHosts[0] ?? options.host}`;
237
+ console.log(`Circuit Studio at ${url}, listening on ${options.host}:${port}, watching ${root}. Stop it with Ctrl+C.`);
238
+ if (options.open && local)
239
+ openBrowser(url);
240
+ });
241
+ }
242
+ export {
243
+ studio,
244
+ isLoopback,
245
+ hostAllowed
246
+ };