@deepseek-ai/dsh-typert-generator 0.2.1-alpha.1 → 0.2.1-alpha.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.
@@ -2,20 +2,31 @@
2
2
  * Optional tsdown (rolldown) plugin face of the typert generator. It lowers
3
3
  * standard decorators in TypeScript dependencies before bundling, then emits
4
4
  * model-driven face artifacts at the package output root. Packages without a
5
- * Typert or Remote export are skipped.
5
+ * Typert or Remote export are skipped. Workspace mode generates in a Worker
6
+ * Thread started by the pass's first `buildStart`, so bundling continues on the
7
+ * main thread while Typert analyzes; the pass's first `writeBundle` awaits the
8
+ * result and writes every artifact once.
6
9
  * @module @deepseek-ai/dsh-typert-generator/tsdown
7
10
  */
8
11
  import type { TypertFace } from './model.ts';
9
12
  /** The subset of the rolldown plugin contract used here (structural; avoids a rolldown type dependency). */
10
13
  interface TypertPlugin {
11
14
  name: string;
12
- transform: (code: string, id: string) => {
13
- code: string;
14
- map: string | undefined;
15
- } | undefined;
15
+ buildStart: (options: {
16
+ cwd: string;
17
+ }) => void;
18
+ transform: {
19
+ filter: {
20
+ id: RegExp;
21
+ };
22
+ handler: (code: string, id: string) => {
23
+ code: string;
24
+ map: string | undefined;
25
+ } | undefined;
26
+ };
16
27
  writeBundle: (options: {
17
28
  dir?: string;
18
- }) => void;
29
+ }) => Promise<void>;
19
30
  }
20
31
  /** Generation scope selected by a tsdown build phase. */
21
32
  export interface TypertPluginOptions {
@@ -24,6 +35,10 @@ export interface TypertPluginOptions {
24
35
  /** Independent TypeScript program faces included in this phase. */
25
36
  readonly faces?: readonly TypertFace[];
26
37
  }
38
+ /** A workspace-mode generation failure reported by, or observed on, the Typert Worker Thread. */
39
+ export declare class TypertWorkerError extends Error {
40
+ name: string;
41
+ }
27
42
  /**
28
43
  * Create the decorator-lowering and typert-generation plugin for the root tsdown config.
29
44
  * @param pluginOptions - package/workspace emission mode and independent program faces.
@@ -2,18 +2,29 @@
2
2
  * Optional tsdown (rolldown) plugin face of the typert generator. It lowers
3
3
  * standard decorators in TypeScript dependencies before bundling, then emits
4
4
  * model-driven face artifacts at the package output root. Packages without a
5
- * Typert or Remote export are skipped.
5
+ * Typert or Remote export are skipped. Workspace mode generates in a Worker
6
+ * Thread started by the pass's first `buildStart`, so bundling continues on the
7
+ * main thread while Typert analyzes; the pass's first `writeBundle` awaits the
8
+ * result and writes every artifact once.
6
9
  * @module @deepseek-ai/dsh-typert-generator/tsdown
7
10
  */
8
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { existsSync, readFileSync } from 'node:fs';
9
12
  import { dirname, join, resolve } from 'node:path';
13
+ import { Worker } from 'node:worker_threads';
10
14
  import ts from 'typescript';
11
- import { WorkspaceTypertGenerator } from "./workspace.js";
15
+ import { writePackageArtifacts, writeWorkspaceArtifacts } from "./artifact-files.js";
16
+ import { findWorkspaceRoot, hasTypertExport, WorkspaceTypertGenerator } from "./workspace.js";
17
+ /** A module id whose path (before any `?query`) names a TypeScript source. */
18
+ const TYPESCRIPT_MODULE = /^[^?]*\.[cm]?tsx?(?:\?|$)/;
12
19
  const DECORATOR_SYNTAX = /^\s*@[A-Za-z_$][\w$]*/m;
13
- // This plugin consumes tsc-emitted `lib/types` output, so every project it
14
- // would re-diagnose has already passed the workspace tsc build in the same
15
- // orchestration; the generator skips its per-package diagnostic pass here.
16
- const TSC_VERIFIED_INPUT = { checkDiagnostics: false };
20
+ // Full builds and typecheck own TypeScript diagnostics. Benchmark-only emission
21
+ // defers them to the required full-build CI jobs; Typert generates reflection
22
+ // without repeating those diagnostics.
23
+ const TSC_OWNED_DIAGNOSTICS = { checkDiagnostics: false };
24
+ /** A workspace-mode generation failure reported by, or observed on, the Typert Worker Thread. */
25
+ export class TypertWorkerError extends Error {
26
+ name = 'TypertWorkerError';
27
+ }
17
28
  /**
18
29
  * Create the decorator-lowering and typert-generation plugin for the root tsdown config.
19
30
  * @param pluginOptions - package/workspace emission mode and independent program faces.
@@ -21,39 +32,68 @@ const TSC_VERIFIED_INPUT = { checkDiagnostics: false };
21
32
  */
22
33
  export function typertPlugin(pluginOptions = {}) {
23
34
  const artifactsByRoot = new Map();
35
+ const generations = new Map();
24
36
  const emittedWorkspaces = new Set();
37
+ const workspaceGeneration = (root) => {
38
+ let generation = generations.get(root);
39
+ if (generation === undefined) {
40
+ generation = generateInWorker({
41
+ root,
42
+ ...(pluginOptions.faces === undefined ? {} : { faces: pluginOptions.faces }),
43
+ options: TSC_OWNED_DIAGNOSTICS,
44
+ });
45
+ generations.set(root, generation);
46
+ }
47
+ return generation;
48
+ };
25
49
  return {
26
50
  name: 'dsh-typert-generator',
27
- transform(code, id) {
28
- const file = id.split('?', 1)[0] ?? id;
29
- if (!/\.[cm]?tsx?$/.test(file) || !DECORATOR_SYNTAX.test(code))
30
- return;
31
- const result = ts.transpileModule(code, {
32
- fileName: file,
33
- compilerOptions: {
34
- target: ts.ScriptTarget.ES2024,
35
- module: ts.ModuleKind.ESNext,
36
- ...(file.endsWith('x') ? { jsx: ts.JsxEmit.ReactJSX } : {}),
37
- sourceMap: true,
38
- },
39
- });
40
- return {
41
- code: result.outputText.replace(/\n?\/\/# sourceMappingURL=.*$/u, '\n'),
42
- map: result.sourceMapText,
43
- };
51
+ buildStart(inputOptions) {
52
+ // tsdown builds every workspace package concurrently through this one
53
+ // plugin instance; the first package build to start launches generation.
54
+ if (pluginOptions.mode === 'workspace')
55
+ void workspaceGeneration(findWorkspaceRoot(inputOptions.cwd));
44
56
  },
45
- writeBundle(bundleOptions) {
57
+ transform: {
58
+ // Rolldown evaluates the id filter natively, so non-TypeScript modules
59
+ // never cross into this JavaScript hook.
60
+ filter: { id: TYPESCRIPT_MODULE },
61
+ handler(code, id) {
62
+ if (!TYPESCRIPT_MODULE.test(id) || !DECORATOR_SYNTAX.test(code))
63
+ return;
64
+ const file = id.replace(/\?.*$/su, '');
65
+ const result = ts.transpileModule(code, {
66
+ fileName: file,
67
+ compilerOptions: {
68
+ target: ts.ScriptTarget.ES2024,
69
+ module: ts.ModuleKind.ESNext,
70
+ ...(file.endsWith('x') ? { jsx: ts.JsxEmit.ReactJSX } : {}),
71
+ sourceMap: true,
72
+ },
73
+ });
74
+ return {
75
+ code: result.outputText.replace(/\n?\/\/# sourceMappingURL=.*$/u, '\n'),
76
+ map: result.sourceMapText,
77
+ };
78
+ },
79
+ },
80
+ async writeBundle(bundleOptions) {
46
81
  // options.dir is the package's absolute outDir (<package>/lib); its
47
82
  // nearest package.json owns the bundle even when a custom config writes
48
83
  // a nested output such as <package>/lib/dev.
49
84
  if (bundleOptions.dir === undefined)
50
85
  return;
51
- const root = workspaceRoot(bundleOptions.dir);
86
+ const root = findWorkspaceRoot(bundleOptions.dir);
52
87
  if (emittedWorkspaces.has(root))
53
88
  return;
54
89
  if (pluginOptions.mode === 'workspace') {
55
- emitWorkspace(root, pluginOptions.faces);
90
+ // The first bundle to finish claims emission and reports any failure;
91
+ // later bundles of the pass return without waiting.
56
92
  emittedWorkspaces.add(root);
93
+ const outcome = await workspaceGeneration(root);
94
+ if (!outcome.ok)
95
+ throw outcome.error;
96
+ writeWorkspaceArtifacts(root, outcome.artifacts);
57
97
  return;
58
98
  }
59
99
  const packageDir = packageRoot(bundleOptions.dir, root);
@@ -64,59 +104,128 @@ export function typertPlugin(pluginOptions = {}) {
64
104
  return;
65
105
  let artifacts = artifactsByRoot.get(root);
66
106
  if (artifacts === undefined) {
67
- const generator = new WorkspaceTypertGenerator(root, TSC_VERIFIED_INPUT);
107
+ const generator = new WorkspaceTypertGenerator(root, TSC_OWNED_DIAGNOSTICS);
68
108
  artifacts = pluginOptions.faces === undefined
69
109
  ? generator.generate()
70
110
  : generator.generate(undefined, pluginOptions.faces);
71
111
  artifactsByRoot.set(root, artifacts);
72
112
  }
73
- emitArtifacts(packageDir, artifacts.filter(candidate => candidate.package === manifest.name));
113
+ writePackageArtifacts(packageDir, artifacts.filter(candidate => candidate.package === manifest.name));
74
114
  },
75
115
  };
76
- function emitWorkspace(root, faces) {
77
- const generator = new WorkspaceTypertGenerator(root, TSC_VERIFIED_INPUT);
78
- const packages = generator.discover(faces)
79
- .filter(candidate => hasTypertExport(readManifest(join(root, candidate.root)).exports))
80
- .map(candidate => candidate.package);
81
- if (packages.length === 0)
82
- return;
83
- for (const artifact of generator.generate(packages, faces)) {
84
- emitArtifacts(join(root, artifact.packageRoot), [artifact]);
85
- }
116
+ }
117
+ /**
118
+ * Run workspace generation in a Worker Thread. The outcome never rejects, and
119
+ * every terminal path terminates the worker before the outcome settles.
120
+ */
121
+ function generateInWorker(request) {
122
+ const worker = spawnWorker(request);
123
+ return new Promise((settle) => {
124
+ let settled = false;
125
+ const finish = (outcome) => {
126
+ if (settled)
127
+ return;
128
+ settled = true;
129
+ worker.terminate().then(() => { settle(outcome); }, (error) => { settle({ ok: false, error: workerError(request, 'could not terminate its worker', error) }); });
130
+ };
131
+ const fail = (problem, cause) => {
132
+ finish({ ok: false, error: workerError(request, problem, cause) });
133
+ };
134
+ worker.once('message', (value) => {
135
+ const response = parseWorkerResponse(value);
136
+ if (response === undefined) {
137
+ fail('received a malformed worker response');
138
+ }
139
+ else if (response.kind === 'failure') {
140
+ const cause = new Error(response.message);
141
+ cause.name = response.name;
142
+ if (response.stack !== undefined)
143
+ cause.stack = response.stack;
144
+ fail(`failed: ${response.name}: ${response.message}`, cause);
145
+ }
146
+ else {
147
+ finish({ ok: true, artifacts: response.artifacts });
148
+ }
149
+ });
150
+ worker.once('messageerror', (error) => { fail('received a worker response that could not be deserialized', error); });
151
+ worker.once('error', (error) => { fail(`crashed: ${error.message}`, error); });
152
+ worker.once('exit', (code) => { fail(`stopped: its worker exited with code ${String(code)} before reporting artifacts`); });
153
+ });
154
+ }
155
+ function workerError(request, problem, cause) {
156
+ return new TypertWorkerError(`typert-generator: workspace generation for ${request.root} ${problem}`, cause === undefined ? undefined : { cause });
157
+ }
158
+ function spawnWorker(request) {
159
+ /* v8 ignore next 3 -- the tsdown host build runs the built worker entry. */
160
+ if (!import.meta.url.endsWith('.ts')) {
161
+ return new Worker(new URL('./worker.js', import.meta.url), { workerData: request });
86
162
  }
163
+ // Source runs load the TypeScript worker entry through tsx.
164
+ const bootstrap = [
165
+ `import { register } from ${JSON.stringify(import.meta.resolve('tsx/esm/api'))}`,
166
+ 'register()',
167
+ `await import(${JSON.stringify(new URL('./worker.ts', import.meta.url).href)})`,
168
+ ].join('\n');
169
+ return new Worker(new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`), { workerData: request, execArgv: [] });
87
170
  }
88
- function emitArtifacts(packageDir, artifacts) {
89
- const output = join(packageDir, 'lib');
90
- mkdirSync(output, { recursive: true });
91
- let emittedRemote = false;
92
- for (const artifact of artifacts) {
93
- writeFileSync(join(output, `typert.${artifact.face}.js`), artifact.js);
94
- writeFileSync(join(output, `typert.${artifact.face}.d.ts`), artifact.dts);
95
- if (artifact.remote !== undefined) {
96
- emittedRemote = true;
97
- writeFileSync(join(output, 'typert.remote-client.js'), artifact.remote.js);
98
- writeFileSync(join(output, 'typert.remote-client.d.ts'), artifact.remote.dts);
99
- writeFileSync(join(output, 'typert.remote-client.d.ts.map'), artifact.remote.dtsMap);
100
- }
171
+ function parseWorkerResponse(value) {
172
+ if (!isRecord(value))
173
+ return undefined;
174
+ if (value.kind === 'failure') {
175
+ if (typeof value.name !== 'string' || typeof value.message !== 'string'
176
+ || (value.stack !== undefined && typeof value.stack !== 'string'))
177
+ return undefined;
178
+ return {
179
+ kind: 'failure',
180
+ name: value.name,
181
+ message: value.message,
182
+ ...(value.stack === undefined ? {} : { stack: value.stack }),
183
+ };
101
184
  }
102
- if (!emittedRemote && artifacts.some(artifact => artifact.face === 'host')) {
103
- for (const file of [
104
- 'typert.remote-client.js',
105
- 'typert.remote-client.d.ts',
106
- 'typert.remote-client.d.ts.map',
107
- ])
108
- rmSync(join(output, file), { force: true });
185
+ if (value.kind !== 'artifacts' || !Array.isArray(value.artifacts))
186
+ return undefined;
187
+ const artifacts = [];
188
+ for (const artifact of value.artifacts) {
189
+ const parsed = parseArtifact(artifact);
190
+ if (parsed === undefined)
191
+ return undefined;
192
+ artifacts.push(parsed);
109
193
  }
194
+ return { kind: 'artifacts', artifacts };
110
195
  }
111
- function readManifest(packageDir) {
112
- return JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'));
196
+ function parseArtifact(value) {
197
+ if (!isRecord(value)
198
+ || typeof value.package !== 'string'
199
+ || typeof value.packageRoot !== 'string'
200
+ || (value.face !== 'host' && value.face !== 'client')
201
+ || !Array.isArray(value.exports)
202
+ || !value.exports.every((entry) => typeof entry === 'string')
203
+ || typeof value.js !== 'string'
204
+ || typeof value.dts !== 'string')
205
+ return undefined;
206
+ const remote = parseRemoteArtifact(value.remote);
207
+ if (value.remote !== undefined && remote === undefined)
208
+ return undefined;
209
+ return {
210
+ package: value.package,
211
+ packageRoot: value.packageRoot,
212
+ face: value.face,
213
+ exports: value.exports,
214
+ js: value.js,
215
+ dts: value.dts,
216
+ ...(remote === undefined ? {} : { remote }),
217
+ };
218
+ }
219
+ function parseRemoteArtifact(value) {
220
+ if (!isRecord(value)
221
+ || typeof value.js !== 'string'
222
+ || typeof value.dts !== 'string'
223
+ || typeof value.dtsMap !== 'string')
224
+ return undefined;
225
+ return { js: value.js, dts: value.dts, dtsMap: value.dtsMap };
113
226
  }
114
- function hasTypertExport(exportsField) {
115
- if (exportsField === null || typeof exportsField !== 'object' || Array.isArray(exportsField))
116
- return false;
117
- return Object.hasOwn(exportsField, './typert')
118
- || Object.hasOwn(exportsField, './client/typert')
119
- || Object.hasOwn(exportsField, './remote');
227
+ function isRecord(value) {
228
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
120
229
  }
121
230
  function packageRoot(start, workspace) {
122
231
  let current = resolve(start);
@@ -127,14 +236,4 @@ function packageRoot(start, workspace) {
127
236
  }
128
237
  return undefined;
129
238
  }
130
- function workspaceRoot(start) {
131
- let current = resolve(start);
132
- while (!existsSync(join(current, 'tsconfig.host.json'))) {
133
- const parent = dirname(current);
134
- if (parent === current)
135
- throw new Error(`typert-generator: cannot find workspace root above ${start}`);
136
- current = parent;
137
- }
138
- return current;
139
- }
140
239
  //# sourceMappingURL=tsdown-plugin.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Worker Thread entry for workspace-mode Typert generation. It generates every
3
+ * explicit contributor of the requested workspace, posts exactly one
4
+ * {@link WorkspaceWorkerResponse}, and exits.
5
+ * @module @deepseek-ai/dsh-typert-generator/worker
6
+ */
7
+ import type { WorkspaceEmitResult, WorkspaceTypertGeneratorOptions } from './workspace.ts';
8
+ import type { TypertFace } from './model.ts';
9
+ /** Generation inputs passed as `workerData`. */
10
+ export interface WorkspaceWorkerRequest {
11
+ /** Workspace root containing the face aggregate tsconfigs. */
12
+ readonly root: string;
13
+ /** Faces to generate; every face when absent. */
14
+ readonly faces?: readonly TypertFace[];
15
+ /** Generator switches applied to the pass. */
16
+ readonly options: WorkspaceTypertGeneratorOptions;
17
+ }
18
+ /** The single message the worker posts: every generated artifact, or the failure that stopped generation. */
19
+ export type WorkspaceWorkerResponse = {
20
+ readonly kind: 'artifacts';
21
+ readonly artifacts: readonly WorkspaceEmitResult[];
22
+ } | {
23
+ readonly kind: 'failure';
24
+ readonly name: string;
25
+ readonly message: string;
26
+ readonly stack?: string;
27
+ };
28
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Worker Thread entry for workspace-mode Typert generation. It generates every
3
+ * explicit contributor of the requested workspace, posts exactly one
4
+ * {@link WorkspaceWorkerResponse}, and exits.
5
+ * @module @deepseek-ai/dsh-typert-generator/worker
6
+ */
7
+ import { parentPort, workerData } from 'node:worker_threads';
8
+ import { WorkspaceTypertGenerator } from "./workspace.js";
9
+ function parseRequest(value) {
10
+ const request = typeof value === 'object' && value !== null
11
+ ? value
12
+ : {};
13
+ const { root, faces, options } = request;
14
+ const checkDiagnostics = typeof options === 'object' && options !== null
15
+ ? options.checkDiagnostics
16
+ : null;
17
+ if (typeof root !== 'string'
18
+ || (faces !== undefined
19
+ && (!Array.isArray(faces) || !faces.every((face) => face === 'host' || face === 'client')))
20
+ || (checkDiagnostics !== undefined && typeof checkDiagnostics !== 'boolean')) {
21
+ throw new TypeError('typert-generator: malformed workspace worker request');
22
+ }
23
+ return {
24
+ root,
25
+ ...(faces === undefined ? {} : { faces }),
26
+ options: checkDiagnostics === undefined ? {} : { checkDiagnostics },
27
+ };
28
+ }
29
+ function respond() {
30
+ try {
31
+ const request = parseRequest(workerData);
32
+ const generator = new WorkspaceTypertGenerator(request.root, request.options);
33
+ return { kind: 'artifacts', artifacts: generator.generateContributors(request.faces) };
34
+ }
35
+ catch (error) {
36
+ if (!(error instanceof Error))
37
+ return { kind: 'failure', name: 'Error', message: String(error) };
38
+ return {
39
+ kind: 'failure',
40
+ name: error.name,
41
+ message: error.message,
42
+ ...(error.stack === undefined ? {} : { stack: error.stack }),
43
+ };
44
+ }
45
+ }
46
+ if (parentPort === null)
47
+ throw new Error('typert-generator: the workspace worker entry must run in a Worker Thread');
48
+ parentPort.postMessage(respond());
49
+ //# sourceMappingURL=worker.js.map
@@ -19,6 +19,13 @@ export interface WorkspaceTypertGeneratorOptions {
19
19
  * merges) run regardless.
20
20
  */
21
21
  readonly checkDiagnostics?: boolean;
22
+ /**
23
+ * Fail when an analyzed face program loads a file from a workspace
24
+ * package's `lib/` directory or cannot resolve an import of a workspace
25
+ * package (default false); see
26
+ * `WorkspaceAnalyzerOptions.rejectBuildOutputs`.
27
+ */
28
+ readonly rejectBuildOutputs?: boolean;
22
29
  }
23
30
  /** Discover, analyze, and emit package reflection from independent faces. */
24
31
  export declare class WorkspaceTypertGenerator {
@@ -36,16 +43,41 @@ export declare class WorkspaceTypertGenerator {
36
43
  * Find public package faces that contribute Cordis services/events or
37
44
  * explicitly tagged Typert roots.
38
45
  * @param faces - optional independent program faces to inspect.
46
+ * @param includeManifest - optional `package.json` predicate; a rejected package's sources and project config are not read.
39
47
  * @returns discovered packages in stable package-name order.
40
48
  */
41
- discover(faces?: readonly TypertFace[]): DiscoveredTypertPackage[];
49
+ discover(faces?: readonly TypertFace[], includeManifest?: (manifest: Readonly<Record<string, unknown>>) => boolean): DiscoveredTypertPackage[];
42
50
  /**
43
51
  * Generate all discovered contributors, or an explicit package subset.
44
- * @param packages - optional exact package names for a focused pass.
52
+ * @param packages - optional exact package names to emit; every pass includes the same face-wide declaration merges.
45
53
  * @param faces - optional independent program faces to analyze.
46
54
  * @returns one artifact per package face.
47
55
  */
48
56
  generate(packages?: readonly string[], faces?: readonly TypertFace[]): WorkspaceEmitResult[];
57
+ /**
58
+ * Generate every explicit contributor: a package whose manifest declares a
59
+ * Typert artifact export and whose public graph has a Typert surface.
60
+ * @param faces - optional independent program faces to analyze.
61
+ * @returns one artifact per contributor face.
62
+ */
63
+ generateContributors(faces?: readonly TypertFace[]): WorkspaceEmitResult[];
49
64
  private validateExport;
50
65
  }
66
+ /**
67
+ * Find the workspace root that Typert generation runs against: the nearest
68
+ * directory at or above `start` that holds both `tsconfig.host.json` and
69
+ * `packages/`. The analyzer registers projects under `<root>/packages`, so a
70
+ * package's own `tsconfig.host.json` face leaf does not qualify.
71
+ * @param start - directory to search from, such as a bundle output or a working directory.
72
+ * @returns the absolute workspace root.
73
+ * @throws If no ancestor of `start` qualifies.
74
+ */
75
+ export declare function findWorkspaceRoot(start: string): string;
76
+ /**
77
+ * Whether a `package.json#exports` field declares a Typert artifact subpath
78
+ * (`./typert`, `./client/typert`, or `./remote`).
79
+ * @param exportsField - the manifest's `exports` value.
80
+ * @returns true when the package opts in to Typert publication.
81
+ */
82
+ export declare function hasTypertExport(exportsField: unknown): boolean;
51
83
  //# sourceMappingURL=workspace.d.ts.map
@@ -2,8 +2,8 @@
2
2
  * Workspace-level discovery and model-driven Typert generation.
3
3
  * @module @deepseek-ai/dsh-typert-generator/workspace
4
4
  */
5
- import { readFileSync } from 'node:fs';
6
- import { resolve } from 'node:path';
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { dirname, join, resolve } from 'node:path';
7
7
  import { TypertAnalysisError, WorkspaceAnalyzer, WorkspaceCaches } from "./analyzer.js";
8
8
  import { FaceModelEmitter } from "./emitter.js";
9
9
  /** Discover, analyze, and emit package reflection from independent faces. */
@@ -25,34 +25,39 @@ export class WorkspaceTypertGenerator {
25
25
  * Find public package faces that contribute Cordis services/events or
26
26
  * explicitly tagged Typert roots.
27
27
  * @param faces - optional independent program faces to inspect.
28
+ * @param includeManifest - optional `package.json` predicate; a rejected package's sources and project config are not read.
28
29
  * @returns discovered packages in stable package-name order.
29
30
  */
30
- discover(faces) {
31
+ discover(faces, includeManifest) {
31
32
  return new WorkspaceAnalyzer({
32
33
  root: this.root,
33
34
  caches: this.caches,
34
35
  ...(faces === undefined ? {} : { faces }),
35
- }).discoverPackages();
36
+ }).discoverPackages(includeManifest);
36
37
  }
37
38
  /**
38
39
  * Generate all discovered contributors, or an explicit package subset.
39
- * @param packages - optional exact package names for a focused pass.
40
+ * @param packages - optional exact package names to emit; every pass includes the same face-wide declaration merges.
40
41
  * @param faces - optional independent program faces to analyze.
41
42
  * @returns one artifact per package face.
42
43
  */
43
44
  generate(packages, faces) {
44
- const selected = packages ?? this.discover(faces).map(candidate => candidate.package);
45
+ const contributors = this.discover(faces).map(candidate => candidate.package);
46
+ const selected = new Set(packages ?? contributors);
45
47
  const workspace = new WorkspaceAnalyzer({
46
48
  root: this.root,
47
- packages: selected,
49
+ packages: contributors,
48
50
  caches: this.caches,
49
51
  ...(faces === undefined ? {} : { faces }),
50
52
  ...(this.options.checkDiagnostics === undefined ? {} : { checkDiagnostics: this.options.checkDiagnostics }),
53
+ ...(this.options.rejectBuildOutputs === undefined ? {} : { rejectBuildOutputs: this.options.rejectBuildOutputs }),
51
54
  }).analyze();
52
55
  const artifacts = [];
53
56
  for (const face of workspace.faces) {
54
57
  const emitter = new FaceModelEmitter(face);
55
58
  for (const packageModel of face.packages) {
59
+ if (!selected.has(packageModel.name))
60
+ continue;
56
61
  const artifact = {
57
62
  ...emitter.emit(packageModel.name),
58
63
  packageRoot: packageModel.root,
@@ -63,6 +68,17 @@ export class WorkspaceTypertGenerator {
63
68
  }
64
69
  return artifacts;
65
70
  }
71
+ /**
72
+ * Generate every explicit contributor: a package whose manifest declares a
73
+ * Typert artifact export and whose public graph has a Typert surface.
74
+ * @param faces - optional independent program faces to analyze.
75
+ * @returns one artifact per contributor face.
76
+ */
77
+ generateContributors(faces) {
78
+ const packages = this.discover(faces, manifest => hasTypertExport(manifest.exports))
79
+ .map(candidate => candidate.package);
80
+ return packages.length === 0 ? [] : this.generate(packages, faces);
81
+ }
66
82
  validateExport(artifact) {
67
83
  const manifestPath = resolve(this.root, artifact.packageRoot, 'package.json');
68
84
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
@@ -115,6 +131,38 @@ export class WorkspaceTypertGenerator {
115
131
  }
116
132
  }
117
133
  }
134
+ /**
135
+ * Find the workspace root that Typert generation runs against: the nearest
136
+ * directory at or above `start` that holds both `tsconfig.host.json` and
137
+ * `packages/`. The analyzer registers projects under `<root>/packages`, so a
138
+ * package's own `tsconfig.host.json` face leaf does not qualify.
139
+ * @param start - directory to search from, such as a bundle output or a working directory.
140
+ * @returns the absolute workspace root.
141
+ * @throws If no ancestor of `start` qualifies.
142
+ */
143
+ export function findWorkspaceRoot(start) {
144
+ let current = resolve(start);
145
+ while (!existsSync(join(current, 'tsconfig.host.json')) || !existsSync(join(current, 'packages'))) {
146
+ const parent = dirname(current);
147
+ if (parent === current)
148
+ throw new Error(`typert-generator: cannot find workspace root above ${start}`);
149
+ current = parent;
150
+ }
151
+ return current;
152
+ }
153
+ /**
154
+ * Whether a `package.json#exports` field declares a Typert artifact subpath
155
+ * (`./typert`, `./client/typert`, or `./remote`).
156
+ * @param exportsField - the manifest's `exports` value.
157
+ * @returns true when the package opts in to Typert publication.
158
+ */
159
+ export function hasTypertExport(exportsField) {
160
+ if (exportsField === null || typeof exportsField !== 'object' || Array.isArray(exportsField))
161
+ return false;
162
+ return Object.hasOwn(exportsField, './typert')
163
+ || Object.hasOwn(exportsField, './client/typert')
164
+ || Object.hasOwn(exportsField, './remote');
165
+ }
118
166
  function sameExport(actual, expected) {
119
167
  if (actual === null || typeof actual !== 'object' || Array.isArray(actual))
120
168
  return false;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-typert-generator",
3
3
  "description": "TypeScript project analyzer and model-driven Typert artifact generator",
4
- "version": "0.2.1-alpha.1",
4
+ "version": "0.2.1-alpha.3",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -36,12 +36,13 @@
36
36
  "typescript": "^6.0.3"
37
37
  },
38
38
  "peerDependencies": {
39
- "@deepseek-ai/cordis": "~4.0.5-alpha.1"
39
+ "@deepseek-ai/cordis": "~4.0.5-alpha.2"
40
40
  },
41
41
  "devDependencies": {
42
- "zod": "^4.4.3",
43
- "@deepseek-ai/dsh-tool-cordis": "0.2.1-alpha.1",
44
- "@deepseek-ai/dsh-typert-registry": "0.2.1-alpha.1",
45
- "@deepseek-ai/cordis": "~4.0.5-alpha.1"
42
+ "@deepseek-ai/dsh-tools": "0.2.1-alpha.3",
43
+ "@deepseek-ai/dsh-tool-cordis": "0.2.1-alpha.3",
44
+ "@deepseek-ai/dsh-typert-registry": "0.2.1-alpha.3",
45
+ "@deepseek-ai/cordis": "~4.0.5-alpha.2",
46
+ "zod": "4.4.3"
46
47
  }
47
48
  }