@watchtowerobservability/node 0.7.7 → 0.7.9
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/CHANGELOG.md +10 -0
- package/README.md +1 -1
- package/dist/cjs/env.d.ts +7 -0
- package/dist/cjs/env.js +21 -0
- package/dist/cjs/index.js +1 -0
- package/dist/cjs/instrument.js +9 -2
- package/dist/cjs/integrations/next-build.d.ts +9 -2
- package/dist/cjs/integrations/next-build.js +46 -4
- package/dist/cjs/load.d.ts +1 -1
- package/dist/cjs/load.js +2 -2
- package/dist/cjs/next-doctor-cli.js +11 -3
- package/dist/cjs/next-doctor.d.ts +9 -1
- package/dist/cjs/next-doctor.js +43 -3
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/env.d.ts +7 -0
- package/dist/esm/env.js +19 -0
- package/dist/esm/index.js +2 -1
- package/dist/esm/instrument.js +9 -2
- package/dist/esm/integrations/next-build.d.ts +9 -2
- package/dist/esm/integrations/next-build.js +45 -4
- package/dist/esm/load.d.ts +1 -1
- package/dist/esm/load.js +2 -2
- package/dist/esm/next-doctor-cli.js +12 -4
- package/dist/esm/next-doctor.d.ts +9 -1
- package/dist/esm/next-doctor.js +41 -3
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.9 (2026-11-16)
|
|
4
|
+
|
|
5
|
+
- Fix (Next.js standalone, pnpm and monorepos; B22, WT-13): `withWatchtower` listed `node_modules/@opentelemetry/**` globs in `outputFileTracingIncludes`. Under pnpm those copied each peer as a plain folder without its own dependencies, or matched nothing when the `.pnpm` store sits at the workspace root, so `init` failed with `missing @opentelemetry/resources`. It now walks the SDK's dependency closure from the app at config time and lists each package's real store folder plus the pnpm links to it, which Next recreates as links. Verified with a pnpm workspace (`apps/web`, `outputFileTracingRoot` at the root, `output: 'standalone'`, peers as direct deps of the app, no peer imports in `instrumentation`): `server.js` starts with no missing-package warning and `wt-next-doctor` exits 0. Your own `outputFileTracingIncludes` are kept. New export: `tracingIncludes(ids, cwd)`.
|
|
6
|
+
- `wt-next-doctor` also looks in the app's own `node_modules` (`.next/standalone/<app path>/node_modules`), then loads the SDK (as ESM, the way Next does) and each peer from the standalone `server.js`, and exits 1 naming any that fail, not only the ones whose folder is missing.
|
|
7
|
+
|
|
8
|
+
## 0.7.8 (2026-11-16)
|
|
9
|
+
|
|
10
|
+
- Fix: on a non-cloud VM the OpenTelemetry resource detectors probed `169.254.169.254` and the 10 s timeout surfaced as a `UND_ERR_CONNECT_TIMEOUT` issue. When `OTEL_NODE_RESOURCE_DETECTORS` is unset, `init()` now sets it to `env,host,os,process`, adding `aws`, `gcp` or `azure` only when an environment variable shows that cloud (for example `AWS_REGION`, `K_SERVICE`, `WEBSITE_SITE_NAME`). Set `OTEL_NODE_RESOURCE_DETECTORS` yourself to override. Call `init()` (or use the `register` preload) before your own `NodeSDK` starts.
|
|
11
|
+
- The http and undici instrumentations ignore requests to cloud metadata endpoints (`169.254.169.254`, `169.254.170.2`, `metadata.google.internal`, `metadata.azure.internal`), so a failed probe is never reported as an error.
|
|
12
|
+
|
|
3
13
|
## 0.7.7 (2026-11-16)
|
|
4
14
|
|
|
5
15
|
- Quieter traces by default: `pg-pool.connect`, bare `BEGIN` / `COMMIT` / `ROLLBACK` statement spans and Express middleware layer spans (`middleware - *`, `expressInit`, `query`) are dropped before export; errored spans are always kept. `noisySpans: true` (or `WT_NOISY_SPANS=1`) keeps them. Your own `spanFilter` still runs on what is left.
|
package/README.md
CHANGED
|
@@ -118,7 +118,7 @@ to close, so a very slow export can still be cut.
|
|
|
118
118
|
|
|
119
119
|
Install the OpenTelemetry peers above in the app itself (with pnpm, as direct dependencies). The SDK loads peers at run time through `createRequire`, which webpack does not follow, so a build prints no "Module not found" warning for peers you did not install. Next's standalone file tracer does not follow them either.
|
|
120
120
|
|
|
121
|
-
Standalone recipe: wrap the config, `module.exports = withWatchtower(nextConfig)` (from `@watchtowerobservability/node/next-build`, or `@watchtowerobservability/next`). It adds the SDK and its OpenTelemetry peers to `serverExternalPackages
|
|
121
|
+
Standalone recipe: wrap the config, `module.exports = withWatchtower(nextConfig)` (from `@watchtowerobservability/node/next-build`, or `@watchtowerobservability/next`). It adds the SDK and its OpenTelemetry peers to `serverExternalPackages`, and to `outputFileTracingIncludes` each of them with its dependencies and pnpm links, resolved from the app (npm, pnpm, monorepos with `outputFileTracingRoot` at the workspace root). By hand, add the same packages to `serverExternalPackages` and import each peer literally in `instrumentation.ts`; plain `node_modules/@opentelemetry/**` include globs do not work under pnpm, since they copy each peer without its dependencies. If a peer is missing at run time, `init` logs one warning naming it; after `next build`, `npx wt-next-doctor` checks that `.next/standalone` holds the SDK and its peers and that each one loads from `server.js`, and exits 1 otherwise.
|
|
122
122
|
|
|
123
123
|
Bundling with esbuild or webpack (ESM or CommonJS output) works without warnings; mark the peers you use as externals (or ship `node_modules`), because they are resolved at run time. Declarations name optional peers behind `// @ts-ignore`, so `skipLibCheck: false` builds compile without them installed.
|
|
124
124
|
|
package/dist/cjs/env.d.ts
CHANGED
|
@@ -20,3 +20,10 @@ export declare function gitHeadSha(from: string): string | undefined;
|
|
|
20
20
|
* (`WT_BUILD_STAMP`, `BUILD_STAMP`), then the `.git` HEAD found upward from `gitFrom` (skipped when not given). Empty and `unknown` count as absent.
|
|
21
21
|
*/
|
|
22
22
|
export declare function resolveRelease(opt: string | undefined, env: NodeJS.ProcessEnv, otelResource: Record<string, string>, gitFrom?: string): string | undefined;
|
|
23
|
+
/** Cloud metadata endpoints; probing them from a non-cloud host times out, so they never become spans or issues. */
|
|
24
|
+
export declare const METADATA_HOSTS: Set<string>;
|
|
25
|
+
/**
|
|
26
|
+
* When OTEL_NODE_RESOURCE_DETECTORS is unset, limit the OTel Node resource detectors to local ones; a cloud detector is added only
|
|
27
|
+
* when an env var shows that cloud. Otherwise the detectors probe 169.254.169.254 and a non-cloud VM waits out a 10 s connect timeout.
|
|
28
|
+
*/
|
|
29
|
+
export declare function defaultResourceDetectors(env?: NodeJS.ProcessEnv): void;
|
package/dist/cjs/env.js
CHANGED
|
@@ -33,10 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.METADATA_HOSTS = void 0;
|
|
36
37
|
exports.parseKv = parseKv;
|
|
37
38
|
exports.otelEnv = otelEnv;
|
|
38
39
|
exports.gitHeadSha = gitHeadSha;
|
|
39
40
|
exports.resolveRelease = resolveRelease;
|
|
41
|
+
exports.defaultResourceDetectors = defaultResourceDetectors;
|
|
40
42
|
const fs = __importStar(require("node:fs"));
|
|
41
43
|
const nodePath = __importStar(require("node:path"));
|
|
42
44
|
// Standard OTEL_* environment variables, used as fallbacks after the WT_* ones.
|
|
@@ -132,3 +134,22 @@ function resolveRelease(opt, env, otelResource, gitFrom) {
|
|
|
132
134
|
}
|
|
133
135
|
return gitFrom ? gitHeadSha(gitFrom) : undefined;
|
|
134
136
|
}
|
|
137
|
+
/** Cloud metadata endpoints; probing them from a non-cloud host times out, so they never become spans or issues. */
|
|
138
|
+
exports.METADATA_HOSTS = new Set(['169.254.169.254', 'metadata.google.internal', '169.254.170.2', 'metadata.azure.internal']);
|
|
139
|
+
/**
|
|
140
|
+
* When OTEL_NODE_RESOURCE_DETECTORS is unset, limit the OTel Node resource detectors to local ones; a cloud detector is added only
|
|
141
|
+
* when an env var shows that cloud. Otherwise the detectors probe 169.254.169.254 and a non-cloud VM waits out a 10 s connect timeout.
|
|
142
|
+
*/
|
|
143
|
+
function defaultResourceDetectors(env = process.env) {
|
|
144
|
+
if (env.OTEL_NODE_RESOURCE_DETECTORS)
|
|
145
|
+
return;
|
|
146
|
+
const on = (...k) => k.some((x) => !!env[x]);
|
|
147
|
+
const d = ['env', 'host', 'os', 'process'];
|
|
148
|
+
if (on('AWS_REGION', 'AWS_DEFAULT_REGION', 'AWS_EXECUTION_ENV', 'ECS_CONTAINER_METADATA_URI'))
|
|
149
|
+
d.push('aws');
|
|
150
|
+
if (on('GOOGLE_CLOUD_PROJECT', 'GCP_PROJECT', 'K_SERVICE', 'GAE_SERVICE'))
|
|
151
|
+
d.push('gcp');
|
|
152
|
+
if (on('WEBSITE_SITE_NAME', 'AZURE_FUNCTIONS_ENVIRONMENT', 'AZURE_CLIENT_ID', 'AZURE_TENANT_ID'))
|
|
153
|
+
d.push('azure');
|
|
154
|
+
env.OTEL_NODE_RESOURCE_DETECTORS = d.join(',');
|
|
155
|
+
}
|
package/dist/cjs/index.js
CHANGED
|
@@ -405,6 +405,7 @@ function registerGlobals(c) {
|
|
|
405
405
|
}
|
|
406
406
|
}
|
|
407
407
|
function init(opts) {
|
|
408
|
+
(0, env_js_1.defaultResourceDetectors)(); // before any NodeSDK reads OTEL_NODE_RESOURCE_DETECTORS
|
|
408
409
|
const missing = (0, load_js_1.missingPeers)();
|
|
409
410
|
if (missing.length)
|
|
410
411
|
console.warn(`[watchtower] missing OpenTelemetry package(s): ${missing.join(', ')}. Next.js standalone: ${load_js_1.STANDALONE_HINT}. Otherwise: npm install ${missing.join(' ')}`);
|
package/dist/cjs/instrument.js
CHANGED
|
@@ -7,19 +7,26 @@ exports.instrumentAll = instrumentAll;
|
|
|
7
7
|
const load_js_1 = require("./load.js");
|
|
8
8
|
const sqlite_js_1 = require("./integrations/sqlite.js");
|
|
9
9
|
const postgres_js_1 = require("./integrations/postgres.js");
|
|
10
|
+
const env_js_1 = require("./env.js");
|
|
10
11
|
const util_js_1 = require("./integrations/util.js");
|
|
11
12
|
/** Instrumentation packages already registered in this process (by `init` or `instrument()`), so none is patched twice. */
|
|
12
13
|
exports.registered = new Set();
|
|
14
|
+
const hostOf = (o) => { try {
|
|
15
|
+
return new URL(o ?? '').hostname;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return '';
|
|
19
|
+
} };
|
|
13
20
|
const ENTRIES = [
|
|
14
21
|
{
|
|
15
22
|
pkg: '@opentelemetry/instrumentation-http', ctor: 'HttpInstrumentation',
|
|
16
23
|
// our own exports and API calls must not become spans
|
|
17
24
|
// routeNamer: server spans become `GET /users/:id` from the matched Express / Nest route (http alone names them just `GET`)
|
|
18
|
-
opts: (self) => ({ applyCustomAttributesOnSpan: util_js_1.routeNamer, ignoreOutgoingRequestHook: (r) => self.some((u) => (r.hostname || r.host) === u.hostname && String(r.port ?? (u.protocol === 'https:' ? 443 : 80)) === String(u.port || (u.protocol === 'https:' ? 443 : 80))) }),
|
|
25
|
+
opts: (self) => ({ applyCustomAttributesOnSpan: util_js_1.routeNamer, ignoreOutgoingRequestHook: (r) => env_js_1.METADATA_HOSTS.has(String(r.hostname || r.host).replace(/:\d+$/, '')) || self.some((u) => (r.hostname || r.host) === u.hostname && String(r.port ?? (u.protocol === 'https:' ? 443 : 80)) === String(u.port || (u.protocol === 'https:' ? 443 : 80))) }),
|
|
19
26
|
},
|
|
20
27
|
{
|
|
21
28
|
pkg: '@opentelemetry/instrumentation-undici', ctor: 'UndiciInstrumentation',
|
|
22
|
-
opts: (self) => ({ ignoreRequestHook: (r) => self.some((u) => r.origin === u.origin) }),
|
|
29
|
+
opts: (self) => ({ ignoreRequestHook: (r) => env_js_1.METADATA_HOSTS.has(hostOf(r.origin)) || self.some((u) => r.origin === u.origin) }),
|
|
23
30
|
},
|
|
24
31
|
{ pkg: '@opentelemetry/instrumentation-pg', ctor: 'PgInstrumentation', opts: () => ({}) },
|
|
25
32
|
{ pkg: '@opentelemetry/instrumentation-ioredis', ctor: 'IORedisInstrumentation', opts: () => ({}) },
|
|
@@ -38,10 +38,17 @@ export interface WatchtowerNextOptions {
|
|
|
38
38
|
export declare function hasSentry(cwd?: string): boolean;
|
|
39
39
|
/** The `serverExternalPackages` withWatchtower adds; `sentry` drops the packages a bundled Sentry shares. */
|
|
40
40
|
export declare function externalPackages(sentry: boolean): string[];
|
|
41
|
+
/**
|
|
42
|
+
* `outputFileTracingIncludes` globs for `ids` and everything they depend on, relative to `cwd`: each package's real
|
|
43
|
+
* folder plus every pnpm symlink on the way to it, which Next recreates as links (what its tracer emits for a static
|
|
44
|
+
* import). A plain `node_modules/<pkg>/**` glob copies a pnpm link as a folder cut off from its dependencies (B22).
|
|
45
|
+
*/
|
|
46
|
+
export declare function tracingIncludes(ids: string[], cwd?: string): string[];
|
|
41
47
|
/**
|
|
42
48
|
* `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`. Makes `output: 'standalone'` work with no other
|
|
43
|
-
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages
|
|
44
|
-
*
|
|
49
|
+
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages`, and `outputFileTracingIncludes`
|
|
50
|
+
* for every route lists each one with its dependencies and pnpm links (npm, pnpm, monorepos; see tracingIncludes), so
|
|
51
|
+
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
45
52
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
46
53
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
47
54
|
*/
|
|
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.hasSentry = hasSentry;
|
|
37
37
|
exports.externalPackages = externalPackages;
|
|
38
|
+
exports.tracingIncludes = tracingIncludes;
|
|
38
39
|
exports.withWatchtower = withWatchtower;
|
|
39
40
|
exports.makeTar = makeTar;
|
|
40
41
|
exports.uploadSourcemaps = uploadSourcemaps;
|
|
@@ -73,12 +74,53 @@ function hasSentry(cwd = process.cwd()) {
|
|
|
73
74
|
function externalPackages(sentry) {
|
|
74
75
|
return sentry ? EXTERNAL.filter((n) => !SHARED_WITH_SENTRY.has(n)) : EXTERNAL;
|
|
75
76
|
}
|
|
77
|
+
/** Where Node finds package `id` from `from`: the lookup path (may be a pnpm symlink) and its real folder. */
|
|
78
|
+
function locate(id, from) {
|
|
79
|
+
for (let d = from;; d = nodePath.dirname(d)) {
|
|
80
|
+
const link = nodePath.join(d, 'node_modules', id);
|
|
81
|
+
if (fs.existsSync(nodePath.join(link, 'package.json')))
|
|
82
|
+
return { link, real: fs.realpathSync(link) };
|
|
83
|
+
if (nodePath.dirname(d) === d)
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* `outputFileTracingIncludes` globs for `ids` and everything they depend on, relative to `cwd`: each package's real
|
|
89
|
+
* folder plus every pnpm symlink on the way to it, which Next recreates as links (what its tracer emits for a static
|
|
90
|
+
* import). A plain `node_modules/<pkg>/**` glob copies a pnpm link as a folder cut off from its dependencies (B22).
|
|
91
|
+
*/
|
|
92
|
+
function tracingIncludes(ids, cwd = process.cwd()) {
|
|
93
|
+
const out = new Set(), seen = new Set();
|
|
94
|
+
const rel = (p) => nodePath.relative(cwd, p).split(nodePath.sep).join('/').replace(/[()[\]{}*?!]/g, '\\$&');
|
|
95
|
+
const visit = (id, from) => {
|
|
96
|
+
const hit = locate(id, from);
|
|
97
|
+
if (!hit)
|
|
98
|
+
return; // an optional peer that is not installed
|
|
99
|
+
if (fs.lstatSync(hit.link).isSymbolicLink())
|
|
100
|
+
out.add(rel(hit.link));
|
|
101
|
+
if (seen.has(hit.real))
|
|
102
|
+
return;
|
|
103
|
+
seen.add(hit.real);
|
|
104
|
+
out.add(`${rel(hit.real)}/**/*`);
|
|
105
|
+
try {
|
|
106
|
+
const pkg = JSON.parse(fs.readFileSync(nodePath.join(hit.real, 'package.json'), 'utf8'));
|
|
107
|
+
// peers: only OpenTelemetry ones (the SDK's peers are in `ids` already; following `next` would copy all of it)
|
|
108
|
+
const peers = Object.keys(pkg.peerDependencies ?? {}).filter((n) => n.startsWith('@opentelemetry/'));
|
|
109
|
+
for (const dep of [...Object.keys({ ...pkg.dependencies, ...pkg.optionalDependencies }), ...peers])
|
|
110
|
+
visit(dep, hit.real);
|
|
111
|
+
}
|
|
112
|
+
catch { /* unreadable package.json: its own files are still included */ }
|
|
113
|
+
};
|
|
114
|
+
for (const id of ids)
|
|
115
|
+
visit(id, cwd);
|
|
116
|
+
return [...out];
|
|
117
|
+
}
|
|
76
118
|
const SHA_ENV = ['WT_RELEASE', 'GITHUB_SHA', 'CI_COMMIT_SHA', 'VERCEL_GIT_COMMIT_SHA', 'SOURCE_VERSION', 'BUILD_SHA', 'RENDER_GIT_COMMIT', 'HEROKU_SLUG_COMMIT'];
|
|
77
|
-
const INCLUDE = ['@watchtowerobservability/node', '@opentelemetry'].flatMap((p) => [`./node_modules/${p}/**/*`, `./node_modules/.pnpm/${p.replace('/', '+')}*/**/*`]);
|
|
78
119
|
/**
|
|
79
120
|
* `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`. Makes `output: 'standalone'` work with no other
|
|
80
|
-
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages
|
|
81
|
-
*
|
|
121
|
+
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages`, and `outputFileTracingIncludes`
|
|
122
|
+
* for every route lists each one with its dependencies and pnpm links (npm, pnpm, monorepos; see tracingIncludes), so
|
|
123
|
+
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
82
124
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
83
125
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
84
126
|
*/
|
|
@@ -87,7 +129,7 @@ function withWatchtower(config = {}, opts = {}) {
|
|
|
87
129
|
const release = opts.release || SHA_ENV.map((k) => process.env[k]).find((v) => v && v !== 'unknown');
|
|
88
130
|
const apply = (c) => {
|
|
89
131
|
const inc = { ...c.outputFileTracingIncludes };
|
|
90
|
-
inc['/*'] = [...new Set([...(inc['/*'] ?? []), ...
|
|
132
|
+
inc['/*'] = [...new Set([...(inc['/*'] ?? []), ...tracingIncludes(EXTERNAL)])];
|
|
91
133
|
const out = {
|
|
92
134
|
...c,
|
|
93
135
|
serverExternalPackages: [...new Set([...(c.serverExternalPackages ?? []), ...externalPackages(opts.sentry ?? hasSentry())])],
|
package/dist/cjs/load.d.ts
CHANGED
|
@@ -4,6 +4,6 @@ export declare function load(id: string): unknown;
|
|
|
4
4
|
export declare const SDK_PEERS: string[];
|
|
5
5
|
/** Load an OpenTelemetry SDK package (an optional peer); a missing one throws an error naming what to install. */
|
|
6
6
|
export declare function need<T>(id: string): T;
|
|
7
|
-
export declare const STANDALONE_HINT = "use withWatchtower() from @watchtowerobservability/next
|
|
7
|
+
export declare const STANDALONE_HINT = "use withWatchtower() from @watchtowerobservability/next (node SDK 0.7.9 or later) in next.config";
|
|
8
8
|
/** Required OpenTelemetry peers that cannot be loaded from the SDK's location or the app root. */
|
|
9
9
|
export declare function missingPeers(): string[];
|
package/dist/cjs/load.js
CHANGED
|
@@ -14,7 +14,7 @@ const node_path_1 = __importDefault(require("node:path"));
|
|
|
14
14
|
// Bundlers must NOT follow this: an optional peer the app did not install would make webpack warn "Module not found",
|
|
15
15
|
// and a bare require call on a variable id is a "Critical dependency" warning. createRequire() is opaque to webpack/esbuild/Next's tracer,
|
|
16
16
|
// so peers resolve at run time from the SDK's own location, then from the app root (cwd). Install the peers in the app
|
|
17
|
-
// (pnpm: as direct dependencies)
|
|
17
|
+
// (pnpm: as direct dependencies). A Next standalone build gets them through withWatchtower's tracingIncludes (next-build.ts).
|
|
18
18
|
/** Where peers are searched, in order: the SDK's own location, the cwd, the entry script's directory (pnpm monorepo apps run from the repo root). */
|
|
19
19
|
function searchPaths() {
|
|
20
20
|
const entry = process.argv[1] ? `${node_path_1.default.dirname(node_path_1.default.resolve(process.argv[1]))}/` : '';
|
|
@@ -54,7 +54,7 @@ function need(id) {
|
|
|
54
54
|
throw e;
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
exports.STANDALONE_HINT = 'use withWatchtower() from @watchtowerobservability/next
|
|
57
|
+
exports.STANDALONE_HINT = 'use withWatchtower() from @watchtowerobservability/next (node SDK 0.7.9 or later) in next.config';
|
|
58
58
|
/** Required OpenTelemetry peers that cannot be loaded from the SDK's location or the app root. */
|
|
59
59
|
function missingPeers() {
|
|
60
60
|
return exports.SDK_PEERS.filter((id) => {
|
|
@@ -1,15 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
// `wt-next-doctor [dir]`: exit 1 when .next/standalone lacks the SDK or an OpenTelemetry peer
|
|
4
|
+
// `wt-next-doctor [dir]`: exit 1 when .next/standalone lacks the SDK or an OpenTelemetry peer, or one of them does not
|
|
5
|
+
// load from the standalone server.js (see next-doctor.ts).
|
|
5
6
|
const next_doctor_js_1 = require("./next-doctor.js");
|
|
6
7
|
const load_js_1 = require("./load.js");
|
|
7
|
-
const
|
|
8
|
+
const dir = process.argv[2];
|
|
9
|
+
const missing = (0, next_doctor_js_1.standaloneMissing)(dir);
|
|
10
|
+
const server = missing && !missing.length ? (0, next_doctor_js_1.standaloneServer)(dir) : undefined;
|
|
11
|
+
const broken = server ? (0, next_doctor_js_1.standaloneUnloadable)(server) : [];
|
|
8
12
|
if (!missing)
|
|
9
13
|
console.log('[watchtower] no .next/standalone found; nothing to check');
|
|
10
14
|
else if (missing.length) {
|
|
11
15
|
console.error(`[watchtower] missing from .next/standalone/node_modules: ${missing.join(', ')}\n[watchtower] fix: ${load_js_1.STANDALONE_HINT}`);
|
|
12
16
|
process.exit(1);
|
|
13
17
|
}
|
|
18
|
+
else if (broken.length) {
|
|
19
|
+
console.error(`[watchtower] present but failing to load from ${server}:\n ${broken.join('\n ')}\n[watchtower] fix: ${load_js_1.STANDALONE_HINT}`);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
14
22
|
else
|
|
15
|
-
console.log(
|
|
23
|
+
console.log(`[watchtower] standalone build includes the SDK and its OpenTelemetry peers${server ? ', and they load' : ''}`);
|
|
@@ -1,2 +1,10 @@
|
|
|
1
|
-
/** Packages missing from `<dir>/.next/standalone/node_modules
|
|
1
|
+
/** Packages missing from `<dir>/.next/standalone/node_modules` (and the app's own, next to server.js); undefined when there is no standalone build. */
|
|
2
2
|
export declare function standaloneMissing(dir?: string): string[] | undefined;
|
|
3
|
+
/** The standalone `server.js` (an app in a monorepo sits below `.next/standalone/<path>`); undefined when none. */
|
|
4
|
+
export declare function standaloneServer(dir?: string): string | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Import the SDK and load each peer the way the server will (from the SDK's location, then from server.js), in a child
|
|
7
|
+
* process; returns `id: error` for each that fails. Catches a peer copied without its own dependencies, which a
|
|
8
|
+
* folder check cannot see.
|
|
9
|
+
*/
|
|
10
|
+
export declare function standaloneUnloadable(server: string): string[];
|
package/dist/cjs/next-doctor.js
CHANGED
|
@@ -34,17 +34,57 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.standaloneMissing = standaloneMissing;
|
|
37
|
+
exports.standaloneServer = standaloneServer;
|
|
38
|
+
exports.standaloneUnloadable = standaloneUnloadable;
|
|
37
39
|
// After `next build` with output 'standalone', check that the SDK and its OpenTelemetry peers were traced into
|
|
38
|
-
// .next/standalone/node_modules (npm layout, or pnpm's .pnpm store)
|
|
40
|
+
// .next/standalone/node_modules (npm layout, or pnpm's .pnpm store), then load each one from the standalone server.js
|
|
41
|
+
// (wt-next-doctor exits 1 on either failure), so a peer copied without its own dependencies also fails.
|
|
42
|
+
const node_child_process_1 = require("node:child_process");
|
|
39
43
|
const fs = __importStar(require("node:fs"));
|
|
40
44
|
const nodePath = __importStar(require("node:path"));
|
|
41
45
|
const load_js_1 = require("./load.js");
|
|
42
|
-
/** Packages missing from `<dir>/.next/standalone/node_modules
|
|
46
|
+
/** Packages missing from `<dir>/.next/standalone/node_modules` (and the app's own, next to server.js); undefined when there is no standalone build. */
|
|
43
47
|
function standaloneMissing(dir = '.') {
|
|
44
48
|
const nm = nodePath.join(dir, '.next', 'standalone', 'node_modules');
|
|
45
49
|
if (!fs.existsSync(nodePath.join(dir, '.next', 'standalone')))
|
|
46
50
|
return undefined;
|
|
47
51
|
const pnpm = nodePath.join(nm, '.pnpm');
|
|
48
52
|
const store = fs.existsSync(pnpm) ? fs.readdirSync(pnpm) : [];
|
|
49
|
-
|
|
53
|
+
const server = standaloneServer(dir); // a monorepo app has its own node_modules next to server.js
|
|
54
|
+
const appNm = server ? nodePath.join(nodePath.dirname(server), 'node_modules') : nm;
|
|
55
|
+
return ['@watchtowerobservability/node', ...load_js_1.SDK_PEERS].filter((id) => !fs.existsSync(nodePath.join(nm, id)) && !fs.existsSync(nodePath.join(appNm, id)) && !store.some((e) => e.startsWith(`${id.replace('/', '+')}@`)));
|
|
56
|
+
}
|
|
57
|
+
/** The standalone `server.js` (an app in a monorepo sits below `.next/standalone/<path>`); undefined when none. */
|
|
58
|
+
function standaloneServer(dir = '.') {
|
|
59
|
+
const find = (d, depth) => {
|
|
60
|
+
if (fs.existsSync(nodePath.join(d, 'server.js')))
|
|
61
|
+
return nodePath.join(d, 'server.js');
|
|
62
|
+
if (depth === 0)
|
|
63
|
+
return undefined;
|
|
64
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
65
|
+
if (!e.isDirectory() || e.name === 'node_modules' || e.name.startsWith('.'))
|
|
66
|
+
continue;
|
|
67
|
+
const hit = find(nodePath.join(d, e.name), depth - 1);
|
|
68
|
+
if (hit)
|
|
69
|
+
return hit;
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
};
|
|
73
|
+
const root = nodePath.join(dir, '.next', 'standalone');
|
|
74
|
+
return fs.existsSync(root) ? find(root, 4) : undefined;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Import the SDK and load each peer the way the server will (from the SDK's location, then from server.js), in a child
|
|
78
|
+
* process; returns `id: error` for each that fails. Catches a peer copied without its own dependencies, which a
|
|
79
|
+
* folder check cannot see.
|
|
80
|
+
*/
|
|
81
|
+
function standaloneUnloadable(server) {
|
|
82
|
+
const abs = nodePath.resolve(server);
|
|
83
|
+
// ESM, as Next loads the external SDK (its CJS build is not traced); bare specifiers resolve from cwd
|
|
84
|
+
const code = `import { createRequire } from 'node:module'; const app = createRequire(${JSON.stringify(abs)}); const bad = [];
|
|
85
|
+
let sdk; try { await import('@watchtowerobservability/node'); sdk = createRequire(import.meta.resolve('@watchtowerobservability/node')); } catch (e) { bad.push('@watchtowerobservability/node: ' + e.message.split('\\n')[0]); }
|
|
86
|
+
for (const id of ${JSON.stringify(load_js_1.SDK_PEERS)}) { try { (sdk || app)(id); } catch (e) { try { app(id); } catch { bad.push(id + ': ' + e.message.split('\\n')[0]); } } }
|
|
87
|
+
process.stdout.write(JSON.stringify(bad)); process.exit(0);`;
|
|
88
|
+
const out = (0, node_child_process_1.execFileSync)(process.execPath, ['--input-type=module', '-e', code], { cwd: nodePath.dirname(abs), encoding: 'utf8' });
|
|
89
|
+
return JSON.parse(out);
|
|
50
90
|
}
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export declare const VERSION = "0.7.
|
|
2
|
+
export declare const VERSION = "0.7.9";
|
package/dist/cjs/version.js
CHANGED
package/dist/esm/env.d.ts
CHANGED
|
@@ -20,3 +20,10 @@ export declare function gitHeadSha(from: string): string | undefined;
|
|
|
20
20
|
* (`WT_BUILD_STAMP`, `BUILD_STAMP`), then the `.git` HEAD found upward from `gitFrom` (skipped when not given). Empty and `unknown` count as absent.
|
|
21
21
|
*/
|
|
22
22
|
export declare function resolveRelease(opt: string | undefined, env: NodeJS.ProcessEnv, otelResource: Record<string, string>, gitFrom?: string): string | undefined;
|
|
23
|
+
/** Cloud metadata endpoints; probing them from a non-cloud host times out, so they never become spans or issues. */
|
|
24
|
+
export declare const METADATA_HOSTS: Set<string>;
|
|
25
|
+
/**
|
|
26
|
+
* When OTEL_NODE_RESOURCE_DETECTORS is unset, limit the OTel Node resource detectors to local ones; a cloud detector is added only
|
|
27
|
+
* when an env var shows that cloud. Otherwise the detectors probe 169.254.169.254 and a non-cloud VM waits out a 10 s connect timeout.
|
|
28
|
+
*/
|
|
29
|
+
export declare function defaultResourceDetectors(env?: NodeJS.ProcessEnv): void;
|
package/dist/esm/env.js
CHANGED
|
@@ -93,3 +93,22 @@ export function resolveRelease(opt, env, otelResource, gitFrom) {
|
|
|
93
93
|
}
|
|
94
94
|
return gitFrom ? gitHeadSha(gitFrom) : undefined;
|
|
95
95
|
}
|
|
96
|
+
/** Cloud metadata endpoints; probing them from a non-cloud host times out, so they never become spans or issues. */
|
|
97
|
+
export const METADATA_HOSTS = new Set(['169.254.169.254', 'metadata.google.internal', '169.254.170.2', 'metadata.azure.internal']);
|
|
98
|
+
/**
|
|
99
|
+
* When OTEL_NODE_RESOURCE_DETECTORS is unset, limit the OTel Node resource detectors to local ones; a cloud detector is added only
|
|
100
|
+
* when an env var shows that cloud. Otherwise the detectors probe 169.254.169.254 and a non-cloud VM waits out a 10 s connect timeout.
|
|
101
|
+
*/
|
|
102
|
+
export function defaultResourceDetectors(env = process.env) {
|
|
103
|
+
if (env.OTEL_NODE_RESOURCE_DETECTORS)
|
|
104
|
+
return;
|
|
105
|
+
const on = (...k) => k.some((x) => !!env[x]);
|
|
106
|
+
const d = ['env', 'host', 'os', 'process'];
|
|
107
|
+
if (on('AWS_REGION', 'AWS_DEFAULT_REGION', 'AWS_EXECUTION_ENV', 'ECS_CONTAINER_METADATA_URI'))
|
|
108
|
+
d.push('aws');
|
|
109
|
+
if (on('GOOGLE_CLOUD_PROJECT', 'GCP_PROJECT', 'K_SERVICE', 'GAE_SERVICE'))
|
|
110
|
+
d.push('gcp');
|
|
111
|
+
if (on('WEBSITE_SITE_NAME', 'AZURE_FUNCTIONS_ENVIRONMENT', 'AZURE_CLIENT_ID', 'AZURE_TENANT_ID'))
|
|
112
|
+
d.push('azure');
|
|
113
|
+
env.OTEL_NODE_RESOURCE_DETECTORS = d.join(',');
|
|
114
|
+
}
|
package/dist/esm/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { inspect } from 'node:util';
|
|
4
4
|
import { context, diag, metrics, propagation, trace } from '@opentelemetry/api';
|
|
5
5
|
import { missingPeers, need as needPeer, STANDALONE_HINT } from './load.js';
|
|
6
|
-
import { otelEnv, resolveRelease } from './env.js';
|
|
6
|
+
import { defaultResourceDetectors, otelEnv, resolveRelease } from './env.js';
|
|
7
7
|
import { dbRequireParent, setHttpServerActive } from './integrations/db.js';
|
|
8
8
|
import { instrumentAll } from './instrument.js';
|
|
9
9
|
import { LOG_BODY_KEY, redactor } from './redact.js';
|
|
@@ -357,6 +357,7 @@ function registerGlobals(c) {
|
|
|
357
357
|
}
|
|
358
358
|
}
|
|
359
359
|
export function init(opts) {
|
|
360
|
+
defaultResourceDetectors(); // before any NodeSDK reads OTEL_NODE_RESOURCE_DETECTORS
|
|
360
361
|
const missing = missingPeers();
|
|
361
362
|
if (missing.length)
|
|
362
363
|
console.warn(`[watchtower] missing OpenTelemetry package(s): ${missing.join(', ')}. Next.js standalone: ${STANDALONE_HINT}. Otherwise: npm install ${missing.join(' ')}`);
|
package/dist/esm/instrument.js
CHANGED
|
@@ -2,19 +2,26 @@
|
|
|
2
2
|
import { load } from './load.js';
|
|
3
3
|
import { instrumentBetterSqlite3 } from './integrations/sqlite.js';
|
|
4
4
|
import { instrumentPostgres } from './integrations/postgres.js';
|
|
5
|
+
import { METADATA_HOSTS } from './env.js';
|
|
5
6
|
import { routeNamer } from './integrations/util.js';
|
|
6
7
|
/** Instrumentation packages already registered in this process (by `init` or `instrument()`), so none is patched twice. */
|
|
7
8
|
export const registered = new Set();
|
|
9
|
+
const hostOf = (o) => { try {
|
|
10
|
+
return new URL(o ?? '').hostname;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return '';
|
|
14
|
+
} };
|
|
8
15
|
const ENTRIES = [
|
|
9
16
|
{
|
|
10
17
|
pkg: '@opentelemetry/instrumentation-http', ctor: 'HttpInstrumentation',
|
|
11
18
|
// our own exports and API calls must not become spans
|
|
12
19
|
// routeNamer: server spans become `GET /users/:id` from the matched Express / Nest route (http alone names them just `GET`)
|
|
13
|
-
opts: (self) => ({ applyCustomAttributesOnSpan: routeNamer, ignoreOutgoingRequestHook: (r) => self.some((u) => (r.hostname || r.host) === u.hostname && String(r.port ?? (u.protocol === 'https:' ? 443 : 80)) === String(u.port || (u.protocol === 'https:' ? 443 : 80))) }),
|
|
20
|
+
opts: (self) => ({ applyCustomAttributesOnSpan: routeNamer, ignoreOutgoingRequestHook: (r) => METADATA_HOSTS.has(String(r.hostname || r.host).replace(/:\d+$/, '')) || self.some((u) => (r.hostname || r.host) === u.hostname && String(r.port ?? (u.protocol === 'https:' ? 443 : 80)) === String(u.port || (u.protocol === 'https:' ? 443 : 80))) }),
|
|
14
21
|
},
|
|
15
22
|
{
|
|
16
23
|
pkg: '@opentelemetry/instrumentation-undici', ctor: 'UndiciInstrumentation',
|
|
17
|
-
opts: (self) => ({ ignoreRequestHook: (r) => self.some((u) => r.origin === u.origin) }),
|
|
24
|
+
opts: (self) => ({ ignoreRequestHook: (r) => METADATA_HOSTS.has(hostOf(r.origin)) || self.some((u) => r.origin === u.origin) }),
|
|
18
25
|
},
|
|
19
26
|
{ pkg: '@opentelemetry/instrumentation-pg', ctor: 'PgInstrumentation', opts: () => ({}) },
|
|
20
27
|
{ pkg: '@opentelemetry/instrumentation-ioredis', ctor: 'IORedisInstrumentation', opts: () => ({}) },
|
|
@@ -38,10 +38,17 @@ export interface WatchtowerNextOptions {
|
|
|
38
38
|
export declare function hasSentry(cwd?: string): boolean;
|
|
39
39
|
/** The `serverExternalPackages` withWatchtower adds; `sentry` drops the packages a bundled Sentry shares. */
|
|
40
40
|
export declare function externalPackages(sentry: boolean): string[];
|
|
41
|
+
/**
|
|
42
|
+
* `outputFileTracingIncludes` globs for `ids` and everything they depend on, relative to `cwd`: each package's real
|
|
43
|
+
* folder plus every pnpm symlink on the way to it, which Next recreates as links (what its tracer emits for a static
|
|
44
|
+
* import). A plain `node_modules/<pkg>/**` glob copies a pnpm link as a folder cut off from its dependencies (B22).
|
|
45
|
+
*/
|
|
46
|
+
export declare function tracingIncludes(ids: string[], cwd?: string): string[];
|
|
41
47
|
/**
|
|
42
48
|
* `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`. Makes `output: 'standalone'` work with no other
|
|
43
|
-
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages
|
|
44
|
-
*
|
|
49
|
+
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages`, and `outputFileTracingIncludes`
|
|
50
|
+
* for every route lists each one with its dependencies and pnpm links (npm, pnpm, monorepos; see tracingIncludes), so
|
|
51
|
+
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
45
52
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
46
53
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
47
54
|
*/
|
|
@@ -33,12 +33,53 @@ export function hasSentry(cwd = process.cwd()) {
|
|
|
33
33
|
export function externalPackages(sentry) {
|
|
34
34
|
return sentry ? EXTERNAL.filter((n) => !SHARED_WITH_SENTRY.has(n)) : EXTERNAL;
|
|
35
35
|
}
|
|
36
|
+
/** Where Node finds package `id` from `from`: the lookup path (may be a pnpm symlink) and its real folder. */
|
|
37
|
+
function locate(id, from) {
|
|
38
|
+
for (let d = from;; d = nodePath.dirname(d)) {
|
|
39
|
+
const link = nodePath.join(d, 'node_modules', id);
|
|
40
|
+
if (fs.existsSync(nodePath.join(link, 'package.json')))
|
|
41
|
+
return { link, real: fs.realpathSync(link) };
|
|
42
|
+
if (nodePath.dirname(d) === d)
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* `outputFileTracingIncludes` globs for `ids` and everything they depend on, relative to `cwd`: each package's real
|
|
48
|
+
* folder plus every pnpm symlink on the way to it, which Next recreates as links (what its tracer emits for a static
|
|
49
|
+
* import). A plain `node_modules/<pkg>/**` glob copies a pnpm link as a folder cut off from its dependencies (B22).
|
|
50
|
+
*/
|
|
51
|
+
export function tracingIncludes(ids, cwd = process.cwd()) {
|
|
52
|
+
const out = new Set(), seen = new Set();
|
|
53
|
+
const rel = (p) => nodePath.relative(cwd, p).split(nodePath.sep).join('/').replace(/[()[\]{}*?!]/g, '\\$&');
|
|
54
|
+
const visit = (id, from) => {
|
|
55
|
+
const hit = locate(id, from);
|
|
56
|
+
if (!hit)
|
|
57
|
+
return; // an optional peer that is not installed
|
|
58
|
+
if (fs.lstatSync(hit.link).isSymbolicLink())
|
|
59
|
+
out.add(rel(hit.link));
|
|
60
|
+
if (seen.has(hit.real))
|
|
61
|
+
return;
|
|
62
|
+
seen.add(hit.real);
|
|
63
|
+
out.add(`${rel(hit.real)}/**/*`);
|
|
64
|
+
try {
|
|
65
|
+
const pkg = JSON.parse(fs.readFileSync(nodePath.join(hit.real, 'package.json'), 'utf8'));
|
|
66
|
+
// peers: only OpenTelemetry ones (the SDK's peers are in `ids` already; following `next` would copy all of it)
|
|
67
|
+
const peers = Object.keys(pkg.peerDependencies ?? {}).filter((n) => n.startsWith('@opentelemetry/'));
|
|
68
|
+
for (const dep of [...Object.keys({ ...pkg.dependencies, ...pkg.optionalDependencies }), ...peers])
|
|
69
|
+
visit(dep, hit.real);
|
|
70
|
+
}
|
|
71
|
+
catch { /* unreadable package.json: its own files are still included */ }
|
|
72
|
+
};
|
|
73
|
+
for (const id of ids)
|
|
74
|
+
visit(id, cwd);
|
|
75
|
+
return [...out];
|
|
76
|
+
}
|
|
36
77
|
const SHA_ENV = ['WT_RELEASE', 'GITHUB_SHA', 'CI_COMMIT_SHA', 'VERCEL_GIT_COMMIT_SHA', 'SOURCE_VERSION', 'BUILD_SHA', 'RENDER_GIT_COMMIT', 'HEROKU_SLUG_COMMIT'];
|
|
37
|
-
const INCLUDE = ['@watchtowerobservability/node', '@opentelemetry'].flatMap((p) => [`./node_modules/${p}/**/*`, `./node_modules/.pnpm/${p.replace('/', '+')}*/**/*`]);
|
|
38
78
|
/**
|
|
39
79
|
* `module.exports = withWatchtower(nextConfig, { sourcemaps: true })`. Makes `output: 'standalone'` work with no other
|
|
40
|
-
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages
|
|
41
|
-
*
|
|
80
|
+
* config: the node SDK and its OpenTelemetry peers go into `serverExternalPackages`, and `outputFileTracingIncludes`
|
|
81
|
+
* for every route lists each one with its dependencies and pnpm links (npm, pnpm, monorepos; see tracingIncludes), so
|
|
82
|
+
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
42
83
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
43
84
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
44
85
|
*/
|
|
@@ -47,7 +88,7 @@ export function withWatchtower(config = {}, opts = {}) {
|
|
|
47
88
|
const release = opts.release || SHA_ENV.map((k) => process.env[k]).find((v) => v && v !== 'unknown');
|
|
48
89
|
const apply = (c) => {
|
|
49
90
|
const inc = { ...c.outputFileTracingIncludes };
|
|
50
|
-
inc['/*'] = [...new Set([...(inc['/*'] ?? []), ...
|
|
91
|
+
inc['/*'] = [...new Set([...(inc['/*'] ?? []), ...tracingIncludes(EXTERNAL)])];
|
|
51
92
|
const out = {
|
|
52
93
|
...c,
|
|
53
94
|
serverExternalPackages: [...new Set([...(c.serverExternalPackages ?? []), ...externalPackages(opts.sentry ?? hasSentry())])],
|
package/dist/esm/load.d.ts
CHANGED
|
@@ -4,6 +4,6 @@ export declare function load(id: string): unknown;
|
|
|
4
4
|
export declare const SDK_PEERS: string[];
|
|
5
5
|
/** Load an OpenTelemetry SDK package (an optional peer); a missing one throws an error naming what to install. */
|
|
6
6
|
export declare function need<T>(id: string): T;
|
|
7
|
-
export declare const STANDALONE_HINT = "use withWatchtower() from @watchtowerobservability/next
|
|
7
|
+
export declare const STANDALONE_HINT = "use withWatchtower() from @watchtowerobservability/next (node SDK 0.7.9 or later) in next.config";
|
|
8
8
|
/** Required OpenTelemetry peers that cannot be loaded from the SDK's location or the app root. */
|
|
9
9
|
export declare function missingPeers(): string[];
|
package/dist/esm/load.js
CHANGED
|
@@ -4,7 +4,7 @@ import nodePath from 'node:path';
|
|
|
4
4
|
// Bundlers must NOT follow this: an optional peer the app did not install would make webpack warn "Module not found",
|
|
5
5
|
// and a bare require call on a variable id is a "Critical dependency" warning. createRequire() is opaque to webpack/esbuild/Next's tracer,
|
|
6
6
|
// so peers resolve at run time from the SDK's own location, then from the app root (cwd). Install the peers in the app
|
|
7
|
-
// (pnpm: as direct dependencies)
|
|
7
|
+
// (pnpm: as direct dependencies). A Next standalone build gets them through withWatchtower's tracingIncludes (next-build.ts).
|
|
8
8
|
/** Where peers are searched, in order: the SDK's own location, the cwd, the entry script's directory (pnpm monorepo apps run from the repo root). */
|
|
9
9
|
export function searchPaths() {
|
|
10
10
|
const entry = process.argv[1] ? `${nodePath.dirname(nodePath.resolve(process.argv[1]))}/` : '';
|
|
@@ -44,7 +44,7 @@ export function need(id) {
|
|
|
44
44
|
throw e;
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
export const STANDALONE_HINT = 'use withWatchtower() from @watchtowerobservability/next
|
|
47
|
+
export const STANDALONE_HINT = 'use withWatchtower() from @watchtowerobservability/next (node SDK 0.7.9 or later) in next.config';
|
|
48
48
|
/** Required OpenTelemetry peers that cannot be loaded from the SDK's location or the app root. */
|
|
49
49
|
export function missingPeers() {
|
|
50
50
|
return SDK_PEERS.filter((id) => {
|
|
@@ -1,13 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// `wt-next-doctor [dir]`: exit 1 when .next/standalone lacks the SDK or an OpenTelemetry peer
|
|
3
|
-
|
|
2
|
+
// `wt-next-doctor [dir]`: exit 1 when .next/standalone lacks the SDK or an OpenTelemetry peer, or one of them does not
|
|
3
|
+
// load from the standalone server.js (see next-doctor.ts).
|
|
4
|
+
import { standaloneMissing, standaloneServer, standaloneUnloadable } from './next-doctor.js';
|
|
4
5
|
import { STANDALONE_HINT } from './load.js';
|
|
5
|
-
const
|
|
6
|
+
const dir = process.argv[2];
|
|
7
|
+
const missing = standaloneMissing(dir);
|
|
8
|
+
const server = missing && !missing.length ? standaloneServer(dir) : undefined;
|
|
9
|
+
const broken = server ? standaloneUnloadable(server) : [];
|
|
6
10
|
if (!missing)
|
|
7
11
|
console.log('[watchtower] no .next/standalone found; nothing to check');
|
|
8
12
|
else if (missing.length) {
|
|
9
13
|
console.error(`[watchtower] missing from .next/standalone/node_modules: ${missing.join(', ')}\n[watchtower] fix: ${STANDALONE_HINT}`);
|
|
10
14
|
process.exit(1);
|
|
11
15
|
}
|
|
16
|
+
else if (broken.length) {
|
|
17
|
+
console.error(`[watchtower] present but failing to load from ${server}:\n ${broken.join('\n ')}\n[watchtower] fix: ${STANDALONE_HINT}`);
|
|
18
|
+
process.exit(1);
|
|
19
|
+
}
|
|
12
20
|
else
|
|
13
|
-
console.log(
|
|
21
|
+
console.log(`[watchtower] standalone build includes the SDK and its OpenTelemetry peers${server ? ', and they load' : ''}`);
|
|
@@ -1,2 +1,10 @@
|
|
|
1
|
-
/** Packages missing from `<dir>/.next/standalone/node_modules
|
|
1
|
+
/** Packages missing from `<dir>/.next/standalone/node_modules` (and the app's own, next to server.js); undefined when there is no standalone build. */
|
|
2
2
|
export declare function standaloneMissing(dir?: string): string[] | undefined;
|
|
3
|
+
/** The standalone `server.js` (an app in a monorepo sits below `.next/standalone/<path>`); undefined when none. */
|
|
4
|
+
export declare function standaloneServer(dir?: string): string | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Import the SDK and load each peer the way the server will (from the SDK's location, then from server.js), in a child
|
|
7
|
+
* process; returns `id: error` for each that fails. Catches a peer copied without its own dependencies, which a
|
|
8
|
+
* folder check cannot see.
|
|
9
|
+
*/
|
|
10
|
+
export declare function standaloneUnloadable(server: string): string[];
|
package/dist/esm/next-doctor.js
CHANGED
|
@@ -1,14 +1,52 @@
|
|
|
1
1
|
// After `next build` with output 'standalone', check that the SDK and its OpenTelemetry peers were traced into
|
|
2
|
-
// .next/standalone/node_modules (npm layout, or pnpm's .pnpm store)
|
|
2
|
+
// .next/standalone/node_modules (npm layout, or pnpm's .pnpm store), then load each one from the standalone server.js
|
|
3
|
+
// (wt-next-doctor exits 1 on either failure), so a peer copied without its own dependencies also fails.
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
3
5
|
import * as fs from 'node:fs';
|
|
4
6
|
import * as nodePath from 'node:path';
|
|
5
7
|
import { SDK_PEERS } from './load.js';
|
|
6
|
-
/** Packages missing from `<dir>/.next/standalone/node_modules
|
|
8
|
+
/** Packages missing from `<dir>/.next/standalone/node_modules` (and the app's own, next to server.js); undefined when there is no standalone build. */
|
|
7
9
|
export function standaloneMissing(dir = '.') {
|
|
8
10
|
const nm = nodePath.join(dir, '.next', 'standalone', 'node_modules');
|
|
9
11
|
if (!fs.existsSync(nodePath.join(dir, '.next', 'standalone')))
|
|
10
12
|
return undefined;
|
|
11
13
|
const pnpm = nodePath.join(nm, '.pnpm');
|
|
12
14
|
const store = fs.existsSync(pnpm) ? fs.readdirSync(pnpm) : [];
|
|
13
|
-
|
|
15
|
+
const server = standaloneServer(dir); // a monorepo app has its own node_modules next to server.js
|
|
16
|
+
const appNm = server ? nodePath.join(nodePath.dirname(server), 'node_modules') : nm;
|
|
17
|
+
return ['@watchtowerobservability/node', ...SDK_PEERS].filter((id) => !fs.existsSync(nodePath.join(nm, id)) && !fs.existsSync(nodePath.join(appNm, id)) && !store.some((e) => e.startsWith(`${id.replace('/', '+')}@`)));
|
|
18
|
+
}
|
|
19
|
+
/** The standalone `server.js` (an app in a monorepo sits below `.next/standalone/<path>`); undefined when none. */
|
|
20
|
+
export function standaloneServer(dir = '.') {
|
|
21
|
+
const find = (d, depth) => {
|
|
22
|
+
if (fs.existsSync(nodePath.join(d, 'server.js')))
|
|
23
|
+
return nodePath.join(d, 'server.js');
|
|
24
|
+
if (depth === 0)
|
|
25
|
+
return undefined;
|
|
26
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
27
|
+
if (!e.isDirectory() || e.name === 'node_modules' || e.name.startsWith('.'))
|
|
28
|
+
continue;
|
|
29
|
+
const hit = find(nodePath.join(d, e.name), depth - 1);
|
|
30
|
+
if (hit)
|
|
31
|
+
return hit;
|
|
32
|
+
}
|
|
33
|
+
return undefined;
|
|
34
|
+
};
|
|
35
|
+
const root = nodePath.join(dir, '.next', 'standalone');
|
|
36
|
+
return fs.existsSync(root) ? find(root, 4) : undefined;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Import the SDK and load each peer the way the server will (from the SDK's location, then from server.js), in a child
|
|
40
|
+
* process; returns `id: error` for each that fails. Catches a peer copied without its own dependencies, which a
|
|
41
|
+
* folder check cannot see.
|
|
42
|
+
*/
|
|
43
|
+
export function standaloneUnloadable(server) {
|
|
44
|
+
const abs = nodePath.resolve(server);
|
|
45
|
+
// ESM, as Next loads the external SDK (its CJS build is not traced); bare specifiers resolve from cwd
|
|
46
|
+
const code = `import { createRequire } from 'node:module'; const app = createRequire(${JSON.stringify(abs)}); const bad = [];
|
|
47
|
+
let sdk; try { await import('@watchtowerobservability/node'); sdk = createRequire(import.meta.resolve('@watchtowerobservability/node')); } catch (e) { bad.push('@watchtowerobservability/node: ' + e.message.split('\\n')[0]); }
|
|
48
|
+
for (const id of ${JSON.stringify(SDK_PEERS)}) { try { (sdk || app)(id); } catch (e) { try { app(id); } catch { bad.push(id + ': ' + e.message.split('\\n')[0]); } } }
|
|
49
|
+
process.stdout.write(JSON.stringify(bad)); process.exit(0);`;
|
|
50
|
+
const out = execFileSync(process.execPath, ['--input-type=module', '-e', code], { cwd: nodePath.dirname(abs), encoding: 'utf8' });
|
|
51
|
+
return JSON.parse(out);
|
|
14
52
|
}
|
package/dist/esm/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export declare const VERSION = "0.7.
|
|
2
|
+
export declare const VERSION = "0.7.9";
|
package/dist/esm/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export const VERSION = '0.7.
|
|
2
|
+
export const VERSION = '0.7.9';
|