soma-core 2.1.1 → 2.1.3

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.
@@ -1,10 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import createJiti from 'jiti';
4
3
  import type { IService } from './IService';
5
4
  import { resolveServiceFilePath } from './service-path';
6
- import { getSomaAssetSources } from '../host/source-packages';
7
- import { resolveServerOnlyEmpty } from '../host/host-assembly';
5
+ import { getSomaAssetSources, getSomaHostSourceRoot } from '../host/source-packages';
6
+ import { ensureNodeServerOnlyInterop, getJitiFactory } from '../host/host-assembly';
8
7
 
9
8
  function isService(obj: unknown): obj is IService {
10
9
  if (!obj || typeof obj !== 'object') return false;
@@ -13,22 +12,24 @@ function isService(obj: unknown): obj is IService {
13
12
  }
14
13
 
15
14
  function getCoreDir(): string {
16
- // soma-core 根目录(route 运行于 next dev/build,cwd 即 soma-core)
15
+ // soma-core 根目录(route 运行于 next dev/build,cwd 即工作区,其下有 core)
17
16
  return path.resolve(process.cwd(), 'core');
18
17
  }
19
18
 
20
- let jitiLoader: ReturnType<typeof createJiti> | null = null;
19
+ let jitiLoader: ((file: string) => unknown) | null = null;
21
20
  let jitiHostDir: string | null = null;
22
21
  const instanceCache = new Map<string, IService>();
23
22
 
24
- function getJiti(hostDir: string): ReturnType<typeof createJiti> {
23
+ function getJiti(hostDir: string): (file: string) => unknown {
25
24
  if (!jitiLoader || jitiHostDir !== hostDir) {
26
- const serverOnlyEmpty = resolveServerOnlyEmpty();
27
- jitiLoader = createJiti(import.meta.url, {
25
+ const serverOnlyEmpty = ensureNodeServerOnlyInterop(hostDir);
26
+ const createJiti = getJitiFactory(hostDir);
27
+ const hostSourceRoot = getSomaHostSourceRoot(hostDir);
28
+ jitiLoader = createJiti(path.resolve(hostDir, 'package.json'), {
28
29
  interopDefault: true,
29
30
  alias: {
30
31
  '@core': getCoreDir(),
31
- '@soma-host': hostDir,
32
+ '@soma-host': hostSourceRoot,
32
33
  ...(serverOnlyEmpty !== undefined ? { 'server-only': serverOnlyEmpty } : {}),
33
34
  },
34
35
  });
@@ -41,6 +42,7 @@ function getJiti(hostDir: string): ReturnType<typeof createJiti> {
41
42
  * 按约定从宿主 api/service/ 加载 IService 实例(运行时读盘,无需手写 registry)。
42
43
  */
43
44
  export function loadHostService(segments: string[]): IService | null {
45
+ if (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge') return null;
44
46
  const hostDir = process.env.SOMA_HOST_DIR;
45
47
  if (!hostDir) return null;
46
48
 
@@ -9,10 +9,48 @@
9
9
  // 不变式:形状不对当场抛(半套装配比没有更难查);同一应用根只加载一次(进程内缓存)。
10
10
 
11
11
  import fs from 'node:fs';
12
- import { createRequire } from 'node:module';
12
+ import nodeModule from 'node:module';
13
13
  import path from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
- import createJiti from 'jiti';
15
+
16
+ export type JitiFactory = (id: string, opts?: unknown) => (file: string) => unknown;
17
+
18
+ // 绕过 Webpack CommonJsImportsParserPlugin 对字面量 createRequire 的静态拦截(Webpack 会把字面量调用抹成 undefined)
19
+ const CREATE_REQUIRE_KEY = 'createRequire' as const;
20
+ const RESOLVE_FILENAME_KEY = '_resolveFilename' as const;
21
+ const SERVER_ONLY_HOOK_KEY = Symbol.for('soma.core.serverOnlyNodeHook');
22
+
23
+ export function createNodeRequire(anchorDir?: string): NodeRequire {
24
+ const createReq = (nodeModule as unknown as Record<string, (id: string) => NodeRequire>)[CREATE_REQUIRE_KEY];
25
+ const anchor = anchorDir
26
+ ? path.resolve(anchorDir, 'package.json')
27
+ : typeof import.meta?.url === 'string' && import.meta.url.startsWith('file:')
28
+ ? import.meta.url
29
+ : path.resolve(process.cwd(), 'package.json');
30
+ return createReq(anchor);
31
+ }
32
+
33
+ let cachedJiti: JitiFactory | null = null;
34
+ export function getJitiFactory(anchorDir?: string): JitiFactory {
35
+ if (cachedJiti === null) {
36
+ const candidates = [anchorDir, process.cwd(), undefined];
37
+ let lastErr: unknown;
38
+ for (const dir of candidates) {
39
+ try {
40
+ const req = createNodeRequire(dir);
41
+ const jitiMod = req('jiti');
42
+ cachedJiti = ((jitiMod as { default?: JitiFactory }).default ?? jitiMod) as JitiFactory;
43
+ break;
44
+ } catch (e) {
45
+ lastErr = e;
46
+ }
47
+ }
48
+ if (cachedJiti === null) {
49
+ throw lastErr instanceof Error ? lastErr : new Error('Cannot load jiti in Node runtime');
50
+ }
51
+ }
52
+ return cachedJiti;
53
+ }
16
54
  import type { SomaHostAssembly } from '../../shared/types/host-assembly.types';
17
55
  import { getSomaHostSourceRoot } from './source-packages';
18
56
 
@@ -173,18 +211,61 @@ export function loadHostAssemblySync(appRoot: string): SomaHostAssembly | null {
173
211
  * 会解析到抛错的 index.js("This module cannot be imported from a Client Component module")。
174
212
  * 将 server-only 别名指向 server-only/empty.js 可让经 jiti 加载的服务端代码正常运行。
175
213
  */
176
- export function resolveServerOnlyEmpty(): string | undefined {
214
+ function resolveSelfCoreDir(): string {
177
215
  try {
178
- const req = createRequire(import.meta.url);
179
- const serverOnlyPath = req.resolve('server-only');
180
- const emptyPath = path.join(path.dirname(serverOnlyPath), 'empty.js');
181
- return fs.existsSync(emptyPath) ? emptyPath : undefined;
182
- } catch {
183
- return undefined;
216
+ if (typeof import.meta?.url === 'string' && import.meta.url.startsWith('file:')) {
217
+ const candidate = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../');
218
+ if (fs.existsSync(candidate)) return candidate;
219
+ }
220
+ } catch {}
221
+ return path.resolve(process.cwd(), 'core');
222
+ }
223
+
224
+ export function resolveServerOnlyEmpty(anchorDir?: string): string | undefined {
225
+ // 1. 优先取 soma-core 自带的内置空垫片(零外部包解析依赖、100% 确定性)
226
+ const selfCore = resolveSelfCoreDir();
227
+ const builtinNoop = path.join(selfCore, 'server', 'host', 'server-only-noop.cjs');
228
+ if (fs.existsSync(builtinNoop)) return builtinNoop;
229
+
230
+ // 2. 兜底从宿主或当前工作区解析 server-only/empty.js
231
+ for (const dir of [anchorDir, process.cwd(), undefined]) {
232
+ try {
233
+ const req = createNodeRequire(dir);
234
+ const serverOnlyPath = req.resolve('server-only');
235
+ const emptyPath = path.join(path.dirname(serverOnlyPath), 'empty.js');
236
+ if (fs.existsSync(emptyPath)) return emptyPath;
237
+ } catch {}
238
+ }
239
+ return undefined;
240
+ }
241
+
242
+ /**
243
+ * 在纯 Node 进程内安装一次幂等的 Module._resolveFilename 守卫:
244
+ * 不仅覆盖 jiti 直接转译的 TS 文件中的 `import 'server-only'`,还覆盖被间接加载的第三方已编译 CJS/ESM 包中的 `require('server-only')`。
245
+ */
246
+ export function ensureNodeServerOnlyInterop(anchorDir?: string): string | undefined {
247
+ if (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge') return undefined;
248
+ const stub = resolveServerOnlyEmpty(anchorDir);
249
+ if (!stub) return undefined;
250
+ const g = globalThis as Record<symbol, unknown>;
251
+ if (!g[SERVER_ONLY_HOOK_KEY]) {
252
+ const modRecord = nodeModule as unknown as Record<string, unknown>;
253
+ const orig = modRecord[RESOLVE_FILENAME_KEY];
254
+ if (typeof orig === 'function') {
255
+ modRecord[RESOLVE_FILENAME_KEY] = function somaResolveServerOnly(request: string, ...rest: unknown[]) {
256
+ if (request === 'server-only') return stub;
257
+ return (orig as (...args: unknown[]) => unknown).call(this, request, ...rest);
258
+ };
259
+ g[SERVER_ONLY_HOOK_KEY] = stub;
260
+ }
184
261
  }
262
+ return stub;
185
263
  }
186
264
 
187
265
  function loadAppSync(appRoot: string): LoadedApp | null {
266
+ if (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge') {
267
+ return null;
268
+ }
188
269
  const key = path.resolve(appRoot);
189
270
  const cached = cache.get(key);
190
271
  if (cached !== undefined) return cached;
@@ -195,13 +276,15 @@ function loadAppSync(appRoot: string): LoadedApp | null {
195
276
  cache.set(key, null);
196
277
  return null;
197
278
  }
198
- const serverOnlyEmpty = resolveServerOnlyEmpty();
199
- const loader = createJiti(import.meta.url, {
279
+ const serverOnlyEmpty = ensureNodeServerOnlyInterop(key);
280
+ const createJiti = getJitiFactory(key);
281
+ const coreDir = resolveSelfCoreDir();
282
+ const loader = createJiti(path.resolve(key, 'package.json'), {
200
283
  interopDefault: false,
201
284
  requireCache: false,
202
285
  alias: {
203
286
  '@soma-host': hostRoot,
204
- '@core': path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'),
287
+ '@core': coreDir,
205
288
  ...(serverOnlyEmpty !== undefined ? { 'server-only': serverOnlyEmpty } : {}),
206
289
  },
207
290
  });
@@ -217,6 +300,7 @@ function loadAppSync(appRoot: string): LoadedApp | null {
217
300
  * Host 的同步消费点(编译点、虚拟页、树上下文)要求本函数先完成:入口路由在首次取页 / 取接口前 await 它。
218
301
  */
219
302
  export async function loadHostAssembly(appRoot: string): Promise<SomaHostAssembly | null> {
303
+ if (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge') return null;
220
304
  const key = path.resolve(appRoot);
221
305
  const app = loadAppSync(key);
222
306
  if (app === null) return null;
@@ -237,6 +321,7 @@ export async function loadHostAssembly(appRoot: string): Promise<SomaHostAssembl
237
321
  * 只由宿主壳的启动入口(`instrumentation.ts`)调用;`soma build` 不调用。
238
322
  */
239
323
  export async function runHostStartup(appRoot: string): Promise<void> {
324
+ if (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge') return;
240
325
  const key = path.resolve(appRoot);
241
326
  let pending = startups.get(key);
242
327
  if (pending === undefined) {
@@ -24,6 +24,7 @@ export async function resolveHostResponseHeaders(
24
24
  hostDir: string | undefined = process.env.SOMA_HOST_DIR,
25
25
  ): Promise<Readonly<Record<string, string>> | undefined> {
26
26
  if (hostDir === undefined || hostDir.trim() === '') return undefined;
27
+ if (typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge') return undefined;
27
28
  const assembly = await loadHostAssembly(hostDir);
28
29
  if (assembly?.responseHeaders === undefined) return undefined;
29
30
  const headers = await assembly.responseHeaders({
@@ -0,0 +1,2 @@
1
+ // 纯 Node 运行时下供 jiti 与原生 CJS 加载器解析 'server-only' 的空垫片(避免 Next.js 外层 server-only/index.js 误判为客户端组件而抛错)。
2
+ module.exports = {};
@@ -1,3 +1,6 @@
1
+ export type JitiFactory = (id: string, opts?: unknown) => (file: string) => unknown;
2
+ export declare function createNodeRequire(anchorDir?: string): NodeRequire;
3
+ export declare function getJitiFactory(anchorDir?: string): JitiFactory;
1
4
  import type { SomaHostAssembly } from '../../shared/types/host-assembly.types';
2
5
  /** Host 装配文件相对应用根的位置 */
3
6
  export declare const SOMA_HOST_ASSEMBLY_FILE = "soma.app.ts";
@@ -35,14 +38,12 @@ export declare function resolveHostLoginPath(assembly?: {
35
38
  * 结果按应用根缓存。
36
39
  */
37
40
  export declare function loadHostAssemblySync(appRoot: string): SomaHostAssembly | null;
41
+ export declare function resolveServerOnlyEmpty(anchorDir?: string): string | undefined;
38
42
  /**
39
- * 解析 'server-only' 的空垫片路径(empty.js)。
40
- *
41
- * 为什么需要:Host 装配在纯 Node 里经 jiti 加载,Next.js 的 server-only 在纯 Node 默认导出条件下
42
- * 会解析到抛错的 index.js("This module cannot be imported from a Client Component module")。
43
- * 将 server-only 别名指向 server-only/empty.js 可让经 jiti 加载的服务端代码正常运行。
43
+ * 在纯 Node 进程内安装一次幂等的 Module._resolveFilename 守卫:
44
+ * 不仅覆盖 jiti 直接转译的 TS 文件中的 `import 'server-only'`,还覆盖被间接加载的第三方已编译 CJS/ESM 包中的 `require('server-only')`。
44
45
  */
45
- export declare function resolveServerOnlyEmpty(): string | undefined;
46
+ export declare function ensureNodeServerOnlyInterop(anchorDir?: string): string | undefined;
46
47
  /**
47
48
  * 读 `<应用根>/soma.app.ts` 默认导出并等服务端面装配完成(`await app.server()`);无该文件 → null。
48
49
  * 装配失败(SomaAppAssemblyError)原样上抛——拒绝启动,不静默回落。同一应用根只装配一次(并发调用共享同一 Promise)。
@@ -3,11 +3,16 @@
3
3
  // 时机:`soma dev` / `soma start` 的服务进程启动时(Node 运行时);`soma build` 不执行(build 只跑装配的 `prewarm`)。
4
4
  // 这里加载 `soma.app.ts` 并等服务端面(`server()`)装配完,再 await `startup()`;装配或启动钩子抛错,`register` 随之抛错,
5
5
  // 服务不进入可用状态(`soma start` 进程报错退出)。没有 `soma.app.ts` 或装配没写 `startup` 时只完成装配(无副作用)。
6
+ //
7
+ // Node/Edge 编译隔离:必须使用 `if (process.env.NEXT_RUNTIME === 'nodejs')` 块级条件包裹,
8
+ // 让 Next.js 在为 Edge 运行时编译 instrumentation.ts 时通过死代码消除(DCE)直接抹除对 host-assembly 的依赖,
9
+ // 严禁使用顶层 early return(early return 无法阻止 Webpack 分析后续的动态 import 进而触发 Can't resolve 'fs')。
6
10
  export async function register(): Promise<void> {
7
- if (process.env.NEXT_RUNTIME !== 'nodejs') return;
8
- if (process.env.NEXT_PHASE === 'phase-production-build') return;
9
- const hostDir = process.env.SOMA_HOST_DIR;
10
- if (!hostDir || !hostDir.trim()) return;
11
- const { runHostStartup } = await import('./core/server/host/host-assembly');
12
- await runHostStartup(hostDir);
11
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
12
+ if (process.env.NEXT_PHASE === 'phase-production-build') return;
13
+ const hostDir = process.env.SOMA_HOST_DIR;
14
+ if (!hostDir || !hostDir.trim()) return;
15
+ const { runHostStartup } = await import('./core/server/host/host-assembly');
16
+ await runHostStartup(hostDir);
17
+ }
13
18
  }
@@ -298,7 +298,7 @@ const nextConfig = {
298
298
 
299
299
  transpilePackages,
300
300
 
301
- webpack: (config, { dev, isServer, webpack: webpackInstance }) => {
301
+ webpack: (config, { dev, isServer, nextRuntime, webpack: webpackInstance }) => {
302
302
  if (webpackCacheMode === 'memory' && dev) {
303
303
  config.cache = { type: 'memory' };
304
304
  }
@@ -308,6 +308,19 @@ const nextConfig = {
308
308
  ignored: mergeWatchIgnored(config.watchOptions?.ignored),
309
309
  };
310
310
  }
311
+ // Node/Edge 与浏览器编译隔离:非 Node.js 运行时一律排除 jiti 与 Node 原生模块回退
312
+ if (nextRuntime === 'edge' || !isServer) {
313
+ config.resolve.alias = {
314
+ ...config.resolve.alias,
315
+ jiti: false,
316
+ };
317
+ config.resolve.fallback = {
318
+ ...config.resolve.fallback,
319
+ fs: false,
320
+ path: false,
321
+ module: false,
322
+ };
323
+ }
311
324
  config.resolve.alias['@'] = coreRoot;
312
325
  Object.assign(config.resolve.alias, readCorePublicWebpackAliases());
313
326
  config.resolve.alias['@core'] = path.resolve(coreRoot, 'core');
@@ -340,6 +353,9 @@ const nextConfig = {
340
353
  checkResource(resource) {
341
354
  if (/soma\.server/.test(resource)) return true;
342
355
  if (!hasHostDomainUi && resource.startsWith('@soma-host/domain/ui')) return true;
356
+ if (nextRuntime === 'edge' || !isServer) {
357
+ if (/host-assembly/.test(resource) || resource === 'jiti' || resource.startsWith('jiti/')) return true;
358
+ }
343
359
  return false;
344
360
  },
345
361
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-core",
3
- "version": "2.1.1",
3
+ "version": "2.1.3",
4
4
  "description": "SOMA — Semantic Oriented Modular Architecture. A declarative frontend framework runtime with no UI framework dependency; the Next.js host shell ships in host-next/ (code-isolated from core/, next/react are optional peer dependencies).",
5
5
  "keywords": [
6
6
  "soma",