@contentful/experience-design-system-cli 2.37.1-dev-build-5fe4d4be.0 → 2.37.1-dev-build-04545499.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 (28) hide show
  1. package/dist/app.js +973 -303
  2. package/dist/index.js +1014 -319
  3. package/dist/package.json +1 -1
  4. package/dist/src/tui/import/steps/07-scope-gate/keymap.d.ts +0 -2
  5. package/dist/src/tui/import/steps/07-scope-gate/sidebar/components/GroupedSidebar.d.ts +0 -2
  6. package/dist/src/tui/import/steps/07-scope-gate/state.d.ts +2 -3
  7. package/dist/src/tui/import/steps/07-scope-gate/types.d.ts +0 -7
  8. package/dist/src/tui/import/steps/07-scope-gate/use-scope-gate-flow.d.ts +2 -6
  9. package/dist/src/tui/import/steps/07-scope-gate/use-scope-gate.d.ts +1 -1
  10. package/dist/src/tui/import/steps/08-generation/logic.d.ts +44 -0
  11. package/dist/src/tui/import/steps/08-generation/map-tokens.d.ts +14 -0
  12. package/dist/src/tui/import/steps/08-generation/processes.d.ts +42 -0
  13. package/dist/src/tui/import/steps/08-generation/run.d.ts +26 -0
  14. package/dist/src/tui/import/steps/08-generation/save-decisions.d.ts +8 -0
  15. package/dist/src/tui/import/steps/08-generation/screen.d.ts +12 -0
  16. package/dist/src/tui/import/steps/08-generation/types.d.ts +47 -0
  17. package/dist/src/tui/import/steps/08-generation/use-generation.d.ts +14 -0
  18. package/legacy/dist/src/analyze/select/tui/components/GroupedSidebar.d.ts +0 -2
  19. package/legacy/dist/src/import/tui/WizardApp.d.ts +1 -36
  20. package/legacy/dist/src/import/tui/handoff.d.ts +10 -13
  21. package/legacy/dist/src/import/tui/runLivePreview.d.ts +2 -3
  22. package/legacy/dist/src/index.js +55 -908
  23. package/legacy/dist/src/session/db.d.ts +0 -11
  24. package/legacy/package.json +1 -1
  25. package/package.json +4 -4
  26. package/legacy/dist/src/import/tui/runScopeGate.d.ts +0 -14
  27. package/legacy/dist/src/import/tui/spawn-generate.d.ts +0 -33
  28. package/legacy/dist/src/import/tui/wizard-generate-progress.d.ts +0 -21
package/dist/app.js CHANGED
@@ -772,7 +772,7 @@ async function runAgent(options) {
772
772
  promptLen: prompt.length,
773
773
  promptHead: prompt.slice(0, 500)
774
774
  });
775
- return new Promise((resolve10) => {
775
+ return new Promise((resolve12) => {
776
776
  const bedrockEnv = bedrock ? BEDROCK_ENV_BY_AGENT[agent] : void 0;
777
777
  const child = spawn(binary, args, {
778
778
  stdio: ["pipe", "pipe", "pipe"],
@@ -821,7 +821,7 @@ async function runAgent(options) {
821
821
  stderrLen: stderr.length,
822
822
  stderrTail: stderr.slice(-1e3)
823
823
  });
824
- resolve10(result);
824
+ resolve12(result);
825
825
  });
826
826
  });
827
827
  }
@@ -843,7 +843,7 @@ async function checkAgentAuth(agent) {
843
843
  return "not-found";
844
844
  if (agent !== "claude")
845
845
  return "ok";
846
- return new Promise((resolve10) => {
846
+ return new Promise((resolve12) => {
847
847
  const child = spawn2(binary, ["auth", "status", "--json"], { stdio: ["ignore", "pipe", "pipe"] });
848
848
  let stdout = "";
849
849
  let done = false;
@@ -852,7 +852,7 @@ async function checkAgentAuth(agent) {
852
852
  return;
853
853
  done = true;
854
854
  child.kill("SIGTERM");
855
- resolve10("unauthenticated");
855
+ resolve12("unauthenticated");
856
856
  }, 5e3);
857
857
  child.stdout?.on("data", (chunk) => {
858
858
  stdout += chunk.toString();
@@ -863,14 +863,14 @@ async function checkAgentAuth(agent) {
863
863
  done = true;
864
864
  clearTimeout(timer);
865
865
  if (code !== 0) {
866
- resolve10("unauthenticated");
866
+ resolve12("unauthenticated");
867
867
  return;
868
868
  }
869
869
  try {
870
870
  const status = JSON.parse(stdout);
871
- resolve10(status.loggedIn ? "ok" : "unauthenticated");
871
+ resolve12(status.loggedIn ? "ok" : "unauthenticated");
872
872
  } catch {
873
- resolve10("unauthenticated");
873
+ resolve12("unauthenticated");
874
874
  }
875
875
  });
876
876
  });
@@ -880,9 +880,9 @@ async function binaryIsOnPath(binary) {
880
880
  const fs = await import("node:fs/promises");
881
881
  return fs.access(binary).then(() => true, () => false);
882
882
  }
883
- return new Promise((resolve10) => {
883
+ return new Promise((resolve12) => {
884
884
  const child = spawn2(process.platform === "win32" ? "where" : "which", [binary], { stdio: "ignore" });
885
- child.on("close", (code) => resolve10(code === 0));
885
+ child.on("close", (code) => resolve12(code === 0));
886
886
  });
887
887
  }
888
888
  var init_check_agent_auth = __esm({
@@ -1356,6 +1356,23 @@ var init_flatten = __esm({
1356
1356
  });
1357
1357
 
1358
1358
  // packages/experience-design-system-backend-pipeline/dist/src/steps/shared/dtcg/helpers/validate.js
1359
+ function isDesignTokenType(value) {
1360
+ return typeof value === "string" && TOKEN_TYPE_SET2.has(value);
1361
+ }
1362
+ function validateDTCG(obj) {
1363
+ const errors = [];
1364
+ const tokens = flattenDTCG(obj, "");
1365
+ for (const token of tokens) {
1366
+ if (!isDesignTokenType(token.$type)) {
1367
+ errors.push({
1368
+ path: token.path,
1369
+ message: `Unknown $type "${token.$type}". Must be one of: ${DESIGN_TOKEN_TYPES.join(", ")}.`,
1370
+ actual: token.$type
1371
+ });
1372
+ }
1373
+ }
1374
+ return { valid: errors.length === 0, errors };
1375
+ }
1359
1376
  var TOKEN_TYPE_SET2;
1360
1377
  var init_validate2 = __esm({
1361
1378
  "packages/experience-design-system-backend-pipeline/dist/src/steps/shared/dtcg/helpers/validate.js"() {
@@ -2000,8 +2017,8 @@ var init_cache_keys = __esm({
2000
2017
  });
2001
2018
 
2002
2019
  // packages/experience-design-system-cli/app.tsx
2003
- import { join as join13 } from "node:path";
2004
- import { useEffect as useEffect14, useState as useState20 } from "react";
2020
+ import { join as join14 } from "node:path";
2021
+ import { useEffect as useEffect15, useState as useState21 } from "react";
2005
2022
 
2006
2023
  // packages/experience-design-system-cli/src/tui/home/home.tsx
2007
2024
  import { useEffect as useEffect2, useState as useState2 } from "react";
@@ -2562,6 +2579,59 @@ function indexRowsByKey(items, key) {
2562
2579
  return map;
2563
2580
  }
2564
2581
 
2582
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/sessions/write.js
2583
+ function updateSessionTimestamp(db, sessionId, timestamp) {
2584
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(timestamp, sessionId);
2585
+ }
2586
+
2587
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/helpers/tokens/build-dtcg-groups.js
2588
+ function buildDtcgGroups(groupRows, tokenRows) {
2589
+ return groupRows.map((r) => {
2590
+ const prefix = `${r.path}.`;
2591
+ const tokenIds = tokenRows.filter((t) => t.path.startsWith(prefix) && !t.path.slice(prefix.length).includes(".")).map((t) => t.path);
2592
+ const g = { path: r.path, tokenIds };
2593
+ if (r.description !== null)
2594
+ g.$description = r.description;
2595
+ return g;
2596
+ });
2597
+ }
2598
+
2599
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/helpers/tokens/build-dtcg-tokens.js
2600
+ function buildDtcgTokens(tokenRows) {
2601
+ return tokenRows.map((r) => {
2602
+ const t = {
2603
+ path: r.path,
2604
+ $type: r.type,
2605
+ $value: JSON.parse(r.value)
2606
+ };
2607
+ if (r.description !== null)
2608
+ t.$description = r.description;
2609
+ return t;
2610
+ });
2611
+ }
2612
+
2613
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/tokens/read.js
2614
+ function getDtcgTokensForSession(db, sessionId) {
2615
+ const groupRows = db.prepare("SELECT path, description FROM raw_token_groups WHERE session_id = ? ORDER BY path").all(sessionId).map((row) => ({
2616
+ path: String(row.path),
2617
+ description: row.description === null ? null : String(row.description)
2618
+ }));
2619
+ const tokenRows = db.prepare("SELECT path, type, value, description FROM raw_tokens WHERE session_id = ? ORDER BY path").all(sessionId).map((row) => ({
2620
+ path: String(row.path),
2621
+ type: String(row.type),
2622
+ value: String(row.value),
2623
+ description: row.description === null ? null : String(row.description)
2624
+ }));
2625
+ return {
2626
+ groups: buildDtcgGroups(groupRows, tokenRows),
2627
+ tokens: buildDtcgTokens(tokenRows)
2628
+ };
2629
+ }
2630
+ function getRawTokenNamePaths(db, sessionId) {
2631
+ const rows = db.prepare("SELECT raw_name, path FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId);
2632
+ return Object.fromEntries(rows.map((row) => [String(row.raw_name), String(row.path)]));
2633
+ }
2634
+
2565
2635
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/helpers/components/hash-component-shape.js
2566
2636
  import { createHash } from "node:crypto";
2567
2637
  function hashComponentShape(component) {
@@ -2581,6 +2651,48 @@ function hashComponentShape(component) {
2581
2651
  return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
2582
2652
  }
2583
2653
 
2654
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/tokens/write.js
2655
+ function deleteRawTokensForSession(db, sessionId) {
2656
+ db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(sessionId);
2657
+ db.prepare("DELETE FROM raw_tokens WHERE session_id = ?").run(sessionId);
2658
+ }
2659
+ function createRawTokenGroups(db, sessionId, groups) {
2660
+ const insertGroup = db.prepare(`INSERT INTO raw_token_groups (session_id, path, description) VALUES (?, ?, ?)`);
2661
+ for (const group of groups) {
2662
+ insertGroup.run(sessionId, group.path, group.$description ?? null);
2663
+ }
2664
+ }
2665
+ function createRawTokens(db, sessionId, tokens) {
2666
+ const insertToken = db.prepare(`INSERT INTO raw_tokens (session_id, path, type, value, description) VALUES (?, ?, ?, ?, ?)`);
2667
+ for (const token of tokens) {
2668
+ insertToken.run(sessionId, token.path, token.$type, JSON.stringify(token.$value), token.$description ?? null);
2669
+ }
2670
+ }
2671
+
2672
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/shared/with-transaction.js
2673
+ function withTransaction(db, fn) {
2674
+ db.exec("BEGIN");
2675
+ try {
2676
+ const result = fn();
2677
+ db.exec("COMMIT");
2678
+ return result;
2679
+ } catch (e) {
2680
+ db.exec("ROLLBACK");
2681
+ throw e;
2682
+ }
2683
+ }
2684
+
2685
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/services/tokens/store-dtcg-tokens.js
2686
+ function storeDtcgTokens(db, sessionId, groups, tokens) {
2687
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2688
+ withTransaction(db, () => {
2689
+ deleteRawTokensForSession(db, sessionId);
2690
+ createRawTokenGroups(db, sessionId, groups);
2691
+ createRawTokens(db, sessionId, tokens);
2692
+ updateSessionTimestamp(db, sessionId, now);
2693
+ });
2694
+ }
2695
+
2584
2696
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/db.js
2585
2697
  var SCHEMA = `
2586
2698
  PRAGMA journal_mode = WAL;
@@ -3093,6 +3205,91 @@ function parseReviewReasons(raw) {
3093
3205
  return [];
3094
3206
  }
3095
3207
  }
3208
+ function loadCDFComponents(db, sessionId) {
3209
+ const components = db.prepare(`SELECT component_id, name, description FROM raw_components
3210
+ WHERE session_id = ? AND status = 'generated' ORDER BY rowid`).all(sessionId);
3211
+ if (components.length === 0)
3212
+ return [];
3213
+ const props = db.prepare(`SELECT component_id, name, required, default_value, description,
3214
+ cdf_type, cdf_category, cdf_token_kind, position
3215
+ FROM raw_props
3216
+ WHERE session_id = ? AND cdf_type IS NOT NULL
3217
+ ORDER BY component_id, position`).all(sessionId);
3218
+ const allowedValues = db.prepare(`SELECT component_id, prop_name, value, position
3219
+ FROM raw_prop_allowed_values WHERE session_id = ? ORDER BY component_id, prop_name, position`).all(sessionId);
3220
+ const slots = db.prepare(`SELECT component_id, name, description, required FROM raw_slots WHERE session_id = ? ORDER BY component_id, position`).all(sessionId);
3221
+ const allowedComponents = db.prepare(`SELECT component_id, slot_name, allowed_component
3222
+ FROM raw_slot_allowed_components WHERE session_id = ? ORDER BY component_id, slot_name, position`).all(sessionId);
3223
+ const tokenPaths = db.prepare(`SELECT component_id, prop_name, position, path
3224
+ FROM raw_prop_token_paths WHERE session_id = ? ORDER BY component_id, prop_name, position`).all(sessionId);
3225
+ const resolvedDefaultPaths = getRawTokenNamePaths(db, sessionId);
3226
+ const tokenTypeByPath = new Map(db.prepare("SELECT path, type FROM raw_tokens WHERE session_id = ?").all(sessionId).map((token) => [token.path, token.type]));
3227
+ const propsByComponent = indexRowsByKey(props, (p) => p.component_id);
3228
+ const allowedValuesByProp = indexRowsByKey(allowedValues, (av) => `${av.component_id}::${av.prop_name}`);
3229
+ const slotsByComponent = indexRowsByKey(slots, (s) => s.component_id);
3230
+ const allowedComponentsBySlot = indexRowsByKey(allowedComponents, (ac) => `${ac.component_id}::${ac.slot_name}`);
3231
+ const tokenPathsByProp = indexRowsByKey(tokenPaths, (t) => `${t.component_id}::${t.prop_name}`);
3232
+ const toTokenPaths = (rows) => rows === void 0 ? void 0 : rows.map((r) => r.path);
3233
+ return components.map(({ component_id, name, description }) => {
3234
+ const compProps = propsByComponent.get(component_id) ?? [];
3235
+ const $properties = {};
3236
+ for (const p of compProps) {
3237
+ if (!p.name.trim())
3238
+ continue;
3239
+ const av = allowedValuesByProp.get(`${component_id}::${p.name}`);
3240
+ const propDef = {
3241
+ $type: p.cdf_type,
3242
+ $category: p.cdf_category
3243
+ };
3244
+ if (p.required)
3245
+ propDef.$required = true;
3246
+ const isTokenProp = p.cdf_type === "token" && p.cdf_category === "design";
3247
+ const defaultReference = p.default_value;
3248
+ const resolvedDefault = isTokenProp && p.cdf_token_kind !== null && defaultReference !== null ? resolvedDefaultPaths[defaultReference] : void 0;
3249
+ const compatibleResolvedDefault = resolvedDefault !== void 0 && tokenTypeByPath.get(resolvedDefault) === p.cdf_token_kind ? resolvedDefault : void 0;
3250
+ if (p.default_value !== null) {
3251
+ if (p.cdf_type === "boolean") {
3252
+ propDef.$default = p.default_value === "true";
3253
+ } else {
3254
+ propDef.$default = compatibleResolvedDefault ?? p.default_value;
3255
+ }
3256
+ }
3257
+ if (p.description !== null)
3258
+ propDef.$description = p.description;
3259
+ if (!isTokenProp && av && av.length > 0)
3260
+ propDef.$values = av.map((v) => v.value);
3261
+ if (p.cdf_token_kind !== null)
3262
+ propDef["$token.kind"] = p.cdf_token_kind;
3263
+ if (isTokenProp) {
3264
+ const allowed = toTokenPaths(tokenPathsByProp.get(`${component_id}::${p.name}`));
3265
+ if (allowed !== void 0 && allowed.length > 0)
3266
+ propDef["$token.allowed"] = allowed;
3267
+ }
3268
+ $properties[p.name] = propDef;
3269
+ }
3270
+ const compSlots = slotsByComponent.get(component_id) ?? [];
3271
+ const $slots = {};
3272
+ for (const s of compSlots) {
3273
+ if (!s.name.trim())
3274
+ continue;
3275
+ const ac = allowedComponentsBySlot.get(`${component_id}::${s.name}`);
3276
+ const slotDef = {};
3277
+ if (s.description !== null)
3278
+ slotDef.$description = s.description;
3279
+ if (s.required)
3280
+ slotDef.$required = true;
3281
+ if (ac && ac.length > 0)
3282
+ slotDef.$allowedComponents = ac.map((v) => v.allowed_component);
3283
+ $slots[s.name] = slotDef;
3284
+ }
3285
+ const entry = { $type: "component", $properties };
3286
+ if (description !== null)
3287
+ entry.$description = description;
3288
+ if (Object.keys($slots).length > 0)
3289
+ entry.$slots = $slots;
3290
+ return { key: name, entry };
3291
+ });
3292
+ }
3096
3293
  function loadScopeComponents(db, sessionId) {
3097
3294
  const rows = db.prepare(`SELECT name, component_id, status, reject_reason, review_reasons, needs_review FROM raw_components
3098
3295
  WHERE session_id = ? AND status IN ('extracted', 'accepted', 'rejected')
@@ -3121,6 +3318,38 @@ function loadScopeComponents(db, sessionId) {
3121
3318
  };
3122
3319
  });
3123
3320
  }
3321
+ function applyScopeDecisions(db, sessionId, decisions) {
3322
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3323
+ const acceptedSet = new Set(decisions.accepted);
3324
+ const accepted = [...acceptedSet];
3325
+ const rejected = [...new Set(decisions.rejected)].filter((n) => !acceptedSet.has(n));
3326
+ if (rejected.length > 0) {
3327
+ const placeholders = rejected.map(() => "?").join(",");
3328
+ db.prepare(`UPDATE raw_components SET status = 'rejected' WHERE session_id = ? AND name IN (${placeholders})`).run(sessionId, ...rejected);
3329
+ }
3330
+ if (accepted.length > 0) {
3331
+ const placeholders = accepted.map(() => "?").join(",");
3332
+ db.prepare(`UPDATE raw_components SET status = 'generated' WHERE session_id = ? AND name IN (${placeholders})`).run(sessionId, ...accepted);
3333
+ }
3334
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId);
3335
+ }
3336
+ function copyTokensFromCache(db, sourceSessionId, targetSessionId) {
3337
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3338
+ db.exec("BEGIN");
3339
+ try {
3340
+ db.prepare("DELETE FROM raw_tokens WHERE session_id = ?").run(targetSessionId);
3341
+ db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(targetSessionId);
3342
+ db.prepare(`INSERT INTO raw_token_groups (session_id, path, description)
3343
+ SELECT ?, path, description FROM raw_token_groups WHERE session_id = ?`).run(targetSessionId, sourceSessionId);
3344
+ db.prepare(`INSERT INTO raw_tokens (session_id, path, type, value, description)
3345
+ SELECT ?, path, type, value, description FROM raw_tokens WHERE session_id = ?`).run(targetSessionId, sourceSessionId);
3346
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, targetSessionId);
3347
+ db.exec("COMMIT");
3348
+ } catch (e) {
3349
+ db.exec("ROLLBACK");
3350
+ throw e;
3351
+ }
3352
+ }
3124
3353
  var _cliCacheVersionCache = null;
3125
3354
  async function getCliCacheVersion() {
3126
3355
  if (_cliCacheVersionCache)
@@ -3373,6 +3602,32 @@ init_agents();
3373
3602
  init_agents();
3374
3603
  var DEFAULT_TIMEOUT_MS = Number(process.env.EDS_AGENT_TIMEOUT_MS ?? 5 * 60 * 1e3);
3375
3604
 
3605
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/review-session-paths.js
3606
+ import { resolve as resolve7 } from "node:path";
3607
+ async function getRefineSessionPaths(sessionId, artifactsRoot) {
3608
+ const sessionDir = resolve7(artifactsRoot, sessionId);
3609
+ return {
3610
+ sessionDir,
3611
+ eventsPath: resolve7(sessionDir, "events.jsonl"),
3612
+ statePath: resolve7(sessionDir, "current-review-state.json")
3613
+ };
3614
+ }
3615
+
3616
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/review-artifacts-root.js
3617
+ import { resolve as resolve8 } from "node:path";
3618
+ function getRefineArtifactsRoot() {
3619
+ if (process.env["EDS_REVIEW_ARTIFACTS_DIR"]) {
3620
+ return resolve8(process.env["EDS_REVIEW_ARTIFACTS_DIR"]);
3621
+ }
3622
+ return resolve8(configRoot(), "reviews");
3623
+ }
3624
+
3625
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/save-review-state.js
3626
+ import { writeFile } from "node:fs/promises";
3627
+ async function saveReviewState(statePath, session) {
3628
+ await writeFile(statePath, JSON.stringify(session, null, 2), "utf8");
3629
+ }
3630
+
3376
3631
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/helpers/collect-files/collect-files.js
3377
3632
  import { statSync as statSync2 } from "node:fs";
3378
3633
  import path4 from "node:path";
@@ -3559,15 +3814,15 @@ function walkProjectTree(dir, result, includeContent) {
3559
3814
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/helpers/collect-files/collect-files.js
3560
3815
  function collectFiles(root, options = {}) {
3561
3816
  const resolved = path4.resolve(root);
3562
- let stat2;
3817
+ let stat4;
3563
3818
  try {
3564
- stat2 = statSync2(resolved);
3819
+ stat4 = statSync2(resolved);
3565
3820
  } catch (err) {
3566
3821
  return { ok: false, failure: classifyStatError(err.code), rootPath: resolved };
3567
3822
  }
3568
- if (stat2.isFile())
3823
+ if (stat4.isFile())
3569
3824
  return { ok: false, failure: "is-file", rootPath: resolved };
3570
- if (!stat2.isDirectory())
3825
+ if (!stat4.isDirectory())
3571
3826
  return { ok: false, failure: "not-directory", rootPath: resolved };
3572
3827
  const result = {
3573
3828
  filePaths: [],
@@ -3585,6 +3840,38 @@ function collectFiles(root, options = {}) {
3585
3840
  return { ok: true, result };
3586
3841
  }
3587
3842
 
3843
+ // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/services/write-scope-decisions-snapshot.js
3844
+ import { mkdir } from "node:fs/promises";
3845
+ async function writeScopeDecisionsSnapshot(db, sessionId, decisions) {
3846
+ const acceptedSet = new Set(decisions.accepted);
3847
+ const rawComponents = loadRawComponents(db, sessionId);
3848
+ const records = rawComponents.map((c2) => {
3849
+ const status = acceptedSet.has(c2.name) ? "accepted" : "rejected";
3850
+ const proposal = {
3851
+ name: c2.name,
3852
+ source: c2.source,
3853
+ framework: c2.framework,
3854
+ props: c2.props,
3855
+ slots: c2.slots,
3856
+ ...c2.extractionConfidence !== void 0 ? { extractionConfidence: c2.extractionConfidence } : {},
3857
+ ...c2.reviewReasons !== void 0 ? { reviewReasons: c2.reviewReasons } : {},
3858
+ ...c2.needsReview !== void 0 ? { needsReview: c2.needsReview } : {}
3859
+ };
3860
+ return {
3861
+ id: c2.component_id,
3862
+ name: c2.name,
3863
+ resolvedSourcePath: "",
3864
+ sourceCode: null,
3865
+ originalProposal: proposal,
3866
+ editedProposal: proposal,
3867
+ status
3868
+ };
3869
+ });
3870
+ const paths = await getRefineSessionPaths(sessionId, getRefineArtifactsRoot());
3871
+ await mkdir(paths.sessionDir, { recursive: true });
3872
+ await saveReviewState(paths.statePath, { components: records });
3873
+ }
3874
+
3588
3875
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/index.js
3589
3876
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
3590
3877
 
@@ -3794,7 +4081,7 @@ var defaultPathSerializer = ({ path: path5, url: _url }) => {
3794
4081
  }
3795
4082
  return url;
3796
4083
  };
3797
- var createQuerySerializer = ({ allowReserved, array: array4, object: object2 } = {}) => {
4084
+ var createQuerySerializer = ({ allowReserved, array: array3, object: object2 } = {}) => {
3798
4085
  const querySerializer = (queryParams) => {
3799
4086
  const search = [];
3800
4087
  if (queryParams && typeof queryParams === "object") {
@@ -3810,7 +4097,7 @@ var createQuerySerializer = ({ allowReserved, array: array4, object: object2 } =
3810
4097
  name,
3811
4098
  style: "form",
3812
4099
  value,
3813
- ...array4
4100
+ ...array3
3814
4101
  });
3815
4102
  if (serializedArray)
3816
4103
  search.push(serializedArray);
@@ -4218,7 +4505,7 @@ function errorMessage(error) {
4218
4505
  return error instanceof Error && error.message ? error.message : String(error);
4219
4506
  }
4220
4507
  function defaultSleep(delayMs) {
4221
- return new Promise((resolve10) => setTimeout(resolve10, delayMs));
4508
+ return new Promise((resolve12) => setTimeout(resolve12, delayMs));
4222
4509
  }
4223
4510
 
4224
4511
  // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/sanitize-preview.js
@@ -4457,7 +4744,7 @@ var ApiClient = class {
4457
4744
  const progress = maxAttempts > 1 ? attempt / (maxAttempts - 1) : 0;
4458
4745
  const baseDelay = intervalMs + (maxIntervalMs - intervalMs) * progress;
4459
4746
  const jitter = Math.random() * baseDelay * 0.15;
4460
- await new Promise((resolve10) => setTimeout(resolve10, baseDelay + jitter));
4747
+ await new Promise((resolve12) => setTimeout(resolve12, baseDelay + jitter));
4461
4748
  }
4462
4749
  }
4463
4750
  throw new Error(`Operation ${operationId} timed out after ${maxAttempts} attempts`);
@@ -4650,11 +4937,11 @@ function parseEdsiError(rawInput) {
4650
4937
  ...binding.diagnostics ? { diagnostics: binding.diagnostics } : {}
4651
4938
  };
4652
4939
  }
4653
- const literal3 = parseObjectLiteralTail(cleaned);
4654
- if (literal3 && (literal3.code || literal3.cycle)) {
4940
+ const literal4 = parseObjectLiteralTail(cleaned);
4941
+ if (literal4 && (literal4.code || literal4.cycle)) {
4655
4942
  const braceStart = cleaned.lastIndexOf("{");
4656
4943
  const head = braceStart === -1 ? cleaned : cleaned.slice(0, braceStart).trim();
4657
- return { code: literal3.code ?? null, message: head || cleaned, cycle: literal3.cycle ?? null, raw: false };
4944
+ return { code: literal4.code ?? null, message: head || cleaned, cycle: literal4.cycle ?? null, raw: false };
4658
4945
  }
4659
4946
  return { code: null, message: cleaned || prefix || rawInput, cycle: null, raw: true };
4660
4947
  }
@@ -4735,6 +5022,99 @@ function formatApiError2(request) {
4735
5022
 
4736
5023
  // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/tokens/read-tokens-from-path.js
4737
5024
  init_shared();
5025
+ import { readFile as readFile4, stat as stat2 } from "node:fs/promises";
5026
+
5027
+ // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/tokens/collect-json-files.js
5028
+ import { readdir, stat } from "node:fs/promises";
5029
+ import { join as join5 } from "node:path";
5030
+ var IGNORE_TOKEN_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".next", ".nuxt", ".git"]);
5031
+ async function collectJsonFiles(dir) {
5032
+ const results = [];
5033
+ await walk(dir, results);
5034
+ return results;
5035
+ }
5036
+ async function walk(current, results) {
5037
+ let entries;
5038
+ try {
5039
+ entries = await readdir(current);
5040
+ } catch {
5041
+ return;
5042
+ }
5043
+ await Promise.all(entries.map(async (entry) => {
5044
+ if (IGNORE_TOKEN_DIRS.has(entry))
5045
+ return;
5046
+ const full = join5(current, entry);
5047
+ let s;
5048
+ try {
5049
+ s = await stat(full);
5050
+ } catch {
5051
+ return;
5052
+ }
5053
+ if (s.isDirectory()) {
5054
+ await walk(full, results);
5055
+ } else if (entry.endsWith(".json")) {
5056
+ results.push(full);
5057
+ }
5058
+ }));
5059
+ }
5060
+
5061
+ // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/tokens/read-tokens-from-path.js
5062
+ async function readTokensFromPath(flag, p) {
5063
+ let s;
5064
+ try {
5065
+ s = await stat2(p);
5066
+ } catch {
5067
+ throw new Error(`file not found: ${p} (from ${flag})`);
5068
+ }
5069
+ const merged = s.isDirectory() ? await readMergedFromDir(flag, p) : await readSingleFile(flag, p);
5070
+ const { valid, errors } = validateDTCG(merged);
5071
+ if (!valid) {
5072
+ throw new Error(`${flag} contains invalid token types:
5073
+ ${errors.map((e) => ` ${e.path}: ${e.message}`).join("\n")}`);
5074
+ }
5075
+ return flattenDTCG(merged, "");
5076
+ }
5077
+ async function readMergedFromDir(flag, dir) {
5078
+ const files = await collectJsonFiles(dir);
5079
+ if (files.length === 0)
5080
+ throw new Error(`no .json files found in directory: ${dir} (from ${flag})`);
5081
+ const merged = {};
5082
+ for (const file of files.sort()) {
5083
+ try {
5084
+ const text = await readFile4(file, "utf8");
5085
+ const parsed = JSON.parse(text);
5086
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
5087
+ Object.assign(merged, parsed);
5088
+ }
5089
+ } catch {
5090
+ continue;
5091
+ }
5092
+ }
5093
+ return merged;
5094
+ }
5095
+ async function readSingleFile(flag, p) {
5096
+ let text;
5097
+ try {
5098
+ text = await readFile4(p, "utf8");
5099
+ } catch {
5100
+ throw new Error(`file not found: ${p} (from ${flag})`);
5101
+ }
5102
+ let raw;
5103
+ try {
5104
+ raw = JSON.parse(text);
5105
+ } catch {
5106
+ throw new Error(`${flag} is not valid JSON: ${p}`);
5107
+ }
5108
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
5109
+ throw new Error(`${flag} is not valid JSON: expected an object`);
5110
+ }
5111
+ return raw;
5112
+ }
5113
+
5114
+ // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/controller/tokens/read-tokens-from-path.js
5115
+ function readTokensFromPath2(request) {
5116
+ return readTokensFromPath(request.flag, request.path);
5117
+ }
4738
5118
 
4739
5119
  // packages/experience-design-system-backend-pipeline/dist/src/index.js
4740
5120
  init_agents();
@@ -4749,8 +5129,8 @@ function buildContentfulManagementClient(request) {
4749
5129
  }
4750
5130
 
4751
5131
  // packages/experience-design-system-backend-pipeline/dist/src/steps/generation/src/controller/existing-entities/fetch-and-persist.js
4752
- import { writeFile } from "node:fs/promises";
4753
- import { join as join5 } from "node:path";
5132
+ import { writeFile as writeFile2 } from "node:fs/promises";
5133
+ import { join as join6 } from "node:path";
4754
5134
 
4755
5135
  // packages/experience-design-system-backend-pipeline/dist/src/steps/generation/src/helpers/existing-entities/fetch-from-contentful.js
4756
5136
  import { fetchAll } from "contentful-management";
@@ -4782,8 +5162,8 @@ async function fetchAndPersistExistingContentfulEntities(request) {
4782
5162
  spaceId: request.spaceId,
4783
5163
  environmentId: request.environmentId
4784
5164
  });
4785
- const path5 = join5(request.outDir, ".existing-entities.json");
4786
- await writeFile(path5, JSON.stringify(entities, null, 2), "utf8");
5165
+ const path5 = join6(request.outDir, ".existing-entities.json");
5166
+ await writeFile2(path5, JSON.stringify(entities, null, 2), "utf8");
4787
5167
  return { ok: true, path: path5, durationMs: Date.now() - t0, entities };
4788
5168
  } catch (error) {
4789
5169
  return {
@@ -5300,17 +5680,17 @@ function RunningStep({
5300
5680
  }
5301
5681
 
5302
5682
  // packages/experience-design-system-cli/src/tui/import/steps/05-token-reuse/logic.ts
5303
- import { access, stat } from "node:fs/promises";
5304
- import { join as join6 } from "node:path";
5683
+ import { access, stat as stat3 } from "node:fs/promises";
5684
+ import { join as join7 } from "node:path";
5305
5685
  async function inspectTokens({ rawTokensPath, outDir, cache }) {
5306
5686
  if (!cache) return { kind: "none" };
5307
- const tokensPath = join6(outDir, "tokens.json");
5687
+ const tokensPath = join7(outDir, "tokens.json");
5308
5688
  try {
5309
5689
  await access(tokensPath);
5310
5690
  } catch {
5311
5691
  return { kind: "none" };
5312
5692
  }
5313
- const [generated, source] = await Promise.all([stat(tokensPath), stat(rawTokensPath).catch(() => null)]);
5693
+ const [generated, source] = await Promise.all([stat3(tokensPath), stat3(rawTokensPath).catch(() => null)]);
5314
5694
  return { kind: "cached", tokensPath, sourceChanged: source ? source.mtimeMs > generated.mtimeMs : false };
5315
5695
  }
5316
5696
  function gateText({ tokensPath, sourceChanged }) {
@@ -5502,26 +5882,26 @@ function ExtractionScreen({
5502
5882
 
5503
5883
  // packages/experience-design-system-types/dist/src/config/index.js
5504
5884
  import { randomBytes } from "node:crypto";
5505
- import { mkdir, readFile as readFile4, rename, writeFile as writeFile2 } from "node:fs/promises";
5885
+ import { mkdir as mkdir2, readFile as readFile5, rename, writeFile as writeFile3 } from "node:fs/promises";
5506
5886
  import { homedir as homedir3 } from "node:os";
5507
- import { dirname as dirname5, join as join7 } from "node:path";
5887
+ import { dirname as dirname5, join as join8 } from "node:path";
5508
5888
  function configRoot2() {
5509
- return process.env["EDS_HOME"] || join7(homedir3(), ".contentful", "experience-design-system-cli");
5889
+ return process.env["EDS_HOME"] || join8(homedir3(), ".contentful", "experience-design-system-cli");
5510
5890
  }
5511
- var configFilePath2 = () => join7(configRoot2(), "config.json");
5512
- var debugSessionsDir2 = () => join7(configRoot2(), "debug", "sessions");
5891
+ var configFilePath2 = () => join8(configRoot2(), "config.json");
5892
+ var debugSessionsDir2 = () => join8(configRoot2(), "debug", "sessions");
5513
5893
  async function readSettings2() {
5514
5894
  try {
5515
- return JSON.parse(await readFile4(configFilePath2(), "utf8"));
5895
+ return JSON.parse(await readFile5(configFilePath2(), "utf8"));
5516
5896
  } catch {
5517
5897
  return {};
5518
5898
  }
5519
5899
  }
5520
5900
  async function writeSettings2(settings) {
5521
5901
  const path5 = configFilePath2();
5522
- await mkdir(dirname5(path5), { recursive: true });
5902
+ await mkdir2(dirname5(path5), { recursive: true });
5523
5903
  const tmp = `${path5}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
5524
- await writeFile2(tmp, `${JSON.stringify(settings, null, 2)}
5904
+ await writeFile3(tmp, `${JSON.stringify(settings, null, 2)}
5525
5905
  `, { mode: 384 });
5526
5906
  await rename(tmp, path5);
5527
5907
  }
@@ -5533,8 +5913,8 @@ async function updateSettings2(patch) {
5533
5913
  import { useEffect as useEffect5, useRef as useRef2, useState as useState8 } from "react";
5534
5914
 
5535
5915
  // packages/experience-design-system-cli/src/tui/import/steps/06-extraction/run.ts
5536
- import { mkdir as mkdir2 } from "node:fs/promises";
5537
- import { join as join11, resolve as resolve9 } from "node:path";
5916
+ import { mkdir as mkdir3 } from "node:fs/promises";
5917
+ import { join as join12, resolve as resolve11 } from "node:path";
5538
5918
 
5539
5919
  // packages/experience-design-system-generation/dist/src/agent-names.js
5540
5920
  var AGENT_BINARIES2 = {
@@ -5547,8 +5927,8 @@ var AGENT_BINARIES2 = {
5547
5927
 
5548
5928
  // packages/experience-design-system-generation/dist/src/services/prompts/helpers/resolve-skill-file.js
5549
5929
  import { existsSync as existsSync3 } from "node:fs";
5550
- import { readFile as readFile5 } from "node:fs/promises";
5551
- import { dirname as dirname6, join as join8, resolve as resolve7 } from "node:path";
5930
+ import { readFile as readFile6 } from "node:fs/promises";
5931
+ import { dirname as dirname6, join as join9, resolve as resolve9 } from "node:path";
5552
5932
  import { fileURLToPath as fileURLToPath3 } from "node:url";
5553
5933
  var SKILL_FILES2 = {
5554
5934
  components: "generate-components.md",
@@ -5562,10 +5942,10 @@ function resolveSkillPath2(skill) {
5562
5942
  const thisDir = dirname6(fileURLToPath3(import.meta.url));
5563
5943
  let dir = thisDir;
5564
5944
  for (; ; ) {
5565
- const candidate = join8(dir, "skills");
5945
+ const candidate = join9(dir, "skills");
5566
5946
  if (existsSync3(candidate))
5567
- return join8(candidate, SKILL_FILES2[skill]);
5568
- const parent = resolve7(dir, "..");
5947
+ return join9(candidate, SKILL_FILES2[skill]);
5948
+ const parent = resolve9(dir, "..");
5569
5949
  if (parent === dir) {
5570
5950
  throw new Error(`skill file missing from CLI installation (could not locate skills/ directory from: ${thisDir})`);
5571
5951
  }
@@ -5574,16 +5954,16 @@ function resolveSkillPath2(skill) {
5574
5954
  }
5575
5955
  async function readSkillFile2(skill, override) {
5576
5956
  if (override) {
5577
- const skillPath2 = resolve7(override);
5957
+ const skillPath2 = resolve9(override);
5578
5958
  try {
5579
- return await readFile5(skillPath2, "utf8");
5959
+ return await readFile6(skillPath2, "utf8");
5580
5960
  } catch {
5581
5961
  throw new Error(`custom prompt file not found (skill: ${skill}, path: ${skillPath2})`);
5582
5962
  }
5583
5963
  }
5584
5964
  const skillPath = resolveSkillPath2(skill);
5585
5965
  try {
5586
- return await readFile5(skillPath, "utf8");
5966
+ return await readFile6(skillPath, "utf8");
5587
5967
  } catch {
5588
5968
  throw new Error(`skill file missing from CLI installation \u2014 try reinstalling the CLI (looked for: ${skillPath})`);
5589
5969
  }
@@ -6180,7 +6560,7 @@ async function runAgent2(options) {
6180
6560
  promptLen: prompt.length,
6181
6561
  promptHead: prompt.slice(0, 500)
6182
6562
  });
6183
- return new Promise((resolve10) => {
6563
+ return new Promise((resolve12) => {
6184
6564
  const bedrockEnv = bedrock ? BEDROCK_ENV_BY_AGENT2[agent] : void 0;
6185
6565
  const child = spawn3(binary, args, {
6186
6566
  stdio: ["pipe", "pipe", "pipe"],
@@ -6224,7 +6604,7 @@ async function runAgent2(options) {
6224
6604
  stderrLen: stderr.length,
6225
6605
  stderrTail: stderr.slice(-1e3)
6226
6606
  });
6227
- resolve10(result);
6607
+ resolve12(result);
6228
6608
  });
6229
6609
  });
6230
6610
  }
@@ -6235,7 +6615,7 @@ import { spawn as spawn5 } from "node:child_process";
6235
6615
  // packages/experience-design-system-generation/dist/src/services/agent/helpers/check-claude-auth.js
6236
6616
  import { spawn as spawn4 } from "node:child_process";
6237
6617
  function checkClaudeAuth(binary) {
6238
- return new Promise((resolve10) => {
6618
+ return new Promise((resolve12) => {
6239
6619
  const child = spawn4(binary, ["auth", "status", "--json"], {
6240
6620
  stdio: ["ignore", "pipe", "pipe"]
6241
6621
  });
@@ -6245,7 +6625,7 @@ function checkClaudeAuth(binary) {
6245
6625
  if (!done) {
6246
6626
  done = true;
6247
6627
  child.kill("SIGTERM");
6248
- resolve10("unauthenticated");
6628
+ resolve12("unauthenticated");
6249
6629
  }
6250
6630
  }, 5e3);
6251
6631
  child.stdout?.on("data", (chunk) => {
@@ -6257,14 +6637,14 @@ function checkClaudeAuth(binary) {
6257
6637
  done = true;
6258
6638
  clearTimeout(timer);
6259
6639
  if (code !== 0) {
6260
- resolve10("unauthenticated");
6640
+ resolve12("unauthenticated");
6261
6641
  return;
6262
6642
  }
6263
6643
  try {
6264
6644
  const status = JSON.parse(stdout);
6265
- resolve10(status.loggedIn ? "ok" : "unauthenticated");
6645
+ resolve12(status.loggedIn ? "ok" : "unauthenticated");
6266
6646
  } catch {
6267
- resolve10("unauthenticated");
6647
+ resolve12("unauthenticated");
6268
6648
  }
6269
6649
  });
6270
6650
  });
@@ -6273,13 +6653,13 @@ function checkClaudeAuth(binary) {
6273
6653
  // packages/experience-design-system-generation/dist/src/services/agent/helpers/check-agent-auth.js
6274
6654
  async function checkAgentAuth2(agent) {
6275
6655
  const binary = resolveAgentBinary(agent);
6276
- const binaryExists2 = await new Promise((resolve10) => {
6656
+ const binaryExists2 = await new Promise((resolve12) => {
6277
6657
  if (binary.startsWith("/")) {
6278
- import("node:fs/promises").then((fs) => fs.access(binary).then(() => resolve10(true), () => resolve10(false)));
6658
+ import("node:fs/promises").then((fs) => fs.access(binary).then(() => resolve12(true), () => resolve12(false)));
6279
6659
  return;
6280
6660
  }
6281
6661
  const child = spawn5(process.platform === "win32" ? "where" : "which", [binary], { stdio: "ignore" });
6282
- child.on("close", (code) => resolve10(code === 0));
6662
+ child.on("close", (code) => resolve12(code === 0));
6283
6663
  });
6284
6664
  if (!binaryExists2)
6285
6665
  return "not-found";
@@ -6381,17 +6761,17 @@ function parseSelectToolCallLines(stdout) {
6381
6761
 
6382
6762
  // packages/experience-design-system-cli/src/tui/import/steps/06-extraction/processes.ts
6383
6763
  import { execFile as execFile2, spawn as spawn6 } from "node:child_process";
6384
- import { join as join10 } from "node:path";
6764
+ import { join as join11 } from "node:path";
6385
6765
 
6386
6766
  // packages/experience-design-system-cli/src/legacy/legacy-cli-path.ts
6387
6767
  import { existsSync as existsSync4 } from "node:fs";
6388
- import { join as join9 } from "node:path";
6768
+ import { join as join10 } from "node:path";
6389
6769
  var PACKAGE_NAME2 = "@contentful/experience-design-system-cli";
6390
6770
  function findLegacyCliPath() {
6391
6771
  const root = findPackageRoot(import.meta.url, PACKAGE_NAME2);
6392
6772
  const candidates = [
6393
- join9(root, "legacy", "bin", "cli.js"),
6394
- join9(root, "..", "experience-design-system-cli-legacy", "bin", "cli.js")
6773
+ join10(root, "legacy", "bin", "cli.js"),
6774
+ join10(root, "..", "experience-design-system-cli-legacy", "bin", "cli.js")
6395
6775
  ];
6396
6776
  const found = candidates.find((candidate) => existsSync4(candidate));
6397
6777
  if (!found) {
@@ -6429,7 +6809,7 @@ function buildPrintTokensArgs(tokensPath, tokenSessionId) {
6429
6809
  return ["print", "tokens", "--out", tokensPath, ...tokenSessionId ? ["--session", tokenSessionId] : []];
6430
6810
  }
6431
6811
  function run(args, handlers = {}) {
6432
- return new Promise((resolve10) => {
6812
+ return new Promise((resolve12) => {
6433
6813
  const child = spawn6("node", args);
6434
6814
  let stdout = "";
6435
6815
  let stderr = "";
@@ -6445,17 +6825,17 @@ function run(args, handlers = {}) {
6445
6825
  stderr += chunk;
6446
6826
  stderrLines(chunk);
6447
6827
  });
6448
- child.on("error", (error) => resolve10({ exitCode: 1, stdout, stderr: stderr || error.message }));
6449
- child.on("exit", (code) => resolve10({ exitCode: code ?? 0, stdout, stderr }));
6828
+ child.on("error", (error) => resolve12({ exitCode: 1, stdout, stderr: stderr || error.message }));
6829
+ child.on("exit", (code) => resolve12({ exitCode: code ?? 0, stdout, stderr }));
6450
6830
  });
6451
6831
  }
6452
6832
  function spawnExtract(command, handlers) {
6453
6833
  return run(buildExtractArgs(findLegacyCliPath(), command), handlers);
6454
6834
  }
6455
6835
  function runBuffered(args) {
6456
- return new Promise((resolve10) => {
6836
+ return new Promise((resolve12) => {
6457
6837
  execFile2("node", [findLegacyCliPath(), ...args], (error, stdout, stderr) => {
6458
- resolve10({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
6838
+ resolve12({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
6459
6839
  });
6460
6840
  });
6461
6841
  }
@@ -6465,7 +6845,7 @@ async function runTokenGeneration(input) {
6465
6845
  return { ok: false, step: "generate tokens", message: generated.stderr.trim() || "Unknown error" };
6466
6846
  }
6467
6847
  const tokenSessionId = findSession(generated.stdout);
6468
- const tokensPath = join10(input.outDir, "tokens.json");
6848
+ const tokensPath = join11(input.outDir, "tokens.json");
6469
6849
  const printed = await runBuffered(buildPrintTokensArgs(tokensPath, tokenSessionId));
6470
6850
  if (printed.exitCode !== 0) {
6471
6851
  return { ok: false, step: "print tokens", message: printed.stderr.trim() || "Unknown error" };
@@ -6474,10 +6854,10 @@ async function runTokenGeneration(input) {
6474
6854
  }
6475
6855
 
6476
6856
  // packages/experience-design-system-cli/src/tui/import/steps/06-extraction/selection.ts
6477
- import { resolve as resolve8 } from "node:path";
6857
+ import { resolve as resolve10 } from "node:path";
6478
6858
  var DEFAULT_TIMEOUT_MS3 = Number(process.env.EDS_AGENT_TIMEOUT_MS ?? 5 * 60 * 1e3);
6479
6859
  async function hashSelectPrompt(options) {
6480
- const promptHash = options.promptText ? hashContent(options.promptText) : options.promptPath ? await hashFile(resolve8(options.promptPath)) : await hashFile(resolveSkillPath2("select"));
6860
+ const promptHash = options.promptText ? hashContent(options.promptText) : options.promptPath ? await hashFile(resolve10(options.promptPath)) : await hashFile(resolveSkillPath2("select"));
6481
6861
  return hashContent(`${promptHash}|${options.agent}|${options.model ?? ""}`);
6482
6862
  }
6483
6863
  async function runSelection(options) {
@@ -6566,7 +6946,7 @@ var realDeps = { checkAgentAuth: checkAgentAuth2, fetchEntities, spawnExtract, r
6566
6946
  var fail = (step, message) => ({ ok: false, step, message });
6567
6947
  var errorMessage2 = (error) => error instanceof Error ? error.message : String(error);
6568
6948
  async function runExtraction(input, onProgress, deps = realDeps) {
6569
- const outDir = join11(resolve9(input.projectPath), ".contentful");
6949
+ const outDir = join12(resolve11(input.projectPath), ".contentful");
6570
6950
  let progress = initialProgress({
6571
6951
  hasCredentials: input.credentials !== null,
6572
6952
  hasRawTokens: input.rawTokensPath !== "",
@@ -6651,10 +7031,11 @@ async function runExtraction(input, onProgress, deps = realDeps) {
6651
7031
  const tokens = await tokenGeneration;
6652
7032
  if (tokens && !tokens.ok) return fail(tokens.step, tokens.message);
6653
7033
  if (!sessionId) return fail("analyze extract", "The extract command did not report a session.");
7034
+ const hasTokenSource = input.rawTokensPath !== "" || input.tokenStrategy === "reuse";
6654
7035
  const extraction = {
6655
7036
  sessionId,
6656
7037
  outDir,
6657
- tokensPath: tokens?.ok ? tokens.tokensPath : join11(outDir, "tokens.json"),
7038
+ tokensPath: tokens?.ok ? tokens.tokensPath : hasTokenSource ? join12(outDir, "tokens.json") : "",
6658
7039
  tokenSessionId: tokens?.ok ? tokens.tokenSessionId : null,
6659
7040
  tokenCount: tokens?.ok ? tokens.tokenCount : 0,
6660
7041
  existingEntitiesPath,
@@ -6665,7 +7046,7 @@ async function runExtraction(input, onProgress, deps = realDeps) {
6665
7046
  }
6666
7047
  async function fetchEntities(credentials, outDir) {
6667
7048
  try {
6668
- await mkdir2(outDir, { recursive: true });
7049
+ await mkdir3(outDir, { recursive: true });
6669
7050
  const result = await fetchAndPersistExistingContentfulEntities({
6670
7051
  spaceId: credentials.spaceId,
6671
7052
  environmentId: credentials.environmentId,
@@ -6685,7 +7066,7 @@ async function resolveSelectionPrompt(overrides) {
6685
7066
  if (select?.kind === "text") return { promptText: select.value };
6686
7067
  if (select?.kind === "path") {
6687
7068
  await resolvePromptOverride(select);
6688
- return { promptPath: resolve9(select.value) };
7069
+ return { promptPath: resolve11(select.value) };
6689
7070
  }
6690
7071
  return {};
6691
7072
  }
@@ -7544,7 +7925,7 @@ function buildVisibleRows(props) {
7544
7925
  if (visited.has(target)) continue;
7545
7926
  visited.add(target);
7546
7927
  const isCycleMember = cycleParticipants.has(target);
7547
- out.push({ name: target, depth: cur.depth + 1, isCycleMember, parent: cur.name });
7928
+ out.push({ name: target, depth: cur.depth + 1, isCycleMember });
7548
7929
  queue.push({ name: target, depth: cur.depth + 1 });
7549
7930
  }
7550
7931
  }
@@ -7591,8 +7972,7 @@ function buildVisibleRows(props) {
7591
7972
  sharedSuffix,
7592
7973
  cycleChild: child.isCycleMember || void 0,
7593
7974
  itemIdx: childRec?.idx ?? -1,
7594
- rootName: key,
7595
- parentName: child.parent
7975
+ rootName: key
7596
7976
  });
7597
7977
  });
7598
7978
  }
@@ -7675,19 +8055,13 @@ function buildVisibleRows(props) {
7675
8055
  injectedChildren.push({
7676
8056
  name: target,
7677
8057
  depth: parentDepth + 1,
7678
- isCycleChild: true,
7679
- parent: parentName
8058
+ isCycleChild: true
7680
8059
  });
7681
8060
  }
7682
8061
  };
7683
8062
  emitCycleChildrenOf(root, 0);
7684
8063
  for (const c2 of closureChildren) {
7685
- injectedChildren.push({
7686
- name: c2.name,
7687
- depth: c2.depth,
7688
- isCycleChild: false,
7689
- parent: c2.path[c2.path.length - 2] ?? root
7690
- });
8064
+ injectedChildren.push({ name: c2.name, depth: c2.depth, isCycleChild: false });
7691
8065
  emitCycleChildrenOf(c2.name, c2.depth);
7692
8066
  }
7693
8067
  const isLastAtDepth = (idx) => {
@@ -7721,8 +8095,7 @@ function buildVisibleRows(props) {
7721
8095
  sharedSuffix,
7722
8096
  cycleChild: child.isCycleChild || void 0,
7723
8097
  itemIdx: childRec?.idx ?? -1,
7724
- rootName: root,
7725
- parentName: child.parent
8098
+ rootName: root
7726
8099
  });
7727
8100
  });
7728
8101
  }
@@ -7875,7 +8248,7 @@ function GroupedSidebar(props) {
7875
8248
  const rs = itemName ? renderStatusByKey?.get(itemName) : void 0;
7876
8249
  const badge = itemName ? previewBadge(previewAnnotationByKey?.get(itemName)) : null;
7877
8250
  const showInheritance = rs !== void 0 && row.kind !== "cycle" && row.kind !== "empty" && row.kind !== "group-root";
7878
- const supportsSelectionGlyph = selectionStateByKey !== void 0 && itemName !== void 0 && (row.kind === "standalone" || row.kind === "group-root" || row.kind === "group-child" || row.kind === "flat" || row.kind === "empty" || row.kind === "cycle");
8251
+ const supportsSelectionGlyph = selectionStateByKey !== void 0 && itemName !== void 0 && (row.kind === "standalone" || row.kind === "group-root" || row.kind === "group-child" || row.kind === "flat" || row.kind === "cycle");
7879
8252
  const selState = supportsSelectionGlyph ? selectionStateByKey.get(itemName) ?? "undecided" : void 0;
7880
8253
  const isCycleRow = row.kind === "cycle";
7881
8254
  const selStyle = selectionGlyphStyleFor(selState, isCycleRow);
@@ -7905,7 +8278,7 @@ function GroupedSidebar(props) {
7905
8278
  color: isSelected ? PALETTE2.info : labelStyle.dim ? PALETTE2.muted : labelStyle.color,
7906
8279
  bold: isSelected || labelStyle.bold,
7907
8280
  inverse: false,
7908
- underline: isSelected && focused,
8281
+ underline: isSelected && !focused,
7909
8282
  wrap: wrapLabels ? "wrap" : "truncate",
7910
8283
  children: [
7911
8284
  " ",
@@ -8310,11 +8683,11 @@ function buildCycleUnits(slotCycles) {
8310
8683
  while (parent.get(cur) !== cur) {
8311
8684
  cur = parent.get(cur);
8312
8685
  }
8313
- let walk = x;
8314
- while (parent.get(walk) !== cur) {
8315
- const next = parent.get(walk);
8316
- parent.set(walk, cur);
8317
- walk = next;
8686
+ let walk2 = x;
8687
+ while (parent.get(walk2) !== cur) {
8688
+ const next = parent.get(walk2);
8689
+ parent.set(walk2, cur);
8690
+ walk2 = next;
8318
8691
  }
8319
8692
  return cur;
8320
8693
  };
@@ -8549,7 +8922,6 @@ function resolveKey(mode, key, ctx) {
8549
8922
  function resolveMain(key, ctx) {
8550
8923
  const { input } = key;
8551
8924
  const inMain = ctx.focusedColumn === "main";
8552
- if (key.ctrl && input === "z") return { type: "undo" };
8553
8925
  if (input === "q" || key.escape) {
8554
8926
  if (key.escape && ctx.jumpFilterActive) return { type: "clear-jump-filter" };
8555
8927
  if (key.escape && ctx.searchActive) return { type: "clear-search" };
@@ -8808,42 +9180,21 @@ function rejectNeedsConfirmation(graph, name, state) {
8808
9180
  const ancestors = toReject.filter((n) => n !== name);
8809
9181
  return ancestors.length + toDeselect.length >= 2;
8810
9182
  }
8811
- function removeSlotChild(components, edge) {
8812
- return components.map(
8813
- (component) => component.name === edge.parent ? {
8814
- ...component,
8815
- slots: component.slots?.map((slot) => ({
8816
- ...slot,
8817
- allowedComponents: slot.allowedComponents.filter((name) => name !== edge.child)
8818
- }))
8819
- } : component
8820
- );
8821
- }
8822
- function withoutSlotChildren(components, removedEdges) {
8823
- return removedEdges.reduce(removeSlotChild, components);
8824
- }
8825
- function partitionDecisions(components, state, removedEdges) {
9183
+ function partitionDecisions(components, state) {
8826
9184
  const accepted = [];
8827
9185
  const rejected = [];
8828
9186
  for (const c2 of components) {
8829
9187
  if (state.get(c2.name) === "accepted") accepted.push(c2.name);
8830
9188
  else rejected.push(c2.name);
8831
9189
  }
8832
- const rejectedNames = new Set(rejected);
8833
- const excludedSlotEdges = removedEdges.filter((e) => !rejectedNames.has(e.parent) && !rejectedNames.has(e.child));
8834
- return { accepted, rejected, excludedSlotEdges };
9190
+ return { accepted, rejected };
8835
9191
  }
8836
9192
 
8837
9193
  // packages/experience-design-system-cli/src/tui/import/steps/07-scope-gate/use-scope-gate.ts
8838
- function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
9194
+ function useScopeGate({ components, onConfirm, onQuit }) {
8839
9195
  const { columns: totalWidth, rows: terminalRows } = useTerminalSize();
8840
9196
  const columnPlan = useMemo2(() => computeColumnWidths(totalWidth), [totalWidth]);
8841
9197
  const [decisions, setDecisions] = useState12(/* @__PURE__ */ new Map());
8842
- const [removedEdges, setRemovedEdges] = useState12([]);
8843
- const components = useMemo2(
8844
- () => withoutSlotChildren(loadedComponents, removedEdges),
8845
- [loadedComponents, removedEdges]
8846
- );
8847
9198
  const [nav, setNav] = useState12({ cursor: 0, scrollOffset: 0 });
8848
9199
  const [focusedColumn, setFocusedColumn] = useState12("main");
8849
9200
  const [addedComponentsCursor, setAddedComponentsCursor] = useState12(0);
@@ -9015,14 +9366,6 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
9015
9366
  return void 0;
9016
9367
  }
9017
9368
  };
9018
- const focusedNestedEdge = () => {
9019
- const row = visibleRows[safeCursor];
9020
- if (row?.kind !== "group-child" || !row.parentName || row.itemIdx < 0) return void 0;
9021
- const child = groupedItems[row.itemIdx]?.key;
9022
- return child ? { parent: row.parentName, child } : void 0;
9023
- };
9024
- const removeFromParentSlot = (edge) => setRemovedEdges((edges) => [...edges, edge]);
9025
- const undoSlotRemoval = () => setRemovedEdges((edges) => edges.slice(0, -1));
9026
9369
  const jumpCursorTo = (name) => {
9027
9370
  let idx = -1;
9028
9371
  for (let i = 0; i < visibleRows.length; i++) {
@@ -9122,7 +9465,7 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
9122
9465
  onQuit();
9123
9466
  return;
9124
9467
  case "confirm":
9125
- onConfirm(partitionDecisions(components, decisions, removedEdges));
9468
+ onConfirm(partitionDecisions(components, decisions));
9126
9469
  return;
9127
9470
  case "close-help":
9128
9471
  setShowHelp(false);
@@ -9175,11 +9518,6 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
9175
9518
  return;
9176
9519
  }
9177
9520
  case "reject": {
9178
- const edge = focusedColumn === "main" ? focusedNestedEdge() : void 0;
9179
- if (edge) {
9180
- removeFromParentSlot(edge);
9181
- return;
9182
- }
9183
9521
  const key = focusedColumn === "added-components" ? addedComponents[safeAddedComponentsCursor]?.name : focusedRowKey();
9184
9522
  if (key) requestReject(key);
9185
9523
  return;
@@ -9187,9 +9525,6 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
9187
9525
  case "toggle-all":
9188
9526
  decide({ type: "toggle-all" });
9189
9527
  return;
9190
- case "undo":
9191
- undoSlotRemoval();
9192
- return;
9193
9528
  case "accept-unflagged":
9194
9529
  decide({ type: "accept-unflagged" });
9195
9530
  return;
@@ -9481,9 +9816,9 @@ function parseCacheComponents(stdout) {
9481
9816
  return [];
9482
9817
  }
9483
9818
  }
9484
- var runLegacyCli = (args) => new Promise((resolve10) => {
9819
+ var runLegacyCli = (args) => new Promise((resolve12) => {
9485
9820
  execFile3("node", [findLegacyCliPath(), ...args], (error, stdout, stderr) => {
9486
- resolve10({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
9821
+ resolve12({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
9487
9822
  });
9488
9823
  });
9489
9824
  async function checkGenerationCache(input, run2 = runLegacyCli) {
@@ -9525,31 +9860,320 @@ function useScopeGateFlow(input, deps = realDeps2) {
9525
9860
  const loaded = useMemo3(() => sessionId ? deps.load(sessionId) : void 0, [sessionId]);
9526
9861
  const cacheCheck = useRef5(void 0);
9527
9862
  const [confirmed, setConfirmed] = useState13();
9528
- const [scope, setScope] = useState13();
9529
9863
  useEffect8(() => {
9530
9864
  if (!input || !loaded?.ok || cacheCheck.current) return;
9531
9865
  cacheCheck.current = deps.checkCache(input.cache);
9532
9866
  }, [input, loaded]);
9533
- useEffect8(() => {
9534
- if (!confirmed || !cacheCheck.current) return;
9535
- let current = true;
9536
- void cacheCheck.current.then((cachedNames) => {
9537
- const accepted = new Set(confirmed.accepted);
9538
- if (current) setScope({ ...confirmed, cachedNames: cachedNames.filter((name) => accepted.has(name)) });
9539
- });
9540
- return () => {
9541
- current = false;
9542
- };
9543
- }, [confirmed]);
9544
9867
  if (!input || !loaded) return void 0;
9545
9868
  if (!loaded.ok) return { status: "failed", message: loaded.message };
9546
- if (scope) return { status: "confirmed", scope };
9547
- if (confirmed) return { status: "preparing" };
9869
+ if (confirmed && cacheCheck.current)
9870
+ return { status: "confirmed", decisions: confirmed, cachedNames: cacheCheck.current };
9548
9871
  return { status: "deciding", load: loaded, confirm: setConfirmed };
9549
9872
  }
9550
9873
 
9874
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/logic.ts
9875
+ function initialProgress2() {
9876
+ return { components: null, mapTokens: "idle", mapTokensEligible: null };
9877
+ }
9878
+ var PROGRESS_LINE = /^progress=generate:(\d+)\/(\d+):(.+)$/;
9879
+ var STARTED_LINE = /\[(\d+)\/(\d+)\]\s+(.+)/;
9880
+ function applyGenerateStderr(chunk, previous) {
9881
+ let state = previous;
9882
+ for (const line of chunk.split("\n")) {
9883
+ const finished = PROGRESS_LINE.exec(line);
9884
+ if (finished) {
9885
+ state = { done: Number(finished[1]), total: Number(finished[2]), current: finished[3].trim() };
9886
+ continue;
9887
+ }
9888
+ const started = STARTED_LINE.exec(line);
9889
+ if (started) {
9890
+ state = { done: state?.done ?? 0, total: Number(started[2]), current: started[3].trim() };
9891
+ }
9892
+ }
9893
+ return state;
9894
+ }
9895
+ function parseGenerateResult(output, fallbackCount) {
9896
+ const session = /^session=(.+)$/m.exec(output.stdout);
9897
+ const count = /(\d+) components?/.exec(output.stderr);
9898
+ const renamed = /^renamed-slots:\s*(\d+)$/m.exec(output.stdout);
9899
+ return {
9900
+ generateSessionId: session ? session[1].trim() : null,
9901
+ generatedCount: count ? Number(count[1]) : fallbackCount,
9902
+ renamedSlotsCount: renamed ? Number(renamed[1]) : 0
9903
+ };
9904
+ }
9905
+ function shouldRunMapTokens(counts) {
9906
+ return counts.mappablePropCount > 0 && counts.rawTokenCount > 0;
9907
+ }
9908
+ function formatAcceptanceSummary(counts) {
9909
+ const accepted = `${counts.accepted} component${counts.accepted === 1 ? "" : "s"} accepted`;
9910
+ if (counts.autoRejected === 0) return `${accepted}.`;
9911
+ return `${accepted}, ${counts.autoRejected} excluded due to validation errors.`;
9912
+ }
9913
+ var capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1);
9914
+ function describeGeneration(input) {
9915
+ const agent = capitalize(input.agent);
9916
+ return `${formatAcceptanceSummary({ accepted: input.acceptedCount, autoRejected: 0 })}
9917
+ ${agent} is mapping your selected components to Contentful's Component Definition Format (CDF).${input.hasTokens ? " Using your design tokens for prop resolution." : ""}`;
9918
+ }
9919
+ function progressRows2(progress, agent) {
9920
+ const name = capitalize(agent);
9921
+ const { components, mapTokens } = progress;
9922
+ const rows = [
9923
+ {
9924
+ text: components ? components.current : `Starting up ${name}...`,
9925
+ complete: false,
9926
+ ...components ? { progress: { done: components.done, total: components.total } } : {}
9927
+ }
9928
+ ];
9929
+ if (mapTokens !== "idle") {
9930
+ rows.push({
9931
+ text: mapTokens === "running" ? `Mapping token restrictions via ${name}...` : "Token restrictions ready",
9932
+ complete: mapTokens === "complete"
9933
+ });
9934
+ }
9935
+ return rows;
9936
+ }
9937
+
9938
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/screen.tsx
9939
+ import { jsx as jsx25 } from "react/jsx-runtime";
9940
+ function GenerationScreen({
9941
+ progress,
9942
+ agent,
9943
+ acceptedCount,
9944
+ hasTokens,
9945
+ stepNumber,
9946
+ totalSteps
9947
+ }) {
9948
+ return /* @__PURE__ */ jsx25(
9949
+ RunningStep,
9950
+ {
9951
+ stepNumber,
9952
+ totalSteps,
9953
+ title: "Generating definitions",
9954
+ description: describeGeneration({ acceptedCount, agent, hasTokens }),
9955
+ lines: progressRows2(progress, agent)
9956
+ }
9957
+ );
9958
+ }
9959
+
9960
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/use-generation.ts
9961
+ import { useEffect as useEffect9, useRef as useRef6, useState as useState14 } from "react";
9962
+
9963
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/map-tokens.ts
9964
+ async function prepareMapTokens(input, generatedSessionId) {
9965
+ const db = openPipelineDb();
9966
+ try {
9967
+ if (input.tokenSessionId && input.tokenSessionId !== generatedSessionId) {
9968
+ copyTokensFromCache(db, input.tokenSessionId, generatedSessionId);
9969
+ } else if (!input.tokenSessionId && input.tokensPath) {
9970
+ const tokens = await readTokensFromPath2({ flag: "tokens", path: input.tokensPath });
9971
+ storeDtcgTokens(db, generatedSessionId, [], tokens);
9972
+ }
9973
+ const mappablePropCount = loadCDFComponents(db, generatedSessionId).reduce(
9974
+ (count, { entry }) => count + Object.values(entry.$properties).filter((prop) => prop.$type === "token" && prop.$category === "design").length,
9975
+ 0
9976
+ );
9977
+ const rawTokenCount = getDtcgTokensForSession(db, generatedSessionId).tokens.length;
9978
+ return {
9979
+ eligible: shouldRunMapTokens({ mappablePropCount, rawTokenCount }),
9980
+ mappablePropCount,
9981
+ rawTokenCount
9982
+ };
9983
+ } finally {
9984
+ db.close();
9985
+ }
9986
+ }
9987
+
9988
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/processes.ts
9989
+ import { execFile as execFile4, spawn as spawn7 } from "node:child_process";
9990
+ function buildGenerateArgs(cliPath, command) {
9991
+ const args = [cliPath, "__generate", "components", "--agent", command.agent, "--session", command.sessionId];
9992
+ if (command.tokensPath) args.push("--tokens", command.tokensPath);
9993
+ if (command.agentModel) args.push("--model", command.agentModel);
9994
+ if (command.noCache) args.push("--no-cache");
9995
+ if (command.generatePromptPath) args.push("--generate-prompt-path", command.generatePromptPath);
9996
+ for (const prompt of command.promptOverrides) args.push("--prompt", prompt);
9997
+ if (command.existingEntitiesPath) args.push("--existing-entities-path", command.existingEntitiesPath);
9998
+ if (command.cachedComponents.length > 0) args.push("--cached-components", JSON.stringify(command.cachedComponents));
9999
+ return args;
10000
+ }
10001
+ function buildMapTokensArgs(command) {
10002
+ const args = ["map", "tokens", "--session", command.sessionId, "--agent", command.agent];
10003
+ if (command.agentModel) args.push("--model", command.agentModel);
10004
+ if (command.noCache) args.push("--no-cache");
10005
+ for (const prompt of command.promptOverrides) args.push("--prompt", prompt);
10006
+ if (command.existingEntitiesPath) args.push("--existing-entities-path", command.existingEntitiesPath);
10007
+ return args;
10008
+ }
10009
+ function spawnGenerate(command, handlers) {
10010
+ return new Promise((resolve12) => {
10011
+ const child = spawn7("node", buildGenerateArgs(findLegacyCliPath(), command));
10012
+ let stdout = "";
10013
+ let stderr = "";
10014
+ child.stdout.on("data", (data) => {
10015
+ stdout += String(data);
10016
+ });
10017
+ child.stderr.on("data", (data) => {
10018
+ const chunk = String(data);
10019
+ stderr += chunk;
10020
+ handlers.onStderr(chunk);
10021
+ });
10022
+ child.on("error", (error) => resolve12({ exitCode: 1, stdout, stderr: stderr + error.message }));
10023
+ child.on("close", (code) => resolve12({ exitCode: code ?? 0, stdout, stderr }));
10024
+ });
10025
+ }
10026
+ function runMapTokens2(command) {
10027
+ return new Promise((resolve12) => {
10028
+ execFile4("node", [findLegacyCliPath(), ...buildMapTokensArgs(command)], (error, stdout, stderr) => {
10029
+ resolve12({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
10030
+ });
10031
+ });
10032
+ }
10033
+
10034
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/save-decisions.ts
10035
+ async function saveDecisions(input) {
10036
+ const db = openPipelineDb();
10037
+ try {
10038
+ applyScopeDecisions(db, input.sessionId, input.decisions);
10039
+ await writeScopeDecisionsSnapshot(db, input.sessionId, input.decisions);
10040
+ } finally {
10041
+ db.close();
10042
+ }
10043
+ }
10044
+
10045
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/run.ts
10046
+ var realDeps3 = {
10047
+ checkAgentAuth: checkAgentAuth2,
10048
+ saveDecisions,
10049
+ checkCache: checkGenerationCache,
10050
+ spawnGenerate,
10051
+ prepareMapTokens,
10052
+ runMapTokens: runMapTokens2
10053
+ };
10054
+ var fail2 = (step, message) => ({ ok: false, step, message });
10055
+ var errorMessage3 = (error) => error instanceof Error ? error.message : String(error);
10056
+ async function runGeneration(input, onProgress, deps = realDeps3) {
10057
+ let progress = initialProgress2();
10058
+ const update = (change) => {
10059
+ progress = { ...progress, ...change };
10060
+ onProgress(progress);
10061
+ };
10062
+ const accepted = input.decisions.accepted;
10063
+ const handedOverNames = await input.cachedNames.catch(() => []);
10064
+ try {
10065
+ await deps.saveDecisions({ sessionId: input.sessionId, decisions: input.decisions });
10066
+ } catch (error) {
10067
+ return fail2("save decisions", errorMessage3(error));
10068
+ }
10069
+ if (accepted.length === 0) return { ok: true, generation: { route: "push", acceptedCount: 0 } };
10070
+ const auth = await deps.checkAgentAuth(input.agent);
10071
+ if (auth === "not-found" || auth === "unauthenticated") {
10072
+ return fail2(`${input.agent} auth check`, agentAuthMessage(input.agent, auth));
10073
+ }
10074
+ const acceptedSet = new Set(accepted);
10075
+ let cachedNames = handedOverNames;
10076
+ let cacheHit = !input.noCache && accepted.length > 0 && accepted.every((name) => cachedNames.includes(name));
10077
+ if (!cacheHit && !input.noCache && accepted.length > 0) {
10078
+ const fresh = await deps.checkCache(cacheCheckFor(input));
10079
+ cachedNames = fresh.filter((name) => acceptedSet.has(name));
10080
+ cacheHit = accepted.every((name) => cachedNames.includes(name));
10081
+ }
10082
+ let generatedSessionId = input.sessionId;
10083
+ let generatedCount = accepted.length;
10084
+ if (!cacheHit) {
10085
+ const result = await deps.spawnGenerate(
10086
+ {
10087
+ sessionId: input.sessionId,
10088
+ tokensPath: input.tokensPath,
10089
+ agent: input.agent,
10090
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
10091
+ promptOverrides: input.promptOverrides,
10092
+ ...input.generatePromptPath ? { generatePromptPath: input.generatePromptPath } : {},
10093
+ noCache: input.noCache,
10094
+ existingEntitiesPath: input.existingEntitiesPath,
10095
+ cachedComponents: cachedNames
10096
+ },
10097
+ {
10098
+ onStderr: (chunk) => {
10099
+ const components = applyGenerateStderr(chunk, progress.components);
10100
+ if (components !== progress.components) update({ components });
10101
+ }
10102
+ }
10103
+ );
10104
+ if (result.exitCode !== 0) return fail2("generate components", result.stderr.trim() || "Unknown error");
10105
+ const parsed = parseGenerateResult(result, accepted.length);
10106
+ generatedSessionId = parsed.generateSessionId ?? input.sessionId;
10107
+ generatedCount = parsed.generatedCount;
10108
+ }
10109
+ let plan;
10110
+ try {
10111
+ plan = await deps.prepareMapTokens(input, generatedSessionId);
10112
+ } catch (error) {
10113
+ return fail2("map tokens", errorMessage3(error));
10114
+ }
10115
+ update({ mapTokensEligible: plan.eligible });
10116
+ if (plan.eligible) {
10117
+ update({ mapTokens: "running" });
10118
+ const mapped = await deps.runMapTokens({
10119
+ sessionId: generatedSessionId,
10120
+ agent: input.agent,
10121
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
10122
+ promptOverrides: input.promptOverrides,
10123
+ noCache: input.noCache,
10124
+ existingEntitiesPath: input.existingEntitiesPath
10125
+ });
10126
+ if (mapped.exitCode !== 0) return fail2("map tokens", mapped.stderr.trim() || "Unknown error");
10127
+ }
10128
+ update({ mapTokens: "complete" });
10129
+ return {
10130
+ ok: true,
10131
+ generation: {
10132
+ route: "review",
10133
+ sessionId: generatedSessionId,
10134
+ acceptedCount: accepted.length,
10135
+ generatedCount,
10136
+ mapTokensEligible: plan.eligible
10137
+ }
10138
+ };
10139
+ }
10140
+ function cacheCheckFor(input) {
10141
+ return {
10142
+ sessionId: input.sessionId,
10143
+ tokensPath: input.tokensPath,
10144
+ agent: input.agent,
10145
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
10146
+ promptOverrides: input.promptOverrides,
10147
+ existingEntitiesPath: input.existingEntitiesPath,
10148
+ noCache: input.noCache
10149
+ };
10150
+ }
10151
+
10152
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/use-generation.ts
10153
+ function useGeneration(input) {
10154
+ const [state, setState] = useState14();
10155
+ const current = useRef6();
10156
+ useEffect9(() => {
10157
+ current.current = input;
10158
+ if (!input) {
10159
+ setState(void 0);
10160
+ return;
10161
+ }
10162
+ setState({ status: "running", progress: initialProgress2() });
10163
+ void runGeneration(input, (progress) => {
10164
+ if (current.current === input) setState({ status: "running", progress });
10165
+ }).then((result) => {
10166
+ if (current.current === input) setState({ status: "done", result });
10167
+ });
10168
+ return () => {
10169
+ if (current.current === input) current.current = void 0;
10170
+ };
10171
+ }, [input]);
10172
+ return state;
10173
+ }
10174
+
9551
10175
  // packages/experience-design-system-cli/src/tui/import/spawn-v1-import.ts
9552
- import { spawn as spawn7 } from "node:child_process";
10176
+ import { spawn as spawn8 } from "node:child_process";
9553
10177
 
9554
10178
  // packages/experience-design-system-cli/src/commands/import-options.ts
9555
10179
  function importOptionArgs(options) {
@@ -9583,27 +10207,36 @@ var ExtractionSchema = z5.object({
9583
10207
  /** The only phases the scope gate can start from. */
9584
10208
  compositionPhase: z5.enum(["done", "cache-hit"])
9585
10209
  });
9586
- var ScopeSchema = z5.object({
9587
- /** The components the user kept at the scope gate. The wizard saves these, then generates them. */
9588
- accepted: z5.array(z5.string()),
9589
- /** Everything else at the gate, which counts as rejected. */
9590
- rejected: z5.array(z5.string()),
9591
- /** Slot edges the user removed at the gate. The child stays accepted; only that parent stops allowing it. */
9592
- excludedSlotEdges: z5._default(z5.array(z5.object({ parent: z5.string(), child: z5.string() })), []),
9593
- /**
9594
- * Components the generation cache already holds, found by the check that ran while the gate was open and which has
9595
- * finished (and restored them) before the wizard starts. Empty when the cache is off or the check failed.
9596
- */
9597
- cachedNames: z5.array(z5.string())
9598
- });
10210
+ var GenerationSchema = z5.discriminatedUnion("route", [
10211
+ /** At least one component was accepted: the definitions were generated and the wizard opens the review screen. */
10212
+ z5.object({
10213
+ route: z5.literal("review"),
10214
+ /** The session the generated definitions are in. The review screen opens it, and saving and pushing read it. */
10215
+ sessionId: NonEmpty,
10216
+ /** How many components the user accepted at the scope gate. */
10217
+ acceptedCount: z5.number(),
10218
+ /** How many definitions were generated, which can differ from the accepted count. */
10219
+ generatedCount: z5.number(),
10220
+ /**
10221
+ * Whether token mapping was worth running (there were design props that are tokens, and tokens to map them from).
10222
+ * The step count the wizard shows depends on it.
10223
+ */
10224
+ mapTokensEligible: z5.boolean()
10225
+ }),
10226
+ /** Nothing was accepted: nothing is generated and the wizard goes straight to the push flow, as it always did. */
10227
+ z5.object({ route: z5.literal("push"), acceptedCount: z5.literal(0) })
10228
+ ]);
9599
10229
  var ImportHandoffSchema = z5.object({
9600
10230
  /** The user skipped the credentials screen, so nothing is fetched from or pushed to Contentful. */
9601
10231
  credentialsSkipped: z5.boolean(),
9602
10232
  tokens: TokensSchema,
9603
10233
  /** Present once the CLI has run the extraction stage; the wizard then starts at the scope gate. */
9604
10234
  extraction: z5.optional(ExtractionSchema),
9605
- /** Present once the user has confirmed the scope gate; the wizard then saves the decisions and starts generating. */
9606
- scope: z5.optional(ScopeSchema)
10235
+ /**
10236
+ * Present once the CLI has shown the scope gate, saved the decisions and generated the definitions; the wizard then
10237
+ * starts at the review screen (or goes straight to pushing when nothing was accepted).
10238
+ */
10239
+ generation: z5.optional(GenerationSchema)
9607
10240
  });
9608
10241
  function serializeHandoff(handoff) {
9609
10242
  return JSON.stringify(handoff);
@@ -9628,7 +10261,7 @@ async function spawnV1Import(options = {}) {
9628
10261
  const cliPath = findLegacyCliPath();
9629
10262
  const args = buildArgs2(options);
9630
10263
  return new Promise((resolvePromise) => {
9631
- const child = spawn7("node", [cliPath, ...args], {
10264
+ const child = spawn8("node", [cliPath, ...args], {
9632
10265
  stdio: "inherit",
9633
10266
  env: buildEnv(options)
9634
10267
  });
@@ -9646,7 +10279,7 @@ function getTerminalHandle() {
9646
10279
  return process.stdin._handle;
9647
10280
  }
9648
10281
  async function stopReadingTerminal() {
9649
- await new Promise((resolve10) => setImmediate(resolve10));
10282
+ await new Promise((resolve12) => setImmediate(resolve12));
9650
10283
  const handle = getTerminalHandle();
9651
10284
  if (!handle?.readStop) return;
9652
10285
  handle.reading = false;
@@ -9660,13 +10293,13 @@ function startReadingTerminal() {
9660
10293
  }
9661
10294
 
9662
10295
  // packages/experience-design-system-cli/src/tui/help/PageContainer.tsx
9663
- import { useEffect as useEffect9, useState as useState14 } from "react";
10296
+ import { useEffect as useEffect10, useState as useState15 } from "react";
9664
10297
  import { Box as Box21, Text as Text23, useInput as useInput9 } from "ink";
9665
10298
 
9666
10299
  // packages/experience-design-system-cli/src/tui/debug-store.ts
9667
- import { mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
10300
+ import { mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
9668
10301
  import { existsSync as existsSync5, readdirSync as readdirSync2 } from "node:fs";
9669
- import { join as join12 } from "node:path";
10302
+ import { join as join13 } from "node:path";
9670
10303
 
9671
10304
  // packages/experience-design-system-cli/src/tui/settings/debug-mode/debug-mode-store.ts
9672
10305
  var DEFAULT_DEBUG_MODE_SETTING = {
@@ -9707,14 +10340,14 @@ function generateSessionId3() {
9707
10340
  }
9708
10341
  var SESSION_ID = generateSessionId3();
9709
10342
  function sessionDebugDir() {
9710
- return join12(debugSessionsDir2(), SESSION_ID);
10343
+ return join13(debugSessionsDir2(), SESSION_ID);
9711
10344
  }
9712
10345
  function currentDebugSessionDir() {
9713
10346
  return sessionDebugDir();
9714
10347
  }
9715
10348
  void isDebugModeEnabled().then((enabled) => {
9716
10349
  if (!enabled) return void 0;
9717
- return mkdir3(sessionDebugDir(), { recursive: true });
10350
+ return mkdir4(sessionDebugDir(), { recursive: true });
9718
10351
  });
9719
10352
  async function isDebugModeEnabled() {
9720
10353
  try {
@@ -9756,10 +10389,10 @@ async function finishDebugRun({
9756
10389
  const durationMs = Date.now() - run2.startedAt;
9757
10390
  const content = renderMarkdown(run2, { outputs: redact(outputs), status, exitMethod, durationMs });
9758
10391
  const flowSegments = run2.flow.split("/");
9759
- const dir = join12(sessionDebugDir(), ...flowSegments);
9760
- await mkdir3(dir, { recursive: true });
10392
+ const dir = join13(sessionDebugDir(), ...flowSegments);
10393
+ await mkdir4(dir, { recursive: true });
9761
10394
  const filename = nextAttemptFilename(dir, run2.menuOption);
9762
- await writeFile3(join12(dir, filename), content, { mode: 384 });
10395
+ await writeFile4(join13(dir, filename), content, { mode: 384 });
9763
10396
  }
9764
10397
  function nextAttemptFilename(dir, menuOption) {
9765
10398
  const today = datePrefix();
@@ -9842,19 +10475,19 @@ async function readHelpInfo() {
9842
10475
  }
9843
10476
 
9844
10477
  // packages/experience-design-system-cli/src/tui/help/PageContainer.tsx
9845
- import { Fragment as Fragment5, jsx as jsx25, jsxs as jsxs22 } from "react/jsx-runtime";
10478
+ import { Fragment as Fragment5, jsx as jsx26, jsxs as jsxs22 } from "react/jsx-runtime";
9846
10479
  function Section({ title, rows }) {
9847
10480
  return /* @__PURE__ */ jsxs22(Box21, { flexDirection: "column", children: [
9848
- /* @__PURE__ */ jsx25(Text23, { bold: true, color: PALETTE.accent, children: title }),
10481
+ /* @__PURE__ */ jsx26(Text23, { bold: true, color: PALETTE.accent, children: title }),
9849
10482
  rows.map((row) => /* @__PURE__ */ jsxs22(Box21, { gap: 1, children: [
9850
- /* @__PURE__ */ jsx25(Box21, { width: 14, flexShrink: 0, children: /* @__PURE__ */ jsx25(Text23, { color: PALETTE.muted, children: row.label }) }),
9851
- /* @__PURE__ */ jsx25(Text23, { children: row.value })
10483
+ /* @__PURE__ */ jsx26(Box21, { width: 14, flexShrink: 0, children: /* @__PURE__ */ jsx26(Text23, { color: PALETTE.muted, children: row.label }) }),
10484
+ /* @__PURE__ */ jsx26(Text23, { children: row.value })
9852
10485
  ] }, row.label))
9853
10486
  ] });
9854
10487
  }
9855
10488
  function HelpScreen({ onDone }) {
9856
- const [info, setInfo] = useState14();
9857
- useEffect9(() => {
10489
+ const [info, setInfo] = useState15();
10490
+ useEffect10(() => {
9858
10491
  startDebugRun({ flow: "help", step: "01-help", menuOption: "Help", inputs: {} });
9859
10492
  void readHelpInfo().then(setInfo);
9860
10493
  }, []);
@@ -9873,13 +10506,13 @@ function HelpScreen({ onDone }) {
9873
10506
  }
9874
10507
  });
9875
10508
  return /* @__PURE__ */ jsxs22(Box21, { flexDirection: "column", paddingX: 2, paddingY: 1, gap: 1, children: [
9876
- /* @__PURE__ */ jsx25(Text23, { bold: true, children: "Help" }),
10509
+ /* @__PURE__ */ jsx26(Text23, { bold: true, children: "Help" }),
9877
10510
  info ? /* @__PURE__ */ jsxs22(Fragment5, { children: [
9878
- /* @__PURE__ */ jsx25(Section, { title: "Where things are stored", rows: info.storage }),
9879
- /* @__PURE__ */ jsx25(Section, { title: "Troubleshooting", rows: info.troubleshooting }),
9880
- /* @__PURE__ */ jsx25(Text23, { color: PALETTE.muted, children: "Hit a problem? Turn on Debug Mode in Settings, reproduce it, then share the session folder above. The CMA token is redacted from those logs." })
9881
- ] }) : /* @__PURE__ */ jsx25(Text23, { color: PALETTE.accent, children: "Loading..." }),
9882
- /* @__PURE__ */ jsx25(
10511
+ /* @__PURE__ */ jsx26(Section, { title: "Where things are stored", rows: info.storage }),
10512
+ /* @__PURE__ */ jsx26(Section, { title: "Troubleshooting", rows: info.troubleshooting }),
10513
+ /* @__PURE__ */ jsx26(Text23, { color: PALETTE.muted, children: "Hit a problem? Turn on Debug Mode in Settings, reproduce it, then share the session folder above. The CMA token is redacted from those logs." })
10514
+ ] }) : /* @__PURE__ */ jsx26(Text23, { color: PALETTE.accent, children: "Loading..." }),
10515
+ /* @__PURE__ */ jsx26(
9883
10516
  ControlHints,
9884
10517
  {
9885
10518
  hints: [
@@ -9892,14 +10525,14 @@ function HelpScreen({ onDone }) {
9892
10525
  }
9893
10526
 
9894
10527
  // packages/experience-design-system-cli/src/tui/settings/PageContainer.tsx
9895
- import { useState as useState15 } from "react";
10528
+ import { useState as useState16 } from "react";
9896
10529
  import { Box as Box22, Text as Text24, useInput as useInput10 } from "ink";
9897
- import { jsx as jsx26, jsxs as jsxs23 } from "react/jsx-runtime";
10530
+ import { jsx as jsx27, jsxs as jsxs23 } from "react/jsx-runtime";
9898
10531
  function SettingsScreen({
9899
10532
  onNavigate,
9900
10533
  onBack
9901
10534
  }) {
9902
- const [focusIdx, setFocusIdx] = useState15(0);
10535
+ const [focusIdx, setFocusIdx] = useState16(0);
9903
10536
  const items = [
9904
10537
  { label: "Configuration", screen: "settings-configuration" },
9905
10538
  { label: "Opt-in Analytics", screen: "settings-opt-in-analytics" },
@@ -9926,14 +10559,14 @@ function SettingsScreen({
9926
10559
  }
9927
10560
  });
9928
10561
  return /* @__PURE__ */ jsxs23(Box22, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
9929
- /* @__PURE__ */ jsx26(Text24, { bold: true, children: "Settings" }),
9930
- /* @__PURE__ */ jsx26(Text24, { children: " " }),
10562
+ /* @__PURE__ */ jsx27(Text24, { bold: true, children: "Settings" }),
10563
+ /* @__PURE__ */ jsx27(Text24, { children: " " }),
9931
10564
  items.map((item, i) => /* @__PURE__ */ jsxs23(Text24, { color: i === focusIdx ? "cyan" : void 0, children: [
9932
10565
  i === focusIdx ? "> " : " ",
9933
10566
  item.label
9934
10567
  ] }, item.label)),
9935
- /* @__PURE__ */ jsx26(Text24, { children: " " }),
9936
- /* @__PURE__ */ jsx26(
10568
+ /* @__PURE__ */ jsx27(Text24, { children: " " }),
10569
+ /* @__PURE__ */ jsx27(
9937
10570
  ControlHints,
9938
10571
  {
9939
10572
  hints: [
@@ -9947,7 +10580,7 @@ function SettingsScreen({
9947
10580
  }
9948
10581
 
9949
10582
  // packages/experience-design-system-cli/src/tui/settings/contentful-configuration/ContentfulConfigScreen.tsx
9950
- import { useEffect as useEffect10, useState as useState16 } from "react";
10583
+ import { useEffect as useEffect11, useState as useState17 } from "react";
9951
10584
  import { Box as Box23, Text as Text25, useInput as useInput11 } from "ink";
9952
10585
  import TextInput4 from "ink-text-input";
9953
10586
 
@@ -9980,7 +10613,7 @@ async function writeCredentials(config) {
9980
10613
  }
9981
10614
 
9982
10615
  // packages/experience-design-system-cli/src/tui/settings/contentful-configuration/ContentfulConfigScreen.tsx
9983
- import { Fragment as Fragment6, jsx as jsx27, jsxs as jsxs24 } from "react/jsx-runtime";
10616
+ import { Fragment as Fragment6, jsx as jsx28, jsxs as jsxs24 } from "react/jsx-runtime";
9984
10617
  var FIELD_ORDER = [
9985
10618
  "spaceId",
9986
10619
  "environmentId",
@@ -10008,14 +10641,14 @@ var FIELD_LABELS = {
10008
10641
  defaultTokenFile: "Default token file (optional)"
10009
10642
  };
10010
10643
  function ConfigurationScreen({ onDone }) {
10011
- const [stage, setStage] = useState16("loading");
10012
- const [config, setConfig] = useState16(null);
10013
- const [activeField, setActiveField] = useState16("spaceId");
10014
- const [notice, setNotice] = useState16(null);
10015
- const [lastSaved, setLastSaved] = useState16(null);
10016
- const [editing, setEditing] = useState16(false);
10017
- const [valueBeforeEdit, setValueBeforeEdit] = useState16("");
10018
- useEffect10(() => {
10644
+ const [stage, setStage] = useState17("loading");
10645
+ const [config, setConfig] = useState17(null);
10646
+ const [activeField, setActiveField] = useState17("spaceId");
10647
+ const [notice, setNotice] = useState17(null);
10648
+ const [lastSaved, setLastSaved] = useState17(null);
10649
+ const [editing, setEditing] = useState17(false);
10650
+ const [valueBeforeEdit, setValueBeforeEdit] = useState17("");
10651
+ useEffect11(() => {
10019
10652
  readCredentials().then((cfg) => {
10020
10653
  setConfig(cfg);
10021
10654
  setStage("form");
@@ -10093,25 +10726,25 @@ function ConfigurationScreen({ onDone }) {
10093
10726
  });
10094
10727
  if (stage === "loading") {
10095
10728
  return /* @__PURE__ */ jsxs24(Box23, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
10096
- /* @__PURE__ */ jsx27(Text25, { bold: true, children: "Configuration" }),
10097
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
10098
- /* @__PURE__ */ jsx27(Text25, { color: PALETTE.accent, children: "Loading..." })
10729
+ /* @__PURE__ */ jsx28(Text25, { bold: true, children: "Configuration" }),
10730
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
10731
+ /* @__PURE__ */ jsx28(Text25, { color: PALETTE.accent, children: "Loading..." })
10099
10732
  ] });
10100
10733
  }
10101
10734
  return /* @__PURE__ */ jsxs24(Box23, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
10102
- /* @__PURE__ */ jsx27(Text25, { bold: true, children: "Configuration" }),
10103
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
10104
- /* @__PURE__ */ jsx27(Box23, { flexDirection: "column", children: FIELD_ORDER.map((field) => {
10735
+ /* @__PURE__ */ jsx28(Text25, { bold: true, children: "Configuration" }),
10736
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
10737
+ /* @__PURE__ */ jsx28(Box23, { flexDirection: "column", children: FIELD_ORDER.map((field) => {
10105
10738
  const isActive = activeField === field;
10106
10739
  const value = fieldValue(field);
10107
10740
  const display = field === "cmaToken" ? "\u2022".repeat(value.length) : value;
10108
10741
  return /* @__PURE__ */ jsxs24(Box23, { gap: 1, children: [
10109
- /* @__PURE__ */ jsx27(Text25, { color: isActive ? PALETTE.accent : void 0, children: isActive ? "\u276F" : " " }),
10742
+ /* @__PURE__ */ jsx28(Text25, { color: isActive ? PALETTE.accent : void 0, children: isActive ? "\u276F" : " " }),
10110
10743
  /* @__PURE__ */ jsxs24(Text25, { bold: isActive, children: [
10111
10744
  FIELD_LABELS[field],
10112
10745
  ":"
10113
10746
  ] }),
10114
- isActive && editing ? /* @__PURE__ */ jsx27(
10747
+ isActive && editing ? /* @__PURE__ */ jsx28(
10115
10748
  TextInput4,
10116
10749
  {
10117
10750
  value,
@@ -10119,19 +10752,19 @@ function ConfigurationScreen({ onDone }) {
10119
10752
  onSubmit: () => setEditing(false),
10120
10753
  mask: field === "cmaToken" ? "\u2022" : void 0
10121
10754
  }
10122
- ) : /* @__PURE__ */ jsx27(Text25, { children: display || /* @__PURE__ */ jsx27(Text25, { color: PALETTE.muted, children: "(empty)" }) })
10755
+ ) : /* @__PURE__ */ jsx28(Text25, { children: display || /* @__PURE__ */ jsx28(Text25, { color: PALETTE.muted, children: "(empty)" }) })
10123
10756
  ] }, field);
10124
10757
  }) }),
10125
10758
  notice && /* @__PURE__ */ jsxs24(Fragment6, { children: [
10126
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
10759
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
10127
10760
  /* @__PURE__ */ jsxs24(Text25, { color: notice.kind === "success" ? PALETTE.success : PALETTE.error, children: [
10128
10761
  notice.kind === "success" ? "\u2713" : "\u2717",
10129
10762
  " ",
10130
10763
  notice.text
10131
10764
  ] })
10132
10765
  ] }),
10133
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
10134
- /* @__PURE__ */ jsx27(
10766
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
10767
+ /* @__PURE__ */ jsx28(
10135
10768
  ControlHints,
10136
10769
  {
10137
10770
  hints: editing ? [
@@ -10152,7 +10785,7 @@ function ConfigurationScreen({ onDone }) {
10152
10785
  }
10153
10786
 
10154
10787
  // packages/experience-design-system-cli/src/tui/settings/opt-in-analytics/screen.tsx
10155
- import { useEffect as useEffect11, useState as useState17 } from "react";
10788
+ import { useEffect as useEffect12, useState as useState18 } from "react";
10156
10789
  import { Box as Box24, Text as Text26, useInput as useInput12 } from "ink";
10157
10790
 
10158
10791
  // packages/experience-design-system-cli/src/tui/settings/opt-in-analytics/analytics-store.ts
@@ -10171,11 +10804,11 @@ async function writeAnalyticsSetting(setting) {
10171
10804
  }
10172
10805
 
10173
10806
  // packages/experience-design-system-cli/src/tui/settings/opt-in-analytics/screen.tsx
10174
- import { Fragment as Fragment7, jsx as jsx28, jsxs as jsxs25 } from "react/jsx-runtime";
10807
+ import { Fragment as Fragment7, jsx as jsx29, jsxs as jsxs25 } from "react/jsx-runtime";
10175
10808
  function OptInAnalyticsScreen({ onDone }) {
10176
- const [loading, setLoading] = useState17(true);
10177
- const [enabled, setEnabled] = useState17(true);
10178
- useEffect11(() => {
10809
+ const [loading, setLoading] = useState18(true);
10810
+ const [enabled, setEnabled] = useState18(true);
10811
+ useEffect12(() => {
10179
10812
  readAnalyticsSetting().then((setting) => {
10180
10813
  setEnabled(setting.enabled);
10181
10814
  setLoading(false);
@@ -10203,20 +10836,20 @@ function OptInAnalyticsScreen({ onDone }) {
10203
10836
  }
10204
10837
  });
10205
10838
  return /* @__PURE__ */ jsxs25(Box24, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
10206
- /* @__PURE__ */ jsx28(Text26, { bold: true, children: "Settings \u203A Opt-in Analytics" }),
10207
- /* @__PURE__ */ jsx28(Text26, { children: " " }),
10208
- loading ? /* @__PURE__ */ jsx28(Text26, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs25(Fragment7, { children: [
10839
+ /* @__PURE__ */ jsx29(Text26, { bold: true, children: "Settings \u203A Opt-in Analytics" }),
10840
+ /* @__PURE__ */ jsx29(Text26, { children: " " }),
10841
+ loading ? /* @__PURE__ */ jsx29(Text26, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs25(Fragment7, { children: [
10209
10842
  /* @__PURE__ */ jsxs25(Text26, { children: [
10210
10843
  "Share anonymous usage data:",
10211
10844
  " ",
10212
- /* @__PURE__ */ jsx28(Text26, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
10845
+ /* @__PURE__ */ jsx29(Text26, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
10213
10846
  ] }),
10214
- /* @__PURE__ */ jsx28(Text26, { children: " " }),
10215
- /* @__PURE__ */ jsx28(Text26, { color: PALETTE.muted, children: "Shares which CLI commands are used and where imports succeed or fail." }),
10216
- /* @__PURE__ */ jsx28(Text26, { color: PALETTE.muted, children: "Never includes source code, file paths, credentials, or authored content." })
10847
+ /* @__PURE__ */ jsx29(Text26, { children: " " }),
10848
+ /* @__PURE__ */ jsx29(Text26, { color: PALETTE.muted, children: "Shares which CLI commands are used and where imports succeed or fail." }),
10849
+ /* @__PURE__ */ jsx29(Text26, { color: PALETTE.muted, children: "Never includes source code, file paths, credentials, or authored content." })
10217
10850
  ] }),
10218
- /* @__PURE__ */ jsx28(Text26, { children: " " }),
10219
- /* @__PURE__ */ jsx28(
10851
+ /* @__PURE__ */ jsx29(Text26, { children: " " }),
10852
+ /* @__PURE__ */ jsx29(
10220
10853
  ControlHints,
10221
10854
  {
10222
10855
  hints: [
@@ -10229,13 +10862,13 @@ function OptInAnalyticsScreen({ onDone }) {
10229
10862
  }
10230
10863
 
10231
10864
  // packages/experience-design-system-cli/src/tui/upgrade/PageContainer.tsx
10232
- import { useEffect as useEffect12, useState as useState18 } from "react";
10865
+ import { useEffect as useEffect13, useState as useState19 } from "react";
10233
10866
  import { Box as Box25, Text as Text27, useInput as useInput13 } from "ink";
10234
- import { jsx as jsx29, jsxs as jsxs26 } from "react/jsx-runtime";
10867
+ import { jsx as jsx30, jsxs as jsxs26 } from "react/jsx-runtime";
10235
10868
  var UPGRADE_COMMANDS = ["git pull", "pnpm install", "pnpm build"];
10236
10869
  function UpgradeScreen({ onDone }) {
10237
- const [upgradeCheck, setUpgradeCheck] = useState18();
10238
- useEffect12(() => {
10870
+ const [upgradeCheck, setUpgradeCheck] = useState19();
10871
+ useEffect13(() => {
10239
10872
  startDebugRun({
10240
10873
  flow: "upgrade",
10241
10874
  step: "01-upgrade",
@@ -10256,10 +10889,10 @@ function UpgradeScreen({ onDone }) {
10256
10889
  }
10257
10890
  });
10258
10891
  return /* @__PURE__ */ jsxs26(Box25, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
10259
- /* @__PURE__ */ jsx29(Text27, { bold: true, children: "Upgrade" }),
10260
- /* @__PURE__ */ jsx29(Text27, { children: " " }),
10892
+ /* @__PURE__ */ jsx30(Text27, { bold: true, children: "Upgrade" }),
10893
+ /* @__PURE__ */ jsx30(Text27, { children: " " }),
10261
10894
  renderBody(upgradeCheck),
10262
- /* @__PURE__ */ jsx29(Text27, { children: " " }),
10895
+ /* @__PURE__ */ jsx30(Text27, { children: " " }),
10263
10896
  /* @__PURE__ */ jsxs26(Text27, { bold: true, color: PALETTE.accent, children: [
10264
10897
  FOCUS_MARKER,
10265
10898
  " Go Back"
@@ -10268,10 +10901,10 @@ function UpgradeScreen({ onDone }) {
10268
10901
  }
10269
10902
  function renderBody(upgradeCheck) {
10270
10903
  if (!upgradeCheck) {
10271
- return /* @__PURE__ */ jsx29(Text27, { color: PALETTE.muted, children: "Checking for updates\u2026" });
10904
+ return /* @__PURE__ */ jsx30(Text27, { color: PALETTE.muted, children: "Checking for updates\u2026" });
10272
10905
  }
10273
10906
  if (upgradeCheck.status === "error") {
10274
- return /* @__PURE__ */ jsx29(Text27, { color: PALETTE.warning, children: "Couldn't check for updates \u2014 check your network connection and try again." });
10907
+ return /* @__PURE__ */ jsx30(Text27, { color: PALETTE.warning, children: "Couldn't check for updates \u2014 check your network connection and try again." });
10275
10908
  }
10276
10909
  if (upgradeCheck.status === "up-to-date") {
10277
10910
  return /* @__PURE__ */ jsxs26(Text27, { color: PALETTE.success, children: [
@@ -10294,19 +10927,19 @@ function renderBody(upgradeCheck) {
10294
10927
  ] }),
10295
10928
  "). Exit this program, cd into the root of your local clone of contentful/experience-design-system-sdk-public, then run:"
10296
10929
  ] }),
10297
- /* @__PURE__ */ jsx29(Text27, { children: " " }),
10298
- /* @__PURE__ */ jsx29(Box25, { flexDirection: "column", borderStyle: "round", borderColor: PALETTE.border, paddingX: 1, children: UPGRADE_COMMANDS.map((cmd) => /* @__PURE__ */ jsx29(Text27, { bold: true, children: cmd }, cmd)) })
10930
+ /* @__PURE__ */ jsx30(Text27, { children: " " }),
10931
+ /* @__PURE__ */ jsx30(Box25, { flexDirection: "column", borderStyle: "round", borderColor: PALETTE.border, paddingX: 1, children: UPGRADE_COMMANDS.map((cmd) => /* @__PURE__ */ jsx30(Text27, { bold: true, children: cmd }, cmd)) })
10299
10932
  ] });
10300
10933
  }
10301
10934
 
10302
10935
  // packages/experience-design-system-cli/src/tui/settings/debug-mode/screen.tsx
10303
- import { useEffect as useEffect13, useState as useState19 } from "react";
10936
+ import { useEffect as useEffect14, useState as useState20 } from "react";
10304
10937
  import { Box as Box26, Text as Text28, useInput as useInput14 } from "ink";
10305
- import { jsx as jsx30, jsxs as jsxs27 } from "react/jsx-runtime";
10938
+ import { jsx as jsx31, jsxs as jsxs27 } from "react/jsx-runtime";
10306
10939
  function DebugModeScreen({ onDone }) {
10307
- const [loading, setLoading] = useState19(true);
10308
- const [enabled, setEnabled] = useState19(true);
10309
- useEffect13(() => {
10940
+ const [loading, setLoading] = useState20(true);
10941
+ const [enabled, setEnabled] = useState20(true);
10942
+ useEffect14(() => {
10310
10943
  readDebugModeSetting().then((setting) => {
10311
10944
  setEnabled(setting.enabled);
10312
10945
  setLoading(false);
@@ -10334,15 +10967,15 @@ function DebugModeScreen({ onDone }) {
10334
10967
  }
10335
10968
  });
10336
10969
  return /* @__PURE__ */ jsxs27(Box26, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
10337
- /* @__PURE__ */ jsx30(Text28, { bold: true, children: "Settings \u203A Debug Mode" }),
10338
- /* @__PURE__ */ jsx30(Text28, { children: " " }),
10339
- loading ? /* @__PURE__ */ jsx30(Text28, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs27(Text28, { children: [
10970
+ /* @__PURE__ */ jsx31(Text28, { bold: true, children: "Settings \u203A Debug Mode" }),
10971
+ /* @__PURE__ */ jsx31(Text28, { children: " " }),
10972
+ loading ? /* @__PURE__ */ jsx31(Text28, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs27(Text28, { children: [
10340
10973
  "Debug logging:",
10341
10974
  " ",
10342
- /* @__PURE__ */ jsx30(Text28, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
10975
+ /* @__PURE__ */ jsx31(Text28, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
10343
10976
  ] }),
10344
- /* @__PURE__ */ jsx30(Text28, { children: " " }),
10345
- /* @__PURE__ */ jsx30(
10977
+ /* @__PURE__ */ jsx31(Text28, { children: " " }),
10978
+ /* @__PURE__ */ jsx31(
10346
10979
  ControlHints,
10347
10980
  {
10348
10981
  hints: [
@@ -10355,18 +10988,18 @@ function DebugModeScreen({ onDone }) {
10355
10988
  }
10356
10989
 
10357
10990
  // packages/experience-design-system-cli/app.tsx
10358
- import { Fragment as Fragment8, jsx as jsx31 } from "react/jsx-runtime";
10991
+ import { Fragment as Fragment8, jsx as jsx32 } from "react/jsx-runtime";
10359
10992
  function App({ importOptions, onLaunchImport, importExitCode }) {
10360
10993
  const returnedFromImport = importExitCode !== void 0;
10361
- const [screen, setScreen] = useState20(returnedFromImport ? "import" : "start");
10362
- const [showImportResult, setShowImportResult] = useState20(returnedFromImport);
10363
- const [projectPath, setProjectPath] = useState20();
10364
- const [tokensPath, setTokensPath] = useState20();
10365
- const [scannedFiles, setScannedFiles] = useState20();
10366
- const [pendingLaunch, setPendingLaunch] = useState20();
10367
- const [extractionRun, setExtractionRun] = useState20();
10994
+ const [screen, setScreen] = useState21(returnedFromImport ? "import" : "start");
10995
+ const [showImportResult, setShowImportResult] = useState21(returnedFromImport);
10996
+ const [projectPath, setProjectPath] = useState21();
10997
+ const [tokensPath, setTokensPath] = useState21();
10998
+ const [scannedFiles, setScannedFiles] = useState21();
10999
+ const [pendingLaunch, setPendingLaunch] = useState21();
11000
+ const [extractionRun, setExtractionRun] = useState21();
10368
11001
  const extraction = useExtraction(extractionRun?.input);
10369
- const [scopeRun, setScopeRun] = useState20();
11002
+ const [scopeRun, setScopeRun] = useState21();
10370
11003
  const scopeFlow = useScopeGateFlow(
10371
11004
  scopeRun && {
10372
11005
  sessionId: scopeRun.extraction.sessionId,
@@ -10381,8 +11014,10 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10381
11014
  }
10382
11015
  }
10383
11016
  );
10384
- const [importDefaults, setImportDefaults] = useState20();
10385
- useEffect14(() => {
11017
+ const [generationInput, setGenerationInput] = useState21();
11018
+ const generation = useGeneration(generationInput);
11019
+ const [importDefaults, setImportDefaults] = useState21();
11020
+ useEffect15(() => {
10386
11021
  if (screen !== "import") {
10387
11022
  setImportDefaults(void 0);
10388
11023
  return;
@@ -10400,7 +11035,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10400
11035
  const launch = { projectPath: projectPath2, tokens, filePaths, ...importOptions };
10401
11036
  const state = await inspectTokens({
10402
11037
  rawTokensPath: tokens,
10403
- outDir: join13(resolveUserPath(projectPath2), ".contentful"),
11038
+ outDir: join14(resolveUserPath(projectPath2), ".contentful"),
10404
11039
  cache: importOptions.cache
10405
11040
  });
10406
11041
  if (state.kind === "cached") {
@@ -10418,8 +11053,11 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10418
11053
  void startExtraction(pending.launch, tokenStrategy, pending.credentials);
10419
11054
  };
10420
11055
  const startExtraction = async (launch, tokenStrategy, credentials) => {
10421
- const { agent, agentModel } = resolveAgentChoice(launch.agent, await readSettings2());
11056
+ const settings = await readSettings2();
11057
+ const { agent, agentModel } = resolveAgentChoice(launch.agent, settings);
11058
+ const generatePromptPath = typeof settings.generatePromptPath === "string" ? settings.generatePromptPath : void 0;
10422
11059
  setExtractionRun({
11060
+ ...generatePromptPath ? { generatePromptPath } : {},
10423
11061
  // the wizard gets the same agent, so its later steps use what the stage used
10424
11062
  launch: { ...launch, agent: agentModel ? `${agent}:${agentModel}` : agent },
10425
11063
  credentialsSkipped: credentials.skipped,
@@ -10436,25 +11074,44 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10436
11074
  }
10437
11075
  });
10438
11076
  };
10439
- useEffect14(() => {
11077
+ useEffect15(() => {
10440
11078
  if (!extractionRun || extraction?.status !== "done" || !extraction.result.ok) return;
10441
11079
  setExtractionRun(void 0);
10442
11080
  setScopeRun({ ...extractionRun, extraction: extraction.result.extraction });
10443
11081
  }, [extraction, extractionRun]);
10444
- useEffect14(() => {
10445
- if (!scopeRun || scopeFlow?.status !== "confirmed") return;
11082
+ useEffect15(() => {
11083
+ if (!scopeRun || scopeFlow?.status !== "confirmed" || generationInput) return;
11084
+ const { extraction: produced, input, generatePromptPath } = scopeRun;
11085
+ setGenerationInput({
11086
+ sessionId: produced.sessionId,
11087
+ decisions: scopeFlow.decisions,
11088
+ cachedNames: scopeFlow.cachedNames,
11089
+ tokensPath: produced.tokensPath,
11090
+ tokenSessionId: produced.tokenSessionId,
11091
+ existingEntitiesPath: produced.existingEntitiesPath,
11092
+ agent: input.agent,
11093
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
11094
+ promptOverrides: input.promptOverrides,
11095
+ noCache: input.noCache,
11096
+ hasTokens: produced.tokensPath !== "",
11097
+ ...generatePromptPath ? { generatePromptPath } : {}
11098
+ });
11099
+ }, [scopeFlow, scopeRun, generationInput]);
11100
+ useEffect15(() => {
11101
+ if (!scopeRun || generation?.status !== "done" || !generation.result.ok) return;
10446
11102
  const { launch, credentialsSkipped, tokenStrategy, extraction: produced } = scopeRun;
10447
11103
  setScopeRun(void 0);
11104
+ setGenerationInput(void 0);
10448
11105
  onLaunchImport?.({
10449
11106
  ...launch,
10450
11107
  handoff: {
10451
11108
  credentialsSkipped,
10452
11109
  tokens: { strategy: tokenStrategy },
10453
11110
  extraction: produced,
10454
- scope: scopeFlow.scope
11111
+ generation: generation.result.generation
10455
11112
  }
10456
11113
  });
10457
- }, [scopeFlow, scopeRun]);
11114
+ }, [generation, scopeRun]);
10458
11115
  const goToStart = () => setScreen("start");
10459
11116
  const goToSettings = () => setScreen("settings");
10460
11117
  const resetImport = () => {
@@ -10464,6 +11121,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10464
11121
  setPendingLaunch(void 0);
10465
11122
  setExtractionRun(void 0);
10466
11123
  setScopeRun(void 0);
11124
+ setGenerationInput(void 0);
10467
11125
  };
10468
11126
  const finishImportResult = () => {
10469
11127
  setShowImportResult(false);
@@ -10476,13 +11134,13 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10476
11134
  };
10477
11135
  switch (screen) {
10478
11136
  case "import":
10479
- if (showImportResult) return /* @__PURE__ */ jsx31(ImportScreen, { exitCode: importExitCode, onDone: finishImportResult });
10480
- if (importDefaults === void 0) return /* @__PURE__ */ jsx31(Fragment8, {});
11137
+ if (showImportResult) return /* @__PURE__ */ jsx32(ImportScreen, { exitCode: importExitCode, onDone: finishImportResult });
11138
+ if (importDefaults === void 0) return /* @__PURE__ */ jsx32(Fragment8, {});
10481
11139
  if (projectPath === void 0) {
10482
- return /* @__PURE__ */ jsx31(WelcomeScreen, { onContinue: setProjectPath, onQuit: leaveImport, initialPath: importDefaults.componentDir });
11140
+ return /* @__PURE__ */ jsx32(WelcomeScreen, { onContinue: setProjectPath, onQuit: leaveImport, initialPath: importDefaults.componentDir });
10483
11141
  }
10484
11142
  if (tokensPath === void 0) {
10485
- return /* @__PURE__ */ jsx31(
11143
+ return /* @__PURE__ */ jsx32(
10486
11144
  TokenInputScreen,
10487
11145
  {
10488
11146
  initialPath: importDefaults.tokenFile,
@@ -10492,7 +11150,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10492
11150
  );
10493
11151
  }
10494
11152
  if (scannedFiles === void 0) {
10495
- return /* @__PURE__ */ jsx31(
11153
+ return /* @__PURE__ */ jsx32(
10496
11154
  PathValidationScreen,
10497
11155
  {
10498
11156
  projectPath,
@@ -10504,10 +11162,10 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10504
11162
  }
10505
11163
  if (extractionRun) {
10506
11164
  if (extraction?.status === "done" && !extraction.result.ok) {
10507
- return /* @__PURE__ */ jsx31(ErrorStep, { stepName: extraction.result.step, message: extraction.result.message, onExit: leaveImport });
11165
+ return /* @__PURE__ */ jsx32(ErrorStep, { stepName: extraction.result.step, message: extraction.result.message, onExit: leaveImport });
10508
11166
  }
10509
11167
  if (extraction?.status === "running") {
10510
- return /* @__PURE__ */ jsx31(
11168
+ return /* @__PURE__ */ jsx32(
10511
11169
  ExtractionScreen,
10512
11170
  {
10513
11171
  progress: extraction.progress,
@@ -10516,14 +11174,14 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10516
11174
  }
10517
11175
  );
10518
11176
  }
10519
- return /* @__PURE__ */ jsx31(Fragment8, {});
11177
+ return /* @__PURE__ */ jsx32(Fragment8, {});
10520
11178
  }
10521
11179
  if (scopeRun && scopeFlow) {
10522
11180
  if (scopeFlow.status === "failed") {
10523
- return /* @__PURE__ */ jsx31(ErrorStep, { stepName: "scope gate", message: scopeFlow.message, onExit: leaveImport });
11181
+ return /* @__PURE__ */ jsx32(ErrorStep, { stepName: "scope gate", message: scopeFlow.message, onExit: leaveImport });
10524
11182
  }
10525
11183
  if (scopeFlow.status === "deciding") {
10526
- return /* @__PURE__ */ jsx31(
11184
+ return /* @__PURE__ */ jsx32(
10527
11185
  ScopeGateScreen,
10528
11186
  {
10529
11187
  components: scopeFlow.load.components,
@@ -10532,19 +11190,31 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10532
11190
  }
10533
11191
  );
10534
11192
  }
10535
- const numbers = stepNumbers({ hasRawTokens: scopeRun.input.rawTokensPath !== "" });
10536
- return /* @__PURE__ */ jsx31(
10537
- RunningStep,
10538
- {
10539
- stepNumber: numbers.stepNumber + 1,
10540
- totalSteps: numbers.totalSteps,
10541
- title: "Preparing",
10542
- description: "Checking which components are already generated..."
10543
- }
10544
- );
11193
+ if (generation?.status === "done" && !generation.result.ok) {
11194
+ return /* @__PURE__ */ jsx32(ErrorStep, { stepName: generation.result.step, message: generation.result.message, onExit: leaveImport });
11195
+ }
11196
+ if (generation?.status === "running") {
11197
+ const hasRawTokens = scopeRun.input.rawTokensPath !== "";
11198
+ const counted = stepNumbers({
11199
+ hasRawTokens,
11200
+ mapTokensEligible: generation.progress.mapTokensEligible
11201
+ });
11202
+ return /* @__PURE__ */ jsx32(
11203
+ GenerationScreen,
11204
+ {
11205
+ progress: generation.progress,
11206
+ agent: scopeRun.input.agent,
11207
+ acceptedCount: scopeFlow.decisions.accepted.length,
11208
+ hasTokens: scopeRun.extraction.tokensPath !== "",
11209
+ stepNumber: hasRawTokens ? 4 : 3,
11210
+ totalSteps: counted.totalSteps
11211
+ }
11212
+ );
11213
+ }
11214
+ return /* @__PURE__ */ jsx32(Fragment8, {});
10545
11215
  }
10546
11216
  if (pendingLaunch?.cached) {
10547
- return /* @__PURE__ */ jsx31(
11217
+ return /* @__PURE__ */ jsx32(
10548
11218
  TokenReuseScreen,
10549
11219
  {
10550
11220
  tokensPath: pendingLaunch.cached.tokensPath,
@@ -10555,7 +11225,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10555
11225
  }
10556
11226
  );
10557
11227
  }
10558
- return /* @__PURE__ */ jsx31(
11228
+ return /* @__PURE__ */ jsx32(
10559
11229
  CredentialsScreen,
10560
11230
  {
10561
11231
  initial: importDefaults.credentials,
@@ -10564,26 +11234,26 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
10564
11234
  }
10565
11235
  );
10566
11236
  case "help":
10567
- return /* @__PURE__ */ jsx31(HelpScreen, { onDone: goToStart });
11237
+ return /* @__PURE__ */ jsx32(HelpScreen, { onDone: goToStart });
10568
11238
  case "upgrade":
10569
- return /* @__PURE__ */ jsx31(UpgradeScreen, { onDone: goToStart });
11239
+ return /* @__PURE__ */ jsx32(UpgradeScreen, { onDone: goToStart });
10570
11240
  case "settings":
10571
- return /* @__PURE__ */ jsx31(SettingsScreen, { onNavigate: setScreen, onBack: goToStart });
11241
+ return /* @__PURE__ */ jsx32(SettingsScreen, { onNavigate: setScreen, onBack: goToStart });
10572
11242
  case "settings-configuration":
10573
- return /* @__PURE__ */ jsx31(ConfigurationScreen, { onDone: goToSettings });
11243
+ return /* @__PURE__ */ jsx32(ConfigurationScreen, { onDone: goToSettings });
10574
11244
  case "settings-opt-in-analytics":
10575
- return /* @__PURE__ */ jsx31(OptInAnalyticsScreen, { onDone: goToSettings });
11245
+ return /* @__PURE__ */ jsx32(OptInAnalyticsScreen, { onDone: goToSettings });
10576
11246
  case "settings-debug-mode":
10577
- return /* @__PURE__ */ jsx31(DebugModeScreen, { onDone: goToSettings });
11247
+ return /* @__PURE__ */ jsx32(DebugModeScreen, { onDone: goToSettings });
10578
11248
  case "start":
10579
- return /* @__PURE__ */ jsx31(HomeScreen, { onNavigate: setScreen });
11249
+ return /* @__PURE__ */ jsx32(HomeScreen, { onNavigate: setScreen });
10580
11250
  }
10581
11251
  }
10582
11252
  var CLEAR_SCREEN = "\x1B[2J\x1B[H";
10583
11253
  async function renderUntilImportRequestedOrExit(renderApp, importOptions, importExitCode) {
10584
11254
  let requestedImport;
10585
11255
  const instance = renderApp(
10586
- /* @__PURE__ */ jsx31(
11256
+ /* @__PURE__ */ jsx32(
10587
11257
  App,
10588
11258
  {
10589
11259
  importOptions,