@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.
@@ -0,0 +1,43 @@
1
+ import type * as TS from "typescript";
2
+ export type TypeScript = typeof TS;
3
+ export declare const SDK_PACKAGE = "@nestjs/observe";
4
+ /** Where the setup by hand is written down, for whatever link cannot do. */
5
+ export declare const QUICK_START_URL = "https://observe.nestjs.com/documentation/sdk#quick-start";
6
+ /** What link has to do to the project, besides writing the key pair. */
7
+ export interface ProjectSetup {
8
+ /**
9
+ * `@nestjs/observe` is not a dependency yet - or the app still has to be
10
+ * wired and the installed SDK is older than this one, whose types the
11
+ * wiring is written against.
12
+ */
13
+ install: boolean;
14
+ /** No source file uses `@nestjs/observe` yet. */
15
+ wire: boolean;
16
+ /** Why the project cannot take the SDK, when it cannot. */
17
+ unsupported?: string;
18
+ }
19
+ /**
20
+ * Looks at the project before anything is asked of the API, so a project the
21
+ * SDK cannot run in is turned away before a key is issued for it, and the
22
+ * person approving knows what else the command is about to change.
23
+ */
24
+ export declare function inspectProject(cwd: string, version: string, ts: TypeScript | undefined): ProjectSetup;
25
+ /**
26
+ * The project's own TypeScript, which the code is edited with - parsed by the
27
+ * compiler that will build it, so whatever syntax the project uses, it reads.
28
+ * Undefined without one; the CLI does not bring a compiler of its own.
29
+ */
30
+ export declare function loadTypeScript(cwd: string): TypeScript | undefined;
31
+ /**
32
+ * The entry files of the project's applications, relative to it: the root
33
+ * application's, and every application project's in a monorepo. A monorepo's
34
+ * root usually names one of its own projects, so duplicates collapse.
35
+ */
36
+ export declare function findEntryFiles(cwd: string, ts: TypeScript | undefined): string[];
37
+ /**
38
+ * The application's name the way the dashboard turns it into a `serviceId`
39
+ * for the setup it shows, so the two agree: lower-case, dashes for spaces,
40
+ * nothing else but letters and digits. The package name stands in when the
41
+ * application's name leaves nothing.
42
+ */
43
+ export declare function serviceIdFor(...names: Array<string | undefined>): string;
@@ -0,0 +1,249 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, posix } from "node:path";
4
+ export const SDK_PACKAGE = "@nestjs/observe";
5
+ /** The oldest NestJS major the SDK's peer range takes. */
6
+ const MIN_NEST_MAJOR = 11;
7
+ /** Where the setup by hand is written down, for whatever link cannot do. */
8
+ export const QUICK_START_URL = "https://observe.nestjs.com/documentation/sdk#quick-start";
9
+ /** Directories never searched for the SDK's imports. */
10
+ const SKIPPED_DIRECTORIES = new Set([
11
+ "node_modules",
12
+ "dist",
13
+ "build",
14
+ "coverage",
15
+ ".git",
16
+ ]);
17
+ /** Enough to cover any real source tree, and a bound on a pathological one. */
18
+ const MAX_SCANNED_FILES = 20_000;
19
+ /**
20
+ * Looks at the project before anything is asked of the API, so a project the
21
+ * SDK cannot run in is turned away before a key is issued for it, and the
22
+ * person approving knows what else the command is about to change.
23
+ */
24
+ export function inspectProject(cwd, version, ts) {
25
+ const pkg = readPackageJson(cwd);
26
+ const declared = declaredRange(pkg, SDK_PACKAGE);
27
+ const wire = !usesSdk(cwd, readNestCliConfig(cwd, ts));
28
+ const installed = installedVersion(cwd, SDK_PACKAGE);
29
+ const install = declared === undefined ||
30
+ (wire && (installed === undefined || isOlder(installed, version)));
31
+ if (!install) {
32
+ return { install, wire };
33
+ }
34
+ const nest = installedVersion(cwd, "@nestjs/core") ?? declaredRange(pkg, "@nestjs/core");
35
+ if (nest === undefined) {
36
+ return {
37
+ install,
38
+ wire,
39
+ unsupported: "This does not look like a NestJS project: package.json has no @nestjs/core",
40
+ };
41
+ }
42
+ const major = Number(/\d+/.exec(nest)?.[0]);
43
+ if (major < MIN_NEST_MAJOR) {
44
+ return {
45
+ install,
46
+ wire,
47
+ unsupported: `NestJS Observe needs NestJS ${MIN_NEST_MAJOR} or later, and this project has @nestjs/core ${nest}. Upgrade NestJS first`,
48
+ };
49
+ }
50
+ return { install, wire };
51
+ }
52
+ /**
53
+ * The project's own TypeScript, which the code is edited with - parsed by the
54
+ * compiler that will build it, so whatever syntax the project uses, it reads.
55
+ * Undefined without one; the CLI does not bring a compiler of its own.
56
+ */
57
+ export function loadTypeScript(cwd) {
58
+ try {
59
+ const ts = createRequire(join(cwd, "package.json"))("typescript");
60
+ return typeof ts.createSourceFile === "function" ? ts : undefined;
61
+ }
62
+ catch {
63
+ return undefined;
64
+ }
65
+ }
66
+ /**
67
+ * `nest-cli.json`, the file the Nest CLI loads. It may carry comments, which
68
+ * only the project's TypeScript can read past; without it such a file counts
69
+ * as absent, and the defaults - `src/main.ts` - apply.
70
+ */
71
+ function readNestCliConfig(cwd, ts) {
72
+ for (const name of ["nest-cli.json", ".nest-cli.json"]) {
73
+ const path = join(cwd, name);
74
+ if (!existsSync(path)) {
75
+ continue;
76
+ }
77
+ const text = readFileSync(path, "utf8");
78
+ try {
79
+ return JSON.parse(text);
80
+ }
81
+ catch {
82
+ const parsed = ts?.parseConfigFileTextToJson(path, text);
83
+ return parsed?.config ?? {};
84
+ }
85
+ }
86
+ return {};
87
+ }
88
+ /**
89
+ * The entry files of the project's applications, relative to it: the root
90
+ * application's, and every application project's in a monorepo. A monorepo's
91
+ * root usually names one of its own projects, so duplicates collapse.
92
+ */
93
+ export function findEntryFiles(cwd, ts) {
94
+ const config = readNestCliConfig(cwd, ts);
95
+ const found = new Set();
96
+ const add = (sourceRoot, entryFile) => {
97
+ if (!sourceRoot) {
98
+ return;
99
+ }
100
+ const path = posix.normalize(`${sourceRoot.replace(/\\/g, "/")}/${entryFile ?? "main"}.ts`);
101
+ if (existsSync(join(cwd, path))) {
102
+ found.add(path);
103
+ }
104
+ };
105
+ for (const project of Object.values(config.projects ?? {})) {
106
+ if (project?.type === "library") {
107
+ continue;
108
+ }
109
+ add(project?.sourceRoot ??
110
+ (project?.root ? `${project.root}/src` : undefined), project?.entryFile);
111
+ }
112
+ add(config.sourceRoot ?? "src", config.entryFile);
113
+ return [...found];
114
+ }
115
+ /**
116
+ * Whether any source file already imports the SDK: a `nest new` project
117
+ * generated with Observe, or one wired by hand. Either way the code is left
118
+ * alone.
119
+ */
120
+ function usesSdk(cwd, config) {
121
+ const roots = new Set([config.sourceRoot ?? "src", "apps", "libs"]);
122
+ for (const project of Object.values(config.projects ?? {})) {
123
+ const root = project?.sourceRoot ?? project?.root;
124
+ if (root) {
125
+ roots.add(root);
126
+ }
127
+ }
128
+ let budget = MAX_SCANNED_FILES;
129
+ const search = (dir) => {
130
+ let entries;
131
+ try {
132
+ entries = readdirSync(dir, { withFileTypes: true });
133
+ }
134
+ catch {
135
+ return false;
136
+ }
137
+ for (const entry of entries) {
138
+ if (budget <= 0) {
139
+ return false;
140
+ }
141
+ const path = join(dir, entry.name);
142
+ if (entry.isDirectory()) {
143
+ if (!SKIPPED_DIRECTORIES.has(entry.name) && search(path)) {
144
+ return true;
145
+ }
146
+ }
147
+ else if (/\.[cm]?[jt]s$/.test(entry.name)) {
148
+ budget -= 1;
149
+ if (readFileSync(path, "utf8").includes(SDK_PACKAGE)) {
150
+ return true;
151
+ }
152
+ }
153
+ }
154
+ return false;
155
+ };
156
+ return [...roots].some((root) => search(join(cwd, root)));
157
+ }
158
+ function readPackageJson(cwd) {
159
+ try {
160
+ return JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
161
+ }
162
+ catch {
163
+ return {};
164
+ }
165
+ }
166
+ /** The range package.json asks for `name` in, from any dependency section. */
167
+ function declaredRange(pkg, name) {
168
+ for (const section of [
169
+ "dependencies",
170
+ "devDependencies",
171
+ "peerDependencies",
172
+ ]) {
173
+ const range = pkg[section]?.[name];
174
+ if (typeof range === "string") {
175
+ return range;
176
+ }
177
+ }
178
+ return undefined;
179
+ }
180
+ /**
181
+ * The version of `name` the project resolves, hoisted or not. Read off the
182
+ * package's own package.json, found from its entry point when the package
183
+ * does not export that file.
184
+ */
185
+ function installedVersion(cwd, name) {
186
+ const require = createRequire(join(cwd, "package.json"));
187
+ const readVersion = (path) => {
188
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
189
+ return pkg.name === name ? pkg.version : undefined;
190
+ };
191
+ try {
192
+ return readVersion(require.resolve(`${name}/package.json`));
193
+ }
194
+ catch {
195
+ // Not exported, or not installed: try the entry point.
196
+ }
197
+ try {
198
+ for (let dir = dirname(require.resolve(name));; dir = dirname(dir)) {
199
+ const path = join(dir, "package.json");
200
+ if (existsSync(path)) {
201
+ const version = readVersion(path);
202
+ if (version) {
203
+ return version;
204
+ }
205
+ }
206
+ if (dirname(dir) === dir) {
207
+ return undefined;
208
+ }
209
+ }
210
+ }
211
+ catch {
212
+ return undefined;
213
+ }
214
+ }
215
+ /** `"0.3.16"`, or `"0.3.16-beta.1"`, as `[0, 3, 16]`. */
216
+ function releaseOf(version) {
217
+ return (/(\d+)\.(\d+)\.(\d+)/.exec(version) ?? []).slice(1, 4).map(Number);
218
+ }
219
+ /** Whether `a` is an older release than `b`, by major, minor and patch. */
220
+ function isOlder(a, b) {
221
+ const [x, y] = [releaseOf(a), releaseOf(b)];
222
+ for (let i = 0; i < 3; i++) {
223
+ if ((x[i] ?? 0) !== (y[i] ?? 0)) {
224
+ return (x[i] ?? 0) < (y[i] ?? 0);
225
+ }
226
+ }
227
+ return false;
228
+ }
229
+ /**
230
+ * The application's name the way the dashboard turns it into a `serviceId`
231
+ * for the setup it shows, so the two agree: lower-case, dashes for spaces,
232
+ * nothing else but letters and digits. The package name stands in when the
233
+ * application's name leaves nothing.
234
+ */
235
+ export function serviceIdFor(...names) {
236
+ for (const name of names) {
237
+ const id = (name ?? "")
238
+ .replace(/^@[^/]+\//, "")
239
+ .toLowerCase()
240
+ .trim()
241
+ .replace(/\s+/g, "-")
242
+ .replace(/-{2,}/g, "-")
243
+ .replace(/[^a-z0-9-]/g, "");
244
+ if (id) {
245
+ return id;
246
+ }
247
+ }
248
+ return "app";
249
+ }
@@ -0,0 +1,29 @@
1
+ import { TypeScript } from "./project-setup.js";
2
+ /** One file the wiring changed, and what it changed there. */
3
+ export interface WiredFile {
4
+ /** Relative to the project, with forward slashes. */
5
+ path: string;
6
+ change: string;
7
+ }
8
+ export type WireResult = {
9
+ kind: "wired";
10
+ files: WiredFile[];
11
+ } | {
12
+ kind: "manual";
13
+ reason: string;
14
+ };
15
+ /**
16
+ * Wires `@nestjs/observe` into one application the way `nest new` generates
17
+ * it: `createObserveModule()` and `ObserveModule.forRoot()` in the root
18
+ * module, `ObserveInstrument` passed to `NestFactory.create()`.
19
+ *
20
+ * The root module is the one `main.ts` hands to `NestFactory.create()`, found
21
+ * by following its import - not assumed to be `app.module.ts`. The key pair is
22
+ * read from `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET`, which link has just
23
+ * written into `.env`.
24
+ *
25
+ * Both files change or neither does: every edit is worked out first, and
26
+ * each edited file has to parse before anything is written. Whatever cannot
27
+ * be done safely comes back as a reason, for the person to finish by hand.
28
+ */
29
+ export declare function wireApplication(ts: TypeScript, cwd: string, mainPath: string, serviceId: string): WireResult;