@open-document/core 0.14.1 → 0.14.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.
Files changed (43) hide show
  1. package/dist/{build-I0cgoERP.js → build-4K9V8ysT.js} +1 -1
  2. package/dist/{check-Dys96QSL.js → check-B40JlWME.js} +3 -3
  3. package/dist/cli/bin.js +9 -9
  4. package/dist/{context-C-osJW5f.js → context-Clm_nmr1.js} +1 -1
  5. package/dist/{dev-CC4PrIOC.js → dev-De3pLYn_.js} +1 -1
  6. package/dist/{diff-DhutD4TJ.js → diff-nU9ybiMk.js} +2 -2
  7. package/dist/{export-KrajVJO7.js → export-B9rrNBx2.js} +3 -3
  8. package/dist/{import-Yv34za3L.js → import-C3542Wry.js} +3 -3
  9. package/dist/ops/index.js +2 -2
  10. package/dist/{ops-Dux5HlkH.js → ops-ByJnGyuE.js} +1 -1
  11. package/dist/{preview-7eqn9Wzf.js → preview-id9mj3IU.js} +1 -1
  12. package/dist/{session-BSbrC5gK.js → session-CdkoJhi1.js} +15 -6
  13. package/dist/{templates-s-VLTSRc.js → templates-UJ_v7H-a.js} +3 -3
  14. package/dist/vite/index.js +1 -1
  15. package/package.json +6 -1
  16. package/src/agent/check-after-turn.ts +59 -0
  17. package/src/agent/detect.ts +158 -0
  18. package/src/agent/install.ts +73 -0
  19. package/src/agent/prompt.ts +175 -0
  20. package/src/agent/provider.ts +126 -0
  21. package/src/agent/providers/codex.ts +209 -0
  22. package/src/agent/providers/index.ts +7 -0
  23. package/src/agent/providers/sdk-types.ts +71 -0
  24. package/src/agent/runner.ts +392 -0
  25. package/src/agent/status.ts +64 -0
  26. package/src/agent/store.ts +271 -0
  27. package/src/agent/types.ts +174 -0
  28. package/src/diagram/index.ts +46 -0
  29. package/src/diagram/layout.ts +627 -0
  30. package/src/diagram/parse.ts +335 -0
  31. package/src/diagram/render.ts +162 -0
  32. package/src/editing/placeholder-id.ts +2 -0
  33. package/src/app/lib/chart.test.ts +0 -123
  34. package/src/app/lib/docx/ooxml.test.ts +0 -484
  35. package/src/app/lib/flow-measure.test.ts +0 -30
  36. package/src/app/lib/flow.test.ts +0 -129
  37. package/src/app/lib/footnotes.test.tsx +0 -102
  38. package/src/app/lib/i18n.test.ts +0 -24
  39. package/src/app/lib/inspector/inline-edit.test.ts +0 -244
  40. package/src/app/lib/page-range.test.ts +0 -104
  41. package/src/app/lib/records.test.ts +0 -38
  42. package/src/app/lib/sdk.test.ts +0 -30
  43. package/src/app/lib/view-mode.test.ts +0 -46
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-BSbrC5gK.js";
1
+ import { r as createViteConfig } from "./session-CdkoJhi1.js";
2
2
  import path from "node:path";
3
3
  import { build as build$1, mergeConfig } from "vite";
4
4
  //#region src/cli/build.ts
@@ -1,6 +1,6 @@
1
- import { R as listDocIds, S as closeRenderSession, x as checkLayout } from "./session-BSbrC5gK.js";
2
- import "./ops-Dux5HlkH.js";
3
- import { t as cliContext } from "./context-C-osJW5f.js";
1
+ import { R as listDocIds, S as closeRenderSession, x as checkLayout } from "./session-CdkoJhi1.js";
2
+ import "./ops-ByJnGyuE.js";
3
+ import { t as cliContext } from "./context-Clm_nmr1.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/check.ts
6
6
  function line(finding) {
package/dist/cli/bin.js CHANGED
@@ -143,39 +143,39 @@ async function run(argv) {
143
143
  program.name("open-doc").description("Author documents — we handle the Vite/React stack, pagination, and export.").version(version, "-v, --version", "print version").helpOption("-h, --help", "show help").showHelpAfterError(chalk.dim("(run `open-doc --help` for usage)"));
144
144
  program.command("dev").description("Start the dev server").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").option("--no-skills-check", "skip the built-in skills drift check").option("--mcp", "serve an MCP endpoint at /mcp (requires @open-document/mcp)").action(async (flags) => {
145
145
  if (flags.skillsCheck !== false) await runSkillsDriftCheck(resolveBuiltinSkillsDir());
146
- const { dev } = await import("../dev-CC4PrIOC.js");
146
+ const { dev } = await import("../dev-De3pLYn_.js");
147
147
  await dev(flags);
148
148
  });
149
149
  program.command("build").description("Build a static site").option("--out-dir <dir>", "output directory (defaults to `dist`)").action(async (flags) => {
150
- const { build } = await import("../build-I0cgoERP.js");
150
+ const { build } = await import("../build-4K9V8ysT.js");
151
151
  await build(flags);
152
152
  });
153
153
  program.command("preview").description("Preview the production build").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").action(async (flags) => {
154
- const { preview } = await import("../preview-7eqn9Wzf.js");
154
+ const { preview } = await import("../preview-id9mj3IU.js");
155
155
  await preview(flags);
156
156
  });
157
157
  program.command("export [docIds...]").description("Render documents headlessly to PDF, HTML, PNG, or DOCX").addOption(new Option("-f, --format <format>", "output format").choices([...EXPORT_FORMATS])).option("-o, --out-dir <dir>", "directory to write into (defaults to `out`)").option("--all", "export every document under docs/").option("--each", "one copy per row of the document's `records`").option("--name <pattern>", "with --each: file name, e.g. \"certificate-{name}\" ({#} is the row number)").action(async (docIds, flags) => {
158
- const { exportDocs } = await import("../export-KrajVJO7.js");
158
+ const { exportDocs } = await import("../export-B9rrNBx2.js");
159
159
  await exportDocs(docIds, flags);
160
160
  });
161
161
  program.command("diff <docId>").description("Show what changed in a document since a git revision, page by page").option("-s, --since <rev>", "revision to compare against (defaults to HEAD)").option("-o, --out-dir <dir>", "directory to write the report into (defaults to `out`)").option("--json", "print the result as JSON").action(async (docId, flags) => {
162
- const { diffDoc } = await import("../diff-DhutD4TJ.js");
162
+ const { diffDoc } = await import("../diff-nU9ybiMk.js");
163
163
  await diffDoc(docId, flags);
164
164
  });
165
165
  program.command("check [docIds...]").description("Report layout faults — clipped content, blank sheets, stranded headings").option("--json", "print the full report as JSON").action(async (docIds, flags) => {
166
- const { checkDocs } = await import("../check-Dys96QSL.js");
166
+ const { checkDocs } = await import("../check-B40JlWME.js");
167
167
  await checkDocs(docIds, flags);
168
168
  });
169
169
  program.command("templates").description("List the templates a new document can start from").option("--json", "print them as JSON").action(async (flags) => {
170
- const { printTemplates } = await import("../templates-s-VLTSRc.js");
170
+ const { printTemplates } = await import("../templates-UJ_v7H-a.js");
171
171
  await printTemplates(flags);
172
172
  });
173
173
  program.command("new [docId]").description("Create a document under docs/ from a template (see `open-doc templates`)").option("-t, --template <name>", "template to start from (defaults to blank)").option("--title <title>", "title of the new document").action(async (docId, flags) => {
174
- const { newDoc } = await import("../templates-s-VLTSRc.js");
174
+ const { newDoc } = await import("../templates-UJ_v7H-a.js");
175
175
  await newDoc(docId, flags);
176
176
  });
177
177
  program.command("import <file>").description("Turn a Markdown file into a document under docs/").option("--id <id>", "document id (defaults to a slug of the title)").option("--title <title>", "override the title").option("--subtitle <subtitle>", "subtitle, also used as the cover eyebrow").option("--lang <tag>", "language of the text, e.g. zh-Hant-TW (detected for CJK when omitted)").option("--author <author>", "author line on the cover").option("--theme <theme>", "theme id to back-link from meta.theme").addOption(new Option("--page-size <size>", "page size").choices(PAGE_SIZE_NAMES)).addOption(new Option("--orientation <orientation>", "page orientation").choices(ORIENTATIONS)).option("--no-cover", "skip the title page").option("--contents", "add a self-filling contents page").action(async (file, flags) => {
178
- const { importDoc } = await import("../import-Yv34za3L.js");
178
+ const { importDoc } = await import("../import-C3542Wry.js");
179
179
  await importDoc(file, flags);
180
180
  });
181
181
  program.command("sync:skills").description("Sync built-in skills from @open-document/core into this workspace").option("--dry-run", "show what would change without writing").action(async (flags) => {
@@ -1,6 +1,6 @@
1
1
  import { n as readCoreVersion } from "./package-version-C89gtYSk.js";
2
2
  import { n as loadUserConfig } from "./open-doc-plugin-DnX5usgI.js";
3
- import { W as makeContext } from "./session-BSbrC5gK.js";
3
+ import { W as makeContext } from "./session-CdkoJhi1.js";
4
4
  //#region src/cli/context.ts
5
5
  /** The same context the dev API and the MCP server run on, for commands that call `ops/`. */
6
6
  async function cliContext(userCwd = process.cwd()) {
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-BSbrC5gK.js";
1
+ import { r as createViteConfig } from "./session-CdkoJhi1.js";
2
2
  import { createServer, mergeConfig } from "vite";
3
3
  //#region src/cli/dev.ts
4
4
  async function dev(opts = {}) {
@@ -1,5 +1,5 @@
1
- import { t as diffDocument } from "./ops-Dux5HlkH.js";
2
- import { t as cliContext } from "./context-C-osJW5f.js";
1
+ import { t as diffDocument } from "./ops-ByJnGyuE.js";
2
+ import { t as cliContext } from "./context-Clm_nmr1.js";
3
3
  import chalk from "chalk";
4
4
  //#region src/cli/diff.ts
5
5
  const MARK = {
@@ -1,7 +1,7 @@
1
1
  import { r as EXPORT_FORMATS } from "./sdk-CqNZzbkz.js";
2
- import { C as exportDocument, R as listDocIds, S as closeRenderSession } from "./session-BSbrC5gK.js";
3
- import "./ops-Dux5HlkH.js";
4
- import { t as cliContext } from "./context-C-osJW5f.js";
2
+ import { C as exportDocument, R as listDocIds, S as closeRenderSession } from "./session-CdkoJhi1.js";
3
+ import "./ops-ByJnGyuE.js";
4
+ import { t as cliContext } from "./context-Clm_nmr1.js";
5
5
  import chalk from "chalk";
6
6
  //#region src/cli/export.ts
7
7
  const FORMATS = EXPORT_FORMATS;
@@ -1,6 +1,6 @@
1
- import { T as importMarkdown } from "./session-BSbrC5gK.js";
2
- import "./ops-Dux5HlkH.js";
3
- import { t as cliContext } from "./context-C-osJW5f.js";
1
+ import { T as importMarkdown } from "./session-CdkoJhi1.js";
2
+ import "./ops-ByJnGyuE.js";
3
+ import { t as cliContext } from "./context-Clm_nmr1.js";
4
4
  import chalk from "chalk";
5
5
  import path from "node:path";
6
6
  //#region src/cli/import.ts
package/dist/ops/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as ORIENTATIONS, o as PAGE_SIZE_NAMES, r as EXPORT_FORMATS } from "../sdk-CqNZzbkz.js";
2
- import { A as assertExpectedSource, B as readDocument, C as exportDocument, D as listRevisions, E as slugify, F as deleteDocument, H as resolveEntry, I as docDir, L as duplicateDocument, M as withFileLock, N as OpsError, O as readChanges, P as createDocument, R as listDocIds, S as closeRenderSession, T as importMarkdown, U as writeDocument, V as renameDocument, W as makeContext, _ as listFolders, a as readText, b as writeAsset, c as writeTexts, d as suggestDocId, f as createFolder, g as listAssets, h as findAssetUsages, i as addComment, j as hashSource, k as revertChange, l as createFromTemplate, m as fileDocument, o as writeEdits, p as deleteAsset, s as writeText, u as listTemplates, v as listThemes, w as renderDocPage, x as checkLayout, y as readTheme, z as listDocuments } from "../session-BSbrC5gK.js";
3
- import { t as diffDocument } from "../ops-Dux5HlkH.js";
2
+ import { A as assertExpectedSource, B as readDocument, C as exportDocument, D as listRevisions, E as slugify, F as deleteDocument, H as resolveEntry, I as docDir, L as duplicateDocument, M as withFileLock, N as OpsError, O as readChanges, P as createDocument, R as listDocIds, S as closeRenderSession, T as importMarkdown, U as writeDocument, V as renameDocument, W as makeContext, _ as listFolders, a as readText, b as writeAsset, c as writeTexts, d as suggestDocId, f as createFolder, g as listAssets, h as findAssetUsages, i as addComment, j as hashSource, k as revertChange, l as createFromTemplate, m as fileDocument, o as writeEdits, p as deleteAsset, s as writeText, u as listTemplates, v as listThemes, w as renderDocPage, x as checkLayout, y as readTheme, z as listDocuments } from "../session-CdkoJhi1.js";
3
+ import { t as diffDocument } from "../ops-ByJnGyuE.js";
4
4
  export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
@@ -1,4 +1,4 @@
1
- import { H as resolveEntry, N as OpsError, n as createRenderSession, t as RenderUnavailableError } from "./session-BSbrC5gK.js";
1
+ import { H as resolveEntry, N as OpsError, n as createRenderSession, t as RenderUnavailableError } from "./session-CdkoJhi1.js";
2
2
  import path from "node:path";
3
3
  import fs from "node:fs/promises";
4
4
  import { execFile } from "node:child_process";
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-BSbrC5gK.js";
1
+ import { r as createViteConfig } from "./session-CdkoJhi1.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -2248,15 +2248,23 @@ function firstCommaToken(value) {
2248
2248
  const [first] = value.split(",", 1);
2249
2249
  return first?.trim() || null;
2250
2250
  }
2251
+ /**
2252
+ * `null` when nothing says which scheme the browser used: a plain socket with no
2253
+ * `x-forwarded-proto`. Cloud Shell's Web Preview terminates TLS and forwards the
2254
+ * host without the proto, so the page is https while the socket is http.
2255
+ */
2251
2256
  function requestProto(req) {
2252
2257
  const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
2253
2258
  if (forwarded === "http" || forwarded === "https") return forwarded;
2254
- return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
2259
+ return "encrypted" in req.socket && req.socket.encrypted ? "https" : null;
2255
2260
  }
2256
- function normalizedOrigin(origin) {
2261
+ function parsedOrigin(origin) {
2257
2262
  try {
2258
2263
  const url = new URL(origin);
2259
- return `${url.protocol}//${url.host}`.toLowerCase();
2264
+ return {
2265
+ scheme: url.protocol.slice(0, -1).toLowerCase(),
2266
+ host: url.host.toLowerCase()
2267
+ };
2260
2268
  } catch {
2261
2269
  return null;
2262
2270
  }
@@ -2285,8 +2293,8 @@ function validateMutationRequest(req, opts = {}) {
2285
2293
  status: 403,
2286
2294
  error: "opaque origin is not allowed"
2287
2295
  };
2288
- const actualOrigin = normalizedOrigin(originRaw);
2289
- if (!actualOrigin) return {
2296
+ const actual = parsedOrigin(originRaw);
2297
+ if (!actual) return {
2290
2298
  ok: false,
2291
2299
  status: 403,
2292
2300
  error: "invalid origin header"
@@ -2297,7 +2305,8 @@ function validateMutationRequest(req, opts = {}) {
2297
2305
  status: 400,
2298
2306
  error: "missing host header"
2299
2307
  };
2300
- if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
2308
+ const proto = requestProto(req);
2309
+ if (!(proto ? actual.scheme === proto : actual.scheme === "http" || actual.scheme === "https") || actual.host !== host.toLowerCase()) return {
2301
2310
  ok: false,
2302
2311
  status: 403,
2303
2312
  error: "origin mismatch"
@@ -1,6 +1,6 @@
1
- import { l as createFromTemplate, u as listTemplates } from "./session-BSbrC5gK.js";
2
- import "./ops-Dux5HlkH.js";
3
- import { t as cliContext } from "./context-C-osJW5f.js";
1
+ import { l as createFromTemplate, u as listTemplates } from "./session-CdkoJhi1.js";
2
+ import "./ops-ByJnGyuE.js";
3
+ import { t as cliContext } from "./context-Clm_nmr1.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/templates.ts
6
6
  /**
@@ -1,3 +1,3 @@
1
1
  import { r as openDocPlugin } from "../open-doc-plugin-DnX5usgI.js";
2
- import { r as createViteConfig } from "../session-BSbrC5gK.js";
2
+ import { r as createViteConfig } from "../session-CdkoJhi1.js";
3
3
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.14.1",
3
+ "version": "0.14.3",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,6 +28,11 @@
28
28
  "dist",
29
29
  "env.d.ts",
30
30
  "src/app",
31
+ "src/agent",
32
+ "src/diagram",
33
+ "src/editing/placeholder-id.ts",
34
+ "!src/**/*.test.ts",
35
+ "!src/**/*.test.tsx",
31
36
  "skills",
32
37
  "templates",
33
38
  "README.md",
@@ -0,0 +1,59 @@
1
+ import type { AgentCheckFinding, AgentItem, AgentSession } from './types.ts';
2
+
3
+ /** How many findings a check item keeps; the rest are only counted. */
4
+ export const CHECK_FINDINGS_KEPT = 20;
5
+
6
+ // A file's mtime can trail the clock that stamped the message by a little.
7
+ const CLOCK_SLACK_MS = 1000;
8
+
9
+ /**
10
+ * Whether the dev server should run `open-doc check` for the turn that just
11
+ * ended: only for an agent that cannot start a browser itself, only when the
12
+ * turn ran to its end, and only when it touched the document's source — it
13
+ * used a tool, and the file changed after the message. The mtime alone is not
14
+ * enough: a document copied or made from a template a moment earlier reads as
15
+ * fresh to a turn whose agent never even started.
16
+ */
17
+ export function shouldCheckAfterTurn(opts: {
18
+ session: Pick<AgentSession, 'docId' | 'items'>;
19
+ userItemId: string;
20
+ canOpenBrowser: boolean;
21
+ entryMtimeMs: number | null;
22
+ }): boolean {
23
+ const { session, userItemId, canOpenBrowser, entryMtimeMs } = opts;
24
+ if (canOpenBrowser || !session.docId || entryMtimeMs === null) return false;
25
+ const start = session.items.findIndex((i) => i.id === userItemId);
26
+ if (start === -1) return false;
27
+ const turn = session.items.slice(start + 1);
28
+ const result = [...turn].reverse().find((i) => i.kind === 'result');
29
+ if (result?.kind === 'result' && result.aborted) return false;
30
+ if (!turn.some((i) => i.kind === 'tool')) return false;
31
+ const startedAt = Date.parse(session.items[start].ts);
32
+ return Number.isFinite(startedAt) && entryMtimeMs >= startedAt - CLOCK_SLACK_MS;
33
+ }
34
+
35
+ type Report = {
36
+ pageCount: number;
37
+ findings: Array<{
38
+ page: number;
39
+ severity: 'error' | 'warn';
40
+ message: string;
41
+ loc?: string;
42
+ }>;
43
+ };
44
+
45
+ /** A check report as the transcript keeps it: errors first, the rest counted. */
46
+ export function checkItemResult(
47
+ report: Report,
48
+ ): Pick<Extract<AgentItem, { kind: 'check' }>, 'pageCount' | 'findings' | 'total'> {
49
+ const ordered = [...report.findings].sort(
50
+ (a, b) => Number(b.severity === 'error') - Number(a.severity === 'error') || a.page - b.page,
51
+ );
52
+ const findings: AgentCheckFinding[] = ordered.slice(0, CHECK_FINDINGS_KEPT).map((f) => ({
53
+ page: f.page,
54
+ severity: f.severity,
55
+ message: f.message,
56
+ ...(f.loc ? { loc: f.loc } : {}),
57
+ }));
58
+ return { pageCount: report.pageCount, findings, total: report.findings.length };
59
+ }
@@ -0,0 +1,158 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, readFileSync, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+
6
+ const IS_WINDOWS = process.platform === 'win32';
7
+ const VERSION_TIMEOUT_MS = 5000;
8
+
9
+ export function findOnPath(command: string, env: NodeJS.ProcessEnv = process.env): string | null {
10
+ const dirs = (env.PATH ?? env.Path ?? '').split(path.delimiter).filter(Boolean);
11
+ const exts = IS_WINDOWS ? (env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';') : [''];
12
+ for (const dir of dirs) {
13
+ for (const ext of exts) {
14
+ const candidate = path.join(dir, command + ext.toLowerCase());
15
+ try {
16
+ if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
17
+ } catch {}
18
+ }
19
+ }
20
+ return null;
21
+ }
22
+
23
+ // The SDKs spawn the CLI without a shell, which cannot run a Windows .cmd shim,
24
+ // so only a real executable is worth overriding their bundled default with.
25
+ export function findSpawnableCli(command: string, env: NodeJS.ProcessEnv = process.env) {
26
+ const found = findOnPath(command, env);
27
+ if (!found || !IS_WINDOWS) return found;
28
+ return found.toLowerCase().endsWith('.exe') ? found : null;
29
+ }
30
+
31
+ const versionCache = new Map<string, Promise<string | null>>();
32
+
33
+ export function commandVersion(file: string): Promise<string | null> {
34
+ let cached = versionCache.get(file);
35
+ if (!cached) {
36
+ cached = readVersion(file);
37
+ versionCache.set(file, cached);
38
+ }
39
+ return cached;
40
+ }
41
+
42
+ function readVersion(file: string): Promise<string | null> {
43
+ return new Promise((resolve) => {
44
+ let out = '';
45
+ let child: ReturnType<typeof spawn>;
46
+ try {
47
+ child = spawn(file, ['--version'], {
48
+ stdio: ['ignore', 'pipe', 'pipe'],
49
+ shell: IS_WINDOWS,
50
+ windowsHide: true,
51
+ });
52
+ } catch {
53
+ resolve(null);
54
+ return;
55
+ }
56
+ const timer = setTimeout(() => {
57
+ child.kill();
58
+ resolve(null);
59
+ }, VERSION_TIMEOUT_MS);
60
+ child.stdout?.on('data', (c: Buffer) => {
61
+ out += c.toString('utf8');
62
+ });
63
+ child.stderr?.on('data', (c: Buffer) => {
64
+ out += c.toString('utf8');
65
+ });
66
+ child.on('error', () => {
67
+ clearTimeout(timer);
68
+ resolve(null);
69
+ });
70
+ child.on('close', () => {
71
+ clearTimeout(timer);
72
+ resolve(parseVersion(out));
73
+ });
74
+ });
75
+ }
76
+
77
+ export function parseVersion(output: string): string | null {
78
+ const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
79
+ return m ? m[1] : null;
80
+ }
81
+
82
+ type PackageJson = {
83
+ version?: string;
84
+ main?: string;
85
+ module?: string;
86
+ exports?: unknown;
87
+ };
88
+
89
+ export type ResolvedPackage = { dir: string; version: string; entry: string };
90
+
91
+ export function entryFromPackageJson(pkg: PackageJson): string | null {
92
+ const root = pickExport(pkg.exports);
93
+ if (root) return root;
94
+ return pkg.module ?? pkg.main ?? null;
95
+ }
96
+
97
+ function pickExport(exportsField: unknown): string | null {
98
+ if (!exportsField) return null;
99
+ if (typeof exportsField === 'string') return exportsField;
100
+ if (typeof exportsField !== 'object') return null;
101
+ const record = exportsField as Record<string, unknown>;
102
+ const keys = Object.keys(record);
103
+ const isSubpathMap = keys.some((k) => k.startsWith('.'));
104
+ const target = isSubpathMap ? record['.'] : exportsField;
105
+ return pickCondition(target);
106
+ }
107
+
108
+ function pickCondition(target: unknown): string | null {
109
+ if (!target) return null;
110
+ if (typeof target === 'string') return target;
111
+ if (Array.isArray(target)) {
112
+ for (const t of target) {
113
+ const hit = pickCondition(t);
114
+ if (hit) return hit;
115
+ }
116
+ return null;
117
+ }
118
+ if (typeof target !== 'object') return null;
119
+ const record = target as Record<string, unknown>;
120
+ for (const key of ['import', 'node', 'default', 'require']) {
121
+ if (key in record) {
122
+ const hit = pickCondition(record[key]);
123
+ if (hit) return hit;
124
+ }
125
+ }
126
+ return null;
127
+ }
128
+
129
+ // Walks node_modules up from the workspace like Node does, but reads
130
+ // package.json directly: the SDKs' `exports` maps don't expose it, so
131
+ // `require.resolve('<pkg>/package.json')` would refuse.
132
+ export function resolveWorkspacePackage(userCwd: string, name: string): ResolvedPackage | null {
133
+ let dir = path.resolve(userCwd);
134
+ while (true) {
135
+ const pkgJsonPath = path.join(dir, 'node_modules', name, 'package.json');
136
+ if (existsSync(pkgJsonPath)) {
137
+ let pkg: PackageJson;
138
+ try {
139
+ pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf8')) as PackageJson;
140
+ } catch {
141
+ return null;
142
+ }
143
+ const entry = entryFromPackageJson(pkg);
144
+ if (!entry) return null;
145
+ const pkgDir = path.dirname(pkgJsonPath);
146
+ return { dir: pkgDir, version: pkg.version ?? '0.0.0', entry: path.resolve(pkgDir, entry) };
147
+ }
148
+ const parent = path.dirname(dir);
149
+ if (parent === dir) return null;
150
+ dir = parent;
151
+ }
152
+ }
153
+
154
+ export async function importWorkspacePackage<T>(userCwd: string, name: string): Promise<T | null> {
155
+ const resolved = resolveWorkspacePackage(userCwd, name);
156
+ if (!resolved) return null;
157
+ return (await import(pathToFileURL(resolved.entry).href)) as T;
158
+ }
@@ -0,0 +1,73 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
6
+
7
+ type CommandSpec = { cmd: string; args: string[] };
8
+
9
+ const LOCKFILES: ReadonlyArray<readonly [string, PackageManager]> = [
10
+ ['pnpm-lock.yaml', 'pnpm'],
11
+ ['yarn.lock', 'yarn'],
12
+ ['bun.lockb', 'bun'],
13
+ ['bun.lock', 'bun'],
14
+ ['package-lock.json', 'npm'],
15
+ ];
16
+
17
+ async function fileExists(file: string): Promise<boolean> {
18
+ try {
19
+ await fs.access(file);
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ export async function detectPackageManager(cwd: string): Promise<PackageManager> {
27
+ const ua = process.env.npm_config_user_agent ?? '';
28
+ if (ua.startsWith('pnpm')) return 'pnpm';
29
+ if (ua.startsWith('yarn')) return 'yarn';
30
+ if (ua.startsWith('bun')) return 'bun';
31
+ if (ua.startsWith('npm')) return 'npm';
32
+
33
+ // Workspace members have no lockfile of their own; it lives at the root.
34
+ let dir = cwd;
35
+ while (true) {
36
+ for (const [lockfile, pm] of LOCKFILES) {
37
+ if (await fileExists(path.join(dir, lockfile))) return pm;
38
+ }
39
+ const parent = path.dirname(dir);
40
+ if (parent === dir) return 'npm';
41
+ dir = parent;
42
+ }
43
+ }
44
+
45
+ export async function runCommand(spec: CommandSpec, cwd: string, timeoutMs: number): Promise<void> {
46
+ const label = [spec.cmd, ...spec.args].join(' ');
47
+ await new Promise<void>((resolve, reject) => {
48
+ const child = spawn(spec.cmd, spec.args, {
49
+ cwd,
50
+ env: process.env,
51
+ shell: process.platform === 'win32',
52
+ stdio: ['ignore', 'ignore', 'pipe'],
53
+ windowsHide: true,
54
+ });
55
+ let stderr = '';
56
+ const timer = setTimeout(() => {
57
+ child.kill();
58
+ reject(new Error(`${label} timed out`));
59
+ }, timeoutMs);
60
+ child.stderr.on('data', (chunk: Buffer) => {
61
+ stderr = (stderr + chunk.toString('utf8')).slice(-2000);
62
+ });
63
+ child.on('error', (err) => {
64
+ clearTimeout(timer);
65
+ reject(err);
66
+ });
67
+ child.on('close', (code) => {
68
+ clearTimeout(timer);
69
+ if (code === 0) return resolve();
70
+ reject(new Error(stderr.trim() || `${label} exited with code ${code ?? 'unknown'}`));
71
+ });
72
+ });
73
+ }