@bleedingdev/modern-js-server-utils 3.9.0-ultramodern.17 → 3.9.0-ultramodern.19

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,140 @@
1
+ import __rslib_shim_module__ from "node:module";
2
+ const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(/*#__PURE__*/ (()=>import.meta.url)());
3
+ import { fs } from "@modern-js/utils";
4
+ import { spawn } from "child_process";
5
+ import path from "path";
6
+ import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
7
+ import { dirname as __rspack_dirname } from "node:path";
8
+ var __rspack_import_meta_dirname__ = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
9
+ let resolvedConfigCount = 0;
10
+ const createResolvedTsgoConfig = async (appDirectory, tsconfigPath, sourceDirs, tsgoBinPath, excludeFiles = [])=>{
11
+ const tsconfigDir = path.dirname(tsconfigPath);
12
+ const output = await runTsgo(tsgoBinPath, [
13
+ '--showConfig',
14
+ '-p',
15
+ tsconfigPath
16
+ ], {
17
+ cwd: tsconfigDir
18
+ });
19
+ const config = JSON.parse(output.stdout);
20
+ config.compilerOptions ??= {};
21
+ const options = config.compilerOptions;
22
+ options.rootDir = appDirectory;
23
+ options.composite = false;
24
+ options.declarationMap = false;
25
+ options.incremental = false;
26
+ options.noEmit = true !== options.declaration;
27
+ options.jsx ??= 'react-jsx';
28
+ delete options.emitDeclarationOnly;
29
+ delete options.outDir;
30
+ delete options.tsBuildInfoFile;
31
+ config.files = filterSourceFiles(tsconfigDir, sourceDirs, config.files, excludeFiles);
32
+ delete config.include;
33
+ delete config.references;
34
+ if (void 0 !== options.baseUrl) {
35
+ const baseUrl = path.resolve(tsconfigDir, options.baseUrl);
36
+ if (options.paths) options.paths = Object.fromEntries(Object.entries(options.paths).map(([key, targets])=>[
37
+ key,
38
+ targets.map((target)=>{
39
+ const relative = path.relative(tsconfigDir, path.resolve(baseUrl, target)).split(path.sep).join(path.posix.sep);
40
+ return relative.startsWith('.') ? relative : `./${relative}`;
41
+ })
42
+ ]));
43
+ delete options.baseUrl;
44
+ }
45
+ if ([
46
+ 'node',
47
+ 'node10'
48
+ ].includes(String(options.moduleResolution).toLowerCase())) delete options.moduleResolution;
49
+ const resolvedConfigPath = path.join(tsconfigDir, `.tsgo.${process.pid}.${resolvedConfigCount++}.resolved.json`);
50
+ await fs.writeFile(resolvedConfigPath, JSON.stringify(config, null, 2));
51
+ return {
52
+ config,
53
+ resolvedConfigPath
54
+ };
55
+ };
56
+ const toPosix = (file)=>file.split(path.sep).join(path.posix.sep);
57
+ const filterSourceFiles = (tsconfigDir, sourceDirs, files = [], excludeFiles = [])=>{
58
+ const sourcePosixPaths = sourceDirs.map(toPosix);
59
+ const excludedPaths = new Set(excludeFiles.map((file)=>toPosix(path.normalize(file))));
60
+ return files.filter((fileName)=>{
61
+ const absoluteFileName = toPosix(path.resolve(tsconfigDir, fileName));
62
+ if (excludedPaths.has(absoluteFileName)) return false;
63
+ return fileName.endsWith('.d.ts') || sourcePosixPaths.some((sourceDir)=>absoluteFileName.includes(sourceDir));
64
+ });
65
+ };
66
+ const runTsgo = (tsgoBinPath, args, options)=>new Promise((resolve, reject)=>{
67
+ const child = spawn(process.execPath, [
68
+ tsgoBinPath,
69
+ ...args
70
+ ], {
71
+ cwd: options.cwd,
72
+ stdio: [
73
+ 'ignore',
74
+ 'pipe',
75
+ 'pipe'
76
+ ]
77
+ });
78
+ let stdout = '';
79
+ let stderr = '';
80
+ child.stdout.on('data', (data)=>{
81
+ stdout += data;
82
+ });
83
+ child.stderr.on('data', (data)=>{
84
+ stderr += data;
85
+ });
86
+ child.on('error', reject);
87
+ child.on('close', (code)=>{
88
+ const result = {
89
+ stdout,
90
+ stderr,
91
+ code: code ?? 1
92
+ };
93
+ if (false !== options.reject && 0 !== result.code) return void reject(new Error(stderr || stdout || `tsgo exited with ${result.code}`));
94
+ resolve(result);
95
+ });
96
+ });
97
+ const getTsgoBinEntry = (pkg)=>{
98
+ if ('string' == typeof pkg.bin) return pkg.bin;
99
+ return pkg.bin?.tsc ?? pkg.bin?.tsgo;
100
+ };
101
+ const TSGO_PACKAGES = [
102
+ "@typescript/native",
103
+ "@typescript/native-preview"
104
+ ];
105
+ const resolveTsgoPackage = (resolvePaths)=>{
106
+ for (const name of TSGO_PACKAGES)try {
107
+ const pkgPath = require.resolve(`${name}/package.json`, {
108
+ paths: resolvePaths
109
+ });
110
+ return {
111
+ name,
112
+ pkgPath
113
+ };
114
+ } catch {}
115
+ throw new Error('tsgo could not be found! Please install "@typescript/native" (or legacy "@typescript/native-preview") in your project to type-check BFF/server code.');
116
+ };
117
+ const getTsgoBinPath = (appDirectory, resolvePaths = [
118
+ appDirectory,
119
+ __rspack_import_meta_dirname__
120
+ ])=>{
121
+ const { pkgPath } = resolveTsgoPackage(resolvePaths);
122
+ const pkgDir = path.dirname(pkgPath);
123
+ const pkg = require(pkgPath);
124
+ const declaredBinEntry = getTsgoBinEntry(pkg);
125
+ const candidates = [
126
+ declaredBinEntry ? path.resolve(pkgDir, declaredBinEntry) : void 0,
127
+ path.join(pkgDir, 'bin/tsgo.js')
128
+ ].filter((candidate)=>Boolean(candidate));
129
+ return candidates.find((candidate)=>fs.existsSync(candidate)) ?? candidates[0];
130
+ };
131
+ const getTsgoModulePath = (appDirectory, resolvePaths = [
132
+ appDirectory,
133
+ __rspack_import_meta_dirname__
134
+ ])=>{
135
+ const { name } = resolveTsgoPackage(resolvePaths);
136
+ return require.resolve(name, {
137
+ paths: resolvePaths
138
+ });
139
+ };
140
+ export { createResolvedTsgoConfig, getTsgoBinPath, getTsgoModulePath, runTsgo };
@@ -6,9 +6,6 @@ export interface Pattern {
6
6
  }
7
7
  export interface IConfig {
8
8
  alias?: SourceNormalizedConfig['alias'];
9
- server?: {
10
- compiler?: 'typescript';
11
- };
12
9
  }
13
10
  export interface CompileOptions {
14
11
  sourceDirs: string[];
@@ -0,0 +1,10 @@
1
+ import type { CompileOptions, IConfig } from '../common/index.js';
2
+ /**
3
+ * Compile server sources file-by-file with Rslib (bundleless, Node target).
4
+ * Rspack resolves `source.alias` and tsconfig `paths` while it emits, so the
5
+ * output specifiers and source maps are right the first time. TS-Go only
6
+ * type-checks, and emits declarations when the app's tsconfig asks for them.
7
+ */
8
+ export declare const compileServerSources: (appDirectory: string, config: IConfig, options: CompileOptions & {
9
+ tsconfigPath: string;
10
+ }) => Promise<void>;
@@ -0,0 +1,49 @@
1
+ type TsgoConfig = {
2
+ compilerOptions?: {
3
+ allowJs?: boolean;
4
+ baseUrl?: string;
5
+ composite?: boolean;
6
+ declaration?: boolean;
7
+ declarationMap?: boolean;
8
+ emitDeclarationOnly?: boolean;
9
+ experimentalDecorators?: boolean;
10
+ incremental?: boolean;
11
+ jsx?: string;
12
+ moduleResolution?: string;
13
+ noEmit?: boolean;
14
+ noEmitOnError?: boolean;
15
+ outDir?: string;
16
+ paths?: Record<string, string[]>;
17
+ rootDir?: string;
18
+ tsBuildInfoFile?: string;
19
+ };
20
+ files?: string[];
21
+ include?: string[];
22
+ references?: Array<{
23
+ path: string;
24
+ }>;
25
+ };
26
+ /**
27
+ * Write a one-shot tsconfig for type-checking (and, when the app asks for
28
+ * declarations, declaration emit) of exactly the server source directories.
29
+ * JavaScript is emitted by Rslib, so nothing here shapes runtime output.
30
+ */
31
+ export declare const createResolvedTsgoConfig: (appDirectory: string, tsconfigPath: string, sourceDirs: string[], tsgoBinPath: string, excludeFiles?: string[]) => Promise<{
32
+ config: TsgoConfig;
33
+ resolvedConfigPath: string;
34
+ }>;
35
+ export declare const runTsgo: (tsgoBinPath: string, args: string[], options: {
36
+ cwd: string;
37
+ reject?: boolean;
38
+ }) => Promise<{
39
+ stdout: string;
40
+ stderr: string;
41
+ code: number;
42
+ }>;
43
+ export declare const getTsgoBinPath: (appDirectory: string, resolvePaths?: string[]) => string;
44
+ /**
45
+ * The TS-Go package entry that Rslib's declaration emitter loads to read the
46
+ * compiler version and locate its executable.
47
+ */
48
+ export declare const getTsgoModulePath: (appDirectory: string, resolvePaths?: string[]) => string;
49
+ export {};
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "modern",
18
18
  "modern.js"
19
19
  ],
20
- "version": "3.9.0-ultramodern.17",
20
+ "version": "3.9.0-ultramodern.19",
21
21
  "types": "./dist/types/index.d.ts",
22
22
  "main": "./dist/cjs/index.js",
23
23
  "exports": {
@@ -38,13 +38,12 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.0-ultramodern.17",
42
- "@swc/core": "1.16.2",
41
+ "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.0-ultramodern.19",
42
+ "@rslib/core": "1.0.2",
43
43
  "@swc/helpers": "^0.5.23"
44
44
  },
45
45
  "devDependencies": {
46
- "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.9.0-ultramodern.17",
47
- "@rslib/core": "1.0.2",
46
+ "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.9.0-ultramodern.19",
48
47
  "@scripts/rstest-config": "2.66.0",
49
48
  "@types/node": "^26.6.2",
50
49
  "@typescript/native-preview": "7.0.0-dev.20260707.2"
@@ -64,6 +63,6 @@
64
63
  "scripts": {
65
64
  "dev": "rslib build --watch",
66
65
  "build": "rslib build",
67
- "test": "rstest --passWithNoTests"
66
+ "test": "rstest"
68
67
  }
69
68
  }
@@ -1,175 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.d = (exports1, getters, values)=>{
5
- var define = (defs, kind)=>{
6
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
- enumerable: true,
8
- [kind]: defs[key]
9
- });
10
- };
11
- define(getters, "get");
12
- define(values, "value");
13
- };
14
- })();
15
- (()=>{
16
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
- })();
18
- (()=>{
19
- __webpack_require__.r = (exports1)=>{
20
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
- value: 'Module'
22
- });
23
- Object.defineProperty(exports1, '__esModule', {
24
- value: true
25
- });
26
- };
27
- })();
28
- var __webpack_exports__ = {};
29
- __webpack_require__.r(__webpack_exports__);
30
- __webpack_require__.d(__webpack_exports__, {
31
- assertNoNativeModuleOutputCollision: ()=>assertNoNativeModuleOutputCollision,
32
- rewriteImportSpecifiers: ()=>rewriteImportSpecifiers
33
- });
34
- const core_namespaceObject = require("@swc/core");
35
- const assertNoNativeModuleOutputCollision = (sourceFile, fileExists)=>{
36
- const rawModuleFile = sourceFile.endsWith('.mts') ? `${sourceFile.slice(0, -4)}.mjs` : sourceFile.endsWith('.cts') ? `${sourceFile.slice(0, -4)}.cjs` : void 0;
37
- if (rawModuleFile && fileExists(rawModuleFile)) throw new Error(`Native module sources collide: "${sourceFile}" and "${rawModuleFile}" publish the same output.`);
38
- };
39
- const isObjectRecord = (value)=>'object' == typeof value && null !== value;
40
- const isAstNode = (value)=>isObjectRecord(value) && 'string' == typeof value.type;
41
- const isStringLiteral = (value)=>isAstNode(value) && 'StringLiteral' === value.type && 'string' == typeof value.value && 'object' == typeof value.span && null !== value.span && 'number' == typeof value.span.start && 'number' == typeof value.span.end;
42
- const getCallSpecifier = (node)=>{
43
- if ('CallExpression' !== node.type || !Array.isArray(node.arguments)) return;
44
- const callee = node.callee;
45
- const isDynamicImport = isAstNode(callee) && 'Import' === callee.type;
46
- const isCommonJsRequire = isAstNode(callee) && 'Identifier' === callee.type && 'require' === callee.value;
47
- if (!isDynamicImport && !isCommonJsRequire) return;
48
- const firstArgument = node.arguments[0];
49
- if (!isObjectRecord(firstArgument)) return;
50
- return isStringLiteral(firstArgument.expression) ? firstArgument.expression : void 0;
51
- };
52
- const collectSpecifierLiterals = (content)=>{
53
- const parserOptions = {
54
- decorators: true,
55
- syntax: "typescript",
56
- target: 'esnext'
57
- };
58
- let program;
59
- try {
60
- program = (0, core_namespaceObject.parseSync)(content, parserOptions);
61
- } catch (typescriptError) {
62
- try {
63
- program = (0, core_namespaceObject.parseSync)(content, {
64
- ...parserOptions,
65
- tsx: true
66
- });
67
- } catch {
68
- throw typescriptError;
69
- }
70
- }
71
- const literals = [];
72
- const seenSpans = new Set();
73
- const add = (value)=>{
74
- if (!isStringLiteral(value)) return;
75
- const spanKey = `${value.span.start}:${value.span.end}`;
76
- if (!seenSpans.has(spanKey)) {
77
- seenSpans.add(spanKey);
78
- literals.push(value);
79
- }
80
- };
81
- const visit = (value)=>{
82
- if (Array.isArray(value)) return void value.forEach(visit);
83
- if (!isObjectRecord(value)) return;
84
- if (isAstNode(value)) switch(value.type){
85
- case 'ImportDeclaration':
86
- case 'ExportAllDeclaration':
87
- case 'ExportNamedDeclaration':
88
- add(value.source);
89
- break;
90
- case 'TsImportType':
91
- add(value.argument);
92
- break;
93
- case 'TsExternalModuleReference':
94
- add(value.expression);
95
- break;
96
- case 'CallExpression':
97
- add(getCallSpecifier(value));
98
- break;
99
- }
100
- for (const [key, child] of Object.entries(value))if ('span' !== key) visit(child);
101
- };
102
- visit(program);
103
- return literals.sort((left, right)=>left.span.start - right.span.start);
104
- };
105
- const mapUtf8ByteOffsets = (content, byteOffsets)=>{
106
- const pending = new Set(byteOffsets);
107
- const result = new Map();
108
- let byteOffset = 0;
109
- let stringOffset = 0;
110
- while(stringOffset <= content.length && pending.size > 0){
111
- if (pending.delete(byteOffset)) result.set(byteOffset, stringOffset);
112
- if (stringOffset === content.length) break;
113
- const codePoint = content.codePointAt(stringOffset);
114
- if (void 0 === codePoint) break;
115
- const character = String.fromCodePoint(codePoint);
116
- byteOffset += Buffer.byteLength(character);
117
- stringOffset += character.length;
118
- }
119
- if (pending.size > 0) throw new Error('SWC returned an import specifier span outside its source');
120
- return result;
121
- };
122
- const scanSpecifiers = (content)=>{
123
- const literals = collectSpecifierLiterals(content);
124
- const byteOffsets = literals.flatMap((literal)=>[
125
- literal.span.start,
126
- literal.span.end - 2
127
- ]);
128
- const stringOffsets = mapUtf8ByteOffsets(content, byteOffsets);
129
- return literals.map((literal)=>{
130
- const start = stringOffsets.get(literal.span.start);
131
- const end = stringOffsets.get(literal.span.end - 2);
132
- if (void 0 === start || void 0 === end) throw new Error('Could not locate an SWC import specifier in its source');
133
- return {
134
- start,
135
- end,
136
- value: content.slice(start, end)
137
- };
138
- });
139
- };
140
- const rewriteImportSpecifiers = (content, rewrite)=>{
141
- const specifiers = scanSpecifiers(content);
142
- if (0 === specifiers.length) return {
143
- content,
144
- changed: false
145
- };
146
- let result = '';
147
- let cursor = 0;
148
- let changed = false;
149
- for (const specifier of specifiers){
150
- if (specifier.value.includes('\\')) continue;
151
- const next = rewrite(specifier.value);
152
- if (void 0 !== next && next !== specifier.value) {
153
- changed = true;
154
- result += content.slice(cursor, specifier.start) + next;
155
- cursor = specifier.end;
156
- }
157
- }
158
- if (!changed) return {
159
- content,
160
- changed: false
161
- };
162
- return {
163
- content: result + content.slice(cursor),
164
- changed: true
165
- };
166
- };
167
- exports.assertNoNativeModuleOutputCollision = __webpack_exports__.assertNoNativeModuleOutputCollision;
168
- exports.rewriteImportSpecifiers = __webpack_exports__.rewriteImportSpecifiers;
169
- for(var __rspack_i in __webpack_exports__)if (-1 === [
170
- "assertNoNativeModuleOutputCollision",
171
- "rewriteImportSpecifiers"
172
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
173
- Object.defineProperty(exports, '__esModule', {
174
- value: true
175
- });