@celljs/vite 0.0.0-stage → 4.1.0

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.
Files changed (166) hide show
  1. package/README.md +29 -2
  2. package/assets/favicon.ico +0 -0
  3. package/lib/builder/cell-builder.d.ts +19 -0
  4. package/lib/builder/cell-builder.d.ts.map +1 -0
  5. package/lib/builder/cell-builder.js +59 -0
  6. package/lib/builder/cell-builder.js.map +1 -0
  7. package/lib/builder/cell-builder.spec.d.ts +2 -0
  8. package/lib/builder/cell-builder.spec.d.ts.map +1 -0
  9. package/lib/builder/cell-builder.spec.js +280 -0
  10. package/lib/builder/cell-builder.spec.js.map +1 -0
  11. package/lib/constants.d.ts +24 -0
  12. package/lib/constants.d.ts.map +1 -0
  13. package/lib/constants.js +23 -0
  14. package/lib/constants.js.map +1 -0
  15. package/lib/dev/cell-dev-server.d.ts +113 -0
  16. package/lib/dev/cell-dev-server.d.ts.map +1 -0
  17. package/lib/dev/cell-dev-server.js +307 -0
  18. package/lib/dev/cell-dev-server.js.map +1 -0
  19. package/lib/dev/cell-dev-server.spec.d.ts +2 -0
  20. package/lib/dev/cell-dev-server.spec.d.ts.map +1 -0
  21. package/lib/dev/cell-dev-server.spec.js +188 -0
  22. package/lib/dev/cell-dev-server.spec.js.map +1 -0
  23. package/lib/expression/expression-evaluator.d.ts +28 -0
  24. package/lib/expression/expression-evaluator.d.ts.map +1 -0
  25. package/lib/expression/expression-evaluator.js +91 -0
  26. package/lib/expression/expression-evaluator.js.map +1 -0
  27. package/lib/expression/expression-evaluator.spec.d.ts +2 -0
  28. package/lib/expression/expression-evaluator.spec.d.ts.map +1 -0
  29. package/lib/expression/expression-evaluator.spec.js +48 -0
  30. package/lib/expression/expression-evaluator.spec.js.map +1 -0
  31. package/lib/generator/config-generator.d.ts +18 -0
  32. package/lib/generator/config-generator.d.ts.map +1 -0
  33. package/lib/generator/config-generator.js +45 -0
  34. package/lib/generator/config-generator.js.map +1 -0
  35. package/lib/generator/container-generator.d.ts +13 -0
  36. package/lib/generator/container-generator.d.ts.map +1 -0
  37. package/lib/generator/container-generator.js +41 -0
  38. package/lib/generator/container-generator.js.map +1 -0
  39. package/lib/generator/generator.spec.d.ts +2 -0
  40. package/lib/generator/generator.spec.d.ts.map +1 -0
  41. package/lib/generator/generator.spec.js +61 -0
  42. package/lib/generator/generator.spec.js.map +1 -0
  43. package/lib/generator/html-generator.d.ts +13 -0
  44. package/lib/generator/html-generator.d.ts.map +1 -0
  45. package/lib/generator/html-generator.js +42 -0
  46. package/lib/generator/html-generator.js.map +1 -0
  47. package/lib/index.d.ts +21 -0
  48. package/lib/index.d.ts.map +1 -0
  49. package/lib/index.js +21 -0
  50. package/lib/index.js.map +1 -0
  51. package/lib/output/asset-embedder.d.ts +19 -0
  52. package/lib/output/asset-embedder.d.ts.map +1 -0
  53. package/lib/output/asset-embedder.js +35 -0
  54. package/lib/output/asset-embedder.js.map +1 -0
  55. package/lib/output/externals-copier.d.ts +20 -0
  56. package/lib/output/externals-copier.d.ts.map +1 -0
  57. package/lib/output/externals-copier.js +62 -0
  58. package/lib/output/externals-copier.js.map +1 -0
  59. package/lib/output/externals-copier.spec.d.ts +2 -0
  60. package/lib/output/externals-copier.spec.d.ts.map +1 -0
  61. package/lib/output/externals-copier.spec.js +30 -0
  62. package/lib/output/externals-copier.spec.js.map +1 -0
  63. package/lib/output/output-writer.d.ts +39 -0
  64. package/lib/output/output-writer.d.ts.map +1 -0
  65. package/lib/output/output-writer.js +102 -0
  66. package/lib/output/output-writer.js.map +1 -0
  67. package/lib/output/output-writer.spec.d.ts +2 -0
  68. package/lib/output/output-writer.spec.d.ts.map +1 -0
  69. package/lib/output/output-writer.spec.js +34 -0
  70. package/lib/output/output-writer.spec.js.map +1 -0
  71. package/lib/plugin/cell-plugin.d.ts +134 -0
  72. package/lib/plugin/cell-plugin.d.ts.map +1 -0
  73. package/lib/plugin/cell-plugin.js +429 -0
  74. package/lib/plugin/cell-plugin.js.map +1 -0
  75. package/lib/plugin/cell-plugin.spec.d.ts +2 -0
  76. package/lib/plugin/cell-plugin.spec.d.ts.map +1 -0
  77. package/lib/plugin/cell-plugin.spec.js +74 -0
  78. package/lib/plugin/cell-plugin.spec.js.map +1 -0
  79. package/lib/plugin/node-polyfills.d.ts +13 -0
  80. package/lib/plugin/node-polyfills.d.ts.map +1 -0
  81. package/lib/plugin/node-polyfills.js +55 -0
  82. package/lib/plugin/node-polyfills.js.map +1 -0
  83. package/lib/plugin/node-polyfills.spec.d.ts +2 -0
  84. package/lib/plugin/node-polyfills.spec.d.ts.map +1 -0
  85. package/lib/plugin/node-polyfills.spec.js +16 -0
  86. package/lib/plugin/node-polyfills.spec.js.map +1 -0
  87. package/lib/project/component-collector.d.ts +32 -0
  88. package/lib/project/component-collector.d.ts.map +1 -0
  89. package/lib/project/component-collector.js +93 -0
  90. package/lib/project/component-collector.js.map +1 -0
  91. package/lib/project/config-loader.d.ts +16 -0
  92. package/lib/project/config-loader.d.ts.map +1 -0
  93. package/lib/project/config-loader.js +76 -0
  94. package/lib/project/config-loader.js.map +1 -0
  95. package/lib/project/env-overrides.d.ts +23 -0
  96. package/lib/project/env-overrides.d.ts.map +1 -0
  97. package/lib/project/env-overrides.js +48 -0
  98. package/lib/project/env-overrides.js.map +1 -0
  99. package/lib/project/env-overrides.spec.d.ts +2 -0
  100. package/lib/project/env-overrides.spec.d.ts.map +1 -0
  101. package/lib/project/env-overrides.spec.js +41 -0
  102. package/lib/project/env-overrides.spec.js.map +1 -0
  103. package/lib/project/module-resolver.d.ts +15 -0
  104. package/lib/project/module-resolver.d.ts.map +1 -0
  105. package/lib/project/module-resolver.js +32 -0
  106. package/lib/project/module-resolver.js.map +1 -0
  107. package/lib/project/project-loader.d.ts +54 -0
  108. package/lib/project/project-loader.d.ts.map +1 -0
  109. package/lib/project/project-loader.js +117 -0
  110. package/lib/project/project-loader.js.map +1 -0
  111. package/lib/project/project-loader.spec.d.ts +2 -0
  112. package/lib/project/project-loader.spec.d.ts.map +1 -0
  113. package/lib/project/project-loader.spec.js +178 -0
  114. package/lib/project/project-loader.spec.js.map +1 -0
  115. package/lib/test/fixture-project.d.ts +17 -0
  116. package/lib/test/fixture-project.d.ts.map +1 -0
  117. package/lib/test/fixture-project.js +43 -0
  118. package/lib/test/fixture-project.js.map +1 -0
  119. package/lib/testing/memory-http.d.ts +82 -0
  120. package/lib/testing/memory-http.d.ts.map +1 -0
  121. package/lib/testing/memory-http.js +210 -0
  122. package/lib/testing/memory-http.js.map +1 -0
  123. package/lib/testing/test-app.d.ts +54 -0
  124. package/lib/testing/test-app.d.ts.map +1 -0
  125. package/lib/testing/test-app.js +132 -0
  126. package/lib/testing/test-app.js.map +1 -0
  127. package/lib/testing/test-app.spec.d.ts +2 -0
  128. package/lib/testing/test-app.spec.d.ts.map +1 -0
  129. package/lib/testing/test-app.spec.js +115 -0
  130. package/lib/testing/test-app.spec.js.map +1 -0
  131. package/lib/utils/config-util.d.ts +6 -0
  132. package/lib/utils/config-util.d.ts.map +1 -0
  133. package/lib/utils/config-util.js +25 -0
  134. package/lib/utils/config-util.js.map +1 -0
  135. package/lib/utils/config-util.spec.d.ts +2 -0
  136. package/lib/utils/config-util.spec.d.ts.map +1 -0
  137. package/lib/utils/config-util.spec.js +22 -0
  138. package/lib/utils/config-util.spec.js.map +1 -0
  139. package/lib/utils/tsconfig-util.d.ts +5 -0
  140. package/lib/utils/tsconfig-util.d.ts.map +1 -0
  141. package/lib/utils/tsconfig-util.js +21 -0
  142. package/lib/utils/tsconfig-util.js.map +1 -0
  143. package/package.json +50 -4
  144. package/src/builder/cell-builder.ts +72 -0
  145. package/src/constants.ts +30 -0
  146. package/src/dev/cell-dev-server.ts +387 -0
  147. package/src/expression/expression-evaluator.ts +99 -0
  148. package/src/generator/config-generator.ts +45 -0
  149. package/src/generator/container-generator.ts +41 -0
  150. package/src/generator/html-generator.ts +43 -0
  151. package/src/index.ts +20 -0
  152. package/src/output/asset-embedder.ts +42 -0
  153. package/src/output/externals-copier.ts +64 -0
  154. package/src/output/output-writer.ts +113 -0
  155. package/src/plugin/cell-plugin.ts +481 -0
  156. package/src/plugin/node-polyfills.ts +57 -0
  157. package/src/project/component-collector.ts +107 -0
  158. package/src/project/config-loader.ts +77 -0
  159. package/src/project/env-overrides.ts +55 -0
  160. package/src/project/module-resolver.ts +39 -0
  161. package/src/project/project-loader.ts +153 -0
  162. package/src/test/fixture-project.ts +50 -0
  163. package/src/testing/memory-http.ts +238 -0
  164. package/src/testing/test-app.ts +155 -0
  165. package/src/utils/config-util.ts +21 -0
  166. package/src/utils/tsconfig-util.ts +19 -0
@@ -0,0 +1,77 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CellError, type Target } from '@celljs/kit';
4
+ import yaml from 'js-yaml';
5
+ import { TOOLING_KEYS } from '../constants.js';
6
+ import { ConfigUtil } from '../utils/config-util.js';
7
+ import type { Component } from './component-collector.js';
8
+
9
+ /**
10
+ * Merges the configuration layers of all components: for each component in order, `cell.yml` then
11
+ * `cell.<mode>.yml` for every active mode. Records the files it read on each component.
12
+ */
13
+ export class ConfigLoader {
14
+ constructor(protected readonly mode: string[]) {}
15
+
16
+ load(components: Component[]): Record<string, any> {
17
+ const merged: Record<string, any> = {};
18
+ for (const component of components) {
19
+ for (const file of this.layerFiles(component)) {
20
+ component.configFiles.push(file);
21
+ ConfigUtil.merge(merged, this.readYaml(file));
22
+ }
23
+ }
24
+ return merged;
25
+ }
26
+
27
+ /** Application configuration of one target: shared keys, then the target section, without tooling keys. */
28
+ forTarget(merged: Record<string, any>, target: Target): Record<string, unknown> {
29
+ const config: Record<string, any> = {};
30
+ for (const [key, value] of Object.entries(merged)) {
31
+ if (!TOOLING_KEYS.includes(key)) {
32
+ config[key] = structuredClone(value);
33
+ }
34
+ }
35
+ ConfigUtil.merge(config, structuredClone(merged[target] ?? {}));
36
+ for (const key of TOOLING_KEYS) {
37
+ delete config[key];
38
+ }
39
+ config.mode = [...this.mode];
40
+ return config;
41
+ }
42
+
43
+ protected layerFiles(component: Component): string[] {
44
+ return ['cell.yml', ...this.mode.map(m => `cell.${m}.yml`)].map(name => join(component.dir, name)).filter(existsSync);
45
+ }
46
+
47
+ protected readYaml(file: string): Record<string, any> {
48
+ let value: unknown;
49
+ try {
50
+ value = yaml.load(readFileSync(file, 'utf8'));
51
+ } catch (cause) {
52
+ const mark = (cause as { mark?: { line: number; column: number } }).mark;
53
+ throw new CellError({
54
+ code: 'CELL_CONFIG_PARSE',
55
+ message: `Invalid YAML in ${file}: ${(cause as Error).message.split('\n')[0]}`,
56
+ file,
57
+ line: mark && mark.line + 1,
58
+ column: mark && mark.column + 1,
59
+ hint: 'Fix the YAML syntax at the reported position.',
60
+ cause,
61
+ });
62
+ }
63
+ if (value === undefined || value === null) {
64
+ return {};
65
+ }
66
+ if (!ConfigUtil.isPlainObject(value)) {
67
+ throw new CellError({
68
+ code: 'CELL_CONFIG_NOT_OBJECT',
69
+ message: `${file} must contain a YAML mapping at the top level.`,
70
+ file,
71
+ line: 1,
72
+ hint: 'Start the file with keys such as `cell:` or `backend:`.',
73
+ });
74
+ }
75
+ return value;
76
+ }
77
+ }
@@ -0,0 +1,55 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join } from 'node:path';
3
+ import { CellError, type EnvOverrideReport, type Target } from '@celljs/kit';
4
+
5
+ interface EnvConfigUtil {
6
+ PREFIXES: Record<Target, string>;
7
+ apply(config: Record<string, unknown>, env: Record<string, string | undefined>, target: Target): EnvOverrideReport;
8
+ }
9
+
10
+ /**
11
+ * Applies `CELL_FRONTEND__*` / `CELL_BACKEND__*` environment variables with the `EnvConfigUtil` of
12
+ * the project's own @celljs/core, the same code the server runs at startup, so build and runtime agree.
13
+ */
14
+ export class EnvOverrides {
15
+ static readonly PREFIXES: Record<Target, string> = { frontend: 'CELL_FRONTEND__', backend: 'CELL_BACKEND__' };
16
+
17
+ protected util?: EnvConfigUtil;
18
+
19
+ constructor(
20
+ protected readonly root: string,
21
+ protected readonly env: Record<string, string | undefined>,
22
+ ) {}
23
+
24
+ /** Applies the variables of `target` to `config` in place. */
25
+ apply(target: Target, config: Record<string, unknown>): EnvOverrideReport {
26
+ const prefix = EnvOverrides.PREFIXES[target];
27
+ if (!Object.keys(this.env).some(name => name.startsWith(prefix))) {
28
+ return { applied: [], problems: [] };
29
+ }
30
+ return this.load().apply(config, this.env, target);
31
+ }
32
+
33
+ /** What the variables of `target` would change, leaving `config` alone. */
34
+ preview(target: Target, config: Record<string, unknown>): EnvOverrideReport {
35
+ return this.apply(target, structuredClone(config));
36
+ }
37
+
38
+ protected load(): EnvConfigUtil {
39
+ if (!this.util) {
40
+ const require = createRequire(join(this.root, 'package.json'));
41
+ try {
42
+ this.util = require('@celljs/core/lib/common/config/env-config-util').EnvConfigUtil as EnvConfigUtil;
43
+ } catch (cause) {
44
+ throw new CellError({
45
+ code: 'CELL_CORE_NOT_FOUND',
46
+ message: 'The @celljs/core of this project cannot apply CELL_FRONTEND__ / CELL_BACKEND__ variables.',
47
+ file: join(this.root, 'package.json'),
48
+ hint: 'Depend on @celljs/core 4 or later.',
49
+ cause,
50
+ });
51
+ }
52
+ }
53
+ return this.util;
54
+ }
55
+ }
@@ -0,0 +1,39 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type { ModuleRef, Target } from '@celljs/kit';
4
+ import type { Component } from './component-collector.js';
5
+
6
+ export type ModuleKind = 'modules' | 'staticModules';
7
+
8
+ /**
9
+ * Lists the DI modules a component contributes to a target. Framework packages declare them in the
10
+ * `cell` field of package.json; the project itself follows the conventions under `src/`.
11
+ */
12
+ export class ModuleResolver {
13
+ static readonly SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.mjs'];
14
+
15
+ /** Candidate module paths for a target, in load order, relative to `base`. */
16
+ static conventionalPaths(base: string, target: Target, kind: ModuleKind): string[] {
17
+ const suffix = kind === 'modules' ? 'module' : 'static-module';
18
+ const platform = target === 'frontend' ? 'browser' : 'node';
19
+ return [`common/${suffix}`, `${platform}/${target}-${suffix}`, `${platform}/${suffix}`, suffix, `${target}-${suffix}`].map(path => `${base}/${path}`);
20
+ }
21
+
22
+ resolve(component: Component, target: Target, kind: ModuleKind): ModuleRef[] {
23
+ const importer = join(component.dir, 'package.json');
24
+ const declared = component.manifest[kind]?.[target];
25
+ if (!component.root) {
26
+ return (declared ?? []).map(sub => ({ component: component.name, specifier: `${component.name}/${sub}`, importer }));
27
+ }
28
+ const paths = declared ?? ModuleResolver.conventionalPaths('src', target, kind);
29
+ return paths
30
+ .map(path => this.findSource(component.dir, path))
31
+ .filter((file): file is string => file !== undefined)
32
+ .map(file => ({ component: component.name, specifier: file, importer }));
33
+ }
34
+
35
+ protected findSource(dir: string, path: string): string | undefined {
36
+ const ext = ModuleResolver.SOURCE_EXTENSIONS.find(e => existsSync(join(dir, path + e)));
37
+ return ext === undefined ? undefined : join(dir, path + ext);
38
+ }
39
+ }
@@ -0,0 +1,153 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CellError, type ModuleRef, type ProjectModel, type Target, type TargetModel } from '@celljs/kit';
4
+ import { DEFAULT_ENTRY, PUBLIC_DIR, TARGETS } from '../constants.js';
5
+ import { ExpressionEvaluator } from '../expression/expression-evaluator.js';
6
+ import type { Component } from './component-collector.js';
7
+ import { ComponentCollector } from './component-collector.js';
8
+ import { ConfigLoader } from './config-loader.js';
9
+ import { EnvOverrides } from './env-overrides.js';
10
+ import { ModuleResolver } from './module-resolver.js';
11
+
12
+ export interface ProjectLoaderOptions {
13
+ root?: string;
14
+ /** Active modes, in order; later modes override earlier ones. */
15
+ mode?: string[];
16
+ /** Explicit entry specifiers; they win over {@link entryName}. */
17
+ entry?: Partial<Record<Target, string>>;
18
+ /** Name of the backend entry to pick from the components' `entries` (chosen by the preset, e.g. `http`). */
19
+ entryName?: string;
20
+ /** Targets to build; default: `backend` plus the components' `targets`. */
21
+ targets?: Target[];
22
+ /** Components left out entirely, with the dependencies only they lead to (`'!name'` in cell.config.ts). */
23
+ disabled?: string[];
24
+ /** Components whose DI modules are left out; their configuration still applies. */
25
+ runtimeDisabled?: string[];
26
+ /** DI modules added by toolchain modules, loaded after the components' own (`cell.addRuntimeModule`). */
27
+ extraModules?: ExtraModule[];
28
+ /** Environment for `${env.*}` in frontend configuration and `CELL_FRONTEND__` / `CELL_BACKEND__` overrides. Default: `process.env`. */
29
+ env?: Record<string, string | undefined>;
30
+ }
31
+
32
+ /** A DI module that a toolchain module adds to a target. */
33
+ export interface ExtraModule {
34
+ target: Target;
35
+ /** File path or package specifier, resolved from the project root. */
36
+ specifier: string;
37
+ static?: boolean;
38
+ /** Name of the toolchain module that added it. */
39
+ component: string;
40
+ }
41
+
42
+ /**
43
+ * Builds the project model from package.json and cell*.yml files only. No project code runs, so it
44
+ * is cheap enough for `cell info` and editor tooling (docs/design/agent-first.md R2).
45
+ */
46
+ export class ProjectLoader {
47
+ protected readonly root: string;
48
+ protected readonly mode: string[];
49
+ protected readonly env: Record<string, string | undefined>;
50
+
51
+ constructor(protected readonly options: ProjectLoaderOptions = {}) {
52
+ const root = options.root ?? process.cwd();
53
+ if (!existsSync(join(root, 'package.json'))) {
54
+ throw new CellError({
55
+ code: 'CELL_PROJECT_NOT_FOUND',
56
+ message: `No package.json in ${root}.`,
57
+ file: join(root, 'package.json'),
58
+ hint: 'Run the command in the project root, or pass `root`.',
59
+ });
60
+ }
61
+ this.root = realpathSync(root);
62
+ this.mode = options.mode ?? [];
63
+ this.env = options.env ?? process.env;
64
+ }
65
+
66
+ load(): ProjectModel {
67
+ const collector = new ComponentCollector(this.root, new Set(this.options.disabled));
68
+ const components = collector.collect();
69
+ this.checkFilters(collector.excluded, components);
70
+ const runtimeDisabled = new Set(this.options.runtimeDisabled);
71
+ const runtime = components.filter(c => !runtimeDisabled.has(c.name));
72
+ const configLoader = new ConfigLoader(this.mode);
73
+ const merged = configLoader.load(components);
74
+ const targets = this.targets(components);
75
+ const model: ProjectModel = {
76
+ schemaVersion: 1,
77
+ root: this.root,
78
+ mode: [...this.mode],
79
+ targets,
80
+ components: components.map(({ manifest: _manifest, ...info }) => info),
81
+ };
82
+ const moduleResolver = new ModuleResolver();
83
+ const overrides = new EnvOverrides(this.root, this.env);
84
+ for (const target of targets) {
85
+ const config = configLoader.forTarget(merged, target);
86
+ if (target === 'backend') {
87
+ // Where the server finds the frontend; `${paths.public}` in cell.yml (serve-static) refers to it.
88
+ config.paths = { public: PUBLIC_DIR, ...(config.paths as object) };
89
+ }
90
+ const envOverrides = target === 'frontend' ? overrides.apply(target, config) : overrides.preview(target, config);
91
+ const targetModel: TargetModel = {
92
+ target,
93
+ ...this.entry(target, runtime),
94
+ staticModules: [...runtime.flatMap(c => moduleResolver.resolve(c, target, 'staticModules')), ...this.extraModules(target, true)],
95
+ modules: [...runtime.flatMap(c => moduleResolver.resolve(c, target, 'modules')), ...this.extraModules(target, false)],
96
+ config: this.evaluate(target, config),
97
+ envOverrides,
98
+ };
99
+ model[target] = targetModel;
100
+ }
101
+ return model;
102
+ }
103
+
104
+ protected extraModules(target: Target, isStatic: boolean): ModuleRef[] {
105
+ const importer = join(this.root, 'package.json');
106
+ return (this.options.extraModules ?? [])
107
+ .filter(m => m.target === target && (m.static ?? false) === isStatic)
108
+ .map(m => ({ component: m.component, specifier: m.specifier, importer }));
109
+ }
110
+
111
+ /** Every project has a backend; components add targets (`@celljs/widget` adds the frontend). Explicit targets replace both. */
112
+ protected targets(components: Component[]): Target[] {
113
+ const declared = this.options.targets ?? ['backend', ...components.flatMap(c => c.manifest.targets ?? [])];
114
+ return TARGETS.filter(t => declared.includes(t));
115
+ }
116
+
117
+ /** Explicit entry, else the named entry of the last component providing it, else the core default. */
118
+ protected entry(target: Target, components: Component[]): Pick<TargetModel, 'entry' | 'entryComponent'> {
119
+ const explicit = this.options.entry?.[target];
120
+ if (explicit) {
121
+ return { entry: explicit };
122
+ }
123
+ const name = this.options.entryName;
124
+ const provider = target === 'backend' && name ? [...components].reverse().find(c => c.manifest.entries?.[name]) : undefined;
125
+ const subpath = name ? provider?.manifest.entries?.[name] : undefined;
126
+ if (!provider || !subpath) {
127
+ return { entry: DEFAULT_ENTRY };
128
+ }
129
+ return { entry: provider.root ? join(provider.dir, subpath) : `${provider.name}/${subpath}`, entryComponent: provider.name };
130
+ }
131
+
132
+ /** A filter naming a package that is not a component of the project is a mistake, not a no-op. */
133
+ protected checkFilters(excluded: readonly string[], components: { name: string }[]): void {
134
+ const found = components.map(c => c.name);
135
+ const unknown = [
136
+ ...(this.options.disabled ?? []).filter(name => !excluded.includes(name)),
137
+ ...(this.options.runtimeDisabled ?? []).filter(name => !found.includes(name) || found.at(-1) === name),
138
+ ];
139
+ if (unknown.length > 0) {
140
+ throw new CellError({
141
+ code: 'CELL_COMPONENT_NOT_FOUND',
142
+ message: `Not a component of this project: ${unknown.join(', ')}. Components: ${found.slice(0, -1).join(', ') || '(none)'}.`,
143
+ file: join(this.root, 'package.json'),
144
+ hint: 'Fix the package name in `modules` of cell.config.ts, or remove the entry; only components reached through `dependencies` can be filtered.',
145
+ });
146
+ }
147
+ }
148
+
149
+ /** The browser has no runtime environment, so frontend expressions are evaluated at build time. */
150
+ protected evaluate(target: Target, config: Record<string, unknown>): Record<string, unknown> {
151
+ return target === 'frontend' ? new ExpressionEvaluator(this.root).evaluate(config, { env: { ...this.env } }) : config;
152
+ }
153
+ }
@@ -0,0 +1,50 @@
1
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ /**
6
+ * A throw-away project on disk for tests. It lives under this package's `.fixtures/` directory so
7
+ * that the repository's node_modules (and therefore @celljs/core) are resolvable from it.
8
+ */
9
+ export class FixtureProject {
10
+ /** Created eagerly: Bun's resolver caches a missing directory, which would break later lookups from it. */
11
+ static readonly BASE = FixtureProject.createBase();
12
+
13
+ protected static createBase(): string {
14
+ const base = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '.fixtures');
15
+ mkdirSync(base, { recursive: true });
16
+ return base;
17
+ }
18
+
19
+ readonly root: string;
20
+
21
+ constructor(name: string) {
22
+ this.root = join(FixtureProject.BASE, `${name}-${process.pid}-${Math.random().toString(36).slice(2, 8)}`);
23
+ mkdirSync(this.root, { recursive: true });
24
+ }
25
+
26
+ file(path: string, content: string | object): this {
27
+ const file = join(this.root, path);
28
+ mkdirSync(dirname(file), { recursive: true });
29
+ writeFileSync(file, typeof content === 'string' ? content : `${JSON.stringify(content, null, 2)}\n`);
30
+ return this;
31
+ }
32
+
33
+ /** Adds a package under `node_modules` (or nested under `under`). */
34
+ dependency(name: string, pkg: Record<string, unknown> = {}, files: Record<string, string> = {}, under = ''): this {
35
+ const dir = join(under, 'node_modules', name);
36
+ this.file(join(dir, 'package.json'), { name, version: '1.0.0', ...pkg });
37
+ for (const [path, content] of Object.entries(files)) {
38
+ this.file(join(dir, path), content);
39
+ }
40
+ return this;
41
+ }
42
+
43
+ path(...parts: string[]): string {
44
+ return join(this.root, ...parts);
45
+ }
46
+
47
+ dispose(): void {
48
+ rmSync(this.root, { recursive: true, force: true });
49
+ }
50
+ }
@@ -0,0 +1,238 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { IncomingHttpHeaders } from 'node:http';
3
+ import { Readable, Writable } from 'node:stream';
4
+
5
+ /** The socket of an in-memory request: what request libraries read from `req.socket`. */
6
+ class MemorySocket extends EventEmitter {
7
+ readonly remoteAddress = '127.0.0.1';
8
+ readonly remotePort = 0;
9
+ readonly remoteFamily = 'IPv4';
10
+ readonly localAddress = '127.0.0.1';
11
+ readonly localPort = 0;
12
+ readonly encrypted = false;
13
+ readable = true;
14
+ writable = true;
15
+ destroyed = false;
16
+
17
+ setTimeout(): this {
18
+ return this;
19
+ }
20
+
21
+ setNoDelay(): this {
22
+ return this;
23
+ }
24
+
25
+ setKeepAlive(): this {
26
+ return this;
27
+ }
28
+
29
+ address(): { address: string; family: string; port: number } {
30
+ return { address: this.localAddress, family: 'IPv4', port: 0 };
31
+ }
32
+
33
+ destroy(): this {
34
+ this.destroyed = true;
35
+ this.readable = this.writable = false;
36
+ this.emit('close');
37
+ return this;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Express replaces the prototype of every request and response with its own, which extends Node's
43
+ * `IncomingMessage` / `ServerResponse`. Methods that must keep working without a real connection
44
+ * are therefore copied onto the instance.
45
+ */
46
+ function ownMethods<T extends object>(target: T, names: string[]): void {
47
+ for (const name of names) {
48
+ const method = (target as Record<string, unknown>)[name];
49
+ if (typeof method === 'function') {
50
+ Object.defineProperty(target, name, { value: method.bind(target), writable: true, configurable: true });
51
+ }
52
+ }
53
+ }
54
+
55
+ /** An `http.IncomingMessage` without a connection: method, url, headers and a body stream. */
56
+ export class MemoryRequest extends Readable {
57
+ readonly httpVersion = '1.1';
58
+ readonly httpVersionMajor = 1;
59
+ readonly httpVersionMinor = 1;
60
+ readonly socket = new MemorySocket();
61
+ readonly connection = this.socket;
62
+ readonly rawHeaders: string[];
63
+ readonly headers: IncomingHttpHeaders;
64
+ readonly trailers = {};
65
+ readonly rawTrailers: string[] = [];
66
+ complete = false;
67
+ aborted = false;
68
+
69
+ constructor(
70
+ public method: string,
71
+ public url: string,
72
+ headers: Headers,
73
+ body?: Buffer,
74
+ ) {
75
+ super();
76
+ ownMethods(this, ['_read', 'setTimeout']);
77
+ this.rawHeaders = [...headers].flat();
78
+ this.headers = Object.fromEntries(headers);
79
+ if (body && body.length > 0) {
80
+ this.push(body);
81
+ }
82
+ this.push(null);
83
+ this.on('end', () => {
84
+ this.complete = true;
85
+ });
86
+ }
87
+
88
+ override _read(): void {}
89
+
90
+ setTimeout(): this {
91
+ return this;
92
+ }
93
+ }
94
+
95
+ /** An `http.ServerResponse` that collects status, headers and body for a `Response`. */
96
+ export class MemoryResponse extends Writable {
97
+ statusCode = 200;
98
+ statusMessage = '';
99
+ sendDate = true;
100
+ finished = false;
101
+ /** What Node's `headersSent` reads; set once the headers are sent. */
102
+ _header: string | null = null;
103
+ readonly socket: MemorySocket;
104
+ readonly connection: MemorySocket;
105
+ protected readonly headers = new Map<string, { name: string; value: number | string | string[] }>();
106
+ protected readonly chunks: Buffer[] = [];
107
+
108
+ constructor(readonly req: MemoryRequest) {
109
+ super();
110
+ this.socket = req.socket;
111
+ this.connection = req.socket;
112
+ ownMethods(this, [
113
+ 'setHeader',
114
+ 'appendHeader',
115
+ 'getHeader',
116
+ 'getHeaders',
117
+ 'getHeaderNames',
118
+ 'hasHeader',
119
+ 'removeHeader',
120
+ 'writeHead',
121
+ 'flushHeaders',
122
+ 'writeContinue',
123
+ 'setTimeout',
124
+ 'write',
125
+ 'end',
126
+ '_write',
127
+ 'toResponse',
128
+ 'implicitHeader',
129
+ ]);
130
+ Object.defineProperty(this, 'headersSent', { get: () => this._header !== null, configurable: true });
131
+ }
132
+
133
+ get headersSent(): boolean {
134
+ return this._header !== null;
135
+ }
136
+
137
+ setHeader(name: string, value: number | string | readonly string[]): this {
138
+ this.headers.set(name.toLowerCase(), { name, value: Array.isArray(value) ? [...value] : (value as number | string) });
139
+ return this;
140
+ }
141
+
142
+ appendHeader(name: string, value: string | readonly string[]): this {
143
+ const current = this.getHeader(name);
144
+ const list = current === undefined ? [] : Array.isArray(current) ? current : [String(current)];
145
+ return this.setHeader(name, [...list, ...(Array.isArray(value) ? value : [value as string])]);
146
+ }
147
+
148
+ getHeader(name: string): number | string | string[] | undefined {
149
+ return this.headers.get(name.toLowerCase())?.value;
150
+ }
151
+
152
+ getHeaders(): Record<string, number | string | string[]> {
153
+ return Object.fromEntries([...this.headers].map(([key, { value }]) => [key, value]));
154
+ }
155
+
156
+ getHeaderNames(): string[] {
157
+ return [...this.headers.keys()];
158
+ }
159
+
160
+ hasHeader(name: string): boolean {
161
+ return this.headers.has(name.toLowerCase());
162
+ }
163
+
164
+ removeHeader(name: string): void {
165
+ this.headers.delete(name.toLowerCase());
166
+ }
167
+
168
+ writeHead(statusCode: number, message?: string | Record<string, unknown> | unknown[], headers?: Record<string, unknown> | unknown[]): this {
169
+ if (typeof message !== 'string') {
170
+ headers = message;
171
+ message = undefined;
172
+ }
173
+ this.statusCode = statusCode;
174
+ if (message) {
175
+ this.statusMessage = message;
176
+ }
177
+ if (Array.isArray(headers)) {
178
+ for (let i = 0; i + 1 < headers.length; i += 2) {
179
+ this.setHeader(String(headers[i]), String(headers[i + 1]));
180
+ }
181
+ } else if (headers) {
182
+ for (const [name, value] of Object.entries(headers)) {
183
+ this.setHeader(name, value as string);
184
+ }
185
+ }
186
+ this._header = `HTTP/1.1 ${this.statusCode}`;
187
+ return this;
188
+ }
189
+
190
+ flushHeaders(): void {
191
+ this.implicitHeader();
192
+ }
193
+
194
+ writeContinue(): void {}
195
+
196
+ setTimeout(): this {
197
+ return this;
198
+ }
199
+
200
+ override write(chunk: any, encoding?: any, callback?: any): boolean {
201
+ this.implicitHeader();
202
+ return super.write(chunk, encoding, callback);
203
+ }
204
+
205
+ override end(chunk?: any, encoding?: any, callback?: any): this {
206
+ this.implicitHeader();
207
+ this.finished = true;
208
+ if (this.req.method === 'HEAD' && typeof chunk !== 'function') {
209
+ chunk = undefined;
210
+ }
211
+ super.end(chunk, encoding, callback);
212
+ return this;
213
+ }
214
+
215
+ override _write(chunk: Buffer | string, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
216
+ this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding));
217
+ callback();
218
+ }
219
+
220
+ /** The response once the handler ended it. */
221
+ toResponse(): Response {
222
+ const headers = new Headers();
223
+ for (const { name, value } of this.headers.values()) {
224
+ for (const item of Array.isArray(value) ? value : [value]) {
225
+ headers.append(name, String(item));
226
+ }
227
+ }
228
+ const empty = this.statusCode === 204 || this.statusCode === 304 || this.statusCode < 200 || this.req.method === 'HEAD';
229
+ return new Response(empty ? null : Buffer.concat(this.chunks), { status: this.statusCode, statusText: this.statusMessage, headers });
230
+ }
231
+
232
+ /** Like Node: the first write sends the headers through writeHead, which libraries such as on-headers wrap. */
233
+ protected implicitHeader(): void {
234
+ if (this._header === null) {
235
+ this.writeHead(this.statusCode);
236
+ }
237
+ }
238
+ }