@impact-ai/setup 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/args.js ADDED
@@ -0,0 +1,99 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // The command line: flags, the impact.ai origin, and the help text.
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { parseArgs } from "node:util";
7
+
8
+ /** The package's version, from its package.json. */
9
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
10
+
11
+ /** What the command calls itself in the start request (`client`) and in its User-Agent. */
12
+ export const CLIENT = `@impact-ai/setup/${VERSION}`;
13
+
14
+ // PLACEHOLDER: the production app's origin, used when neither --url nor IMPACT_URL names one. Confirm it before the
15
+ // first release to npm; every other environment passes --url.
16
+ export const PRODUCTION_ORIGIN_PLACEHOLDER = "https://app.impact.ai";
17
+
18
+ export const AGENT_CHOICES = ["claude", "codex", "cursor"];
19
+
20
+ export class UsageError extends Error {}
21
+
22
+ export function usage() {
23
+ return `Connect the application in this folder to impact.ai.
24
+
25
+ Usage: npx @impact-ai/setup [options]
26
+
27
+ It signs you in through the browser, writes one ingest key to .env, hands the instrumentation to the coding agent
28
+ installed on this computer (Claude Code, Codex or Cursor), runs the application once, and finishes when impact.ai has
29
+ received and checked its first trace.
30
+
31
+ Options:
32
+ --url <origin> impact.ai's address (default: IMPACT_URL, or ${PRODUCTION_ORIGIN_PLACEHOLDER})
33
+ --agent <name> the coding agent to use: claude, codex or cursor (default: the first installed, in that order)
34
+ -y, --yes answer yes to every question, for a run without a terminal
35
+ -h, --help show this help
36
+ -v, --version show the version
37
+
38
+ Exit codes:
39
+ 0 set up, and the first trace was checked
40
+ 3 set up, but no checked trace arrived in time
41
+ 1 failed: not allowed, stopped, the agent failed, or the run failed
42
+ 2 usage error
43
+ `;
44
+ }
45
+
46
+ function loopback(hostname) {
47
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(hostname);
48
+ }
49
+
50
+ /**
51
+ * The origin to talk to, from --url or IMPACT_URL: https, or http on this computer only (the answers carry secrets).
52
+ * @param {string} value
53
+ * @returns {string}
54
+ */
55
+ export function parseOrigin(value) {
56
+ let url;
57
+ try {
58
+ url = new URL(value);
59
+ } catch {
60
+ throw new UsageError(`--url: ${JSON.stringify(value)} is not an address (for example https://app.example.com)`);
61
+ }
62
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback(url.hostname))) {
63
+ throw new UsageError(`--url: ${url.origin} must start with https:// (http:// only for this computer)`);
64
+ }
65
+ return url.origin;
66
+ }
67
+
68
+ /**
69
+ * @param {string[]} argv
70
+ * @param {Record<string, string | undefined>} env
71
+ * @returns {{ origin: string, agent: string | null, yes: boolean, help: boolean, version: boolean }}
72
+ */
73
+ export function parse(argv, env) {
74
+ let values;
75
+ try {
76
+ ({ values } = parseArgs({
77
+ args: argv,
78
+ options: {
79
+ url: { type: "string" },
80
+ agent: { type: "string" },
81
+ yes: { type: "boolean", short: "y" },
82
+ help: { type: "boolean", short: "h" },
83
+ version: { type: "boolean", short: "v" },
84
+ },
85
+ strict: true,
86
+ allowPositionals: false,
87
+ }));
88
+ } catch (error) {
89
+ throw new UsageError(error.message);
90
+ }
91
+ const agent = values.agent ?? null;
92
+ if (agent !== null && !AGENT_CHOICES.includes(agent)) {
93
+ throw new UsageError(`--agent: ${JSON.stringify(agent)} is not one of ${AGENT_CHOICES.join(", ")}`);
94
+ }
95
+ const help = Boolean(values.help);
96
+ const version = Boolean(values.version);
97
+ const origin = help || version ? "" : parseOrigin(values.url ?? env.IMPACT_URL ?? PRODUCTION_ORIGIN_PLACEHOLDER);
98
+ return { origin, agent, yes: Boolean(values.yes), help, version };
99
+ }
package/src/dotenv.js ADDED
@@ -0,0 +1,122 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // The two variables in the folder's .env, and .env in its .gitignore. The key's value is written to .env and nowhere
4
+ // else.
5
+
6
+ import { readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+
9
+ export const KEY = "IMPACT_INGEST_KEY";
10
+ export const ENDPOINT = "IMPACT_INGEST_ENDPOINT";
11
+
12
+ function assignment(name) {
13
+ return new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`);
14
+ }
15
+
16
+ function readText(file) {
17
+ try {
18
+ return readFileSync(file, "utf8");
19
+ } catch (error) {
20
+ if (error.code === "ENOENT") return null;
21
+ throw error;
22
+ }
23
+ }
24
+
25
+ /** Whether the folder's .env already gives IMPACT_INGEST_KEY a value. */
26
+ export function holdsKey(folder) {
27
+ const text = readText(path.join(folder, ".env"));
28
+ if (text === null) return false;
29
+ return text.split(/\r?\n/).some((line) => {
30
+ if (!assignment(KEY).test(line)) return false;
31
+ const value = line.slice(line.indexOf("=") + 1).trim();
32
+ return value !== "" && value !== '""' && value !== "''";
33
+ });
34
+ }
35
+
36
+ /** A value as one .env line takes it: bare when it is plain, quoted otherwise; never a line break. */
37
+ export function formatValue(value) {
38
+ if (typeof value !== "string" || value === "" || /[\0-\x1f\x7f]/.test(value)) {
39
+ throw new Error("the value is empty or holds a control character");
40
+ }
41
+ if (/^[A-Za-z0-9_.:/@%+=~,-]+$/.test(value)) return value;
42
+ if (!value.includes("'")) return `'${value}'`;
43
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
44
+ }
45
+
46
+ /**
47
+ * Set the variables in .env: each replaces its line (the first, and drops any later ones), or is added at the end;
48
+ * every other line stays as it was. A new .env is readable by its owner only.
49
+ * @param {string} folder
50
+ * @param {Record<string, string>} values
51
+ */
52
+ export function writeEnv(folder, values) {
53
+ const file = path.join(folder, ".env");
54
+ const before = readText(file);
55
+ const lines = before === null ? [] : before.split(/\r?\n/);
56
+ if (lines.length && lines[lines.length - 1] === "") lines.pop();
57
+ const written = new Set();
58
+ const out = [];
59
+ for (const line of lines) {
60
+ const name = Object.keys(values).find((each) => assignment(each).test(line));
61
+ if (!name) {
62
+ out.push(line);
63
+ } else if (!written.has(name)) {
64
+ out.push(`${name}=${formatValue(values[name])}`);
65
+ written.add(name);
66
+ }
67
+ }
68
+ for (const [name, value] of Object.entries(values)) {
69
+ if (!written.has(name)) out.push(`${name}=${formatValue(value)}`);
70
+ }
71
+ let mode = 0o600;
72
+ try {
73
+ mode = statSync(file).mode & 0o777;
74
+ } catch {
75
+ // a new file
76
+ }
77
+ const temporary = path.join(folder, `.env.impact-setup-${process.pid}`);
78
+ writeFileSync(temporary, `${out.join("\n")}\n`, { mode, flag: "w" });
79
+ renameSync(temporary, file);
80
+ }
81
+
82
+ /** The variables the command wrote, read back from .env for the run. */
83
+ export function readEnvValues(folder, names) {
84
+ const text = readText(path.join(folder, ".env")) ?? "";
85
+ const found = {};
86
+ for (const line of text.split(/\r?\n/)) {
87
+ for (const name of names) {
88
+ if (name in found || !assignment(name).test(line)) continue;
89
+ let value = line.slice(line.indexOf("=") + 1).trim();
90
+ if (value.length >= 2 && value[0] === "'" && value.endsWith("'")) value = value.slice(1, -1);
91
+ else if (value.length >= 2 && value[0] === '"' && value.endsWith('"')) {
92
+ value = value.slice(1, -1).replace(/\\(["\\])/g, "$1");
93
+ }
94
+ found[name] = value;
95
+ }
96
+ }
97
+ return found;
98
+ }
99
+
100
+ const IGNORES_DOTENV = /^\/?(?:\.env|\.env\*|\*\.env|\.env\/?)$/;
101
+
102
+ /**
103
+ * Make sure .env stays out of commits: add it to the folder's .gitignore unless git (or, outside a repository, the
104
+ * folder's .gitignore) already ignores it.
105
+ * @param {string} folder
106
+ * @param {boolean | null} ignoredByGit what `git check-ignore` says, or null outside a repository
107
+ * @returns {"ignored" | "added" | "created"}
108
+ */
109
+ export function ensureIgnored(folder, ignoredByGit) {
110
+ const file = path.join(folder, ".gitignore");
111
+ const text = readText(file);
112
+ if (ignoredByGit === true) return "ignored";
113
+ if (ignoredByGit === null && text !== null && text.split(/\r?\n/).some((line) => IGNORES_DOTENV.test(line.trim()))) {
114
+ return "ignored";
115
+ }
116
+ if (text === null) {
117
+ writeFileSync(file, ".env\n");
118
+ return "created";
119
+ }
120
+ writeFileSync(file, `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}.env\n`);
121
+ return "added";
122
+ }