@smoothbricks/nx-plugin 0.4.9 → 0.4.11
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/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +46 -1
- package/dist/typecheck-test-policy.d.ts.map +1 -1
- package/dist/typecheck-test-policy.js +84 -7
- package/package.json +2 -2
- package/src/index.test.ts +112 -1
- package/src/index.ts +48 -1
- package/src/typecheck-test-policy.test.ts +63 -0
- package/src/typecheck-test-policy.ts +84 -9
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { type CreateNodesV2 } from 'nx/src/devkit-exports.js';
|
|
2
2
|
import { CARGO_TEST_COMPILE_TARGET } from './cargo-workspace.js';
|
|
3
3
|
export { CARGO_TEST_COMPILE_TARGET };
|
|
4
|
+
/** Makes a version live and proves it answers; never cached. */
|
|
5
|
+
export declare const DEPLOY_TARGET = "deploy";
|
|
6
|
+
/** The purely file-derived half a deploy needs built first; cached. */
|
|
7
|
+
export declare const DEPLOY_BUILD_TARGET = "deploy-build";
|
|
4
8
|
type NapiArchitecture = 'arm64' | 'x64';
|
|
5
9
|
type NapiTargetFamily = 'linux' | 'macos';
|
|
6
10
|
interface NapiPlatform {
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,aAAa,EAGnB,MAAM,0BAA0B,CAAC;AAKlC,OAAO,EAKL,yBAAyB,EAW1B,MAAM,sBAAsB,CAAC;AAa9B,OAAO,EAAE,yBAAyB,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,aAAa,EAGnB,MAAM,0BAA0B,CAAC;AAKlC,OAAO,EAKL,yBAAyB,EAW1B,MAAM,sBAAsB,CAAC;AAa9B,OAAO,EAAE,yBAAyB,EAAE,CAAC;AAErC,gEAAgE;AAChE,eAAO,MAAM,aAAa,WAAW,CAAC;AACtC,uEAAuE;AACvE,eAAO,MAAM,mBAAmB,iBAAiB,CAAC;AAmDlD,KAAK,gBAAgB,GAAG,OAAO,GAAG,KAAK,CAAC;AACxC,KAAK,gBAAgB,GAAG,OAAO,GAAG,OAAO,CAAC;AAE1C,UAAU,YAAY;IACpB,YAAY,EAAE,gBAAgB,CAAC;IAC/B,YAAY,EAAE,gBAAgB,CAAC;CAChC;AA8HD,UAAU,oBAAqB,SAAQ,YAAY;IACjD,UAAU,EAAE,MAAM,CAAC;CACpB;AA0CD;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,oBAAoB,GAAG,MAAM,CAEhF;AA+KD,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,GAAG,aAAa,CAEvG;AAED,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,10 @@ import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET, CARGO_FETCH_COMMAND,
|
|
|
11
11
|
import { isNonSourceDirectory } from './source-directories.js';
|
|
12
12
|
import { PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
|
|
13
13
|
export { CARGO_TEST_COMPILE_TARGET };
|
|
14
|
+
/** Makes a version live and proves it answers; never cached. */
|
|
15
|
+
export const DEPLOY_TARGET = 'deploy';
|
|
16
|
+
/** The purely file-derived half a deploy needs built first; cached. */
|
|
17
|
+
export const DEPLOY_BUILD_TARGET = 'deploy-build';
|
|
14
18
|
const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
|
|
15
19
|
const TYPESCRIPT_TOOLCHAIN_INPUTS = [
|
|
16
20
|
'{workspaceRoot}/package.json',
|
|
@@ -132,8 +136,14 @@ const REPO_ROOT_CARGO_OUTPUT_INPUTS = [
|
|
|
132
136
|
'{workspaceRoot}/scripts/*.sh',
|
|
133
137
|
'!{workspaceRoot}/**/target/**',
|
|
134
138
|
];
|
|
139
|
+
// The environment half of a cargo task's identity. Beyond cargo/rustc's own
|
|
140
|
+
// variables, every build script that compiles C/C++ reads the Apple SDK
|
|
141
|
+
// (SDKROOT, DEVELOPER_DIR, the deployment targets), bindgen reads its libclang
|
|
142
|
+
// and extra clang args, cmake-rs forwards CMAKE_*, and zig-based cross links
|
|
143
|
+
// read ZIG*. An output linked against one sysroot must never hash equal to
|
|
144
|
+
// the same sources linked against another.
|
|
135
145
|
const CARGO_ENVIRONMENT_INPUT = {
|
|
136
|
-
runtime: `bun -e 'const fs = require("node:fs"); const path = require("node:path"); const home = process.env.CARGO_HOME || path.join(require("node:os").homedir(), ".cargo"); console.log(JSON.stringify({env: Object.entries(process.env).filter(([name]) => /^(?:CARGO_|RUST|NEXTEST_|CLIPPY_|CC(?:_|$)|CXX(?:_|$)|AR(?:_|$)|CFLAGS|CXXFLAGS|CPPFLAGS|LDFLAGS|PKG_CONFIG|TARGET_|HOST_)/.test(name)).sort(([a], [b]) => a.localeCompare(b)), config: ["config", "config.toml"].map(name => { const file = path.join(home, name); return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; })}));'`,
|
|
146
|
+
runtime: `bun -e 'const fs = require("node:fs"); const path = require("node:path"); const home = process.env.CARGO_HOME || path.join(require("node:os").homedir(), ".cargo"); console.log(JSON.stringify({env: Object.entries(process.env).filter(([name]) => /^(?:CARGO_|RUST|NEXTEST_|CLIPPY_|CC(?:_|$)|CXX(?:_|$)|AR(?:_|$)|CFLAGS|CXXFLAGS|CPPFLAGS|LDFLAGS|PKG_CONFIG|TARGET_|HOST_|SDKROOT$|DEVELOPER_DIR$|MACOSX_DEPLOYMENT_TARGET$|IPHONEOS_DEPLOYMENT_TARGET$|LIBCLANG_PATH$|BINDGEN_EXTRA_CLANG_ARGS|CMAKE_|ZIG)/.test(name)).sort(([a], [b]) => a.localeCompare(b)), config: ["config", "config.toml"].map(name => { const file = path.join(home, name); return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; })}));'`,
|
|
137
147
|
};
|
|
138
148
|
function cargoRuntimeInput(projectRoot, command) {
|
|
139
149
|
const quotedRoot = `'${projectRoot.replaceAll("'", "'\"'\"'")}'`;
|
|
@@ -894,6 +904,41 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
|
|
|
894
904
|
cargoNapi.dependsOn = [...dependsOn, cargoTestCompileDependency];
|
|
895
905
|
}
|
|
896
906
|
}
|
|
907
|
+
// A deploy is never cached; the build half beside it always is.
|
|
908
|
+
//
|
|
909
|
+
// Nx's cache answers "did this exact input set already produce an output". A deploy's real
|
|
910
|
+
// question is "is this exact version live", and the two agree only until someone rolls back.
|
|
911
|
+
// After a rollback the workspace is unchanged, so the hash is unchanged, so a cached `deploy`
|
|
912
|
+
// reports success while the previous version keeps serving. No input tuning repairs that: a
|
|
913
|
+
// `runtime` input cannot even learn WHICH STAGE is being deployed. Nx hashes runtime inputs with
|
|
914
|
+
// the env from `getTaskSpecificEnv`, which deliberately excludes the task coordinates; input
|
|
915
|
+
// strings interpolate only `{workspaceRoot}`/`{projectRoot}`, never `{args.*}`; and overrides
|
|
916
|
+
// are not forwarded to `dependsOn` dependencies, so an auxiliary task cannot carry the stage
|
|
917
|
+
// either. (An executor's custom hasher is the single Nx API that does see `task.overrides`, if
|
|
918
|
+
// hash-level participation is ever genuinely wanted.)
|
|
919
|
+
//
|
|
920
|
+
// So the target is split along the line the question actually falls on. `deploy-build` is purely
|
|
921
|
+
// file-derived — build the artifact and whatever the build registers — and caches honestly.
|
|
922
|
+
// `deploy` reads live state every run and no-ops when live already equals the desired tag, which
|
|
923
|
+
// costs two Cloudflare calls and makes a redundant deploy provably free rather than assumed
|
|
924
|
+
// free. That is what lets ordering be an ordinary `dependsOn: ["<other>:deploy"]` edge at any
|
|
925
|
+
// depth, and it is why such an edge must point at `deploy` and not at `deploy-build`: a
|
|
926
|
+
// dependent has to re-check liveness, not inherit someone else's cache hit.
|
|
927
|
+
//
|
|
928
|
+
// Both are bases for a package-local declaration to land on, per the merge rules above: a
|
|
929
|
+
// declaration naming `cache`, `inputs` or `dependsOn` REPLACES what is set here, so a project
|
|
930
|
+
// adding a cross-project edge writes `"dependsOn": ["...", "backend:deploy"]` to keep the
|
|
931
|
+
// `deploy-build` edge this adds.
|
|
932
|
+
if (DEPLOY_BUILD_TARGET in declaredTargets) {
|
|
933
|
+
targets[DEPLOY_BUILD_TARGET] = { cache: true };
|
|
934
|
+
}
|
|
935
|
+
if (DEPLOY_TARGET in declaredTargets) {
|
|
936
|
+
targets[DEPLOY_TARGET] = {
|
|
937
|
+
cache: false,
|
|
938
|
+
outputs: [],
|
|
939
|
+
...(DEPLOY_BUILD_TARGET in declaredTargets ? { dependsOn: [DEPLOY_BUILD_TARGET] } : {}),
|
|
940
|
+
};
|
|
941
|
+
}
|
|
897
942
|
// No `outputs`, deliberately: this aggregate runs no command, so every file
|
|
898
943
|
// under dist belongs to the concrete target that emitted it. Claiming
|
|
899
944
|
// `{projectRoot}/dist` here would cache the children's bytes a second time
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typecheck-test-policy.d.ts","sourceRoot":"","sources":["../src/typecheck-test-policy.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"typecheck-test-policy.d.ts","sourceRoot":"","sources":["../src/typecheck-test-policy.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAGrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,QAAQ,CAAC;AAI1C;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACvC,WAAW,CAAC,UAAU,CAAC,CAqDzB;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,EAC5C,WAAW,EAAE,MAAM,GAClB,aAAa,EAAE,CAgDjB;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CACxC,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,EAC/C,WAAW,EAAE,MAAM,GAClB,aAAa,EAAE,CAYjB;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrC,OAAO,EAAE;IACP,WAAW,EAAE,WAAW,CAAC,UAAU,CAAC,CAAC;IACrC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,kBAAkB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC7C,cAAc,EAAE,MAAM,EAAE,CAAC;CAC1B,GACA,OAAO,CAsDT;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAO7F;AAED;;GAEG;AACH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,IAAI,GAAG,aAAa,EAAE,CAwCxE;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAyDhE;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,aAAa,EAAE,CAiEtE;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAmE9D"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { join, relative } from 'node:path';
|
|
3
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
4
3
|
import { getProjects, readJson, readProjectConfiguration, updateJson, writeJson } from 'nx/src/devkit-exports.js';
|
|
5
4
|
const workspaceDependencyFields = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
|
|
6
5
|
/**
|
|
@@ -130,11 +129,15 @@ export function applyTypecheckTestDefaults(tsconfigTest, options) {
|
|
|
130
129
|
const extendsValue = options.tsconfigLibExtends ?? '../../tsconfig.base.json';
|
|
131
130
|
let changed = setMissingStringProperty(tsconfigTest, 'extends', extendsValue);
|
|
132
131
|
const compilerOptions = getOrCreateRecord(tsconfigTest, 'compilerOptions');
|
|
133
|
-
//
|
|
132
|
+
// Fill from the lib tsconfig only what the test program has NOT declared. A
|
|
133
|
+
// test program that names its own `lib` is stating a fact the lib program
|
|
134
|
+
// cannot know: it runs on one runtime (Bun's JSC understands
|
|
135
|
+
// change-array-by-copy) while the library's output has to run on the shipping
|
|
136
|
+
// floor. Overwriting it turned `toSorted` into a type error in a suite that
|
|
137
|
+
// calls it every day, and it came back on every `smoo monorepo update`.
|
|
134
138
|
if (options.libCompilerOptions) {
|
|
135
139
|
for (const key of ['baseUrl', 'module', 'moduleResolution', 'jsx', 'lib']) {
|
|
136
|
-
if (Object.hasOwn(options.libCompilerOptions, key) &&
|
|
137
|
-
!isDeepStrictEqual(compilerOptions[key], options.libCompilerOptions[key])) {
|
|
140
|
+
if (Object.hasOwn(options.libCompilerOptions, key) && !Object.hasOwn(compilerOptions, key)) {
|
|
138
141
|
compilerOptions[key] = options.libCompilerOptions[key];
|
|
139
142
|
changed = true;
|
|
140
143
|
}
|
|
@@ -381,6 +384,14 @@ export function applyTypecheckTestPolicy(root) {
|
|
|
381
384
|
referencePaths,
|
|
382
385
|
}) || fileChanged;
|
|
383
386
|
if (fileChanged) {
|
|
387
|
+
// A documented tsconfig cannot survive JSON.stringify, so the policy says
|
|
388
|
+
// what it wants instead of quietly deleting the reasoning. The check
|
|
389
|
+
// half (checkTypecheckTestPolicy) reports the same drift, so CI still
|
|
390
|
+
// fails until a human applies it.
|
|
391
|
+
if (existsSync(tsconfigTestPath) && hasJsonComments(readFileSync(tsconfigTestPath, 'utf8'))) {
|
|
392
|
+
console.error(`refused ${packagePath}/tsconfig.test.json carries comments a rewrite would delete; apply the policy by hand`);
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
384
395
|
writeJsonObjectFs(tsconfigTestPath, tsconfigTest);
|
|
385
396
|
changed = true;
|
|
386
397
|
}
|
|
@@ -580,17 +591,83 @@ function collectTsconfigTestReferencePaths(root, packagePath, pkg, workspaceName
|
|
|
580
591
|
}
|
|
581
592
|
return paths;
|
|
582
593
|
}
|
|
594
|
+
/**
|
|
595
|
+
* Read a tsconfig or package.json. tsconfig files are JSONC — TypeScript
|
|
596
|
+
* permits comments and trailing commas — so a plain `JSON.parse` fails on a
|
|
597
|
+
* documented one. Returning null there meant "file absent", and the caller
|
|
598
|
+
* regenerated it from scratch: a `lib` the test program declared, an
|
|
599
|
+
* `exclude`, an extra `include` glob and every comment explaining them
|
|
600
|
+
* disappeared on the next `smoo monorepo update`. Comments are stripped for
|
|
601
|
+
* parsing only; a caller that intends to write back must decide what to do
|
|
602
|
+
* about them (see writeJsonObjectFs's caller).
|
|
603
|
+
*/
|
|
583
604
|
function readJsonObject(path) {
|
|
584
605
|
if (!existsSync(path)) {
|
|
585
606
|
return null;
|
|
586
607
|
}
|
|
608
|
+
const text = readFileSync(path, 'utf8');
|
|
587
609
|
try {
|
|
588
|
-
const parsed = JSON.parse(
|
|
610
|
+
const parsed = JSON.parse(stripJsonComments(text));
|
|
589
611
|
return isRecord(parsed) ? parsed : null;
|
|
590
612
|
}
|
|
591
|
-
catch {
|
|
592
|
-
|
|
613
|
+
catch (error) {
|
|
614
|
+
// A file that exists but cannot be parsed is a configuration error, not an
|
|
615
|
+
// invitation to overwrite it.
|
|
616
|
+
throw new Error(`${path} is not valid JSON/JSONC: ${error instanceof Error ? error.message : String(error)}`);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
/** Whether the file carries comments a rewrite would destroy. */
|
|
620
|
+
function hasJsonComments(text) {
|
|
621
|
+
return stripJsonComments(text) !== text;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Remove `//` and block comments outside string literals, and trailing commas.
|
|
625
|
+
* Small on purpose: the alternative is a JSONC dependency in a plugin whose
|
|
626
|
+
* only JSONC inputs are tsconfig files.
|
|
627
|
+
*/
|
|
628
|
+
function stripJsonComments(text) {
|
|
629
|
+
let output = '';
|
|
630
|
+
let inString = false;
|
|
631
|
+
let escaped = false;
|
|
632
|
+
let index = 0;
|
|
633
|
+
while (index < text.length) {
|
|
634
|
+
const char = text[index];
|
|
635
|
+
if (inString) {
|
|
636
|
+
output += char;
|
|
637
|
+
if (escaped) {
|
|
638
|
+
escaped = false;
|
|
639
|
+
}
|
|
640
|
+
else if (char === '\\') {
|
|
641
|
+
escaped = true;
|
|
642
|
+
}
|
|
643
|
+
else if (char === '"') {
|
|
644
|
+
inString = false;
|
|
645
|
+
}
|
|
646
|
+
index += 1;
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
649
|
+
if (char === '"') {
|
|
650
|
+
inString = true;
|
|
651
|
+
output += char;
|
|
652
|
+
index += 1;
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
if (char === '/' && text[index + 1] === '/') {
|
|
656
|
+
while (index < text.length && text[index] !== '\n')
|
|
657
|
+
index += 1;
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
if (char === '/' && text[index + 1] === '*') {
|
|
661
|
+
index += 2;
|
|
662
|
+
while (index < text.length && !(text[index] === '*' && text[index + 1] === '/'))
|
|
663
|
+
index += 1;
|
|
664
|
+
index += 2;
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
667
|
+
output += char;
|
|
668
|
+
index += 1;
|
|
593
669
|
}
|
|
670
|
+
return output.replace(/,(\s*[}\]])/g, '$1');
|
|
594
671
|
}
|
|
595
672
|
function writeJsonObjectFs(path, value) {
|
|
596
673
|
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smoothbricks/nx-plugin",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.11",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"main": "./loader.js",
|
|
@@ -108,7 +108,7 @@
|
|
|
108
108
|
"typia": "14.0.2"
|
|
109
109
|
},
|
|
110
110
|
"devDependencies": {
|
|
111
|
-
"@smoothbricks/lmao": "0.3.
|
|
111
|
+
"@smoothbricks/lmao": "0.3.12",
|
|
112
112
|
"@smoothbricks/validation": "0.1.8"
|
|
113
113
|
}
|
|
114
114
|
}
|
package/src/index.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from 'bun:test';
|
|
2
|
-
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
@@ -1475,6 +1475,117 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
|
|
|
1475
1475
|
await workspace.cleanup();
|
|
1476
1476
|
}
|
|
1477
1477
|
});
|
|
1478
|
+
|
|
1479
|
+
it('never caches a declared deploy, and puts its build half in front of it', async () => {
|
|
1480
|
+
const workspace = await createWorkspace();
|
|
1481
|
+
const declared = {
|
|
1482
|
+
deploy: { executor: 'nx:run-commands', options: { command: 'smoo wrangler deploy-stage --stage={args.stage}' } },
|
|
1483
|
+
'deploy-build': { executor: 'nx:run-commands', options: { command: 'bun tooling/build-site.ts' } },
|
|
1484
|
+
};
|
|
1485
|
+
try {
|
|
1486
|
+
await workspace.write('packages/site/package.json', JSON.stringify({ name: 'site', nx: { targets: declared } }));
|
|
1487
|
+
const targets = await inferProjectTargets(workspace, 'packages/site/package.json');
|
|
1488
|
+
|
|
1489
|
+
const deploy = resolveDeclaredOverInferred(targets, declared, 'deploy');
|
|
1490
|
+
// A cache hit on deploy would mean "we once uploaded this hash", which a rollback falsifies
|
|
1491
|
+
// silently; the step has to run and read live state instead.
|
|
1492
|
+
expect(deploy?.cache).toBe(false);
|
|
1493
|
+
expect(deploy?.dependsOn).toEqual(['deploy-build']);
|
|
1494
|
+
expect(resolveDeclaredOverInferred(targets, declared, 'deploy-build')?.cache).toBe(true);
|
|
1495
|
+
} finally {
|
|
1496
|
+
await workspace.cleanup();
|
|
1497
|
+
}
|
|
1498
|
+
});
|
|
1499
|
+
|
|
1500
|
+
it('infers nothing for a project that declares no deploy', async () => {
|
|
1501
|
+
const workspace = await createWorkspace();
|
|
1502
|
+
try {
|
|
1503
|
+
await workspace.write('packages/lib/package.json', '{"name":"plain-lib"}\n');
|
|
1504
|
+
const targets = await inferProjectTargets(workspace, 'packages/lib/package.json');
|
|
1505
|
+
|
|
1506
|
+
expect(Object.keys(targets)).not.toContain('deploy');
|
|
1507
|
+
expect(Object.keys(targets)).not.toContain('deploy-build');
|
|
1508
|
+
} finally {
|
|
1509
|
+
await workspace.cleanup();
|
|
1510
|
+
}
|
|
1511
|
+
});
|
|
1512
|
+
|
|
1513
|
+
it('orders a three-project deploy chain through one run-many', async () => {
|
|
1514
|
+
const workspace = await createWorkspace();
|
|
1515
|
+
const root = workspace.context.workspaceRoot;
|
|
1516
|
+
const repositoryRoot = fileURLToPath(new URL('../../../', import.meta.url));
|
|
1517
|
+
try {
|
|
1518
|
+
await symlink(join(repositoryRoot, 'node_modules'), join(root, 'node_modules'), 'dir');
|
|
1519
|
+
await workspace.write('package.json', '{"name":"chain-workspace","private":true,"workspaces":["packages/*"]}\n');
|
|
1520
|
+
await workspace.write(
|
|
1521
|
+
'nx.json',
|
|
1522
|
+
JSON.stringify({
|
|
1523
|
+
plugins: [fileURLToPath(new URL('../dist/index.js', import.meta.url))],
|
|
1524
|
+
namedInputs: { default: ['{projectRoot}/**/*'] },
|
|
1525
|
+
}),
|
|
1526
|
+
);
|
|
1527
|
+
// c is deepest: a's deploy calls into b's, b's calls into c's. Only the edges are declared;
|
|
1528
|
+
// nothing here says "round one" or "round two", and no project knows the chain's depth.
|
|
1529
|
+
const chain: Record<string, string[]> = { a: ['b:deploy'], b: ['c:deploy'], c: [] };
|
|
1530
|
+
for (const [name, dependsOn] of Object.entries(chain)) {
|
|
1531
|
+
await workspace.write(
|
|
1532
|
+
`packages/${name}/package.json`,
|
|
1533
|
+
JSON.stringify({
|
|
1534
|
+
name,
|
|
1535
|
+
nx: {
|
|
1536
|
+
targets: {
|
|
1537
|
+
deploy: {
|
|
1538
|
+
executor: 'nx:run-commands',
|
|
1539
|
+
...(dependsOn.length > 0 ? { dependsOn: ['...', ...dependsOn] } : {}),
|
|
1540
|
+
// A real deploy command consumes the stage through `{args.stage}`; this fixture
|
|
1541
|
+
// records the order and nothing else, so it declines the forwarded flags.
|
|
1542
|
+
options: {
|
|
1543
|
+
command: `printf '%s\\n' ${name} >> ${join(root, 'deploy-order.txt')}`,
|
|
1544
|
+
forwardAllArgs: false,
|
|
1545
|
+
},
|
|
1546
|
+
},
|
|
1547
|
+
},
|
|
1548
|
+
},
|
|
1549
|
+
}),
|
|
1550
|
+
);
|
|
1551
|
+
}
|
|
1552
|
+
const child = Bun.spawn(
|
|
1553
|
+
[
|
|
1554
|
+
'bun',
|
|
1555
|
+
join(repositoryRoot, 'node_modules/.bin/nx'),
|
|
1556
|
+
'run-many',
|
|
1557
|
+
'-t',
|
|
1558
|
+
'deploy',
|
|
1559
|
+
'--projects=a,b,c',
|
|
1560
|
+
'--parallel=3',
|
|
1561
|
+
'--stage=staging',
|
|
1562
|
+
],
|
|
1563
|
+
{
|
|
1564
|
+
cwd: root,
|
|
1565
|
+
env: {
|
|
1566
|
+
...process.env,
|
|
1567
|
+
PATH: `${join(repositoryRoot, 'node_modules/.bin')}:${process.env.PATH ?? ''}`,
|
|
1568
|
+
NX_DAEMON: 'false',
|
|
1569
|
+
NX_ISOLATE_PLUGINS: 'false',
|
|
1570
|
+
NX_WORKSPACE_DATA_DIRECTORY: join(root, '.nx/workspace-data'),
|
|
1571
|
+
NX_CACHE_DIRECTORY: join(root, '.nx/cache'),
|
|
1572
|
+
},
|
|
1573
|
+
stdout: 'pipe',
|
|
1574
|
+
stderr: 'pipe',
|
|
1575
|
+
},
|
|
1576
|
+
);
|
|
1577
|
+
const [exitCode, stdout, stderr] = await Promise.all([
|
|
1578
|
+
child.exited,
|
|
1579
|
+
new Response(child.stdout).text(),
|
|
1580
|
+
new Response(child.stderr).text(),
|
|
1581
|
+
]);
|
|
1582
|
+
expect({ exitCode, output: stdout + stderr }).toMatchObject({ exitCode: 0 });
|
|
1583
|
+
const order = (await readFile(join(root, 'deploy-order.txt'), 'utf8')).trim().split('\n');
|
|
1584
|
+
expect(order).toEqual(['c', 'b', 'a']);
|
|
1585
|
+
} finally {
|
|
1586
|
+
await workspace.cleanup();
|
|
1587
|
+
}
|
|
1588
|
+
}, 120_000);
|
|
1478
1589
|
//#endregion
|
|
1479
1590
|
});
|
|
1480
1591
|
|
package/src/index.ts
CHANGED
|
@@ -44,6 +44,11 @@ import { PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
|
|
|
44
44
|
|
|
45
45
|
export { CARGO_TEST_COMPILE_TARGET };
|
|
46
46
|
|
|
47
|
+
/** Makes a version live and proves it answers; never cached. */
|
|
48
|
+
export const DEPLOY_TARGET = 'deploy';
|
|
49
|
+
/** The purely file-derived half a deploy needs built first; cached. */
|
|
50
|
+
export const DEPLOY_BUILD_TARGET = 'deploy-build';
|
|
51
|
+
|
|
47
52
|
const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
|
|
48
53
|
const TYPESCRIPT_TOOLCHAIN_INPUTS = [
|
|
49
54
|
'{workspaceRoot}/package.json',
|
|
@@ -179,8 +184,14 @@ const REPO_ROOT_CARGO_OUTPUT_INPUTS = [
|
|
|
179
184
|
'{workspaceRoot}/scripts/*.sh',
|
|
180
185
|
'!{workspaceRoot}/**/target/**',
|
|
181
186
|
];
|
|
187
|
+
// The environment half of a cargo task's identity. Beyond cargo/rustc's own
|
|
188
|
+
// variables, every build script that compiles C/C++ reads the Apple SDK
|
|
189
|
+
// (SDKROOT, DEVELOPER_DIR, the deployment targets), bindgen reads its libclang
|
|
190
|
+
// and extra clang args, cmake-rs forwards CMAKE_*, and zig-based cross links
|
|
191
|
+
// read ZIG*. An output linked against one sysroot must never hash equal to
|
|
192
|
+
// the same sources linked against another.
|
|
182
193
|
const CARGO_ENVIRONMENT_INPUT = {
|
|
183
|
-
runtime: `bun -e 'const fs = require("node:fs"); const path = require("node:path"); const home = process.env.CARGO_HOME || path.join(require("node:os").homedir(), ".cargo"); console.log(JSON.stringify({env: Object.entries(process.env).filter(([name]) => /^(?:CARGO_|RUST|NEXTEST_|CLIPPY_|CC(?:_|$)|CXX(?:_|$)|AR(?:_|$)|CFLAGS|CXXFLAGS|CPPFLAGS|LDFLAGS|PKG_CONFIG|TARGET_|HOST_)/.test(name)).sort(([a], [b]) => a.localeCompare(b)), config: ["config", "config.toml"].map(name => { const file = path.join(home, name); return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; })}));'`,
|
|
194
|
+
runtime: `bun -e 'const fs = require("node:fs"); const path = require("node:path"); const home = process.env.CARGO_HOME || path.join(require("node:os").homedir(), ".cargo"); console.log(JSON.stringify({env: Object.entries(process.env).filter(([name]) => /^(?:CARGO_|RUST|NEXTEST_|CLIPPY_|CC(?:_|$)|CXX(?:_|$)|AR(?:_|$)|CFLAGS|CXXFLAGS|CPPFLAGS|LDFLAGS|PKG_CONFIG|TARGET_|HOST_|SDKROOT$|DEVELOPER_DIR$|MACOSX_DEPLOYMENT_TARGET$|IPHONEOS_DEPLOYMENT_TARGET$|LIBCLANG_PATH$|BINDGEN_EXTRA_CLANG_ARGS|CMAKE_|ZIG)/.test(name)).sort(([a], [b]) => a.localeCompare(b)), config: ["config", "config.toml"].map(name => { const file = path.join(home, name); return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; })}));'`,
|
|
184
195
|
};
|
|
185
196
|
|
|
186
197
|
function cargoRuntimeInput(projectRoot: string, command: string): { runtime: string } {
|
|
@@ -1058,6 +1069,42 @@ async function createProjectTargets(
|
|
|
1058
1069
|
}
|
|
1059
1070
|
}
|
|
1060
1071
|
|
|
1072
|
+
// A deploy is never cached; the build half beside it always is.
|
|
1073
|
+
//
|
|
1074
|
+
// Nx's cache answers "did this exact input set already produce an output". A deploy's real
|
|
1075
|
+
// question is "is this exact version live", and the two agree only until someone rolls back.
|
|
1076
|
+
// After a rollback the workspace is unchanged, so the hash is unchanged, so a cached `deploy`
|
|
1077
|
+
// reports success while the previous version keeps serving. No input tuning repairs that: a
|
|
1078
|
+
// `runtime` input cannot even learn WHICH STAGE is being deployed. Nx hashes runtime inputs with
|
|
1079
|
+
// the env from `getTaskSpecificEnv`, which deliberately excludes the task coordinates; input
|
|
1080
|
+
// strings interpolate only `{workspaceRoot}`/`{projectRoot}`, never `{args.*}`; and overrides
|
|
1081
|
+
// are not forwarded to `dependsOn` dependencies, so an auxiliary task cannot carry the stage
|
|
1082
|
+
// either. (An executor's custom hasher is the single Nx API that does see `task.overrides`, if
|
|
1083
|
+
// hash-level participation is ever genuinely wanted.)
|
|
1084
|
+
//
|
|
1085
|
+
// So the target is split along the line the question actually falls on. `deploy-build` is purely
|
|
1086
|
+
// file-derived — build the artifact and whatever the build registers — and caches honestly.
|
|
1087
|
+
// `deploy` reads live state every run and no-ops when live already equals the desired tag, which
|
|
1088
|
+
// costs two Cloudflare calls and makes a redundant deploy provably free rather than assumed
|
|
1089
|
+
// free. That is what lets ordering be an ordinary `dependsOn: ["<other>:deploy"]` edge at any
|
|
1090
|
+
// depth, and it is why such an edge must point at `deploy` and not at `deploy-build`: a
|
|
1091
|
+
// dependent has to re-check liveness, not inherit someone else's cache hit.
|
|
1092
|
+
//
|
|
1093
|
+
// Both are bases for a package-local declaration to land on, per the merge rules above: a
|
|
1094
|
+
// declaration naming `cache`, `inputs` or `dependsOn` REPLACES what is set here, so a project
|
|
1095
|
+
// adding a cross-project edge writes `"dependsOn": ["...", "backend:deploy"]` to keep the
|
|
1096
|
+
// `deploy-build` edge this adds.
|
|
1097
|
+
if (DEPLOY_BUILD_TARGET in declaredTargets) {
|
|
1098
|
+
targets[DEPLOY_BUILD_TARGET] = { cache: true };
|
|
1099
|
+
}
|
|
1100
|
+
if (DEPLOY_TARGET in declaredTargets) {
|
|
1101
|
+
targets[DEPLOY_TARGET] = {
|
|
1102
|
+
cache: false,
|
|
1103
|
+
outputs: [],
|
|
1104
|
+
...(DEPLOY_BUILD_TARGET in declaredTargets ? { dependsOn: [DEPLOY_BUILD_TARGET] } : {}),
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1061
1108
|
// No `outputs`, deliberately: this aggregate runs no command, so every file
|
|
1062
1109
|
// under dist belongs to the concrete target that emitted it. Claiming
|
|
1063
1110
|
// `{projectRoot}/dist` here would cache the children's bytes a second time
|
|
@@ -199,6 +199,33 @@ describe('applyTypecheckTestDefaults', () => {
|
|
|
199
199
|
expect(references).toContainEqual({ path: './tsconfig.lib.json' });
|
|
200
200
|
});
|
|
201
201
|
|
|
202
|
+
it('fills compiler options the test program left out and keeps the ones it declared', () => {
|
|
203
|
+
// A Bun-only test program declaring es2023 says something the library cannot
|
|
204
|
+
// know: its runtime has change-array-by-copy while the library's output ships
|
|
205
|
+
// to node, workerd and browsers. Overwriting it made `toSorted` a type error
|
|
206
|
+
// in a suite that calls it, and every `smoo monorepo update` reintroduced it.
|
|
207
|
+
const declared: Record<string, unknown> = {
|
|
208
|
+
compilerOptions: { lib: ['es2023'], types: ['bun'], noEmit: true },
|
|
209
|
+
};
|
|
210
|
+
applyTypecheckTestDefaults(declared, {
|
|
211
|
+
testRunners: new Set(['bun'] as const),
|
|
212
|
+
referencePaths: [],
|
|
213
|
+
libCompilerOptions: { lib: ['es2022'], module: 'preserve' },
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
const declaredOptions = expectRecord(declared.compilerOptions);
|
|
217
|
+
expect(declaredOptions.lib).toEqual(['es2023']);
|
|
218
|
+
expect(declaredOptions.module).toBe('preserve');
|
|
219
|
+
|
|
220
|
+
const silent: Record<string, unknown> = { compilerOptions: {} };
|
|
221
|
+
applyTypecheckTestDefaults(silent, {
|
|
222
|
+
testRunners: new Set(['bun'] as const),
|
|
223
|
+
referencePaths: [],
|
|
224
|
+
libCompilerOptions: { lib: ['es2022'] },
|
|
225
|
+
});
|
|
226
|
+
expect(expectRecord(silent.compilerOptions).lib).toEqual(['es2022']);
|
|
227
|
+
});
|
|
228
|
+
|
|
202
229
|
it('uses custom extends from lib tsconfig', () => {
|
|
203
230
|
const tsconfigTest: Record<string, unknown> = {};
|
|
204
231
|
applyTypecheckTestDefaults(tsconfigTest, {
|
|
@@ -491,6 +518,42 @@ describe('typecheck test policy (Tree)', () => {
|
|
|
491
518
|
// ---------------------------------------------------------------------------
|
|
492
519
|
|
|
493
520
|
describe('typecheck test policy', () => {
|
|
521
|
+
it('reads a documented tsconfig.test.json instead of treating it as absent', async () => {
|
|
522
|
+
// tsconfig files are JSONC: TypeScript permits comments. A plain
|
|
523
|
+
// JSON.parse failed, the reader answered "absent", and the policy
|
|
524
|
+
// regenerated the file — deleting a declared `lib`, an `exclude`, extra
|
|
525
|
+
// `include` globs and every comment explaining them. That is how a
|
|
526
|
+
// Bun-only test program loses es2023 and `toSorted` becomes a type error.
|
|
527
|
+
const root = await mkdtemp(join(tmpdir(), 'smoo-typecheck-test-jsonc-'));
|
|
528
|
+
try {
|
|
529
|
+
await writeJsonFs(join(root, 'package.json'), { workspaces: ['packages/*'] });
|
|
530
|
+
await writeJsonFs(join(root, 'packages/app/package.json'), {
|
|
531
|
+
name: '@scope/app',
|
|
532
|
+
scripts: { test: 'bun test' },
|
|
533
|
+
});
|
|
534
|
+
await mkdir(join(root, 'packages/app'), { recursive: true });
|
|
535
|
+
const documented = [
|
|
536
|
+
'{',
|
|
537
|
+
' "extends": "../../tsconfig.base.json",',
|
|
538
|
+
' // WHY es2023: this program is Bun-only and JSC has change-array-by-copy.',
|
|
539
|
+
' "compilerOptions": { "lib": ["es2023"], "types": ["bun"], "noEmit": true, "composite": false,',
|
|
540
|
+
' "declaration": false, "declarationMap": false, "emitDeclarationOnly": false },',
|
|
541
|
+
' "include": ["src/**/*.test.ts", "src/**/*.spec.ts", "src/**/__tests__/**/*.ts",',
|
|
542
|
+
' "src/**/__tests__/**/*.tsx", "src/test-suite-tracer.ts", "tests/**/*.ts"],',
|
|
543
|
+
' "exclude": ["src/lib/ts-plugin.ts"]',
|
|
544
|
+
'}',
|
|
545
|
+
'',
|
|
546
|
+
].join('\n');
|
|
547
|
+
await writeFile(join(root, 'packages/app/tsconfig.test.json'), documented);
|
|
548
|
+
|
|
549
|
+
// Nothing the policy wants is missing, so it must not rewrite the file.
|
|
550
|
+
expect(applyTypecheckTestPolicy(root)).toBe(false);
|
|
551
|
+
expect(await readFile(join(root, 'packages/app/tsconfig.test.json'), 'utf8')).toBe(documented);
|
|
552
|
+
} finally {
|
|
553
|
+
await rm(root, { recursive: true, force: true });
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
|
|
494
557
|
it('creates tsconfig.test.json for bun test package', async () => {
|
|
495
558
|
const root = await mkdtemp(join(tmpdir(), 'smoo-typecheck-test-policy-'));
|
|
496
559
|
try {
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { join, relative } from 'node:path';
|
|
3
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
4
3
|
import type { Tree } from 'nx/src/devkit-exports.js';
|
|
5
4
|
import { getProjects, readJson, readProjectConfiguration, updateJson, writeJson } from 'nx/src/devkit-exports.js';
|
|
6
5
|
|
|
@@ -167,13 +166,15 @@ export function applyTypecheckTestDefaults(
|
|
|
167
166
|
|
|
168
167
|
const compilerOptions = getOrCreateRecord(tsconfigTest, 'compilerOptions');
|
|
169
168
|
|
|
170
|
-
//
|
|
169
|
+
// Fill from the lib tsconfig only what the test program has NOT declared. A
|
|
170
|
+
// test program that names its own `lib` is stating a fact the lib program
|
|
171
|
+
// cannot know: it runs on one runtime (Bun's JSC understands
|
|
172
|
+
// change-array-by-copy) while the library's output has to run on the shipping
|
|
173
|
+
// floor. Overwriting it turned `toSorted` into a type error in a suite that
|
|
174
|
+
// calls it every day, and it came back on every `smoo monorepo update`.
|
|
171
175
|
if (options.libCompilerOptions) {
|
|
172
176
|
for (const key of ['baseUrl', 'module', 'moduleResolution', 'jsx', 'lib']) {
|
|
173
|
-
if (
|
|
174
|
-
Object.hasOwn(options.libCompilerOptions, key) &&
|
|
175
|
-
!isDeepStrictEqual(compilerOptions[key], options.libCompilerOptions[key])
|
|
176
|
-
) {
|
|
177
|
+
if (Object.hasOwn(options.libCompilerOptions, key) && !Object.hasOwn(compilerOptions, key)) {
|
|
177
178
|
compilerOptions[key] = options.libCompilerOptions[key];
|
|
178
179
|
changed = true;
|
|
179
180
|
}
|
|
@@ -458,6 +459,16 @@ export function applyTypecheckTestPolicy(root: string): boolean {
|
|
|
458
459
|
}) || fileChanged;
|
|
459
460
|
|
|
460
461
|
if (fileChanged) {
|
|
462
|
+
// A documented tsconfig cannot survive JSON.stringify, so the policy says
|
|
463
|
+
// what it wants instead of quietly deleting the reasoning. The check
|
|
464
|
+
// half (checkTypecheckTestPolicy) reports the same drift, so CI still
|
|
465
|
+
// fails until a human applies it.
|
|
466
|
+
if (existsSync(tsconfigTestPath) && hasJsonComments(readFileSync(tsconfigTestPath, 'utf8'))) {
|
|
467
|
+
console.error(
|
|
468
|
+
`refused ${packagePath}/tsconfig.test.json carries comments a rewrite would delete; apply the policy by hand`,
|
|
469
|
+
);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
461
472
|
writeJsonObjectFs(tsconfigTestPath, tsconfigTest);
|
|
462
473
|
changed = true;
|
|
463
474
|
}
|
|
@@ -687,16 +698,80 @@ function collectTsconfigTestReferencePaths(
|
|
|
687
698
|
return paths;
|
|
688
699
|
}
|
|
689
700
|
|
|
701
|
+
/**
|
|
702
|
+
* Read a tsconfig or package.json. tsconfig files are JSONC — TypeScript
|
|
703
|
+
* permits comments and trailing commas — so a plain `JSON.parse` fails on a
|
|
704
|
+
* documented one. Returning null there meant "file absent", and the caller
|
|
705
|
+
* regenerated it from scratch: a `lib` the test program declared, an
|
|
706
|
+
* `exclude`, an extra `include` glob and every comment explaining them
|
|
707
|
+
* disappeared on the next `smoo monorepo update`. Comments are stripped for
|
|
708
|
+
* parsing only; a caller that intends to write back must decide what to do
|
|
709
|
+
* about them (see writeJsonObjectFs's caller).
|
|
710
|
+
*/
|
|
690
711
|
function readJsonObject(path: string): Record<string, unknown> | null {
|
|
691
712
|
if (!existsSync(path)) {
|
|
692
713
|
return null;
|
|
693
714
|
}
|
|
715
|
+
const text = readFileSync(path, 'utf8');
|
|
694
716
|
try {
|
|
695
|
-
const parsed: unknown = JSON.parse(
|
|
717
|
+
const parsed: unknown = JSON.parse(stripJsonComments(text));
|
|
696
718
|
return isRecord(parsed) ? parsed : null;
|
|
697
|
-
} catch {
|
|
698
|
-
|
|
719
|
+
} catch (error) {
|
|
720
|
+
// A file that exists but cannot be parsed is a configuration error, not an
|
|
721
|
+
// invitation to overwrite it.
|
|
722
|
+
throw new Error(`${path} is not valid JSON/JSONC: ${error instanceof Error ? error.message : String(error)}`);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** Whether the file carries comments a rewrite would destroy. */
|
|
727
|
+
function hasJsonComments(text: string): boolean {
|
|
728
|
+
return stripJsonComments(text) !== text;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* Remove `//` and block comments outside string literals, and trailing commas.
|
|
733
|
+
* Small on purpose: the alternative is a JSONC dependency in a plugin whose
|
|
734
|
+
* only JSONC inputs are tsconfig files.
|
|
735
|
+
*/
|
|
736
|
+
function stripJsonComments(text: string): string {
|
|
737
|
+
let output = '';
|
|
738
|
+
let inString = false;
|
|
739
|
+
let escaped = false;
|
|
740
|
+
let index = 0;
|
|
741
|
+
while (index < text.length) {
|
|
742
|
+
const char = text[index];
|
|
743
|
+
if (inString) {
|
|
744
|
+
output += char;
|
|
745
|
+
if (escaped) {
|
|
746
|
+
escaped = false;
|
|
747
|
+
} else if (char === '\\') {
|
|
748
|
+
escaped = true;
|
|
749
|
+
} else if (char === '"') {
|
|
750
|
+
inString = false;
|
|
751
|
+
}
|
|
752
|
+
index += 1;
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
if (char === '"') {
|
|
756
|
+
inString = true;
|
|
757
|
+
output += char;
|
|
758
|
+
index += 1;
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
if (char === '/' && text[index + 1] === '/') {
|
|
762
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
765
|
+
if (char === '/' && text[index + 1] === '*') {
|
|
766
|
+
index += 2;
|
|
767
|
+
while (index < text.length && !(text[index] === '*' && text[index + 1] === '/')) index += 1;
|
|
768
|
+
index += 2;
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
output += char;
|
|
772
|
+
index += 1;
|
|
699
773
|
}
|
|
774
|
+
return output.replace(/,(\s*[}\]])/g, '$1');
|
|
700
775
|
}
|
|
701
776
|
|
|
702
777
|
function writeJsonObjectFs(path: string, value: Record<string, unknown>): void {
|