@nestjs/observe 0.3.14 → 0.3.16
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/README.md +30 -14
- package/dist/cli/link.d.ts +41 -0
- package/dist/cli/link.js +217 -0
- package/dist/cli/observe-cli.d.ts +2 -0
- package/dist/cli/observe-cli.js +81 -0
- package/dist/cli/package-manager.d.ts +13 -0
- package/dist/cli/package-manager.js +54 -0
- package/dist/cli/project-files.d.ts +39 -0
- package/dist/cli/project-files.js +107 -0
- package/dist/cli/project-setup.d.ts +43 -0
- package/dist/cli/project-setup.js +249 -0
- package/dist/cli/wire-application.d.ts +29 -0
- package/dist/cli/wire-application.js +390 -0
- package/dist/interfaces/observe-options.interface.d.ts +13 -8
- package/dist/observe.module.js +34 -6
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -65,9 +65,30 @@ $ npm install @nestjs/observe
|
|
|
65
65
|
|
|
66
66
|
## Getting credentials
|
|
67
67
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
68
|
+
The quickest way is from the project's directory:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
$ npx @nestjs/observe link
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
It prints a code, you type it at
|
|
75
|
+
**[observe.nestjs.com/link](https://observe.nestjs.com/link)** (signing up
|
|
76
|
+
first if you have no account) and approve, and it writes the key pair into
|
|
77
|
+
`.env` as `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET`, git-ignores `.env`, and
|
|
78
|
+
adds `--env-file .env` to every script that runs `nest start` (`start`,
|
|
79
|
+
`start:dev` and `start:debug` in a `nest new` project). `ObserveModule` reads those two variables whenever `appKey` and
|
|
80
|
+
`appSecret` are left out or still hold the `nest new` placeholders.
|
|
81
|
+
|
|
82
|
+
In an app that does not use the SDK yet, the same command also installs
|
|
83
|
+
`@nestjs/observe` with the project's package manager and wires it in -
|
|
84
|
+
`ObserveModule.forRoot()` first in the root module's imports, `ObserveInstrument`
|
|
85
|
+
passed to `NestFactory.create()` - so the app reports from its next start. It
|
|
86
|
+
says so before you approve, and leaves a workspace with several applications
|
|
87
|
+
for you to wire by hand, as the [Quick start](#quick-start) shows.
|
|
88
|
+
|
|
89
|
+
Or sign up at **[observe.nestjs.com](https://observe.nestjs.com)** and create a
|
|
90
|
+
service by hand. The dashboard issues an **app key** and an **app secret**,
|
|
91
|
+
which the agent sends on every ingest request.
|
|
71
92
|
|
|
72
93
|
**Free for up to 300,000 events a month**, which covers most individual projects, startups, and small applications.
|
|
73
94
|
|
|
@@ -82,9 +103,9 @@ OBSERVE_APP_SECRET=...
|
|
|
82
103
|
Without valid credentials the collector answers `401` and telemetry is dropped.
|
|
83
104
|
The agent says so once, then backs off - one flush interval, then two, then
|
|
84
105
|
four, up to one attempt an hour - until the credentials are fixed. They are
|
|
85
|
-
read at startup, so that takes a restart. Leave `appKey` or `appSecret` unset
|
|
86
|
-
|
|
87
|
-
instead; a collector of your own at `endpoint` still receives batches without
|
|
106
|
+
read at startup, so that takes a restart. Leave `appKey` or `appSecret` unset,
|
|
107
|
+
with nothing in `OBSERVE_APP_KEY` or `OBSERVE_APP_SECRET` either, and nothing
|
|
108
|
+
is sent to the hosted collector at all, with a warning at startup instead; a collector of your own at `endpoint` still receives batches without
|
|
88
109
|
them.
|
|
89
110
|
|
|
90
111
|
To keep an environment from reporting - local development, say - switch the
|
|
@@ -93,8 +114,6 @@ agent off rather than supplying fake credentials, which are sent and refused:
|
|
|
93
114
|
```ts
|
|
94
115
|
ObserveModule.forRoot({
|
|
95
116
|
enabled: process.env.NODE_ENV === "production",
|
|
96
|
-
appKey: process.env.OBSERVE_APP_KEY ?? "",
|
|
97
|
-
appSecret: process.env.OBSERVE_APP_SECRET ?? "",
|
|
98
117
|
serviceId: "my-service",
|
|
99
118
|
});
|
|
100
119
|
```
|
|
@@ -122,11 +141,8 @@ import { ObserveModule } from "./observe";
|
|
|
122
141
|
|
|
123
142
|
@Module({
|
|
124
143
|
imports: [
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
appSecret: process.env.OBSERVE_APP_SECRET!,
|
|
128
|
-
serviceId: "my-service",
|
|
129
|
-
}),
|
|
144
|
+
// appKey and appSecret default to OBSERVE_APP_KEY and OBSERVE_APP_SECRET.
|
|
145
|
+
ObserveModule.forRoot({ serviceId: "my-service" }),
|
|
130
146
|
],
|
|
131
147
|
})
|
|
132
148
|
export class AppModule {}
|
|
@@ -457,7 +473,7 @@ The MSSQL unit suite uses the real driver's public request APIs with stubbed tra
|
|
|
457
473
|
$ docker run -d -p 6379:6379 redis:7-alpine
|
|
458
474
|
$ docker run -d -p 54321:5432 -e POSTGRES_PASSWORD=postgres-whisprr postgres:16-alpine
|
|
459
475
|
$ docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=test mysql:8
|
|
460
|
-
$ docker run -d -p 27027:27017 mongo:
|
|
476
|
+
$ docker run -d -p 27027:27017 mongo:7
|
|
461
477
|
```
|
|
462
478
|
|
|
463
479
|
To point them elsewhere, set `REDIS_HOST`/`REDIS_PORT`, `PGHOST`/`PGPORT`/`PGUSER`/`PGPASSWORD`/`PGDATABASE`, `MYSQL_HOST`/`MYSQL_PORT`/`MYSQL_USER`/`MYSQL_PASSWORD`/`MYSQL_DATABASE` or `MONGO_HOST`/`MONGO_PORT`.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { TypeScript } from "./project-setup.js";
|
|
2
|
+
export interface LinkOptions {
|
|
3
|
+
/** The project directory: where `package.json` and `.env` live. */
|
|
4
|
+
cwd: string;
|
|
5
|
+
/** The API base URL - the collector's, which also serves the link. */
|
|
6
|
+
endpoint: string;
|
|
7
|
+
/** Whether to try opening the link page in a browser. */
|
|
8
|
+
openBrowser: boolean;
|
|
9
|
+
/** This package's version: what a project without the SDK gets. */
|
|
10
|
+
version: string;
|
|
11
|
+
}
|
|
12
|
+
export interface LinkDependencies {
|
|
13
|
+
fetch: typeof fetch;
|
|
14
|
+
sleep: (ms: number) => Promise<void>;
|
|
15
|
+
openUrl: (url: string) => void;
|
|
16
|
+
log: (line: string) => void;
|
|
17
|
+
hostname: () => string;
|
|
18
|
+
now: () => number;
|
|
19
|
+
/**
|
|
20
|
+
* Runs a command in the project with the terminal attached - the package
|
|
21
|
+
* manager's output is the progress - and resolves to its exit code.
|
|
22
|
+
*/
|
|
23
|
+
run: (command: string, args: string[], cwd: string) => Promise<number>;
|
|
24
|
+
/** The project's own TypeScript, or undefined when it has none. */
|
|
25
|
+
loadTypeScript: (cwd: string) => TypeScript | undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* `npx @nestjs/observe link`: asks the API for a code, has the person type it
|
|
29
|
+
* into the dashboard and approve, then writes the key pair it receives into
|
|
30
|
+
* `.env` and makes the start scripts load it.
|
|
31
|
+
*
|
|
32
|
+
* In a project that does not use the SDK yet, it also installs it with the
|
|
33
|
+
* project's package manager and wires it into the root module and `main.ts`
|
|
34
|
+
* (see `wireApplication`) - so an existing app is set up by the one command,
|
|
35
|
+
* as a `nest new` one is. The person is told before they approve.
|
|
36
|
+
*
|
|
37
|
+
* Returns the process exit code. Nothing is written until the key pair has
|
|
38
|
+
* arrived, so an interrupted, denied or expired link leaves the project as it
|
|
39
|
+
* was.
|
|
40
|
+
*/
|
|
41
|
+
export declare function link(options: LinkOptions, deps: LinkDependencies): Promise<number>;
|
package/dist/cli/link.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { addDependencyCommand, detectPackageManager, } from "./package-manager.js";
|
|
2
|
+
import { addEnvFileToStartScripts, ensureEnvIgnored, readPackageName, writeEnvFile, } from "./project-files.js";
|
|
3
|
+
import { findEntryFiles, inspectProject, QUICK_START_URL, SDK_PACKAGE, serviceIdFor, } from "./project-setup.js";
|
|
4
|
+
import { wireApplication } from "./wire-application.js";
|
|
5
|
+
/** Extra seconds `slow_down` adds to the interval, as RFC 8628 says. */
|
|
6
|
+
const SLOW_DOWN_SECONDS = 5;
|
|
7
|
+
/**
|
|
8
|
+
* `npx @nestjs/observe link`: asks the API for a code, has the person type it
|
|
9
|
+
* into the dashboard and approve, then writes the key pair it receives into
|
|
10
|
+
* `.env` and makes the start scripts load it.
|
|
11
|
+
*
|
|
12
|
+
* In a project that does not use the SDK yet, it also installs it with the
|
|
13
|
+
* project's package manager and wires it into the root module and `main.ts`
|
|
14
|
+
* (see `wireApplication`) - so an existing app is set up by the one command,
|
|
15
|
+
* as a `nest new` one is. The person is told before they approve.
|
|
16
|
+
*
|
|
17
|
+
* Returns the process exit code. Nothing is written until the key pair has
|
|
18
|
+
* arrived, so an interrupted, denied or expired link leaves the project as it
|
|
19
|
+
* was.
|
|
20
|
+
*/
|
|
21
|
+
export async function link(options, deps) {
|
|
22
|
+
const applicationName = readPackageName(options.cwd);
|
|
23
|
+
if (applicationName === undefined) {
|
|
24
|
+
deps.log(`No package.json in ${options.cwd}. Run this in your NestJS project's directory.`);
|
|
25
|
+
return 1;
|
|
26
|
+
}
|
|
27
|
+
const setup = inspectProject(options.cwd, options.version, deps.loadTypeScript(options.cwd));
|
|
28
|
+
if (setup.unsupported) {
|
|
29
|
+
deps.log(`${setup.unsupported}. Nothing was written.`);
|
|
30
|
+
return 1;
|
|
31
|
+
}
|
|
32
|
+
const manager = detectPackageManager(options.cwd);
|
|
33
|
+
let started;
|
|
34
|
+
try {
|
|
35
|
+
started = await post(deps, options.endpoint, "sessions", {
|
|
36
|
+
applicationName,
|
|
37
|
+
hostname: deps.hostname(),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
deps.log(`Could not reach NestJS Observe at ${options.endpoint}: ${describe(err)}`);
|
|
42
|
+
return 1;
|
|
43
|
+
}
|
|
44
|
+
deps.log("");
|
|
45
|
+
deps.log(` Open ${started.verificationUri}`);
|
|
46
|
+
deps.log(` and type ${started.userCode}`);
|
|
47
|
+
deps.log("");
|
|
48
|
+
deps.log(`Waiting for you to approve it in the dashboard. The code expires in ${Math.round(started.expiresIn / 60)} minutes.`);
|
|
49
|
+
const plan = describePlan(setup, manager);
|
|
50
|
+
if (plan) {
|
|
51
|
+
deps.log(plan);
|
|
52
|
+
}
|
|
53
|
+
if (options.openBrowser) {
|
|
54
|
+
// The page only, never the code: the code is typed, so a link that
|
|
55
|
+
// carries it cannot approve anything on its own.
|
|
56
|
+
deps.openUrl(started.verificationUri);
|
|
57
|
+
}
|
|
58
|
+
const credentials = await waitForApproval(deps, options.endpoint, started);
|
|
59
|
+
if (typeof credentials === "string") {
|
|
60
|
+
deps.log(credentials);
|
|
61
|
+
return 1;
|
|
62
|
+
}
|
|
63
|
+
writeEnvFile(options.cwd, credentials.appKey, credentials.appSecret);
|
|
64
|
+
const ignoredNow = ensureEnvIgnored(options.cwd);
|
|
65
|
+
const scripts = addEnvFileToStartScripts(options.cwd);
|
|
66
|
+
deps.log("");
|
|
67
|
+
deps.log(`✔ Linked to ${credentials.applicationName} in ${credentials.projectName}. The key pair is in .env.`);
|
|
68
|
+
if (ignoredNow) {
|
|
69
|
+
deps.log(" Added .env to .gitignore, so the secret stays out of git.");
|
|
70
|
+
}
|
|
71
|
+
if (scripts.updated.length) {
|
|
72
|
+
deps.log(` ${listScripts(scripts.updated)} now load${scripts.updated.length === 1 ? "s" : ""} it with --env-file .env.`);
|
|
73
|
+
}
|
|
74
|
+
if (scripts.skipped.length) {
|
|
75
|
+
deps.log(` ${listScripts(scripts.skipped)} do${scripts.skipped.length === 1 ? "es" : ""} not run nest start, so load .env there yourself (node --env-file=.env).`);
|
|
76
|
+
}
|
|
77
|
+
if (setup.install) {
|
|
78
|
+
const spec = `${SDK_PACKAGE}@^${options.version}`;
|
|
79
|
+
const [command, args] = addDependencyCommand(manager, spec);
|
|
80
|
+
deps.log("");
|
|
81
|
+
deps.log(`Installing ${spec} with ${manager}...`);
|
|
82
|
+
const exitCode = await deps.run(command, args, options.cwd).catch(() => -1);
|
|
83
|
+
if (exitCode !== 0) {
|
|
84
|
+
deps.log(`✖ ${[command, ...args].join(" ")} did not finish. Run it yourself, then add the SDK to the app: ${QUICK_START_URL}`);
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
deps.log(`✔ Installed ${spec}.`);
|
|
88
|
+
}
|
|
89
|
+
let wired = true;
|
|
90
|
+
if (setup.wire) {
|
|
91
|
+
const result = wire(deps, options.cwd, serviceIdFor(credentials.applicationName, applicationName));
|
|
92
|
+
if (result.kind === "wired") {
|
|
93
|
+
deps.log("✔ Wired it into the app:");
|
|
94
|
+
const width = Math.max(...result.files.map((file) => file.path.length));
|
|
95
|
+
for (const file of result.files) {
|
|
96
|
+
deps.log(` ${file.path.padEnd(width)} ${file.change}`);
|
|
97
|
+
}
|
|
98
|
+
deps.log(" Review the changes with git diff.");
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
wired = false;
|
|
102
|
+
deps.log(`! Not wired into the app: ${result.reason}.`);
|
|
103
|
+
deps.log(` Add it by hand - three edits: ${QUICK_START_URL}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
deps.log(` ${wired ? "Start the app" : "Once it is wired, start the app"} and it reports to NestJS Observe. In production, set OBSERVE_APP_KEY and OBSERVE_APP_SECRET in the environment instead.`);
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* What else the link will change, said while the person can still decide not
|
|
111
|
+
* to approve. Nothing for a project that already uses the SDK.
|
|
112
|
+
*/
|
|
113
|
+
function describePlan(setup, manager) {
|
|
114
|
+
const wiring = "wires it into the app's root module and main.ts";
|
|
115
|
+
if (setup.install && setup.wire) {
|
|
116
|
+
return `This project does not use NestJS Observe yet: once you approve, link also installs ${SDK_PACKAGE} with ${manager} and ${wiring}.`;
|
|
117
|
+
}
|
|
118
|
+
if (setup.wire) {
|
|
119
|
+
return `The app does not use ${SDK_PACKAGE} yet: once you approve, link also ${wiring}.`;
|
|
120
|
+
}
|
|
121
|
+
if (setup.install) {
|
|
122
|
+
return `Once you approve, link also installs ${SDK_PACKAGE} with ${manager}.`;
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Wires the SDK into the project's one application. Asked for TypeScript
|
|
128
|
+
* again rather than reusing what the inspection had: an install has just
|
|
129
|
+
* run, and may have been what brought it.
|
|
130
|
+
*/
|
|
131
|
+
function wire(deps, cwd, serviceId) {
|
|
132
|
+
const ts = deps.loadTypeScript(cwd);
|
|
133
|
+
if (!ts) {
|
|
134
|
+
return {
|
|
135
|
+
kind: "manual",
|
|
136
|
+
reason: "the project's TypeScript, which the code is edited with, could not be loaded",
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
const entries = findEntryFiles(cwd, ts);
|
|
140
|
+
if (entries.length === 0) {
|
|
141
|
+
return {
|
|
142
|
+
kind: "manual",
|
|
143
|
+
reason: "could not find the application's main.ts",
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
if (entries.length > 1) {
|
|
147
|
+
// One key is one application: wiring them all would report every app
|
|
148
|
+
// in the workspace as this one.
|
|
149
|
+
return {
|
|
150
|
+
kind: "manual",
|
|
151
|
+
reason: `this workspace has ${entries.length} applications (${entries.join(", ")}), and the key is for one of them`,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
return wireApplication(ts, cwd, entries[0], serviceId);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Polls until the link is approved, denied or expires. A string is the
|
|
158
|
+
* message to end on; transient network failures are retried until the code's
|
|
159
|
+
* own expiry, since the person may still be approving.
|
|
160
|
+
*/
|
|
161
|
+
async function waitForApproval(deps, endpoint, started) {
|
|
162
|
+
const deadline = deps.now() + started.expiresIn * 1000;
|
|
163
|
+
let interval = started.interval;
|
|
164
|
+
while (deps.now() < deadline) {
|
|
165
|
+
await deps.sleep(interval * 1000);
|
|
166
|
+
const response = await deps
|
|
167
|
+
.fetch(`${endpoint}/cli-link/token`, {
|
|
168
|
+
method: "POST",
|
|
169
|
+
headers: { "content-type": "application/json" },
|
|
170
|
+
body: JSON.stringify({ deviceCode: started.deviceCode }),
|
|
171
|
+
})
|
|
172
|
+
.catch(() => null);
|
|
173
|
+
if (!response) {
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const body = (await response.json().catch(() => ({})));
|
|
177
|
+
if (response.ok && body.appKey && body.appSecret) {
|
|
178
|
+
return body;
|
|
179
|
+
}
|
|
180
|
+
switch (body.error) {
|
|
181
|
+
case "authorization_pending":
|
|
182
|
+
continue;
|
|
183
|
+
case "slow_down":
|
|
184
|
+
interval += SLOW_DOWN_SECONDS;
|
|
185
|
+
continue;
|
|
186
|
+
case "access_denied":
|
|
187
|
+
return "The link was denied in the dashboard. Nothing was written.";
|
|
188
|
+
case "expired_token":
|
|
189
|
+
return "The code expired before it was approved. Run npx @nestjs/observe link again.";
|
|
190
|
+
default:
|
|
191
|
+
// A 5xx or a gateway page: try again on the next tick.
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return "The code expired before it was approved. Run npx @nestjs/observe link again.";
|
|
196
|
+
}
|
|
197
|
+
async function post(deps, endpoint, path, body) {
|
|
198
|
+
const response = await deps.fetch(`${endpoint}/cli-link/${path}`, {
|
|
199
|
+
method: "POST",
|
|
200
|
+
headers: { "content-type": "application/json" },
|
|
201
|
+
body: JSON.stringify(body),
|
|
202
|
+
});
|
|
203
|
+
if (!response.ok) {
|
|
204
|
+
throw new Error(`HTTP ${response.status}`);
|
|
205
|
+
}
|
|
206
|
+
return (await response.json());
|
|
207
|
+
}
|
|
208
|
+
/** `"start"`, `"start" and "start:dev"`, `"start", "start:dev" and "start:debug"`. */
|
|
209
|
+
function listScripts(names) {
|
|
210
|
+
const quoted = names.map((name) => `"${name}"`);
|
|
211
|
+
return quoted.length > 1
|
|
212
|
+
? `${quoted.slice(0, -1).join(", ")} and ${quoted[quoted.length - 1]}`
|
|
213
|
+
: quoted[0];
|
|
214
|
+
}
|
|
215
|
+
function describe(err) {
|
|
216
|
+
return err instanceof Error ? err.message : String(err);
|
|
217
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { link } from "./link.js";
|
|
7
|
+
import { loadTypeScript } from "./project-setup.js";
|
|
8
|
+
const { version } = createRequire(import.meta.url)("../../package.json");
|
|
9
|
+
const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
|
|
10
|
+
const USAGE = `Usage: npx @nestjs/observe link [--no-browser] [--cwd <dir>]
|
|
11
|
+
|
|
12
|
+
link Link this project to NestJS Observe: approve a code in the
|
|
13
|
+
dashboard, and the API key pair is written into .env. In an app
|
|
14
|
+
that does not use the SDK yet, it is installed and wired in too.
|
|
15
|
+
|
|
16
|
+
Options:
|
|
17
|
+
--no-browser Print the link page instead of opening it.
|
|
18
|
+
--cwd <dir> The project directory (default: the current one).`;
|
|
19
|
+
/**
|
|
20
|
+
* Opens the link page in the default browser, best effort: a headless box or
|
|
21
|
+
* a missing opener just means the person opens the printed URL themselves.
|
|
22
|
+
*/
|
|
23
|
+
function openUrl(url) {
|
|
24
|
+
const [command, args] = process.platform === "darwin"
|
|
25
|
+
? ["open", [url]]
|
|
26
|
+
: process.platform === "win32"
|
|
27
|
+
? ["cmd", ["/c", "start", "", url]]
|
|
28
|
+
: ["xdg-open", [url]];
|
|
29
|
+
try {
|
|
30
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
|
31
|
+
child.on("error", () => undefined);
|
|
32
|
+
child.unref();
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// Printed above; nothing else to do.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function main(argv) {
|
|
39
|
+
const [command, ...rest] = argv;
|
|
40
|
+
if (command !== "link") {
|
|
41
|
+
console.log(USAGE);
|
|
42
|
+
return command === undefined || command === "--help" || command === "-h"
|
|
43
|
+
? 0
|
|
44
|
+
: 1;
|
|
45
|
+
}
|
|
46
|
+
const cwdIndex = rest.indexOf("--cwd");
|
|
47
|
+
const cwd = resolve(cwdIndex >= 0 ? rest[cwdIndex + 1] ?? "." : ".");
|
|
48
|
+
const interactive = process.stdout.isTTY && !process.env.CI;
|
|
49
|
+
return link({
|
|
50
|
+
cwd,
|
|
51
|
+
endpoint: (process.env.OBSERVE_ENDPOINT ?? HOSTED_COLLECTOR_ENDPOINT).replace(/\/+$/, ""),
|
|
52
|
+
openBrowser: interactive && !rest.includes("--no-browser"),
|
|
53
|
+
version,
|
|
54
|
+
}, {
|
|
55
|
+
fetch,
|
|
56
|
+
sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
|
|
57
|
+
openUrl,
|
|
58
|
+
log: (line) => console.log(line),
|
|
59
|
+
hostname,
|
|
60
|
+
now: Date.now,
|
|
61
|
+
run,
|
|
62
|
+
loadTypeScript,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Runs the package manager with the terminal attached. On Windows through the
|
|
67
|
+
* shell, which is what finds `npm.cmd`; there `^` is cmd.exe's escape
|
|
68
|
+
* character, so each argument is quoted.
|
|
69
|
+
*/
|
|
70
|
+
function run(command, args, cwd) {
|
|
71
|
+
const windows = process.platform === "win32";
|
|
72
|
+
return new Promise((done) => {
|
|
73
|
+
const child = spawn(command, windows ? args.map((arg) => `"${arg}"`) : args, { cwd, stdio: "inherit", shell: windows });
|
|
74
|
+
child.on("error", () => done(-1));
|
|
75
|
+
child.on("close", (code) => done(code ?? -1));
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
79
|
+
console.error(err);
|
|
80
|
+
process.exit(1);
|
|
81
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
|
|
2
|
+
/**
|
|
3
|
+
* The package manager the project is installed with.
|
|
4
|
+
*
|
|
5
|
+
* The nearest lockfile decides, looked for from `cwd` up to the repository's
|
|
6
|
+
* root - a package inside a workspace has its lockfile at the root. Without
|
|
7
|
+
* one, Corepack's `packageManager` field in package.json does, and npm is
|
|
8
|
+
* the answer when neither says anything. Running `npx` says nothing either
|
|
9
|
+
* way: it is how the command was started, not how the project installs.
|
|
10
|
+
*/
|
|
11
|
+
export declare function detectPackageManager(cwd: string): PackageManager;
|
|
12
|
+
/** The command that adds `spec` to the project's dependencies. */
|
|
13
|
+
export declare function addDependencyCommand(manager: PackageManager, spec: string): [command: string, args: string[]];
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
/** Lockfiles, in the order they are looked for in each directory. */
|
|
4
|
+
const LOCKFILES = [
|
|
5
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
6
|
+
["yarn.lock", "yarn"],
|
|
7
|
+
["bun.lock", "bun"],
|
|
8
|
+
["bun.lockb", "bun"],
|
|
9
|
+
["package-lock.json", "npm"],
|
|
10
|
+
["npm-shrinkwrap.json", "npm"],
|
|
11
|
+
];
|
|
12
|
+
const MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
13
|
+
/**
|
|
14
|
+
* The package manager the project is installed with.
|
|
15
|
+
*
|
|
16
|
+
* The nearest lockfile decides, looked for from `cwd` up to the repository's
|
|
17
|
+
* root - a package inside a workspace has its lockfile at the root. Without
|
|
18
|
+
* one, Corepack's `packageManager` field in package.json does, and npm is
|
|
19
|
+
* the answer when neither says anything. Running `npx` says nothing either
|
|
20
|
+
* way: it is how the command was started, not how the project installs.
|
|
21
|
+
*/
|
|
22
|
+
export function detectPackageManager(cwd) {
|
|
23
|
+
for (let dir = cwd;; dir = dirname(dir)) {
|
|
24
|
+
const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
|
|
25
|
+
if (found) {
|
|
26
|
+
return found[1];
|
|
27
|
+
}
|
|
28
|
+
// The repository's root is as far as the project goes: a lockfile
|
|
29
|
+
// above it belongs to something else.
|
|
30
|
+
if (existsSync(join(dir, ".git")) || dirname(dir) === dir) {
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return declaredPackageManager(cwd) ?? "npm";
|
|
35
|
+
}
|
|
36
|
+
/** `"pnpm@9.12.0"` in package.json's `packageManager` field, as `"pnpm"`. */
|
|
37
|
+
function declaredPackageManager(cwd) {
|
|
38
|
+
try {
|
|
39
|
+
const { packageManager } = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
|
|
40
|
+
const name = typeof packageManager === "string"
|
|
41
|
+
? packageManager.split("@")[0]
|
|
42
|
+
: undefined;
|
|
43
|
+
return name && MANAGERS.has(name) ? name : undefined;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** The command that adds `spec` to the project's dependencies. */
|
|
50
|
+
export function addDependencyCommand(manager, spec) {
|
|
51
|
+
return manager === "npm"
|
|
52
|
+
? ["npm", ["install", spec]]
|
|
53
|
+
: [manager, ["add", spec]];
|
|
54
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** The variables `ObserveModule` falls back to for its key pair. */
|
|
2
|
+
export declare const KEY_VARIABLE = "OBSERVE_APP_KEY";
|
|
3
|
+
export declare const SECRET_VARIABLE = "OBSERVE_APP_SECRET";
|
|
4
|
+
/**
|
|
5
|
+
* Writes the key pair into `<cwd>/.env`, replacing an earlier pair and keeping
|
|
6
|
+
* every other line as it was. Created owner-only when it does not exist.
|
|
7
|
+
*
|
|
8
|
+
* Both values are single-quoted. Key and secret are drawn from the same
|
|
9
|
+
* alphabet, which includes `$` and `&`: unquoted, a loader that expands
|
|
10
|
+
* variables (`dotenv-expand`, `ConfigModule` with `expandVariables`) rewrites
|
|
11
|
+
* everything after a `$`, and a shell sourcing the file stops at the `&`.
|
|
12
|
+
* Node's own `--env-file` reads either form literally. Single quotes are
|
|
13
|
+
* literal in all of them, and the alphabet has no quote in it to escape.
|
|
14
|
+
*/
|
|
15
|
+
export declare function writeEnvFile(cwd: string, appKey: string, appSecret: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* Makes sure `.env` is git-ignored, so the secret cannot be committed by
|
|
18
|
+
* accident. `nest new` already ignores it; a project from elsewhere may not.
|
|
19
|
+
* Returns whether the file had to be changed.
|
|
20
|
+
*/
|
|
21
|
+
export declare function ensureEnvIgnored(cwd: string): boolean;
|
|
22
|
+
export interface ScriptsUpdate {
|
|
23
|
+
/** Scripts that now load `.env`. */
|
|
24
|
+
updated: string[];
|
|
25
|
+
/** `start` or `start:dev` scripts that do not run `nest start`, left alone. */
|
|
26
|
+
skipped: string[];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Adds `--env-file .env` to every script that runs `nest start` - `start`,
|
|
30
|
+
* `start:dev` and `start:debug` in a `nest new` project, and any of a
|
|
31
|
+
* monorepo's - so the pair in `.env` reaches the process however the app is
|
|
32
|
+
* started locally. `start:prod` runs `node dist/main` and is left alone: in
|
|
33
|
+
* production the pair comes from the environment. Scripts that already pass
|
|
34
|
+
* an env file are left as they are, and a `start` or `start:dev` that starts
|
|
35
|
+
* the app some other way is reported, so the caller can say how to load it.
|
|
36
|
+
*/
|
|
37
|
+
export declare function addEnvFileToStartScripts(cwd: string): ScriptsUpdate;
|
|
38
|
+
/** The project's package name, which the link proposes as the app's name. */
|
|
39
|
+
export declare function readPackageName(cwd: string): string | undefined;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/** The variables `ObserveModule` falls back to for its key pair. */
|
|
4
|
+
export const KEY_VARIABLE = "OBSERVE_APP_KEY";
|
|
5
|
+
export const SECRET_VARIABLE = "OBSERVE_APP_SECRET";
|
|
6
|
+
/**
|
|
7
|
+
* Scripts every project is expected to start the app with. When one of them
|
|
8
|
+
* does not run `nest start`, it is reported, so the caller can say how to
|
|
9
|
+
* load `.env` instead.
|
|
10
|
+
*/
|
|
11
|
+
const CONVENTIONAL_START_SCRIPTS = new Set(["start", "start:dev"]);
|
|
12
|
+
/**
|
|
13
|
+
* Writes the key pair into `<cwd>/.env`, replacing an earlier pair and keeping
|
|
14
|
+
* every other line as it was. Created owner-only when it does not exist.
|
|
15
|
+
*
|
|
16
|
+
* Both values are single-quoted. Key and secret are drawn from the same
|
|
17
|
+
* alphabet, which includes `$` and `&`: unquoted, a loader that expands
|
|
18
|
+
* variables (`dotenv-expand`, `ConfigModule` with `expandVariables`) rewrites
|
|
19
|
+
* everything after a `$`, and a shell sourcing the file stops at the `&`.
|
|
20
|
+
* Node's own `--env-file` reads either form literally. Single quotes are
|
|
21
|
+
* literal in all of them, and the alphabet has no quote in it to escape.
|
|
22
|
+
*/
|
|
23
|
+
export function writeEnvFile(cwd, appKey, appSecret) {
|
|
24
|
+
const path = join(cwd, ".env");
|
|
25
|
+
const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
26
|
+
const kept = existing
|
|
27
|
+
.split(/\r?\n/)
|
|
28
|
+
.filter((line) => !new RegExp(`^\\s*(export\\s+)?(${KEY_VARIABLE}|${SECRET_VARIABLE})\\s*=`).test(line));
|
|
29
|
+
while (kept.length && kept[kept.length - 1].trim() === "") {
|
|
30
|
+
kept.pop();
|
|
31
|
+
}
|
|
32
|
+
const lines = [
|
|
33
|
+
...kept,
|
|
34
|
+
...(kept.length ? [""] : []),
|
|
35
|
+
`${KEY_VARIABLE}='${appKey}'`,
|
|
36
|
+
`${SECRET_VARIABLE}='${appSecret}'`,
|
|
37
|
+
"",
|
|
38
|
+
];
|
|
39
|
+
writeFileSync(path, lines.join("\n"), existing ? undefined : { mode: 0o600 });
|
|
40
|
+
return path;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Makes sure `.env` is git-ignored, so the secret cannot be committed by
|
|
44
|
+
* accident. `nest new` already ignores it; a project from elsewhere may not.
|
|
45
|
+
* Returns whether the file had to be changed.
|
|
46
|
+
*/
|
|
47
|
+
export function ensureEnvIgnored(cwd) {
|
|
48
|
+
const path = join(cwd, ".gitignore");
|
|
49
|
+
const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
50
|
+
const ignored = existing
|
|
51
|
+
.split(/\r?\n/)
|
|
52
|
+
.map((line) => line.trim())
|
|
53
|
+
.some((line) => line === ".env" || line === "/.env" || line === ".env*");
|
|
54
|
+
if (ignored) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
const separator = existing && !existing.endsWith("\n") ? "\n" : "";
|
|
58
|
+
writeFileSync(path, `${existing}${separator}\n# NestJS Observe key pair\n.env\n`);
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Adds `--env-file .env` to every script that runs `nest start` - `start`,
|
|
63
|
+
* `start:dev` and `start:debug` in a `nest new` project, and any of a
|
|
64
|
+
* monorepo's - so the pair in `.env` reaches the process however the app is
|
|
65
|
+
* started locally. `start:prod` runs `node dist/main` and is left alone: in
|
|
66
|
+
* production the pair comes from the environment. Scripts that already pass
|
|
67
|
+
* an env file are left as they are, and a `start` or `start:dev` that starts
|
|
68
|
+
* the app some other way is reported, so the caller can say how to load it.
|
|
69
|
+
*/
|
|
70
|
+
export function addEnvFileToStartScripts(cwd) {
|
|
71
|
+
const path = join(cwd, "package.json");
|
|
72
|
+
const raw = readFileSync(path, "utf8");
|
|
73
|
+
const pkg = JSON.parse(raw);
|
|
74
|
+
const result = { updated: [], skipped: [] };
|
|
75
|
+
for (const [name, script] of Object.entries(pkg.scripts ?? {})) {
|
|
76
|
+
if (typeof script !== "string" || /--env-file\b/.test(script)) {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (/^\s*nest start\b/.test(script)) {
|
|
80
|
+
pkg.scripts[name] = `${script.trimEnd()} --env-file .env`;
|
|
81
|
+
result.updated.push(name);
|
|
82
|
+
}
|
|
83
|
+
else if (CONVENTIONAL_START_SCRIPTS.has(name)) {
|
|
84
|
+
result.skipped.push(name);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (result.updated.length) {
|
|
88
|
+
const indent = raw.match(/^[ \t]+(?=")/m)?.[0] ?? " ";
|
|
89
|
+
writeFileSync(path, JSON.stringify(pkg, null, indent) + (raw.endsWith("\n") ? "\n" : ""));
|
|
90
|
+
}
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
/** The project's package name, which the link proposes as the app's name. */
|
|
94
|
+
export function readPackageName(cwd) {
|
|
95
|
+
const path = join(cwd, "package.json");
|
|
96
|
+
if (!existsSync(path)) {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const name = JSON.parse(readFileSync(path, "utf8"))
|
|
101
|
+
.name;
|
|
102
|
+
return typeof name === "string" ? name : undefined;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
}
|