@nestjs/observe 0.3.14 → 0.3.15
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 +20 -6
- package/dist/cli/link.d.ts +26 -0
- package/dist/cli/link.js +123 -0
- package/dist/cli/observe-cli.d.ts +2 -0
- package/dist/cli/observe-cli.js +61 -0
- package/dist/cli/project-files.d.ts +39 -0
- package/dist/cli/project-files.js +107 -0
- package/dist/observe.module.js +34 -6
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -65,9 +65,23 @@ $ 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
|
+
Or sign up at **[observe.nestjs.com](https://observe.nestjs.com)** and create a
|
|
83
|
+
service by hand. The dashboard issues an **app key** and an **app secret**,
|
|
84
|
+
which the agent sends on every ingest request.
|
|
71
85
|
|
|
72
86
|
**Free for up to 300,000 events a month**, which covers most individual projects, startups, and small applications.
|
|
73
87
|
|
|
@@ -82,9 +96,9 @@ OBSERVE_APP_SECRET=...
|
|
|
82
96
|
Without valid credentials the collector answers `401` and telemetry is dropped.
|
|
83
97
|
The agent says so once, then backs off - one flush interval, then two, then
|
|
84
98
|
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
|
|
99
|
+
read at startup, so that takes a restart. Leave `appKey` or `appSecret` unset,
|
|
100
|
+
with nothing in `OBSERVE_APP_KEY` or `OBSERVE_APP_SECRET` either, and nothing
|
|
101
|
+
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
102
|
them.
|
|
89
103
|
|
|
90
104
|
To keep an environment from reporting - local development, say - switch the
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface LinkOptions {
|
|
2
|
+
/** The project directory: where `package.json` and `.env` live. */
|
|
3
|
+
cwd: string;
|
|
4
|
+
/** The API base URL - the collector's, which also serves the link. */
|
|
5
|
+
endpoint: string;
|
|
6
|
+
/** Whether to try opening the link page in a browser. */
|
|
7
|
+
openBrowser: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface LinkDependencies {
|
|
10
|
+
fetch: typeof fetch;
|
|
11
|
+
sleep: (ms: number) => Promise<void>;
|
|
12
|
+
openUrl: (url: string) => void;
|
|
13
|
+
log: (line: string) => void;
|
|
14
|
+
hostname: () => string;
|
|
15
|
+
now: () => number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* `npx @nestjs/observe link`: asks the API for a code, has the person type it
|
|
19
|
+
* into the dashboard and approve, then writes the key pair it receives into
|
|
20
|
+
* `.env` and makes the start scripts load it.
|
|
21
|
+
*
|
|
22
|
+
* Returns the process exit code. Nothing is written until the key pair has
|
|
23
|
+
* arrived, so an interrupted, denied or expired link leaves the project as it
|
|
24
|
+
* was.
|
|
25
|
+
*/
|
|
26
|
+
export declare function link(options: LinkOptions, deps: LinkDependencies): Promise<number>;
|
package/dist/cli/link.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { addEnvFileToStartScripts, ensureEnvIgnored, readPackageName, writeEnvFile, } from "./project-files.js";
|
|
2
|
+
/** Extra seconds `slow_down` adds to the interval, as RFC 8628 says. */
|
|
3
|
+
const SLOW_DOWN_SECONDS = 5;
|
|
4
|
+
/**
|
|
5
|
+
* `npx @nestjs/observe link`: asks the API for a code, has the person type it
|
|
6
|
+
* into the dashboard and approve, then writes the key pair it receives into
|
|
7
|
+
* `.env` and makes the start scripts load it.
|
|
8
|
+
*
|
|
9
|
+
* Returns the process exit code. Nothing is written until the key pair has
|
|
10
|
+
* arrived, so an interrupted, denied or expired link leaves the project as it
|
|
11
|
+
* was.
|
|
12
|
+
*/
|
|
13
|
+
export async function link(options, deps) {
|
|
14
|
+
const applicationName = readPackageName(options.cwd);
|
|
15
|
+
if (applicationName === undefined) {
|
|
16
|
+
deps.log(`No package.json in ${options.cwd}. Run this in your NestJS project's directory.`);
|
|
17
|
+
return 1;
|
|
18
|
+
}
|
|
19
|
+
let started;
|
|
20
|
+
try {
|
|
21
|
+
started = await post(deps, options.endpoint, "sessions", {
|
|
22
|
+
applicationName,
|
|
23
|
+
hostname: deps.hostname(),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
deps.log(`Could not reach NestJS Observe at ${options.endpoint}: ${describe(err)}`);
|
|
28
|
+
return 1;
|
|
29
|
+
}
|
|
30
|
+
deps.log("");
|
|
31
|
+
deps.log(` Open ${started.verificationUri}`);
|
|
32
|
+
deps.log(` and type ${started.userCode}`);
|
|
33
|
+
deps.log("");
|
|
34
|
+
deps.log(`Waiting for you to approve it in the dashboard. The code expires in ${Math.round(started.expiresIn / 60)} minutes.`);
|
|
35
|
+
if (options.openBrowser) {
|
|
36
|
+
// The page only, never the code: the code is typed, so a link that
|
|
37
|
+
// carries it cannot approve anything on its own.
|
|
38
|
+
deps.openUrl(started.verificationUri);
|
|
39
|
+
}
|
|
40
|
+
const credentials = await waitForApproval(deps, options.endpoint, started);
|
|
41
|
+
if (typeof credentials === "string") {
|
|
42
|
+
deps.log(credentials);
|
|
43
|
+
return 1;
|
|
44
|
+
}
|
|
45
|
+
writeEnvFile(options.cwd, credentials.appKey, credentials.appSecret);
|
|
46
|
+
const ignoredNow = ensureEnvIgnored(options.cwd);
|
|
47
|
+
const scripts = addEnvFileToStartScripts(options.cwd);
|
|
48
|
+
deps.log("");
|
|
49
|
+
deps.log(`✔ Linked to ${credentials.applicationName} in ${credentials.projectName}. The key pair is in .env.`);
|
|
50
|
+
if (ignoredNow) {
|
|
51
|
+
deps.log(" Added .env to .gitignore, so the secret stays out of git.");
|
|
52
|
+
}
|
|
53
|
+
if (scripts.updated.length) {
|
|
54
|
+
deps.log(` ${listScripts(scripts.updated)} now load${scripts.updated.length === 1 ? "s" : ""} it with --env-file .env.`);
|
|
55
|
+
}
|
|
56
|
+
if (scripts.skipped.length) {
|
|
57
|
+
deps.log(` ${listScripts(scripts.skipped)} do${scripts.skipped.length === 1 ? "es" : ""} not run nest start, so load .env there yourself (node --env-file=.env).`);
|
|
58
|
+
}
|
|
59
|
+
deps.log(" Start the app and it reports to NestJS Observe. In production, set OBSERVE_APP_KEY and OBSERVE_APP_SECRET in the environment instead.");
|
|
60
|
+
return 0;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Polls until the link is approved, denied or expires. A string is the
|
|
64
|
+
* message to end on; transient network failures are retried until the code's
|
|
65
|
+
* own expiry, since the person may still be approving.
|
|
66
|
+
*/
|
|
67
|
+
async function waitForApproval(deps, endpoint, started) {
|
|
68
|
+
const deadline = deps.now() + started.expiresIn * 1000;
|
|
69
|
+
let interval = started.interval;
|
|
70
|
+
while (deps.now() < deadline) {
|
|
71
|
+
await deps.sleep(interval * 1000);
|
|
72
|
+
const response = await deps
|
|
73
|
+
.fetch(`${endpoint}/cli-link/token`, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers: { "content-type": "application/json" },
|
|
76
|
+
body: JSON.stringify({ deviceCode: started.deviceCode }),
|
|
77
|
+
})
|
|
78
|
+
.catch(() => null);
|
|
79
|
+
if (!response) {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const body = (await response.json().catch(() => ({})));
|
|
83
|
+
if (response.ok && body.appKey && body.appSecret) {
|
|
84
|
+
return body;
|
|
85
|
+
}
|
|
86
|
+
switch (body.error) {
|
|
87
|
+
case "authorization_pending":
|
|
88
|
+
continue;
|
|
89
|
+
case "slow_down":
|
|
90
|
+
interval += SLOW_DOWN_SECONDS;
|
|
91
|
+
continue;
|
|
92
|
+
case "access_denied":
|
|
93
|
+
return "The link was denied in the dashboard. Nothing was written.";
|
|
94
|
+
case "expired_token":
|
|
95
|
+
return "The code expired before it was approved. Run npx @nestjs/observe link again.";
|
|
96
|
+
default:
|
|
97
|
+
// A 5xx or a gateway page: try again on the next tick.
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return "The code expired before it was approved. Run npx @nestjs/observe link again.";
|
|
102
|
+
}
|
|
103
|
+
async function post(deps, endpoint, path, body) {
|
|
104
|
+
const response = await deps.fetch(`${endpoint}/cli-link/${path}`, {
|
|
105
|
+
method: "POST",
|
|
106
|
+
headers: { "content-type": "application/json" },
|
|
107
|
+
body: JSON.stringify(body),
|
|
108
|
+
});
|
|
109
|
+
if (!response.ok) {
|
|
110
|
+
throw new Error(`HTTP ${response.status}`);
|
|
111
|
+
}
|
|
112
|
+
return (await response.json());
|
|
113
|
+
}
|
|
114
|
+
/** `"start"`, `"start" and "start:dev"`, `"start", "start:dev" and "start:debug"`. */
|
|
115
|
+
function listScripts(names) {
|
|
116
|
+
const quoted = names.map((name) => `"${name}"`);
|
|
117
|
+
return quoted.length > 1
|
|
118
|
+
? `${quoted.slice(0, -1).join(", ")} and ${quoted[quoted.length - 1]}`
|
|
119
|
+
: quoted[0];
|
|
120
|
+
}
|
|
121
|
+
function describe(err) {
|
|
122
|
+
return err instanceof Error ? err.message : String(err);
|
|
123
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { hostname } from "node:os";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { link } from "./link.js";
|
|
6
|
+
const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
|
|
7
|
+
const USAGE = `Usage: npx @nestjs/observe link [--no-browser] [--cwd <dir>]
|
|
8
|
+
|
|
9
|
+
link Link this project to NestJS Observe: approve a code in the
|
|
10
|
+
dashboard, and the API key pair is written into .env.
|
|
11
|
+
|
|
12
|
+
Options:
|
|
13
|
+
--no-browser Print the link page instead of opening it.
|
|
14
|
+
--cwd <dir> The project directory (default: the current one).`;
|
|
15
|
+
/**
|
|
16
|
+
* Opens the link page in the default browser, best effort: a headless box or
|
|
17
|
+
* a missing opener just means the person opens the printed URL themselves.
|
|
18
|
+
*/
|
|
19
|
+
function openUrl(url) {
|
|
20
|
+
const [command, args] = process.platform === "darwin"
|
|
21
|
+
? ["open", [url]]
|
|
22
|
+
: process.platform === "win32"
|
|
23
|
+
? ["cmd", ["/c", "start", "", url]]
|
|
24
|
+
: ["xdg-open", [url]];
|
|
25
|
+
try {
|
|
26
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
|
27
|
+
child.on("error", () => undefined);
|
|
28
|
+
child.unref();
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// Printed above; nothing else to do.
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function main(argv) {
|
|
35
|
+
const [command, ...rest] = argv;
|
|
36
|
+
if (command !== "link") {
|
|
37
|
+
console.log(USAGE);
|
|
38
|
+
return command === undefined || command === "--help" || command === "-h"
|
|
39
|
+
? 0
|
|
40
|
+
: 1;
|
|
41
|
+
}
|
|
42
|
+
const cwdIndex = rest.indexOf("--cwd");
|
|
43
|
+
const cwd = resolve(cwdIndex >= 0 ? rest[cwdIndex + 1] ?? "." : ".");
|
|
44
|
+
const interactive = process.stdout.isTTY && !process.env.CI;
|
|
45
|
+
return link({
|
|
46
|
+
cwd,
|
|
47
|
+
endpoint: (process.env.OBSERVE_ENDPOINT ?? HOSTED_COLLECTOR_ENDPOINT).replace(/\/+$/, ""),
|
|
48
|
+
openBrowser: interactive && !rest.includes("--no-browser"),
|
|
49
|
+
}, {
|
|
50
|
+
fetch,
|
|
51
|
+
sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
|
|
52
|
+
openUrl,
|
|
53
|
+
log: (line) => console.log(line),
|
|
54
|
+
hostname,
|
|
55
|
+
now: Date.now,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
59
|
+
console.error(err);
|
|
60
|
+
process.exit(1);
|
|
61
|
+
});
|
|
@@ -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
|
+
}
|
package/dist/observe.module.js
CHANGED
|
@@ -64,6 +64,34 @@ function withServiceId(options) {
|
|
|
64
64
|
new Logger("ObserveModule").warn(`serviceId "${named}" is sent as "${sent}": the collector takes at most ${MAX_SERVICE_ID_LENGTH} characters.`);
|
|
65
65
|
return { ...options, serviceId: sent };
|
|
66
66
|
}
|
|
67
|
+
/** The credentials `nest new` writes before an account exists. */
|
|
68
|
+
const SCAFFOLD_CREDENTIALS = {
|
|
69
|
+
appKey: "YOUR_APP_KEY",
|
|
70
|
+
appSecret: "YOUR_APP_SECRET",
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* `appKey` and `appSecret` from `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET`
|
|
74
|
+
* when the options leave them out - or still hold the `nest new`
|
|
75
|
+
* placeholders, which is what a project linked with
|
|
76
|
+
* `npx @nestjs/observe link` keeps in its AppModule while the real pair sits
|
|
77
|
+
* in its `.env`. A value the application passes explicitly always wins.
|
|
78
|
+
*
|
|
79
|
+
* Read when the options resolve, which for `forRoot()` is when AppModule is
|
|
80
|
+
* imported: early enough for `node --env-file` and `nest start --env-file`,
|
|
81
|
+
* which load the file before any module runs.
|
|
82
|
+
*/
|
|
83
|
+
function credentialFromEnv(value, placeholder, variable) {
|
|
84
|
+
return (!value || value === placeholder) && process.env[variable]
|
|
85
|
+
? process.env[variable]
|
|
86
|
+
: value;
|
|
87
|
+
}
|
|
88
|
+
function withCredentialsFromEnv(options) {
|
|
89
|
+
return {
|
|
90
|
+
...options,
|
|
91
|
+
appKey: credentialFromEnv(options.appKey, SCAFFOLD_CREDENTIALS.appKey, "OBSERVE_APP_KEY"),
|
|
92
|
+
appSecret: credentialFromEnv(options.appSecret, SCAFFOLD_CREDENTIALS.appSecret, "OBSERVE_APP_SECRET"),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
67
95
|
/**
|
|
68
96
|
* Names the release when the application did not, so Releases, regressions
|
|
69
97
|
* and fix verification work without anyone threading a version through the
|
|
@@ -116,10 +144,10 @@ export function createObserveModule(options = {}) {
|
|
|
116
144
|
providers: [
|
|
117
145
|
{
|
|
118
146
|
provide: OBSERVE_OPTIONS,
|
|
119
|
-
useValue: withServiceVersion(withServiceId({
|
|
147
|
+
useValue: withServiceVersion(withServiceId(withCredentialsFromEnv({
|
|
120
148
|
...options,
|
|
121
149
|
...observeOpts,
|
|
122
|
-
})),
|
|
150
|
+
}))),
|
|
123
151
|
},
|
|
124
152
|
],
|
|
125
153
|
};
|
|
@@ -158,10 +186,10 @@ export function createObserveModule(options = {}) {
|
|
|
158
186
|
provide: OBSERVE_OPTIONS,
|
|
159
187
|
useFactory: async (...args) => {
|
|
160
188
|
const opts = await useFactory(...args);
|
|
161
|
-
return withServiceVersion(withServiceId({
|
|
189
|
+
return withServiceVersion(withServiceId(withCredentialsFromEnv({
|
|
162
190
|
...options,
|
|
163
191
|
...opts,
|
|
164
|
-
}));
|
|
192
|
+
})));
|
|
165
193
|
},
|
|
166
194
|
inject: asyncOptions.inject || [],
|
|
167
195
|
};
|
|
@@ -172,10 +200,10 @@ export function createObserveModule(options = {}) {
|
|
|
172
200
|
}
|
|
173
201
|
return {
|
|
174
202
|
provide: OBSERVE_OPTIONS,
|
|
175
|
-
useFactory: async (optionsFactory) => withServiceVersion(withServiceId({
|
|
203
|
+
useFactory: async (optionsFactory) => withServiceVersion(withServiceId(withCredentialsFromEnv({
|
|
176
204
|
...options,
|
|
177
205
|
...(await optionsFactory.createObserveOptions()),
|
|
178
|
-
})),
|
|
206
|
+
}))),
|
|
179
207
|
inject: [optionsFactoryToken],
|
|
180
208
|
};
|
|
181
209
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nestjs/observe",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.15",
|
|
4
4
|
"description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
|
|
5
5
|
"author": "Kamil Mysliwiec",
|
|
6
6
|
"homepage": "https://observe.nestjs.com",
|
|
@@ -30,6 +30,9 @@
|
|
|
30
30
|
],
|
|
31
31
|
"main": "./dist/index.js",
|
|
32
32
|
"types": "./dist/index.d.ts",
|
|
33
|
+
"bin": {
|
|
34
|
+
"observe": "./dist/cli/observe-cli.js"
|
|
35
|
+
},
|
|
33
36
|
"exports": {
|
|
34
37
|
".": {
|
|
35
38
|
"types": "./dist/index.d.ts",
|