@watchtowerobservability/wizard 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # @watchtowerobservability/wizard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/watchtowerobservability/watchtower-wizard/actions/workflows/ci.yml/badge.svg)](https://github.com/watchtowerobservability/watchtower-wizard/actions/workflows/ci.yml)
4
+
5
+ One command that detects your project, installs the Watchtower SDK, writes the init snippet, wires
6
+ source-map upload where it can, and sends a test event. Plain JavaScript, no runtime dependencies.
7
+
8
+ ## Install and quick start
9
+
10
+ ```sh
11
+ npx @watchtowerobservability/wizard # run in your project directory
12
+ npx @watchtowerobservability/wizard --dry-run # print the diff, change nothing
13
+ npx @watchtowerobservability/wizard verify # send a test span
14
+ ```
15
+
16
+ The key is typed at a hidden prompt (or read from `WT_INGEST_KEY` / `WT_PUBLISHABLE_KEY` in the
17
+ environment). It is never a command-line flag, and it is written only to `.env.local`, which the
18
+ wizard adds to `.gitignore`. Client apps need a publishable key (`wtp_...`); servers a secret ingest key.
19
+
20
+ ## Integrations
21
+
22
+ | Detected by | Installs | Writes |
23
+ |---|---|---|
24
+ | `package.json` with next, vite, react, vue, angular, sveltekit, webpack | `@watchtowerobservability/browser` | `src/watchtower.(ts\|js)`; Vite config patched with the source-map plugin; other bundlers get a printed step |
25
+ | `package.json` with express, fastify, koa, nestjs | `@watchtowerobservability/node` | `watchtower.js` |
26
+ | `go.mod` | `watchtower-go` | `watchtower.go` |
27
+ | `pyproject.toml` / `requirements.txt` | `watchtower-observability` | `watchtower_setup.py` (and `requirements.txt`) |
28
+ | `Gemfile` | `watchtower-sdk` gem | `config/initializers/watchtower.rb` |
29
+ | `composer.json` | `watchtowerobservability/sdk` | `watchtower.php` |
30
+ | `pom.xml`, `build.gradle(.kts)` | Java SDK dependency inserted | printed init and mapping-upload steps |
31
+ | `*.csproj` | `Watchtower.Sdk` | printed init step |
32
+ | `pubspec.yaml`, `Podfile` | nothing yet | printed instructions (Dart SDK unpublished; iOS uses Swift Package Manager) |
33
+
34
+ Existing files are never overwritten; steps that cannot be applied safely are printed as notes.
35
+
36
+ ## Configuration
37
+
38
+ | Name | Meaning |
39
+ |---|---|
40
+ | `WT_INGEST_KEY` | secret ingest key (server SDKs) |
41
+ | `WT_PUBLISHABLE_KEY` | publishable key (client SDKs); `VITE_` / `NEXT_PUBLIC_` prefixed for those bundlers |
42
+ | `WT_OTLP_ENDPOINT` | default `http://localhost:4318`; used by `verify` |
43
+ | `WT_SERVICE`, `WT_ENVIRONMENT`, `WT_RELEASE` | passed through to the SDK |
44
+ | `WT_API_KEY` | secret API key for source-map upload, kept out of client bundles |
45
+
46
+ ## Provenance
47
+
48
+ Every release artifact carries a GitHub build attestation. Verify one with
49
+ `gh attestation verify <file> --repo watchtowerobservability/watchtower-wizard`.
50
+
51
+ ## License
52
+
53
+ Apache-2.0. Source of truth is the Watchtower monorepo; this repository is a published mirror.
package/bin/wizard.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../src/cli.js";
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@watchtowerobservability/wizard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "repository": { "type": "git", "url": "git+https://github.com/watchtowerobservability/watchtower-wizard.git" },
5
+ "publishConfig": {
6
+ "access": "public",
7
+ "registry": "https://registry.npmjs.org/"
8
+ },
9
+ "description": "Setup wizard: detects your project, installs the Watchtower SDK and wires up init and upload (plain JavaScript)",
10
+ "type": "module",
11
+ "bin": { "wizard": "bin/wizard.js" },
12
+ "main": "src/index.js",
13
+ "types": "src/index.d.ts",
14
+ "files": ["bin", "src"],
15
+ "license": "Apache-2.0",
16
+ "engines": { "node": ">=18" },
17
+ "scripts": { "test": "node --test test/*.test.js" }
18
+ }
package/src/apply.js ADDED
@@ -0,0 +1,74 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+
5
+ const readOr = (f) => (existsSync(f) ? readFileSync(f, "utf8") : null);
6
+
7
+ /** Env lines whose names are in `secrets` are masked wherever a change is displayed. */
8
+ const mask = (text, names) => text.replace(new RegExp(`^([-+ ]?(?:${names.join("|")})=).*$`, "gm"), "$1***");
9
+
10
+ /**
11
+ * Pure: turns a plan + secrets into file changes [{path, before, after, skipped?}].
12
+ * `env` is {NAME: value}; written to .env.local, which is added to .gitignore.
13
+ */
14
+ export function changes(dir, plan, env) {
15
+ const out = [];
16
+ for (const e of plan.edits) {
17
+ const rel = Array.isArray(e.path) ? (e.path.find((p) => existsSync(join(dir, p))) ?? e.path[0]) : e.path;
18
+ const file = join(dir, rel);
19
+ // Later edits to the same file build on earlier ones (vite: import, then plugin entry).
20
+ const prev = out.findLast((c) => c.path === rel && c.after !== undefined);
21
+ const before = prev ? prev.after : readOr(file);
22
+ if (e.op === "write") {
23
+ out.push(before === null ? { path: rel, before: null, after: e.content } : { path: rel, skipped: "exists, left untouched" });
24
+ } else if (e.op === "append") {
25
+ out.push(before !== null && before.includes(e.content.trim()) ? { path: rel, skipped: "already present" } : { path: rel, before: before ?? "", after: (before ?? "") + (before && !before.endsWith("\n") ? "\n" : "") + e.content });
26
+ } else if (before === null) {
27
+ out.push({ path: rel, skipped: "not found, see notes" });
28
+ } else {
29
+ const m = before.match(e.find);
30
+ const text = m ? before.replace(e.find, e.insert(m[0])) : null;
31
+ out.push(text === null || text === before ? { path: rel, skipped: "no insertion point, see notes" } : { path: rel, before: prev ? prev.before : before, after: text });
32
+ if (prev && text !== null) out.splice(out.indexOf(prev), 1);
33
+ }
34
+ }
35
+ const lines = Object.entries(env).filter(([, v]) => v).map(([k, v]) => `${k}=${v}`);
36
+ const envBefore = readOr(join(dir, ".env.local"));
37
+ const fresh = lines.filter((l) => !new RegExp(`^${l.split("=")[0]}=`, "m").test(envBefore ?? ""));
38
+ if (fresh.length) out.push({ path: ".env.local", before: envBefore, after: (envBefore ?? "") + (envBefore && !envBefore.endsWith("\n") ? "\n" : "") + fresh.join("\n") + "\n", secret: true });
39
+ const gi = readOr(join(dir, ".gitignore"));
40
+ if (fresh.length && !(gi ?? "").split(/\r?\n/).some((l) => l.trim() === ".env.local" || l.trim() === ".env*.local" || l.trim() === ".env*")) {
41
+ out.push({ path: ".gitignore", before: gi, after: (gi ?? "") + (gi && !gi.endsWith("\n") ? "\n" : "") + ".env.local\n" });
42
+ }
43
+ return out;
44
+ }
45
+
46
+ /** Minimal diff: shared head and tail lines are context, the middle is -/+. Never contains secret values. */
47
+ export function render(c, secretNames = []) {
48
+ if (c.skipped) return `# ${c.path}: skipped (${c.skipped})\n`;
49
+ const a = (c.before ?? "").split("\n"), b = c.after.split("\n");
50
+ let i = 0;
51
+ while (i < a.length && i < b.length && a[i] === b[i]) i++;
52
+ let j = 0;
53
+ while (j < a.length - i && j < b.length - i && a[a.length - 1 - j] === b[b.length - 1 - j]) j++;
54
+ const body = [...a.slice(i, a.length - j).map((l) => `-${l}`), ...b.slice(i, b.length - j).map((l) => `+${l}`)].join("\n");
55
+ return `--- ${c.before === null ? "/dev/null" : "a/" + c.path}\n+++ b/${c.path}\n${mask(body, secretNames)}\n`;
56
+ }
57
+
58
+ export function write(dir, cs) {
59
+ for (const c of cs) {
60
+ if (c.skipped) continue;
61
+ const f = join(dir, c.path);
62
+ mkdirSync(dirname(f), { recursive: true });
63
+ writeFileSync(f, c.after, c.secret ? { mode: 0o600 } : undefined);
64
+ }
65
+ }
66
+
67
+ /** `run` is injectable for tests; defaults to spawnSync with inherited stdio and no shell. */
68
+ export function install(dir, cmds, run = (cmd, args) => spawnSync(cmd, args, { cwd: dir, stdio: "inherit" })) {
69
+ for (const [cmd, ...args] of cmds) {
70
+ const r = run(cmd, args);
71
+ if (r.status !== 0) return { ok: false, cmd: [cmd, ...args].join(" ") };
72
+ }
73
+ return { ok: true };
74
+ }
package/src/cli.js ADDED
@@ -0,0 +1,104 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { createInterface } from "node:readline";
4
+ import { detect } from "./detect.js";
5
+ import { plan } from "./plans.js";
6
+ import { changes, install, render, write } from "./apply.js";
7
+ import { DEFAULT_ENDPOINT, sendTestEvent } from "./verify.js";
8
+
9
+ const USAGE = `usage: wizard [dir] [--dry-run] [--no-install] [--yes]
10
+ wizard verify [dir]
11
+
12
+ The key is asked for interactively (input hidden) or read from the environment
13
+ (WT_INGEST_KEY, or WT_PUBLISHABLE_KEY for client apps). It is never a flag and is
14
+ written only to .env.local, which is added to .gitignore.
15
+ `;
16
+
17
+ /** Prompt without echoing. Falls back to a plain line read when stdin is not a TTY. */
18
+ export function askHidden(question, { input = process.stdin, output = process.stderr } = {}) {
19
+ return new Promise((res) => {
20
+ output.write(question);
21
+ if (!input.isTTY) {
22
+ const rl = createInterface({ input });
23
+ rl.once("line", (l) => { rl.close(); res(l.trim()); });
24
+ return;
25
+ }
26
+ let buf = "";
27
+ input.setRawMode(true);
28
+ input.resume();
29
+ const onData = (ch) => {
30
+ for (const c of String(ch)) {
31
+ if (c === "\r" || c === "\n") { input.setRawMode(false); input.pause(); input.off("data", onData); output.write("\n"); return res(buf.trim()); }
32
+ if (c === "\u0003") process.exit(130);
33
+ buf = c === "\u007f" ? buf.slice(0, -1) : buf + c;
34
+ }
35
+ };
36
+ input.on("data", onData);
37
+ });
38
+ }
39
+
40
+ function loadEnvLocal(dir) {
41
+ try {
42
+ return Object.fromEntries(readFileSync(join(dir, ".env.local"), "utf8").split(/\r?\n/).filter((l) => /^[A-Z_]+=/.test(l)).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
43
+ } catch { return {}; }
44
+ }
45
+
46
+ export async function main(argv, { env = process.env, ask = askHidden, out = (s) => process.stdout.write(s + "\n"), fetchImpl = fetch, run } = {}) {
47
+ const args = argv.filter((a) => !a.startsWith("--"));
48
+ const flag = (f) => argv.includes(f);
49
+ if (flag("--help") || flag("-h")) { out(USAGE); return 0; }
50
+ // A key on the command line would land in shell history and `ps`.
51
+ if (argv.some((a) => /^--(key|api-?key|token|secret)/i.test(a) || /^wt[a-z]*_/i.test(a))) {
52
+ out("error: keys are never accepted as arguments; the wizard asks for it interactively.");
53
+ return 2;
54
+ }
55
+
56
+ if (args[0] === "verify") {
57
+ const dir = resolve(args[1] ?? ".");
58
+ const e = { ...loadEnvLocal(dir), ...env };
59
+ const key = e.WT_INGEST_KEY || e.WT_PUBLISHABLE_KEY || e.VITE_WT_PUBLISHABLE_KEY || e.NEXT_PUBLIC_WT_PUBLISHABLE_KEY;
60
+ if (!key) { out("error: no key found in the environment or .env.local; run the wizard first."); return 1; }
61
+ const r = await sendTestEvent({ endpoint: e.WT_OTLP_ENDPOINT || DEFAULT_ENDPOINT, key, service: e.WT_SERVICE || "wizard-verify", fetchImpl });
62
+ out(r.ok ? "Test event accepted. Open Traces and look for the span 'wizard.verify'." : `Test event failed (status ${r.status}${r.error ? ", " + r.error : ""}). Check the key and WT_OTLP_ENDPOINT.`);
63
+ return r.ok ? 0 : 1;
64
+ }
65
+
66
+ const dir = resolve(args[0] ?? ".");
67
+ const found = detect(dir);
68
+ if (!found) { out("No supported project found (package.json, go.mod, pyproject/requirements, Gemfile, composer.json, pom/gradle, csproj, pubspec, Podfile)."); return 1; }
69
+ const p = plan(found);
70
+ out(`Detected ${found.framework} (${found.kind}).`);
71
+
72
+ const secrets = {};
73
+ if (p.keyKind !== "none") {
74
+ const label = p.keyKind === "publishable" ? "publishable key (wtp_...)" : "secret ingest key";
75
+ const key = env[p.keyVar] || (await ask(`Watchtower ${label}: `));
76
+ if (!key) { out("error: a key is required."); return 1; }
77
+ if (p.keyKind === "publishable" && !key.startsWith("wtp_")) { out("error: client apps need a publishable key (wtp_...), never a secret key."); return 1; }
78
+ if (p.keyKind === "secret" && key.startsWith("wtp_")) { out("error: this is a server project; use a secret ingest key, not a publishable one."); return 1; }
79
+ secrets[p.keyVar] = key;
80
+ if (found.kind === "browser" && !flag("--dry-run")) {
81
+ const up = env.WT_API_KEY || (await ask("Secret API key for source-map upload (Enter to skip): "));
82
+ if (up) secrets.WT_API_KEY = up;
83
+ }
84
+ }
85
+
86
+ const cs = changes(dir, p, secrets);
87
+ const names = Object.keys(secrets);
88
+ if (flag("--dry-run")) {
89
+ out("Dry run, nothing written or installed.");
90
+ for (const c of p.install) out(`$ ${c.join(" ")}`);
91
+ for (const c of cs) out(render(c, names));
92
+ for (const n of p.notes) out(`note: ${n}`);
93
+ return 0;
94
+ }
95
+ write(dir, cs);
96
+ for (const c of cs) out(c.skipped ? `skipped ${c.path} (${c.skipped})` : `wrote ${c.path}`);
97
+ if (!flag("--no-install")) {
98
+ const r = install(dir, p.install, run);
99
+ if (!r.ok) { out(`Install failed: ${r.cmd}. Run it yourself, then re-run the wizard.`); return 1; }
100
+ }
101
+ for (const n of p.notes) out(`note: ${n}`);
102
+ out(`\nVerify: npx @watchtowerobservability/wizard verify${args[0] ? " " + args[0] : ""}\nThis sends one test span 'wizard.verify' to WT_OTLP_ENDPOINT (default ${DEFAULT_ENDPOINT}).`);
103
+ return 0;
104
+ }
package/src/detect.js ADDED
@@ -0,0 +1,56 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ const read = (dir, f) => {
5
+ try { return readFileSync(join(dir, f), "utf8"); } catch { return null; }
6
+ };
7
+ const has = (dir, f) => existsSync(join(dir, f));
8
+ const ext = (dir, e) => { try { return readdirSync(dir).some((f) => f.endsWith(e)); } catch { return false; } };
9
+
10
+ // Browser frameworks win over server ones (a Next app is browser + server; we wire the browser SDK).
11
+ const JS_BROWSER = ["next", "vite", "react-scripts", "@angular/core", "@sveltejs/kit", "vue", "react"];
12
+ const JS_SERVER = ["@nestjs/core", "fastify", "express", "koa"];
13
+
14
+ function pm(dir) {
15
+ if (has(dir, "pnpm-lock.yaml")) return "pnpm";
16
+ if (has(dir, "yarn.lock")) return "yarn";
17
+ return "npm";
18
+ }
19
+
20
+ /** Returns {kind, framework, ...} for the project in `dir`, or null when nothing is recognised. */
21
+ export function detect(dir) {
22
+ const pkg = read(dir, "package.json");
23
+ if (pkg) {
24
+ let j = {};
25
+ try { j = JSON.parse(pkg); } catch { /* unparsable package.json: treat as no deps */ }
26
+ const deps = { ...j.dependencies, ...j.devDependencies };
27
+ const ts = has(dir, "tsconfig.json");
28
+ const b = JS_BROWSER.find((d) => d in deps);
29
+ if (b) return { kind: "browser", framework: b === "react-scripts" ? "webpack" : b, ts, pm: pm(dir) };
30
+ if ("webpack" in deps) return { kind: "browser", framework: "webpack", ts, pm: pm(dir) };
31
+ return { kind: "node", framework: JS_SERVER.find((d) => d in deps) ?? "node", pm: pm(dir) };
32
+ }
33
+ if (has(dir, "go.mod")) return { kind: "go", framework: "go" };
34
+ const pyproject = read(dir, "pyproject.toml");
35
+ const reqs = read(dir, "requirements.txt");
36
+ if (pyproject !== null || reqs !== null || has(dir, "setup.py")) {
37
+ const txt = ((pyproject ?? "") + "\n" + (reqs ?? "")).toLowerCase();
38
+ const fw = ["django", "fastapi", "flask", "celery"].find((f) => new RegExp(`(^|[\\s"'])${f}\\b`, "m").test(txt));
39
+ return { kind: "python", framework: fw ?? "python", file: pyproject !== null ? "pyproject.toml" : "requirements.txt" };
40
+ }
41
+ const gem = read(dir, "Gemfile");
42
+ if (gem !== null) return { kind: "ruby", framework: /\brails\b/.test(gem) ? "rails" : "ruby" };
43
+ const comp = read(dir, "composer.json");
44
+ if (comp !== null) return { kind: "php", framework: /laravel\/framework/.test(comp) ? "laravel" : /symfony\//.test(comp) ? "symfony" : "php" };
45
+ const pom = read(dir, "pom.xml");
46
+ if (pom !== null) return { kind: "maven", framework: /spring-boot/.test(pom) ? "spring-boot" : "java" };
47
+ for (const g of ["build.gradle.kts", "build.gradle"]) {
48
+ const t = read(dir, g);
49
+ if (t !== null) return { kind: "gradle", framework: /com\.android/.test(t) ? "android" : "java", file: g };
50
+ }
51
+ if (ext(dir, ".csproj")) return { kind: "dotnet", framework: "dotnet" };
52
+ const pub = read(dir, "pubspec.yaml");
53
+ if (pub !== null) return { kind: "dart", framework: /sdk:\s*flutter/.test(pub) ? "flutter" : "dart" };
54
+ if (has(dir, "Podfile")) return { kind: "ios", framework: "cocoapods" };
55
+ return null;
56
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export interface Detected { kind: string; framework: string; pm?: string; ts?: boolean; file?: string }
2
+ export interface Edit { op: "write" | "append" | "patch"; path: string | string[]; content?: string; find?: RegExp; insert?: (m: string) => string }
3
+ export interface Plan { install: string[][]; edits: Edit[]; notes: string[]; keyKind: "secret" | "publishable" | "none"; keyVar: string }
4
+ export interface Change { path: string; before?: string | null; after?: string; skipped?: string; secret?: boolean }
5
+
6
+ export function detect(dir: string): Detected | null;
7
+ export function plan(d: Detected): Plan;
8
+ export function changes(dir: string, p: Plan, env: Record<string, string>): Change[];
9
+ export function render(c: Change, secretNames?: string[]): string;
10
+ export function write(dir: string, cs: Change[]): void;
11
+ export function install(dir: string, cmds: string[][], run?: (cmd: string, args: string[]) => { status: number | null }): { ok: boolean; cmd?: string };
12
+ export function sendTestEvent(o: { endpoint?: string; key: string; service?: string; fetchImpl?: typeof fetch }): Promise<{ ok: boolean; status: number; error?: string }>;
13
+ export function main(argv: string[], o?: Record<string, unknown>): Promise<number>;
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { detect } from "./detect.js";
2
+ export { plan } from "./plans.js";
3
+ export { changes, render, write, install } from "./apply.js";
4
+ export { sendTestEvent } from "./verify.js";
5
+ export { main } from "./cli.js";
package/src/plans.js ADDED
@@ -0,0 +1,119 @@
1
+ // A plan is plain data:
2
+ // install: [[cmd, ...args]] commands run in the project dir
3
+ // edits: [{op, path, ...}] "write" (create, never overwrite), "append", "patch" ({find, insert(match)})
4
+ // notes: [string] manual follow-ups printed at the end
5
+ // keyKind: "secret" | "publishable" | "none", keyVar: env var written to .env.local
6
+ // `path` may be an array of candidates for "patch"; the first existing one is used.
7
+ const PKG = "@watchtowerobservability";
8
+ const GO_INIT = `package main
9
+
10
+ import (
11
+ "context"
12
+ "os"
13
+
14
+ wt "github.com/watchtowerobservability/watchtower-go"
15
+ )
16
+
17
+ // initWatchtower returns a shutdown func; call it first in main and defer the result.
18
+ func initWatchtower(ctx context.Context) (func(context.Context) error, error) {
19
+ return wt.Init(ctx, wt.Options{APIKey: os.Getenv("WT_INGEST_KEY"), Service: os.Getenv("WT_SERVICE")})
20
+ }
21
+ `;
22
+ const JAVA_NOTE = `Init: Watchtower.init(new Watchtower.Options().apiKey(System.getenv("WT_INGEST_KEY"))).`;
23
+
24
+ export function pubVar(fw) {
25
+ if (fw === "next") return "NEXT_PUBLIC_WT_PUBLISHABLE_KEY";
26
+ if (fw === "vite" || fw === "@sveltejs/kit") return "VITE_WT_PUBLISHABLE_KEY";
27
+ return "WT_PUBLISHABLE_KEY";
28
+ }
29
+
30
+ const add = (pm, pkg) => [pm, pm === "npm" ? "install" : "add", pkg];
31
+
32
+ function browser(p) {
33
+ const v = pubVar(p.framework);
34
+ const vite = p.framework === "vite" || p.framework === "@sveltejs/kit";
35
+ const env = (n) => (p.framework === "next" ? `process.env.${n}` : vite ? `import.meta.env.${n}` : `process.env.${n}`);
36
+ const pre = p.framework === "next" ? "NEXT_PUBLIC_" : vite ? "VITE_" : "";
37
+ const edits = [{
38
+ op: "write", path: `src/watchtower.${p.ts ? "ts" : "js"}`,
39
+ content: `import { init } from "${PKG}/browser";\n\nexport const wt = init({\n publishableKey: ${env(v)},\n endpoint: ${env(pre + "WT_OTLP_ENDPOINT")},\n service: "web",\n environment: "production",\n});\n`,
40
+ }];
41
+ const notes = [`Import "./watchtower" once at your app entry point, before anything else.`];
42
+ if (p.framework === "vite") {
43
+ const files = ["vite.config.ts", "vite.config.js", "vite.config.mjs"];
44
+ edits.push(
45
+ { op: "patch", path: files, find: /^/, insert: () => `import { watchtower } from "${PKG}/browser/vite-plugin";\n` },
46
+ { op: "patch", path: files, find: /plugins:\s*\[/, insert: (m) => `${m}watchtower({ api: process.env.WT_API_URL ?? "", project: process.env.WT_PROJECT_ID ?? "" }), ` },
47
+ );
48
+ notes.push(`Source maps: set build.sourcemap to "hidden"; export WT_API_URL, WT_PROJECT_ID and the secret WT_API_KEY in CI only. Maps upload at build and are deleted afterwards.`);
49
+ } else if (p.framework === "next" || p.framework === "webpack") {
50
+ notes.push(`Source maps: add watchtower({ api, project }) from "${PKG}/browser/webpack-plugin" to your webpack config (in next.config, the webpack hook) and enable browser source maps. Export the secret WT_API_KEY in CI only.`);
51
+ } else {
52
+ notes.push(`Source maps: use "${PKG}/browser/rollup-plugin" or \`wtctl sourcemaps upload\` in your build. Export the secret WT_API_KEY in CI only.`);
53
+ }
54
+ return { install: [add(p.pm, `${PKG}/browser`)], edits, notes, keyKind: "publishable", keyVar: v };
55
+ }
56
+
57
+ const BUILDERS = {
58
+ browser,
59
+ node: (p) => ({
60
+ install: [add(p.pm, `${PKG}/node`)],
61
+ edits: [{ op: "write", path: "watchtower.js", content: `import * as wt from "${PKG}/node";\n\nwt.init({ apiKey: process.env.WT_INGEST_KEY, project: process.env.WT_PROJECT_ID, service: process.env.WT_SERVICE ?? "app", bufferDir: ".wt-buffer" });\n` }],
62
+ notes: [`Run with: node --env-file=.env.local --import ./watchtower.js app.js`],
63
+ }),
64
+ go: () => ({
65
+ install: [["go", "get", "github.com/watchtowerobservability/watchtower-go@latest"]],
66
+ edits: [{ op: "write", path: "watchtower.go", content: GO_INIT }],
67
+ notes: [`Load .env.local before running: set -a; . ./.env.local; set +a`],
68
+ }),
69
+ python: (p) => ({
70
+ install: [["pip", "install", "watchtower-observability"]],
71
+ edits: [
72
+ { op: "write", path: "watchtower_setup.py", content: `import os\nimport watchtower\n\nwatchtower.init(os.environ["WT_INGEST_KEY"], project=os.environ["WT_PROJECT_ID"], buffer_dir=".wt-buffer")\n` },
73
+ ...(p.file === "requirements.txt" ? [{ op: "append", path: "requirements.txt", content: "watchtower-observability\n" }] : []),
74
+ ],
75
+ notes: [`Import watchtower_setup before your app code.`, ...(p.file === "pyproject.toml" ? [`Add "watchtower-observability" to your pyproject.toml dependencies.`] : []), `Load .env.local with python-dotenv or: set -a; . ./.env.local; set +a`],
76
+ }),
77
+ ruby: () => ({
78
+ install: [["bundle", "add", "watchtower-sdk"]],
79
+ edits: [{ op: "write", path: "config/initializers/watchtower.rb", content: `require "watchtower"\n\nWatchtower.init(Watchtower::Config.from_env(service: ENV.fetch("WT_SERVICE", "app")))\n` }],
80
+ notes: [`Rails does not read .env.local itself; use dotenv-rails or export the variables.`],
81
+ }),
82
+ php: () => ({
83
+ install: [["composer", "require", "watchtowerobservability/sdk"]],
84
+ edits: [{ op: "write", path: "watchtower.php", content: `<?php\n// require_once this from your front controller before handling requests.\nrequire_once __DIR__ . '/vendor/autoload.php';\n\n$GLOBALS['wt_tracer_provider'] = Watchtower\\Watchtower::init(Watchtower\\Config::fromEnv(getenv('WT_SERVICE') ?: 'app'));\n` }],
85
+ notes: [],
86
+ }),
87
+ maven: () => ({
88
+ install: [],
89
+ edits: [{ op: "patch", path: "pom.xml", find: /<dependencies>/, insert: (m) => `${m}\n <dependency>\n <groupId>io.github.watchtowerobservability</groupId>\n <artifactId>watchtower-sdk</artifactId>\n <version>0.1.0</version>\n </dependency>` }],
90
+ notes: [JAVA_NOTE, `Add the GitHub Packages Maven repository to settings.xml. Mapping upload: the Watchtower Maven plugin (sdks/maven-plugin).`],
91
+ }),
92
+ gradle: (p) => ({
93
+ install: [],
94
+ edits: [{ op: "patch", path: p.file, find: /dependencies\s*\{/, insert: (m) => `${m}\n implementation("io.github.watchtowerobservability:watchtower-sdk:0.1.0")` }],
95
+ notes: [JAVA_NOTE, `ProGuard/R8 mapping upload: add the Watchtower Gradle plugin (sdks/gradle-plugin) to plugins {}.`],
96
+ }),
97
+ dotnet: () => ({
98
+ install: [["dotnet", "add", "package", "Watchtower.Sdk"]],
99
+ edits: [],
100
+ notes: [`Add at startup: using var tp = Watchtower.Init(Config.FromEnv("app"), "MyApp");`, `Add the GitHub Packages NuGet source first (see the SDK README).`],
101
+ }),
102
+ dart: () => ({
103
+ install: [],
104
+ edits: [],
105
+ notes: [`The Dart/Flutter SDK is not published yet; once it is: dart pub add watchtower. Nothing changed.`],
106
+ keyKind: "none",
107
+ }),
108
+ ios: () => ({
109
+ install: [],
110
+ edits: [],
111
+ notes: [`Add https://github.com/watchtowerobservability/watchtower-ios with Swift Package Manager (CocoaPods is not published).`, `Start: Watchtower.start(Config(key: "<publishable-key>", service: "ios-app")). Use a publishable key in apps.`],
112
+ keyKind: "publishable", keyVar: "WT_PUBLISHABLE_KEY",
113
+ }),
114
+ };
115
+
116
+ export function plan(p) {
117
+ const b = BUILDERS[p.kind](p);
118
+ return { keyKind: "secret", keyVar: "WT_INGEST_KEY", ...b };
119
+ }
package/src/verify.js ADDED
@@ -0,0 +1,30 @@
1
+ import { randomBytes } from "node:crypto";
2
+
3
+ export const DEFAULT_ENDPOINT = "http://localhost:4318";
4
+
5
+ /** Sends one OTLP/HTTP JSON span; resolves {ok, status}. The key is only ever placed in the Authorization header. */
6
+ export async function sendTestEvent({ endpoint = DEFAULT_ENDPOINT, key, service = "wizard-verify", fetchImpl = fetch }) {
7
+ const now = BigInt(Date.now()) * 1000000n;
8
+ const body = {
9
+ resourceSpans: [{
10
+ resource: { attributes: [{ key: "service.name", value: { stringValue: service } }] },
11
+ scopeSpans: [{
12
+ scope: { name: "watchtower.wizard" },
13
+ spans: [{
14
+ traceId: randomBytes(16).toString("hex"), spanId: randomBytes(8).toString("hex"),
15
+ name: "wizard.verify", kind: 1, startTimeUnixNano: String(now), endTimeUnixNano: String(now + 1000000n),
16
+ }],
17
+ }],
18
+ }],
19
+ };
20
+ try {
21
+ const r = await fetchImpl(`${endpoint.replace(/\/$/, "")}/v1/traces`, {
22
+ method: "POST",
23
+ headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
24
+ body: JSON.stringify(body),
25
+ });
26
+ return { ok: r.ok, status: r.status };
27
+ } catch (e) {
28
+ return { ok: false, status: 0, error: String(e?.message ?? e).replaceAll(key, "***") };
29
+ }
30
+ }