@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/index.js CHANGED
@@ -736,6 +736,9 @@ var init_read = __esm({
736
736
  });
737
737
 
738
738
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/sessions/write.js
739
+ function updateSessionTimestamp(db, sessionId, timestamp) {
740
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(timestamp, sessionId);
741
+ }
739
742
  var init_write = __esm({
740
743
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/sessions/write.js"() {
741
744
  "use strict";
@@ -774,6 +777,16 @@ var init_session_resolver = __esm({
774
777
  });
775
778
 
776
779
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/helpers/tokens/build-dtcg-groups.js
780
+ function buildDtcgGroups(groupRows, tokenRows) {
781
+ return groupRows.map((r) => {
782
+ const prefix = `${r.path}.`;
783
+ const tokenIds = tokenRows.filter((t) => t.path.startsWith(prefix) && !t.path.slice(prefix.length).includes(".")).map((t) => t.path);
784
+ const g = { path: r.path, tokenIds };
785
+ if (r.description !== null)
786
+ g.$description = r.description;
787
+ return g;
788
+ });
789
+ }
777
790
  var init_build_dtcg_groups = __esm({
778
791
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/helpers/tokens/build-dtcg-groups.js"() {
779
792
  "use strict";
@@ -781,6 +794,18 @@ var init_build_dtcg_groups = __esm({
781
794
  });
782
795
 
783
796
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/helpers/tokens/build-dtcg-tokens.js
797
+ function buildDtcgTokens(tokenRows) {
798
+ return tokenRows.map((r) => {
799
+ const t = {
800
+ path: r.path,
801
+ $type: r.type,
802
+ $value: JSON.parse(r.value)
803
+ };
804
+ if (r.description !== null)
805
+ t.$description = r.description;
806
+ return t;
807
+ });
808
+ }
784
809
  var init_build_dtcg_tokens = __esm({
785
810
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/helpers/tokens/build-dtcg-tokens.js"() {
786
811
  "use strict";
@@ -788,6 +813,26 @@ var init_build_dtcg_tokens = __esm({
788
813
  });
789
814
 
790
815
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/tokens/read.js
816
+ function getDtcgTokensForSession(db, sessionId) {
817
+ const groupRows = db.prepare("SELECT path, description FROM raw_token_groups WHERE session_id = ? ORDER BY path").all(sessionId).map((row) => ({
818
+ path: String(row.path),
819
+ description: row.description === null ? null : String(row.description)
820
+ }));
821
+ const tokenRows = db.prepare("SELECT path, type, value, description FROM raw_tokens WHERE session_id = ? ORDER BY path").all(sessionId).map((row) => ({
822
+ path: String(row.path),
823
+ type: String(row.type),
824
+ value: String(row.value),
825
+ description: row.description === null ? null : String(row.description)
826
+ }));
827
+ return {
828
+ groups: buildDtcgGroups(groupRows, tokenRows),
829
+ tokens: buildDtcgTokens(tokenRows)
830
+ };
831
+ }
832
+ function getRawTokenNamePaths(db, sessionId) {
833
+ const rows = db.prepare("SELECT raw_name, path FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId);
834
+ return Object.fromEntries(rows.map((row) => [String(row.raw_name), String(row.path)]));
835
+ }
791
836
  var init_read3 = __esm({
792
837
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/tokens/read.js"() {
793
838
  "use strict";
@@ -828,6 +873,22 @@ var init_hash_token_content = __esm({
828
873
  });
829
874
 
830
875
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/tokens/write.js
876
+ function deleteRawTokensForSession(db, sessionId) {
877
+ db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(sessionId);
878
+ db.prepare("DELETE FROM raw_tokens WHERE session_id = ?").run(sessionId);
879
+ }
880
+ function createRawTokenGroups(db, sessionId, groups) {
881
+ const insertGroup = db.prepare(`INSERT INTO raw_token_groups (session_id, path, description) VALUES (?, ?, ?)`);
882
+ for (const group of groups) {
883
+ insertGroup.run(sessionId, group.path, group.$description ?? null);
884
+ }
885
+ }
886
+ function createRawTokens(db, sessionId, tokens) {
887
+ const insertToken = db.prepare(`INSERT INTO raw_tokens (session_id, path, type, value, description) VALUES (?, ?, ?, ?, ?)`);
888
+ for (const token of tokens) {
889
+ insertToken.run(sessionId, token.path, token.$type, JSON.stringify(token.$value), token.$description ?? null);
890
+ }
891
+ }
831
892
  var init_write3 = __esm({
832
893
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/tokens/write.js"() {
833
894
  "use strict";
@@ -835,6 +896,17 @@ var init_write3 = __esm({
835
896
  });
836
897
 
837
898
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/shared/with-transaction.js
899
+ function withTransaction(db, fn) {
900
+ db.exec("BEGIN");
901
+ try {
902
+ const result = fn();
903
+ db.exec("COMMIT");
904
+ return result;
905
+ } catch (e) {
906
+ db.exec("ROLLBACK");
907
+ throw e;
908
+ }
909
+ }
838
910
  var init_with_transaction = __esm({
839
911
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/repositories/shared/with-transaction.js"() {
840
912
  "use strict";
@@ -842,6 +914,15 @@ var init_with_transaction = __esm({
842
914
  });
843
915
 
844
916
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/services/tokens/store-dtcg-tokens.js
917
+ function storeDtcgTokens(db, sessionId, groups, tokens) {
918
+ const now = (/* @__PURE__ */ new Date()).toISOString();
919
+ withTransaction(db, () => {
920
+ deleteRawTokensForSession(db, sessionId);
921
+ createRawTokenGroups(db, sessionId, groups);
922
+ createRawTokens(db, sessionId, tokens);
923
+ updateSessionTimestamp(db, sessionId, now);
924
+ });
925
+ }
845
926
  var init_store_dtcg_tokens = __esm({
846
927
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/session/services/tokens/store-dtcg-tokens.js"() {
847
928
  "use strict";
@@ -1645,7 +1726,7 @@ async function runAgent(options) {
1645
1726
  promptLen: prompt.length,
1646
1727
  promptHead: prompt.slice(0, 500)
1647
1728
  });
1648
- return new Promise((resolve10) => {
1729
+ return new Promise((resolve12) => {
1649
1730
  const bedrockEnv = bedrock ? BEDROCK_ENV_BY_AGENT[agent] : void 0;
1650
1731
  const child = spawn3(binary, args, {
1651
1732
  stdio: ["pipe", "pipe", "pipe"],
@@ -1694,7 +1775,7 @@ async function runAgent(options) {
1694
1775
  stderrLen: stderr.length,
1695
1776
  stderrTail: stderr.slice(-1e3)
1696
1777
  });
1697
- resolve10(result);
1778
+ resolve12(result);
1698
1779
  });
1699
1780
  });
1700
1781
  }
@@ -1716,7 +1797,7 @@ async function checkAgentAuth(agent) {
1716
1797
  return "not-found";
1717
1798
  if (agent !== "claude")
1718
1799
  return "ok";
1719
- return new Promise((resolve10) => {
1800
+ return new Promise((resolve12) => {
1720
1801
  const child = spawn4(binary, ["auth", "status", "--json"], { stdio: ["ignore", "pipe", "pipe"] });
1721
1802
  let stdout = "";
1722
1803
  let done = false;
@@ -1725,7 +1806,7 @@ async function checkAgentAuth(agent) {
1725
1806
  return;
1726
1807
  done = true;
1727
1808
  child.kill("SIGTERM");
1728
- resolve10("unauthenticated");
1809
+ resolve12("unauthenticated");
1729
1810
  }, 5e3);
1730
1811
  child.stdout?.on("data", (chunk) => {
1731
1812
  stdout += chunk.toString();
@@ -1736,14 +1817,14 @@ async function checkAgentAuth(agent) {
1736
1817
  done = true;
1737
1818
  clearTimeout(timer);
1738
1819
  if (code !== 0) {
1739
- resolve10("unauthenticated");
1820
+ resolve12("unauthenticated");
1740
1821
  return;
1741
1822
  }
1742
1823
  try {
1743
1824
  const status = JSON.parse(stdout);
1744
- resolve10(status.loggedIn ? "ok" : "unauthenticated");
1825
+ resolve12(status.loggedIn ? "ok" : "unauthenticated");
1745
1826
  } catch {
1746
- resolve10("unauthenticated");
1827
+ resolve12("unauthenticated");
1747
1828
  }
1748
1829
  });
1749
1830
  });
@@ -1753,9 +1834,9 @@ async function binaryIsOnPath(binary) {
1753
1834
  const fs = await import("node:fs/promises");
1754
1835
  return fs.access(binary).then(() => true, () => false);
1755
1836
  }
1756
- return new Promise((resolve10) => {
1837
+ return new Promise((resolve12) => {
1757
1838
  const child = spawn4(process.platform === "win32" ? "where" : "which", [binary], { stdio: "ignore" });
1758
- child.on("close", (code) => resolve10(code === 0));
1839
+ child.on("close", (code) => resolve12(code === 0));
1759
1840
  });
1760
1841
  }
1761
1842
  var init_check_agent_auth = __esm({
@@ -2229,6 +2310,23 @@ var init_flatten = __esm({
2229
2310
  });
2230
2311
 
2231
2312
  // packages/experience-design-system-backend-pipeline/dist/src/steps/shared/dtcg/helpers/validate.js
2313
+ function isDesignTokenType(value) {
2314
+ return typeof value === "string" && TOKEN_TYPE_SET2.has(value);
2315
+ }
2316
+ function validateDTCG(obj) {
2317
+ const errors = [];
2318
+ const tokens = flattenDTCG(obj, "");
2319
+ for (const token of tokens) {
2320
+ if (!isDesignTokenType(token.$type)) {
2321
+ errors.push({
2322
+ path: token.path,
2323
+ message: `Unknown $type "${token.$type}". Must be one of: ${DESIGN_TOKEN_TYPES.join(", ")}.`,
2324
+ actual: token.$type
2325
+ });
2326
+ }
2327
+ }
2328
+ return { valid: errors.length === 0, errors };
2329
+ }
2232
2330
  var TOKEN_TYPE_SET2;
2233
2331
  var init_validate2 = __esm({
2234
2332
  "packages/experience-design-system-backend-pipeline/dist/src/steps/shared/dtcg/helpers/validate.js"() {
@@ -3210,6 +3308,91 @@ function parseReviewReasons(raw) {
3210
3308
  return [];
3211
3309
  }
3212
3310
  }
3311
+ function loadCDFComponents(db, sessionId) {
3312
+ const components = db.prepare(`SELECT component_id, name, description FROM raw_components
3313
+ WHERE session_id = ? AND status = 'generated' ORDER BY rowid`).all(sessionId);
3314
+ if (components.length === 0)
3315
+ return [];
3316
+ const props = db.prepare(`SELECT component_id, name, required, default_value, description,
3317
+ cdf_type, cdf_category, cdf_token_kind, position
3318
+ FROM raw_props
3319
+ WHERE session_id = ? AND cdf_type IS NOT NULL
3320
+ ORDER BY component_id, position`).all(sessionId);
3321
+ const allowedValues = db.prepare(`SELECT component_id, prop_name, value, position
3322
+ FROM raw_prop_allowed_values WHERE session_id = ? ORDER BY component_id, prop_name, position`).all(sessionId);
3323
+ const slots = db.prepare(`SELECT component_id, name, description, required FROM raw_slots WHERE session_id = ? ORDER BY component_id, position`).all(sessionId);
3324
+ const allowedComponents = db.prepare(`SELECT component_id, slot_name, allowed_component
3325
+ FROM raw_slot_allowed_components WHERE session_id = ? ORDER BY component_id, slot_name, position`).all(sessionId);
3326
+ const tokenPaths = db.prepare(`SELECT component_id, prop_name, position, path
3327
+ FROM raw_prop_token_paths WHERE session_id = ? ORDER BY component_id, prop_name, position`).all(sessionId);
3328
+ const resolvedDefaultPaths = getRawTokenNamePaths(db, sessionId);
3329
+ const tokenTypeByPath = new Map(db.prepare("SELECT path, type FROM raw_tokens WHERE session_id = ?").all(sessionId).map((token) => [token.path, token.type]));
3330
+ const propsByComponent = indexRowsByKey(props, (p) => p.component_id);
3331
+ const allowedValuesByProp = indexRowsByKey(allowedValues, (av) => `${av.component_id}::${av.prop_name}`);
3332
+ const slotsByComponent = indexRowsByKey(slots, (s) => s.component_id);
3333
+ const allowedComponentsBySlot = indexRowsByKey(allowedComponents, (ac) => `${ac.component_id}::${ac.slot_name}`);
3334
+ const tokenPathsByProp = indexRowsByKey(tokenPaths, (t) => `${t.component_id}::${t.prop_name}`);
3335
+ const toTokenPaths = (rows) => rows === void 0 ? void 0 : rows.map((r) => r.path);
3336
+ return components.map(({ component_id, name, description }) => {
3337
+ const compProps = propsByComponent.get(component_id) ?? [];
3338
+ const $properties = {};
3339
+ for (const p of compProps) {
3340
+ if (!p.name.trim())
3341
+ continue;
3342
+ const av = allowedValuesByProp.get(`${component_id}::${p.name}`);
3343
+ const propDef = {
3344
+ $type: p.cdf_type,
3345
+ $category: p.cdf_category
3346
+ };
3347
+ if (p.required)
3348
+ propDef.$required = true;
3349
+ const isTokenProp = p.cdf_type === "token" && p.cdf_category === "design";
3350
+ const defaultReference = p.default_value;
3351
+ const resolvedDefault = isTokenProp && p.cdf_token_kind !== null && defaultReference !== null ? resolvedDefaultPaths[defaultReference] : void 0;
3352
+ const compatibleResolvedDefault = resolvedDefault !== void 0 && tokenTypeByPath.get(resolvedDefault) === p.cdf_token_kind ? resolvedDefault : void 0;
3353
+ if (p.default_value !== null) {
3354
+ if (p.cdf_type === "boolean") {
3355
+ propDef.$default = p.default_value === "true";
3356
+ } else {
3357
+ propDef.$default = compatibleResolvedDefault ?? p.default_value;
3358
+ }
3359
+ }
3360
+ if (p.description !== null)
3361
+ propDef.$description = p.description;
3362
+ if (!isTokenProp && av && av.length > 0)
3363
+ propDef.$values = av.map((v) => v.value);
3364
+ if (p.cdf_token_kind !== null)
3365
+ propDef["$token.kind"] = p.cdf_token_kind;
3366
+ if (isTokenProp) {
3367
+ const allowed = toTokenPaths(tokenPathsByProp.get(`${component_id}::${p.name}`));
3368
+ if (allowed !== void 0 && allowed.length > 0)
3369
+ propDef["$token.allowed"] = allowed;
3370
+ }
3371
+ $properties[p.name] = propDef;
3372
+ }
3373
+ const compSlots = slotsByComponent.get(component_id) ?? [];
3374
+ const $slots = {};
3375
+ for (const s of compSlots) {
3376
+ if (!s.name.trim())
3377
+ continue;
3378
+ const ac = allowedComponentsBySlot.get(`${component_id}::${s.name}`);
3379
+ const slotDef = {};
3380
+ if (s.description !== null)
3381
+ slotDef.$description = s.description;
3382
+ if (s.required)
3383
+ slotDef.$required = true;
3384
+ if (ac && ac.length > 0)
3385
+ slotDef.$allowedComponents = ac.map((v) => v.allowed_component);
3386
+ $slots[s.name] = slotDef;
3387
+ }
3388
+ const entry = { $type: "component", $properties };
3389
+ if (description !== null)
3390
+ entry.$description = description;
3391
+ if (Object.keys($slots).length > 0)
3392
+ entry.$slots = $slots;
3393
+ return { key: name, entry };
3394
+ });
3395
+ }
3213
3396
  function loadScopeComponents(db, sessionId) {
3214
3397
  const rows = db.prepare(`SELECT name, component_id, status, reject_reason, review_reasons, needs_review FROM raw_components
3215
3398
  WHERE session_id = ? AND status IN ('extracted', 'accepted', 'rejected')
@@ -3238,6 +3421,38 @@ function loadScopeComponents(db, sessionId) {
3238
3421
  };
3239
3422
  });
3240
3423
  }
3424
+ function applyScopeDecisions(db, sessionId, decisions) {
3425
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3426
+ const acceptedSet = new Set(decisions.accepted);
3427
+ const accepted = [...acceptedSet];
3428
+ const rejected = [...new Set(decisions.rejected)].filter((n) => !acceptedSet.has(n));
3429
+ if (rejected.length > 0) {
3430
+ const placeholders = rejected.map(() => "?").join(",");
3431
+ db.prepare(`UPDATE raw_components SET status = 'rejected' WHERE session_id = ? AND name IN (${placeholders})`).run(sessionId, ...rejected);
3432
+ }
3433
+ if (accepted.length > 0) {
3434
+ const placeholders = accepted.map(() => "?").join(",");
3435
+ db.prepare(`UPDATE raw_components SET status = 'generated' WHERE session_id = ? AND name IN (${placeholders})`).run(sessionId, ...accepted);
3436
+ }
3437
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId);
3438
+ }
3439
+ function copyTokensFromCache(db, sourceSessionId, targetSessionId) {
3440
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3441
+ db.exec("BEGIN");
3442
+ try {
3443
+ db.prepare("DELETE FROM raw_tokens WHERE session_id = ?").run(targetSessionId);
3444
+ db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(targetSessionId);
3445
+ db.prepare(`INSERT INTO raw_token_groups (session_id, path, description)
3446
+ SELECT ?, path, description FROM raw_token_groups WHERE session_id = ?`).run(targetSessionId, sourceSessionId);
3447
+ db.prepare(`INSERT INTO raw_tokens (session_id, path, type, value, description)
3448
+ SELECT ?, path, type, value, description FROM raw_tokens WHERE session_id = ?`).run(targetSessionId, sourceSessionId);
3449
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, targetSessionId);
3450
+ db.exec("COMMIT");
3451
+ } catch (e) {
3452
+ db.exec("ROLLBACK");
3453
+ throw e;
3454
+ }
3455
+ }
3241
3456
  async function getCliCacheVersion() {
3242
3457
  if (_cliCacheVersionCache)
3243
3458
  return _cliCacheVersionCache;
@@ -4355,6 +4570,15 @@ var init_load_and_validate_for_review = __esm({
4355
4570
  });
4356
4571
 
4357
4572
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/review-session-paths.js
4573
+ import { resolve as resolve7 } from "node:path";
4574
+ async function getRefineSessionPaths(sessionId, artifactsRoot) {
4575
+ const sessionDir = resolve7(artifactsRoot, sessionId);
4576
+ return {
4577
+ sessionDir,
4578
+ eventsPath: resolve7(sessionDir, "events.jsonl"),
4579
+ statePath: resolve7(sessionDir, "current-review-state.json")
4580
+ };
4581
+ }
4358
4582
  var init_review_session_paths = __esm({
4359
4583
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/review-session-paths.js"() {
4360
4584
  "use strict";
@@ -4370,6 +4594,13 @@ var init_ensure_review_session = __esm({
4370
4594
  });
4371
4595
 
4372
4596
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/review-artifacts-root.js
4597
+ import { resolve as resolve8 } from "node:path";
4598
+ function getRefineArtifactsRoot() {
4599
+ if (process.env["EDS_REVIEW_ARTIFACTS_DIR"]) {
4600
+ return resolve8(process.env["EDS_REVIEW_ARTIFACTS_DIR"]);
4601
+ }
4602
+ return resolve8(configRoot(), "reviews");
4603
+ }
4373
4604
  var init_review_artifacts_root = __esm({
4374
4605
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/review-artifacts-root.js"() {
4375
4606
  "use strict";
@@ -4378,6 +4609,10 @@ var init_review_artifacts_root = __esm({
4378
4609
  });
4379
4610
 
4380
4611
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/save-review-state.js
4612
+ import { writeFile } from "node:fs/promises";
4613
+ async function saveReviewState(statePath, session) {
4614
+ await writeFile(statePath, JSON.stringify(session, null, 2), "utf8");
4615
+ }
4381
4616
  var init_save_review_state = __esm({
4382
4617
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/repositories/save-review-state.js"() {
4383
4618
  "use strict";
@@ -4645,15 +4880,15 @@ import { statSync as statSync2 } from "node:fs";
4645
4880
  import path4 from "node:path";
4646
4881
  function collectFiles(root, options = {}) {
4647
4882
  const resolved = path4.resolve(root);
4648
- let stat2;
4883
+ let stat4;
4649
4884
  try {
4650
- stat2 = statSync2(resolved);
4885
+ stat4 = statSync2(resolved);
4651
4886
  } catch (err) {
4652
4887
  return { ok: false, failure: classifyStatError(err.code), rootPath: resolved };
4653
4888
  }
4654
- if (stat2.isFile())
4889
+ if (stat4.isFile())
4655
4890
  return { ok: false, failure: "is-file", rootPath: resolved };
4656
- if (!stat2.isDirectory())
4891
+ if (!stat4.isDirectory())
4657
4892
  return { ok: false, failure: "not-directory", rootPath: resolved };
4658
4893
  const result = {
4659
4894
  filePaths: [],
@@ -4859,6 +5094,36 @@ var init_create_review_session_detail = __esm({
4859
5094
  });
4860
5095
 
4861
5096
  // packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/services/write-scope-decisions-snapshot.js
5097
+ import { mkdir } from "node:fs/promises";
5098
+ async function writeScopeDecisionsSnapshot(db, sessionId, decisions) {
5099
+ const acceptedSet = new Set(decisions.accepted);
5100
+ const rawComponents = loadRawComponents(db, sessionId);
5101
+ const records = rawComponents.map((c2) => {
5102
+ const status = acceptedSet.has(c2.name) ? "accepted" : "rejected";
5103
+ const proposal = {
5104
+ name: c2.name,
5105
+ source: c2.source,
5106
+ framework: c2.framework,
5107
+ props: c2.props,
5108
+ slots: c2.slots,
5109
+ ...c2.extractionConfidence !== void 0 ? { extractionConfidence: c2.extractionConfidence } : {},
5110
+ ...c2.reviewReasons !== void 0 ? { reviewReasons: c2.reviewReasons } : {},
5111
+ ...c2.needsReview !== void 0 ? { needsReview: c2.needsReview } : {}
5112
+ };
5113
+ return {
5114
+ id: c2.component_id,
5115
+ name: c2.name,
5116
+ resolvedSourcePath: "",
5117
+ sourceCode: null,
5118
+ originalProposal: proposal,
5119
+ editedProposal: proposal,
5120
+ status
5121
+ };
5122
+ });
5123
+ const paths = await getRefineSessionPaths(sessionId, getRefineArtifactsRoot());
5124
+ await mkdir(paths.sessionDir, { recursive: true });
5125
+ await saveReviewState(paths.statePath, { components: records });
5126
+ }
4862
5127
  var init_write_scope_decisions_snapshot = __esm({
4863
5128
  "packages/experience-design-system-backend-pipeline/dist/src/persistence/src/review-session/services/write-scope-decisions-snapshot.js"() {
4864
5129
  "use strict";
@@ -5306,7 +5571,7 @@ var init_utils_gen = __esm({
5306
5571
  }
5307
5572
  return url;
5308
5573
  };
5309
- createQuerySerializer = ({ allowReserved, array: array4, object: object2 } = {}) => {
5574
+ createQuerySerializer = ({ allowReserved, array: array3, object: object2 } = {}) => {
5310
5575
  const querySerializer = (queryParams) => {
5311
5576
  const search = [];
5312
5577
  if (queryParams && typeof queryParams === "object") {
@@ -5322,7 +5587,7 @@ var init_utils_gen = __esm({
5322
5587
  name,
5323
5588
  style: "form",
5324
5589
  value,
5325
- ...array4
5590
+ ...array3
5326
5591
  });
5327
5592
  if (serializedArray)
5328
5593
  search.push(serializedArray);
@@ -5795,7 +6060,7 @@ function errorMessage(error) {
5795
6060
  return error instanceof Error && error.message ? error.message : String(error);
5796
6061
  }
5797
6062
  function defaultSleep(delayMs) {
5798
- return new Promise((resolve10) => setTimeout(resolve10, delayMs));
6063
+ return new Promise((resolve12) => setTimeout(resolve12, delayMs));
5799
6064
  }
5800
6065
  var MAX_RETRY_AFTER_MS;
5801
6066
  var init_http_utils = __esm({
@@ -6069,7 +6334,7 @@ var init_api_client = __esm({
6069
6334
  const progress = maxAttempts > 1 ? attempt / (maxAttempts - 1) : 0;
6070
6335
  const baseDelay = intervalMs + (maxIntervalMs - intervalMs) * progress;
6071
6336
  const jitter = Math.random() * baseDelay * 0.15;
6072
- await new Promise((resolve10) => setTimeout(resolve10, baseDelay + jitter));
6337
+ await new Promise((resolve12) => setTimeout(resolve12, baseDelay + jitter));
6073
6338
  }
6074
6339
  }
6075
6340
  throw new Error(`Operation ${operationId} timed out after ${maxAttempts} attempts`);
@@ -6480,11 +6745,11 @@ function parseEdsiError(rawInput) {
6480
6745
  ...binding.diagnostics ? { diagnostics: binding.diagnostics } : {}
6481
6746
  };
6482
6747
  }
6483
- const literal3 = parseObjectLiteralTail(cleaned);
6484
- if (literal3 && (literal3.code || literal3.cycle)) {
6748
+ const literal4 = parseObjectLiteralTail(cleaned);
6749
+ if (literal4 && (literal4.code || literal4.cycle)) {
6485
6750
  const braceStart = cleaned.lastIndexOf("{");
6486
6751
  const head = braceStart === -1 ? cleaned : cleaned.slice(0, braceStart).trim();
6487
- return { code: literal3.code ?? null, message: head || cleaned, cycle: literal3.cycle ?? null, raw: false };
6752
+ return { code: literal4.code ?? null, message: head || cleaned, cycle: literal4.cycle ?? null, raw: false };
6488
6753
  }
6489
6754
  return { code: null, message: cleaned || prefix || rawInput, cycle: null, raw: true };
6490
6755
  }
@@ -6628,13 +6893,98 @@ var init_format_api_error2 = __esm({
6628
6893
  });
6629
6894
 
6630
6895
  // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/tokens/collect-json-files.js
6896
+ import { readdir, stat } from "node:fs/promises";
6897
+ import { join as join7 } from "node:path";
6898
+ async function collectJsonFiles(dir) {
6899
+ const results = [];
6900
+ await walk(dir, results);
6901
+ return results;
6902
+ }
6903
+ async function walk(current, results) {
6904
+ let entries;
6905
+ try {
6906
+ entries = await readdir(current);
6907
+ } catch {
6908
+ return;
6909
+ }
6910
+ await Promise.all(entries.map(async (entry) => {
6911
+ if (IGNORE_TOKEN_DIRS.has(entry))
6912
+ return;
6913
+ const full = join7(current, entry);
6914
+ let s;
6915
+ try {
6916
+ s = await stat(full);
6917
+ } catch {
6918
+ return;
6919
+ }
6920
+ if (s.isDirectory()) {
6921
+ await walk(full, results);
6922
+ } else if (entry.endsWith(".json")) {
6923
+ results.push(full);
6924
+ }
6925
+ }));
6926
+ }
6927
+ var IGNORE_TOKEN_DIRS;
6631
6928
  var init_collect_json_files = __esm({
6632
6929
  "packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/tokens/collect-json-files.js"() {
6633
6930
  "use strict";
6931
+ IGNORE_TOKEN_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".next", ".nuxt", ".git"]);
6634
6932
  }
6635
6933
  });
6636
6934
 
6637
6935
  // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/tokens/read-tokens-from-path.js
6936
+ import { readFile as readFile4, stat as stat2 } from "node:fs/promises";
6937
+ async function readTokensFromPath(flag, p) {
6938
+ let s;
6939
+ try {
6940
+ s = await stat2(p);
6941
+ } catch {
6942
+ throw new Error(`file not found: ${p} (from ${flag})`);
6943
+ }
6944
+ const merged = s.isDirectory() ? await readMergedFromDir(flag, p) : await readSingleFile(flag, p);
6945
+ const { valid, errors } = validateDTCG(merged);
6946
+ if (!valid) {
6947
+ throw new Error(`${flag} contains invalid token types:
6948
+ ${errors.map((e) => ` ${e.path}: ${e.message}`).join("\n")}`);
6949
+ }
6950
+ return flattenDTCG(merged, "");
6951
+ }
6952
+ async function readMergedFromDir(flag, dir) {
6953
+ const files = await collectJsonFiles(dir);
6954
+ if (files.length === 0)
6955
+ throw new Error(`no .json files found in directory: ${dir} (from ${flag})`);
6956
+ const merged = {};
6957
+ for (const file of files.sort()) {
6958
+ try {
6959
+ const text = await readFile4(file, "utf8");
6960
+ const parsed = JSON.parse(text);
6961
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6962
+ Object.assign(merged, parsed);
6963
+ }
6964
+ } catch {
6965
+ continue;
6966
+ }
6967
+ }
6968
+ return merged;
6969
+ }
6970
+ async function readSingleFile(flag, p) {
6971
+ let text;
6972
+ try {
6973
+ text = await readFile4(p, "utf8");
6974
+ } catch {
6975
+ throw new Error(`file not found: ${p} (from ${flag})`);
6976
+ }
6977
+ let raw;
6978
+ try {
6979
+ raw = JSON.parse(text);
6980
+ } catch {
6981
+ throw new Error(`${flag} is not valid JSON: ${p}`);
6982
+ }
6983
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
6984
+ throw new Error(`${flag} is not valid JSON: expected an object`);
6985
+ }
6986
+ return raw;
6987
+ }
6638
6988
  var init_read_tokens_from_path = __esm({
6639
6989
  "packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/helpers/tokens/read-tokens-from-path.js"() {
6640
6990
  "use strict";
@@ -6644,6 +6994,9 @@ var init_read_tokens_from_path = __esm({
6644
6994
  });
6645
6995
 
6646
6996
  // packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/controller/tokens/read-tokens-from-path.js
6997
+ function readTokensFromPath2(request) {
6998
+ return readTokensFromPath(request.flag, request.path);
6999
+ }
6647
7000
  var init_read_tokens_from_path2 = __esm({
6648
7001
  "packages/experience-design-system-backend-pipeline/dist/src/steps/apply/src/controller/tokens/read-tokens-from-path.js"() {
6649
7002
  "use strict";
@@ -6690,8 +7043,8 @@ var init_fetch_from_contentful = __esm({
6690
7043
  });
6691
7044
 
6692
7045
  // packages/experience-design-system-backend-pipeline/dist/src/steps/generation/src/controller/existing-entities/fetch-and-persist.js
6693
- import { writeFile } from "node:fs/promises";
6694
- import { join as join7 } from "node:path";
7046
+ import { writeFile as writeFile2 } from "node:fs/promises";
7047
+ import { join as join8 } from "node:path";
6695
7048
  async function fetchAndPersistExistingContentfulEntities(request) {
6696
7049
  const t0 = Date.now();
6697
7050
  try {
@@ -6703,8 +7056,8 @@ async function fetchAndPersistExistingContentfulEntities(request) {
6703
7056
  spaceId: request.spaceId,
6704
7057
  environmentId: request.environmentId
6705
7058
  });
6706
- const path5 = join7(request.outDir, ".existing-entities.json");
6707
- await writeFile(path5, JSON.stringify(entities, null, 2), "utf8");
7059
+ const path5 = join8(request.outDir, ".existing-entities.json");
7060
+ await writeFile2(path5, JSON.stringify(entities, null, 2), "utf8");
6708
7061
  return { ok: true, path: path5, durationMs: Date.now() - t0, entities };
6709
7062
  } catch (error) {
6710
7063
  return {
@@ -7646,17 +7999,17 @@ var init_shared2 = __esm({
7646
7999
  });
7647
8000
 
7648
8001
  // packages/experience-design-system-cli/src/tui/import/steps/05-token-reuse/logic.ts
7649
- import { access, stat } from "node:fs/promises";
7650
- import { join as join8 } from "node:path";
8002
+ import { access, stat as stat3 } from "node:fs/promises";
8003
+ import { join as join9 } from "node:path";
7651
8004
  async function inspectTokens({ rawTokensPath, outDir, cache }) {
7652
8005
  if (!cache) return { kind: "none" };
7653
- const tokensPath = join8(outDir, "tokens.json");
8006
+ const tokensPath = join9(outDir, "tokens.json");
7654
8007
  try {
7655
8008
  await access(tokensPath);
7656
8009
  } catch {
7657
8010
  return { kind: "none" };
7658
8011
  }
7659
- const [generated, source] = await Promise.all([stat(tokensPath), stat(rawTokensPath).catch(() => null)]);
8012
+ const [generated, source] = await Promise.all([stat3(tokensPath), stat3(rawTokensPath).catch(() => null)]);
7660
8013
  return { kind: "cached", tokensPath, sourceChanged: source ? source.mtimeMs > generated.mtimeMs : false };
7661
8014
  }
7662
8015
  function gateText({ tokensPath, sourceChanged }) {
@@ -7887,24 +8240,24 @@ var init_steps = __esm({
7887
8240
 
7888
8241
  // packages/experience-design-system-types/dist/src/config/index.js
7889
8242
  import { randomBytes } from "node:crypto";
7890
- import { mkdir, readFile as readFile4, rename, writeFile as writeFile2 } from "node:fs/promises";
8243
+ import { mkdir as mkdir2, readFile as readFile5, rename, writeFile as writeFile3 } from "node:fs/promises";
7891
8244
  import { homedir as homedir3 } from "node:os";
7892
- import { dirname as dirname5, join as join9 } from "node:path";
8245
+ import { dirname as dirname5, join as join10 } from "node:path";
7893
8246
  function configRoot2() {
7894
- return process.env["EDS_HOME"] || join9(homedir3(), ".contentful", "experience-design-system-cli");
8247
+ return process.env["EDS_HOME"] || join10(homedir3(), ".contentful", "experience-design-system-cli");
7895
8248
  }
7896
8249
  async function readSettings2() {
7897
8250
  try {
7898
- return JSON.parse(await readFile4(configFilePath2(), "utf8"));
8251
+ return JSON.parse(await readFile5(configFilePath2(), "utf8"));
7899
8252
  } catch {
7900
8253
  return {};
7901
8254
  }
7902
8255
  }
7903
8256
  async function writeSettings2(settings) {
7904
8257
  const path5 = configFilePath2();
7905
- await mkdir(dirname5(path5), { recursive: true });
8258
+ await mkdir2(dirname5(path5), { recursive: true });
7906
8259
  const tmp = `${path5}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
7907
- await writeFile2(tmp, `${JSON.stringify(settings, null, 2)}
8260
+ await writeFile3(tmp, `${JSON.stringify(settings, null, 2)}
7908
8261
  `, { mode: 384 });
7909
8262
  await rename(tmp, path5);
7910
8263
  }
@@ -7915,10 +8268,10 @@ var configFilePath2, runsFilePath2, debugSessionsDir2, oldConfigDir2;
7915
8268
  var init_config = __esm({
7916
8269
  "packages/experience-design-system-types/dist/src/config/index.js"() {
7917
8270
  "use strict";
7918
- configFilePath2 = () => join9(configRoot2(), "config.json");
7919
- runsFilePath2 = () => join9(configRoot2(), "state", "runs.json");
7920
- debugSessionsDir2 = () => join9(configRoot2(), "debug", "sessions");
7921
- oldConfigDir2 = () => join9(homedir3(), ".config", "experiences");
8271
+ configFilePath2 = () => join10(configRoot2(), "config.json");
8272
+ runsFilePath2 = () => join10(configRoot2(), "state", "runs.json");
8273
+ debugSessionsDir2 = () => join10(configRoot2(), "debug", "sessions");
8274
+ oldConfigDir2 = () => join10(homedir3(), ".config", "experiences");
7922
8275
  }
7923
8276
  });
7924
8277
 
@@ -7947,8 +8300,8 @@ var init_validate_generation_request = __esm({
7947
8300
 
7948
8301
  // packages/experience-design-system-generation/dist/src/services/prompts/helpers/resolve-skill-file.js
7949
8302
  import { existsSync as existsSync5 } from "node:fs";
7950
- import { readFile as readFile5 } from "node:fs/promises";
7951
- import { dirname as dirname6, join as join10, resolve as resolve7 } from "node:path";
8303
+ import { readFile as readFile6 } from "node:fs/promises";
8304
+ import { dirname as dirname6, join as join11, resolve as resolve9 } from "node:path";
7952
8305
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7953
8306
  function resolveSkillPath2(skill) {
7954
8307
  if (!(skill in SKILL_FILES2))
@@ -7956,10 +8309,10 @@ function resolveSkillPath2(skill) {
7956
8309
  const thisDir = dirname6(fileURLToPath3(import.meta.url));
7957
8310
  let dir = thisDir;
7958
8311
  for (; ; ) {
7959
- const candidate = join10(dir, "skills");
8312
+ const candidate = join11(dir, "skills");
7960
8313
  if (existsSync5(candidate))
7961
- return join10(candidate, SKILL_FILES2[skill]);
7962
- const parent = resolve7(dir, "..");
8314
+ return join11(candidate, SKILL_FILES2[skill]);
8315
+ const parent = resolve9(dir, "..");
7963
8316
  if (parent === dir) {
7964
8317
  throw new Error(`skill file missing from CLI installation (could not locate skills/ directory from: ${thisDir})`);
7965
8318
  }
@@ -7968,16 +8321,16 @@ function resolveSkillPath2(skill) {
7968
8321
  }
7969
8322
  async function readSkillFile2(skill, override) {
7970
8323
  if (override) {
7971
- const skillPath2 = resolve7(override);
8324
+ const skillPath2 = resolve9(override);
7972
8325
  try {
7973
- return await readFile5(skillPath2, "utf8");
8326
+ return await readFile6(skillPath2, "utf8");
7974
8327
  } catch {
7975
8328
  throw new Error(`custom prompt file not found (skill: ${skill}, path: ${skillPath2})`);
7976
8329
  }
7977
8330
  }
7978
8331
  const skillPath = resolveSkillPath2(skill);
7979
8332
  try {
7980
- return await readFile5(skillPath, "utf8");
8333
+ return await readFile6(skillPath, "utf8");
7981
8334
  } catch {
7982
8335
  throw new Error(`skill file missing from CLI installation \u2014 try reinstalling the CLI (looked for: ${skillPath})`);
7983
8336
  }
@@ -8745,7 +9098,7 @@ async function runAgent2(options) {
8745
9098
  promptLen: prompt.length,
8746
9099
  promptHead: prompt.slice(0, 500)
8747
9100
  });
8748
- return new Promise((resolve10) => {
9101
+ return new Promise((resolve12) => {
8749
9102
  const bedrockEnv = bedrock ? BEDROCK_ENV_BY_AGENT2[agent] : void 0;
8750
9103
  const child = spawn5(binary, args, {
8751
9104
  stdio: ["pipe", "pipe", "pipe"],
@@ -8789,7 +9142,7 @@ async function runAgent2(options) {
8789
9142
  stderrLen: stderr.length,
8790
9143
  stderrTail: stderr.slice(-1e3)
8791
9144
  });
8792
- resolve10(result);
9145
+ resolve12(result);
8793
9146
  });
8794
9147
  });
8795
9148
  }
@@ -8806,7 +9159,7 @@ var init_run_agent2 = __esm({
8806
9159
  // packages/experience-design-system-generation/dist/src/services/agent/helpers/check-claude-auth.js
8807
9160
  import { spawn as spawn6 } from "node:child_process";
8808
9161
  function checkClaudeAuth(binary) {
8809
- return new Promise((resolve10) => {
9162
+ return new Promise((resolve12) => {
8810
9163
  const child = spawn6(binary, ["auth", "status", "--json"], {
8811
9164
  stdio: ["ignore", "pipe", "pipe"]
8812
9165
  });
@@ -8816,7 +9169,7 @@ function checkClaudeAuth(binary) {
8816
9169
  if (!done) {
8817
9170
  done = true;
8818
9171
  child.kill("SIGTERM");
8819
- resolve10("unauthenticated");
9172
+ resolve12("unauthenticated");
8820
9173
  }
8821
9174
  }, 5e3);
8822
9175
  child.stdout?.on("data", (chunk) => {
@@ -8828,14 +9181,14 @@ function checkClaudeAuth(binary) {
8828
9181
  done = true;
8829
9182
  clearTimeout(timer);
8830
9183
  if (code !== 0) {
8831
- resolve10("unauthenticated");
9184
+ resolve12("unauthenticated");
8832
9185
  return;
8833
9186
  }
8834
9187
  try {
8835
9188
  const status = JSON.parse(stdout);
8836
- resolve10(status.loggedIn ? "ok" : "unauthenticated");
9189
+ resolve12(status.loggedIn ? "ok" : "unauthenticated");
8837
9190
  } catch {
8838
- resolve10("unauthenticated");
9191
+ resolve12("unauthenticated");
8839
9192
  }
8840
9193
  });
8841
9194
  });
@@ -8850,13 +9203,13 @@ var init_check_claude_auth = __esm({
8850
9203
  import { spawn as spawn7 } from "node:child_process";
8851
9204
  async function checkAgentAuth2(agent) {
8852
9205
  const binary = resolveAgentBinary(agent);
8853
- const binaryExists2 = await new Promise((resolve10) => {
9206
+ const binaryExists2 = await new Promise((resolve12) => {
8854
9207
  if (binary.startsWith("/")) {
8855
- import("node:fs/promises").then((fs) => fs.access(binary).then(() => resolve10(true), () => resolve10(false)));
9208
+ import("node:fs/promises").then((fs) => fs.access(binary).then(() => resolve12(true), () => resolve12(false)));
8856
9209
  return;
8857
9210
  }
8858
9211
  const child = spawn7(process.platform === "win32" ? "where" : "which", [binary], { stdio: "ignore" });
8859
- child.on("close", (code) => resolve10(code === 0));
9212
+ child.on("close", (code) => resolve12(code === 0));
8860
9213
  });
8861
9214
  if (!binaryExists2)
8862
9215
  return "not-found";
@@ -9045,7 +9398,7 @@ var init_src5 = __esm({
9045
9398
 
9046
9399
  // packages/experience-design-system-cli/src/tui/import/steps/06-extraction/processes.ts
9047
9400
  import { execFile as execFile2, spawn as spawn8 } from "node:child_process";
9048
- import { join as join11 } from "node:path";
9401
+ import { join as join12 } from "node:path";
9049
9402
  function lineSplitter(onLine) {
9050
9403
  let buffer = "";
9051
9404
  return (chunk) => {
@@ -9073,7 +9426,7 @@ function buildPrintTokensArgs(tokensPath, tokenSessionId) {
9073
9426
  return ["print", "tokens", "--out", tokensPath, ...tokenSessionId ? ["--session", tokenSessionId] : []];
9074
9427
  }
9075
9428
  function run(args, handlers = {}) {
9076
- return new Promise((resolve10) => {
9429
+ return new Promise((resolve12) => {
9077
9430
  const child = spawn8("node", args);
9078
9431
  let stdout = "";
9079
9432
  let stderr = "";
@@ -9089,17 +9442,17 @@ function run(args, handlers = {}) {
9089
9442
  stderr += chunk;
9090
9443
  stderrLines(chunk);
9091
9444
  });
9092
- child.on("error", (error) => resolve10({ exitCode: 1, stdout, stderr: stderr || error.message }));
9093
- child.on("exit", (code) => resolve10({ exitCode: code ?? 0, stdout, stderr }));
9445
+ child.on("error", (error) => resolve12({ exitCode: 1, stdout, stderr: stderr || error.message }));
9446
+ child.on("exit", (code) => resolve12({ exitCode: code ?? 0, stdout, stderr }));
9094
9447
  });
9095
9448
  }
9096
9449
  function spawnExtract(command, handlers) {
9097
9450
  return run(buildExtractArgs(findLegacyCliPath(), command), handlers);
9098
9451
  }
9099
9452
  function runBuffered(args) {
9100
- return new Promise((resolve10) => {
9453
+ return new Promise((resolve12) => {
9101
9454
  execFile2("node", [findLegacyCliPath(), ...args], (error, stdout, stderr) => {
9102
- resolve10({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
9455
+ resolve12({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
9103
9456
  });
9104
9457
  });
9105
9458
  }
@@ -9109,7 +9462,7 @@ async function runTokenGeneration(input) {
9109
9462
  return { ok: false, step: "generate tokens", message: generated.stderr.trim() || "Unknown error" };
9110
9463
  }
9111
9464
  const tokenSessionId = findSession(generated.stdout);
9112
- const tokensPath = join11(input.outDir, "tokens.json");
9465
+ const tokensPath = join12(input.outDir, "tokens.json");
9113
9466
  const printed = await runBuffered(buildPrintTokensArgs(tokensPath, tokenSessionId));
9114
9467
  if (printed.exitCode !== 0) {
9115
9468
  return { ok: false, step: "print tokens", message: printed.stderr.trim() || "Unknown error" };
@@ -9125,9 +9478,9 @@ var init_processes = __esm({
9125
9478
  });
9126
9479
 
9127
9480
  // packages/experience-design-system-cli/src/tui/import/steps/06-extraction/selection.ts
9128
- import { resolve as resolve8 } from "node:path";
9481
+ import { resolve as resolve10 } from "node:path";
9129
9482
  async function hashSelectPrompt(options) {
9130
- const promptHash = options.promptText ? hashContent(options.promptText) : options.promptPath ? await hashFile(resolve8(options.promptPath)) : await hashFile(resolveSkillPath2("select"));
9483
+ const promptHash = options.promptText ? hashContent(options.promptText) : options.promptPath ? await hashFile(resolve10(options.promptPath)) : await hashFile(resolveSkillPath2("select"));
9131
9484
  return hashContent(`${promptHash}|${options.agent}|${options.model ?? ""}`);
9132
9485
  }
9133
9486
  async function runSelection(options) {
@@ -9221,10 +9574,10 @@ var init_selection2 = __esm({
9221
9574
  });
9222
9575
 
9223
9576
  // packages/experience-design-system-cli/src/tui/import/steps/06-extraction/run.ts
9224
- import { mkdir as mkdir2 } from "node:fs/promises";
9225
- import { join as join12, resolve as resolve9 } from "node:path";
9577
+ import { mkdir as mkdir3 } from "node:fs/promises";
9578
+ import { join as join13, resolve as resolve11 } from "node:path";
9226
9579
  async function runExtraction(input, onProgress, deps = realDeps) {
9227
- const outDir = join12(resolve9(input.projectPath), ".contentful");
9580
+ const outDir = join13(resolve11(input.projectPath), ".contentful");
9228
9581
  let progress = initialProgress({
9229
9582
  hasCredentials: input.credentials !== null,
9230
9583
  hasRawTokens: input.rawTokensPath !== "",
@@ -9309,10 +9662,11 @@ async function runExtraction(input, onProgress, deps = realDeps) {
9309
9662
  const tokens = await tokenGeneration;
9310
9663
  if (tokens && !tokens.ok) return fail(tokens.step, tokens.message);
9311
9664
  if (!sessionId) return fail("analyze extract", "The extract command did not report a session.");
9665
+ const hasTokenSource = input.rawTokensPath !== "" || input.tokenStrategy === "reuse";
9312
9666
  const extraction = {
9313
9667
  sessionId,
9314
9668
  outDir,
9315
- tokensPath: tokens?.ok ? tokens.tokensPath : join12(outDir, "tokens.json"),
9669
+ tokensPath: tokens?.ok ? tokens.tokensPath : hasTokenSource ? join13(outDir, "tokens.json") : "",
9316
9670
  tokenSessionId: tokens?.ok ? tokens.tokenSessionId : null,
9317
9671
  tokenCount: tokens?.ok ? tokens.tokenCount : 0,
9318
9672
  existingEntitiesPath,
@@ -9323,7 +9677,7 @@ async function runExtraction(input, onProgress, deps = realDeps) {
9323
9677
  }
9324
9678
  async function fetchEntities(credentials, outDir) {
9325
9679
  try {
9326
- await mkdir2(outDir, { recursive: true });
9680
+ await mkdir3(outDir, { recursive: true });
9327
9681
  const result = await fetchAndPersistExistingContentfulEntities({
9328
9682
  spaceId: credentials.spaceId,
9329
9683
  environmentId: credentials.environmentId,
@@ -9343,7 +9697,7 @@ async function resolveSelectionPrompt(overrides) {
9343
9697
  if (select?.kind === "text") return { promptText: select.value };
9344
9698
  if (select?.kind === "path") {
9345
9699
  await resolvePromptOverride(select);
9346
- return { promptPath: resolve9(select.value) };
9700
+ return { promptPath: resolve11(select.value) };
9347
9701
  }
9348
9702
  return {};
9349
9703
  }
@@ -10294,7 +10648,7 @@ function buildVisibleRows(props) {
10294
10648
  if (visited.has(target)) continue;
10295
10649
  visited.add(target);
10296
10650
  const isCycleMember = cycleParticipants.has(target);
10297
- out.push({ name: target, depth: cur.depth + 1, isCycleMember, parent: cur.name });
10651
+ out.push({ name: target, depth: cur.depth + 1, isCycleMember });
10298
10652
  queue.push({ name: target, depth: cur.depth + 1 });
10299
10653
  }
10300
10654
  }
@@ -10341,8 +10695,7 @@ function buildVisibleRows(props) {
10341
10695
  sharedSuffix,
10342
10696
  cycleChild: child.isCycleMember || void 0,
10343
10697
  itemIdx: childRec?.idx ?? -1,
10344
- rootName: key,
10345
- parentName: child.parent
10698
+ rootName: key
10346
10699
  });
10347
10700
  });
10348
10701
  }
@@ -10425,19 +10778,13 @@ function buildVisibleRows(props) {
10425
10778
  injectedChildren.push({
10426
10779
  name: target,
10427
10780
  depth: parentDepth + 1,
10428
- isCycleChild: true,
10429
- parent: parentName
10781
+ isCycleChild: true
10430
10782
  });
10431
10783
  }
10432
10784
  };
10433
10785
  emitCycleChildrenOf(root, 0);
10434
10786
  for (const c2 of closureChildren) {
10435
- injectedChildren.push({
10436
- name: c2.name,
10437
- depth: c2.depth,
10438
- isCycleChild: false,
10439
- parent: c2.path[c2.path.length - 2] ?? root
10440
- });
10787
+ injectedChildren.push({ name: c2.name, depth: c2.depth, isCycleChild: false });
10441
10788
  emitCycleChildrenOf(c2.name, c2.depth);
10442
10789
  }
10443
10790
  const isLastAtDepth = (idx) => {
@@ -10471,8 +10818,7 @@ function buildVisibleRows(props) {
10471
10818
  sharedSuffix,
10472
10819
  cycleChild: child.isCycleChild || void 0,
10473
10820
  itemIdx: childRec?.idx ?? -1,
10474
- rootName: root,
10475
- parentName: child.parent
10821
+ rootName: root
10476
10822
  });
10477
10823
  });
10478
10824
  }
@@ -10625,7 +10971,7 @@ function GroupedSidebar(props) {
10625
10971
  const rs = itemName ? renderStatusByKey?.get(itemName) : void 0;
10626
10972
  const badge = itemName ? previewBadge(previewAnnotationByKey?.get(itemName)) : null;
10627
10973
  const showInheritance = rs !== void 0 && row.kind !== "cycle" && row.kind !== "empty" && row.kind !== "group-root";
10628
- 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");
10974
+ 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");
10629
10975
  const selState = supportsSelectionGlyph ? selectionStateByKey.get(itemName) ?? "undecided" : void 0;
10630
10976
  const isCycleRow = row.kind === "cycle";
10631
10977
  const selStyle = selectionGlyphStyleFor(selState, isCycleRow);
@@ -10655,7 +11001,7 @@ function GroupedSidebar(props) {
10655
11001
  color: isSelected ? PALETTE2.info : labelStyle.dim ? PALETTE2.muted : labelStyle.color,
10656
11002
  bold: isSelected || labelStyle.bold,
10657
11003
  inverse: false,
10658
- underline: isSelected && focused,
11004
+ underline: isSelected && !focused,
10659
11005
  wrap: wrapLabels ? "wrap" : "truncate",
10660
11006
  children: [
10661
11007
  " ",
@@ -11131,11 +11477,11 @@ function buildCycleUnits(slotCycles) {
11131
11477
  while (parent.get(cur) !== cur) {
11132
11478
  cur = parent.get(cur);
11133
11479
  }
11134
- let walk = x;
11135
- while (parent.get(walk) !== cur) {
11136
- const next = parent.get(walk);
11137
- parent.set(walk, cur);
11138
- walk = next;
11480
+ let walk2 = x;
11481
+ while (parent.get(walk2) !== cur) {
11482
+ const next = parent.get(walk2);
11483
+ parent.set(walk2, cur);
11484
+ walk2 = next;
11139
11485
  }
11140
11486
  return cur;
11141
11487
  };
@@ -11391,7 +11737,6 @@ function resolveKey(mode, key, ctx) {
11391
11737
  function resolveMain(key, ctx) {
11392
11738
  const { input } = key;
11393
11739
  const inMain = ctx.focusedColumn === "main";
11394
- if (key.ctrl && input === "z") return { type: "undo" };
11395
11740
  if (input === "q" || key.escape) {
11396
11741
  if (key.escape && ctx.jumpFilterActive) return { type: "clear-jump-filter" };
11397
11742
  if (key.escape && ctx.searchActive) return { type: "clear-search" };
@@ -11690,30 +12035,14 @@ function rejectNeedsConfirmation(graph, name, state) {
11690
12035
  const ancestors = toReject.filter((n) => n !== name);
11691
12036
  return ancestors.length + toDeselect.length >= 2;
11692
12037
  }
11693
- function removeSlotChild(components, edge) {
11694
- return components.map(
11695
- (component) => component.name === edge.parent ? {
11696
- ...component,
11697
- slots: component.slots?.map((slot) => ({
11698
- ...slot,
11699
- allowedComponents: slot.allowedComponents.filter((name) => name !== edge.child)
11700
- }))
11701
- } : component
11702
- );
11703
- }
11704
- function withoutSlotChildren(components, removedEdges) {
11705
- return removedEdges.reduce(removeSlotChild, components);
11706
- }
11707
- function partitionDecisions(components, state, removedEdges) {
12038
+ function partitionDecisions(components, state) {
11708
12039
  const accepted = [];
11709
12040
  const rejected = [];
11710
12041
  for (const c2 of components) {
11711
12042
  if (state.get(c2.name) === "accepted") accepted.push(c2.name);
11712
12043
  else rejected.push(c2.name);
11713
12044
  }
11714
- const rejectedNames = new Set(rejected);
11715
- const excludedSlotEdges = removedEdges.filter((e) => !rejectedNames.has(e.parent) && !rejectedNames.has(e.child));
11716
- return { accepted, rejected, excludedSlotEdges };
12045
+ return { accepted, rejected };
11717
12046
  }
11718
12047
  var init_state = __esm({
11719
12048
  "packages/experience-design-system-cli/src/tui/import/steps/07-scope-gate/state.ts"() {
@@ -11725,15 +12054,10 @@ var init_state = __esm({
11725
12054
 
11726
12055
  // packages/experience-design-system-cli/src/tui/import/steps/07-scope-gate/use-scope-gate.ts
11727
12056
  import { useEffect as useEffect7, useMemo as useMemo2, useRef as useRef4, useState as useState12 } from "react";
11728
- function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
12057
+ function useScopeGate({ components, onConfirm, onQuit }) {
11729
12058
  const { columns: totalWidth, rows: terminalRows } = useTerminalSize();
11730
12059
  const columnPlan = useMemo2(() => computeColumnWidths(totalWidth), [totalWidth]);
11731
12060
  const [decisions, setDecisions] = useState12(/* @__PURE__ */ new Map());
11732
- const [removedEdges, setRemovedEdges] = useState12([]);
11733
- const components = useMemo2(
11734
- () => withoutSlotChildren(loadedComponents, removedEdges),
11735
- [loadedComponents, removedEdges]
11736
- );
11737
12061
  const [nav, setNav] = useState12({ cursor: 0, scrollOffset: 0 });
11738
12062
  const [focusedColumn, setFocusedColumn] = useState12("main");
11739
12063
  const [addedComponentsCursor, setAddedComponentsCursor] = useState12(0);
@@ -11905,14 +12229,6 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
11905
12229
  return void 0;
11906
12230
  }
11907
12231
  };
11908
- const focusedNestedEdge = () => {
11909
- const row = visibleRows[safeCursor];
11910
- if (row?.kind !== "group-child" || !row.parentName || row.itemIdx < 0) return void 0;
11911
- const child = groupedItems[row.itemIdx]?.key;
11912
- return child ? { parent: row.parentName, child } : void 0;
11913
- };
11914
- const removeFromParentSlot = (edge) => setRemovedEdges((edges) => [...edges, edge]);
11915
- const undoSlotRemoval = () => setRemovedEdges((edges) => edges.slice(0, -1));
11916
12232
  const jumpCursorTo = (name) => {
11917
12233
  let idx = -1;
11918
12234
  for (let i = 0; i < visibleRows.length; i++) {
@@ -12012,7 +12328,7 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
12012
12328
  onQuit();
12013
12329
  return;
12014
12330
  case "confirm":
12015
- onConfirm(partitionDecisions(components, decisions, removedEdges));
12331
+ onConfirm(partitionDecisions(components, decisions));
12016
12332
  return;
12017
12333
  case "close-help":
12018
12334
  setShowHelp(false);
@@ -12065,11 +12381,6 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
12065
12381
  return;
12066
12382
  }
12067
12383
  case "reject": {
12068
- const edge = focusedColumn === "main" ? focusedNestedEdge() : void 0;
12069
- if (edge) {
12070
- removeFromParentSlot(edge);
12071
- return;
12072
- }
12073
12384
  const key = focusedColumn === "added-components" ? addedComponents[safeAddedComponentsCursor]?.name : focusedRowKey();
12074
12385
  if (key) requestReject(key);
12075
12386
  return;
@@ -12077,9 +12388,6 @@ function useScopeGate({ components: loadedComponents, onConfirm, onQuit }) {
12077
12388
  case "toggle-all":
12078
12389
  decide({ type: "toggle-all" });
12079
12390
  return;
12080
- case "undo":
12081
- undoSlotRemoval();
12082
- return;
12083
12391
  case "accept-unflagged":
12084
12392
  decide({ type: "accept-unflagged" });
12085
12393
  return;
@@ -12425,9 +12733,9 @@ var init_cache_check = __esm({
12425
12733
  "packages/experience-design-system-cli/src/tui/import/steps/07-scope-gate/cache-check.ts"() {
12426
12734
  "use strict";
12427
12735
  init_legacy_cli_path();
12428
- runLegacyCli = (args) => new Promise((resolve10) => {
12736
+ runLegacyCli = (args) => new Promise((resolve12) => {
12429
12737
  execFile3("node", [findLegacyCliPath(), ...args], (error, stdout, stderr) => {
12430
- resolve10({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
12738
+ resolve12({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
12431
12739
  });
12432
12740
  });
12433
12741
  }
@@ -12467,26 +12775,14 @@ function useScopeGateFlow(input, deps = realDeps2) {
12467
12775
  const loaded = useMemo3(() => sessionId ? deps.load(sessionId) : void 0, [sessionId]);
12468
12776
  const cacheCheck = useRef5(void 0);
12469
12777
  const [confirmed, setConfirmed] = useState13();
12470
- const [scope, setScope] = useState13();
12471
12778
  useEffect8(() => {
12472
12779
  if (!input || !loaded?.ok || cacheCheck.current) return;
12473
12780
  cacheCheck.current = deps.checkCache(input.cache);
12474
12781
  }, [input, loaded]);
12475
- useEffect8(() => {
12476
- if (!confirmed || !cacheCheck.current) return;
12477
- let current = true;
12478
- void cacheCheck.current.then((cachedNames) => {
12479
- const accepted = new Set(confirmed.accepted);
12480
- if (current) setScope({ ...confirmed, cachedNames: cachedNames.filter((name) => accepted.has(name)) });
12481
- });
12482
- return () => {
12483
- current = false;
12484
- };
12485
- }, [confirmed]);
12486
12782
  if (!input || !loaded) return void 0;
12487
12783
  if (!loaded.ok) return { status: "failed", message: loaded.message };
12488
- if (scope) return { status: "confirmed", scope };
12489
- if (confirmed) return { status: "preparing" };
12784
+ if (confirmed && cacheCheck.current)
12785
+ return { status: "confirmed", decisions: confirmed, cachedNames: cacheCheck.current };
12490
12786
  return { status: "deciding", load: loaded, confirm: setConfirmed };
12491
12787
  }
12492
12788
  var realDeps2;
@@ -12499,12 +12795,363 @@ var init_use_scope_gate_flow = __esm({
12499
12795
  }
12500
12796
  });
12501
12797
 
12798
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/logic.ts
12799
+ function initialProgress2() {
12800
+ return { components: null, mapTokens: "idle", mapTokensEligible: null };
12801
+ }
12802
+ function applyGenerateStderr(chunk, previous) {
12803
+ let state = previous;
12804
+ for (const line of chunk.split("\n")) {
12805
+ const finished = PROGRESS_LINE.exec(line);
12806
+ if (finished) {
12807
+ state = { done: Number(finished[1]), total: Number(finished[2]), current: finished[3].trim() };
12808
+ continue;
12809
+ }
12810
+ const started = STARTED_LINE.exec(line);
12811
+ if (started) {
12812
+ state = { done: state?.done ?? 0, total: Number(started[2]), current: started[3].trim() };
12813
+ }
12814
+ }
12815
+ return state;
12816
+ }
12817
+ function parseGenerateResult(output, fallbackCount) {
12818
+ const session = /^session=(.+)$/m.exec(output.stdout);
12819
+ const count = /(\d+) components?/.exec(output.stderr);
12820
+ const renamed = /^renamed-slots:\s*(\d+)$/m.exec(output.stdout);
12821
+ return {
12822
+ generateSessionId: session ? session[1].trim() : null,
12823
+ generatedCount: count ? Number(count[1]) : fallbackCount,
12824
+ renamedSlotsCount: renamed ? Number(renamed[1]) : 0
12825
+ };
12826
+ }
12827
+ function shouldRunMapTokens(counts) {
12828
+ return counts.mappablePropCount > 0 && counts.rawTokenCount > 0;
12829
+ }
12830
+ function formatAcceptanceSummary(counts) {
12831
+ const accepted = `${counts.accepted} component${counts.accepted === 1 ? "" : "s"} accepted`;
12832
+ if (counts.autoRejected === 0) return `${accepted}.`;
12833
+ return `${accepted}, ${counts.autoRejected} excluded due to validation errors.`;
12834
+ }
12835
+ function describeGeneration(input) {
12836
+ const agent = capitalize(input.agent);
12837
+ return `${formatAcceptanceSummary({ accepted: input.acceptedCount, autoRejected: 0 })}
12838
+ ${agent} is mapping your selected components to Contentful's Component Definition Format (CDF).${input.hasTokens ? " Using your design tokens for prop resolution." : ""}`;
12839
+ }
12840
+ function progressRows2(progress, agent) {
12841
+ const name = capitalize(agent);
12842
+ const { components, mapTokens } = progress;
12843
+ const rows = [
12844
+ {
12845
+ text: components ? components.current : `Starting up ${name}...`,
12846
+ complete: false,
12847
+ ...components ? { progress: { done: components.done, total: components.total } } : {}
12848
+ }
12849
+ ];
12850
+ if (mapTokens !== "idle") {
12851
+ rows.push({
12852
+ text: mapTokens === "running" ? `Mapping token restrictions via ${name}...` : "Token restrictions ready",
12853
+ complete: mapTokens === "complete"
12854
+ });
12855
+ }
12856
+ return rows;
12857
+ }
12858
+ var PROGRESS_LINE, STARTED_LINE, capitalize;
12859
+ var init_logic10 = __esm({
12860
+ "packages/experience-design-system-cli/src/tui/import/steps/08-generation/logic.ts"() {
12861
+ "use strict";
12862
+ PROGRESS_LINE = /^progress=generate:(\d+)\/(\d+):(.+)$/;
12863
+ STARTED_LINE = /\[(\d+)\/(\d+)\]\s+(.+)/;
12864
+ capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1);
12865
+ }
12866
+ });
12867
+
12868
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/screen.tsx
12869
+ import { jsx as jsx25 } from "react/jsx-runtime";
12870
+ function GenerationScreen({
12871
+ progress,
12872
+ agent,
12873
+ acceptedCount,
12874
+ hasTokens,
12875
+ stepNumber,
12876
+ totalSteps
12877
+ }) {
12878
+ return /* @__PURE__ */ jsx25(
12879
+ RunningStep,
12880
+ {
12881
+ stepNumber,
12882
+ totalSteps,
12883
+ title: "Generating definitions",
12884
+ description: describeGeneration({ acceptedCount, agent, hasTokens }),
12885
+ lines: progressRows2(progress, agent)
12886
+ }
12887
+ );
12888
+ }
12889
+ var init_screen8 = __esm({
12890
+ "packages/experience-design-system-cli/src/tui/import/steps/08-generation/screen.tsx"() {
12891
+ "use strict";
12892
+ init_shared2();
12893
+ init_logic10();
12894
+ }
12895
+ });
12896
+
12897
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/map-tokens.ts
12898
+ async function prepareMapTokens(input, generatedSessionId) {
12899
+ const db = openPipelineDb();
12900
+ try {
12901
+ if (input.tokenSessionId && input.tokenSessionId !== generatedSessionId) {
12902
+ copyTokensFromCache(db, input.tokenSessionId, generatedSessionId);
12903
+ } else if (!input.tokenSessionId && input.tokensPath) {
12904
+ const tokens = await readTokensFromPath2({ flag: "tokens", path: input.tokensPath });
12905
+ storeDtcgTokens(db, generatedSessionId, [], tokens);
12906
+ }
12907
+ const mappablePropCount = loadCDFComponents(db, generatedSessionId).reduce(
12908
+ (count, { entry }) => count + Object.values(entry.$properties).filter((prop) => prop.$type === "token" && prop.$category === "design").length,
12909
+ 0
12910
+ );
12911
+ const rawTokenCount = getDtcgTokensForSession(db, generatedSessionId).tokens.length;
12912
+ return {
12913
+ eligible: shouldRunMapTokens({ mappablePropCount, rawTokenCount }),
12914
+ mappablePropCount,
12915
+ rawTokenCount
12916
+ };
12917
+ } finally {
12918
+ db.close();
12919
+ }
12920
+ }
12921
+ var init_map_tokens = __esm({
12922
+ "packages/experience-design-system-cli/src/tui/import/steps/08-generation/map-tokens.ts"() {
12923
+ "use strict";
12924
+ init_src3();
12925
+ init_logic10();
12926
+ }
12927
+ });
12928
+
12929
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/processes.ts
12930
+ import { execFile as execFile4, spawn as spawn9 } from "node:child_process";
12931
+ function buildGenerateArgs(cliPath, command) {
12932
+ const args = [cliPath, "__generate", "components", "--agent", command.agent, "--session", command.sessionId];
12933
+ if (command.tokensPath) args.push("--tokens", command.tokensPath);
12934
+ if (command.agentModel) args.push("--model", command.agentModel);
12935
+ if (command.noCache) args.push("--no-cache");
12936
+ if (command.generatePromptPath) args.push("--generate-prompt-path", command.generatePromptPath);
12937
+ for (const prompt of command.promptOverrides) args.push("--prompt", prompt);
12938
+ if (command.existingEntitiesPath) args.push("--existing-entities-path", command.existingEntitiesPath);
12939
+ if (command.cachedComponents.length > 0) args.push("--cached-components", JSON.stringify(command.cachedComponents));
12940
+ return args;
12941
+ }
12942
+ function buildMapTokensArgs(command) {
12943
+ const args = ["map", "tokens", "--session", command.sessionId, "--agent", command.agent];
12944
+ if (command.agentModel) args.push("--model", command.agentModel);
12945
+ if (command.noCache) args.push("--no-cache");
12946
+ for (const prompt of command.promptOverrides) args.push("--prompt", prompt);
12947
+ if (command.existingEntitiesPath) args.push("--existing-entities-path", command.existingEntitiesPath);
12948
+ return args;
12949
+ }
12950
+ function spawnGenerate(command, handlers) {
12951
+ return new Promise((resolve12) => {
12952
+ const child = spawn9("node", buildGenerateArgs(findLegacyCliPath(), command));
12953
+ let stdout = "";
12954
+ let stderr = "";
12955
+ child.stdout.on("data", (data) => {
12956
+ stdout += String(data);
12957
+ });
12958
+ child.stderr.on("data", (data) => {
12959
+ const chunk = String(data);
12960
+ stderr += chunk;
12961
+ handlers.onStderr(chunk);
12962
+ });
12963
+ child.on("error", (error) => resolve12({ exitCode: 1, stdout, stderr: stderr + error.message }));
12964
+ child.on("close", (code) => resolve12({ exitCode: code ?? 0, stdout, stderr }));
12965
+ });
12966
+ }
12967
+ function runMapTokens2(command) {
12968
+ return new Promise((resolve12) => {
12969
+ execFile4("node", [findLegacyCliPath(), ...buildMapTokensArgs(command)], (error, stdout, stderr) => {
12970
+ resolve12({ exitCode: error?.code ? Number(error.code) : 0, stdout, stderr });
12971
+ });
12972
+ });
12973
+ }
12974
+ var init_processes2 = __esm({
12975
+ "packages/experience-design-system-cli/src/tui/import/steps/08-generation/processes.ts"() {
12976
+ "use strict";
12977
+ init_legacy_cli_path();
12978
+ }
12979
+ });
12980
+
12981
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/save-decisions.ts
12982
+ async function saveDecisions(input) {
12983
+ const db = openPipelineDb();
12984
+ try {
12985
+ applyScopeDecisions(db, input.sessionId, input.decisions);
12986
+ await writeScopeDecisionsSnapshot(db, input.sessionId, input.decisions);
12987
+ } finally {
12988
+ db.close();
12989
+ }
12990
+ }
12991
+ var init_save_decisions = __esm({
12992
+ "packages/experience-design-system-cli/src/tui/import/steps/08-generation/save-decisions.ts"() {
12993
+ "use strict";
12994
+ init_src3();
12995
+ }
12996
+ });
12997
+
12998
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/run.ts
12999
+ async function runGeneration(input, onProgress, deps = realDeps3) {
13000
+ let progress = initialProgress2();
13001
+ const update = (change) => {
13002
+ progress = { ...progress, ...change };
13003
+ onProgress(progress);
13004
+ };
13005
+ const accepted = input.decisions.accepted;
13006
+ const handedOverNames = await input.cachedNames.catch(() => []);
13007
+ try {
13008
+ await deps.saveDecisions({ sessionId: input.sessionId, decisions: input.decisions });
13009
+ } catch (error) {
13010
+ return fail2("save decisions", errorMessage3(error));
13011
+ }
13012
+ if (accepted.length === 0) return { ok: true, generation: { route: "push", acceptedCount: 0 } };
13013
+ const auth = await deps.checkAgentAuth(input.agent);
13014
+ if (auth === "not-found" || auth === "unauthenticated") {
13015
+ return fail2(`${input.agent} auth check`, agentAuthMessage(input.agent, auth));
13016
+ }
13017
+ const acceptedSet = new Set(accepted);
13018
+ let cachedNames = handedOverNames;
13019
+ let cacheHit = !input.noCache && accepted.length > 0 && accepted.every((name) => cachedNames.includes(name));
13020
+ if (!cacheHit && !input.noCache && accepted.length > 0) {
13021
+ const fresh = await deps.checkCache(cacheCheckFor(input));
13022
+ cachedNames = fresh.filter((name) => acceptedSet.has(name));
13023
+ cacheHit = accepted.every((name) => cachedNames.includes(name));
13024
+ }
13025
+ let generatedSessionId = input.sessionId;
13026
+ let generatedCount = accepted.length;
13027
+ if (!cacheHit) {
13028
+ const result = await deps.spawnGenerate(
13029
+ {
13030
+ sessionId: input.sessionId,
13031
+ tokensPath: input.tokensPath,
13032
+ agent: input.agent,
13033
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
13034
+ promptOverrides: input.promptOverrides,
13035
+ ...input.generatePromptPath ? { generatePromptPath: input.generatePromptPath } : {},
13036
+ noCache: input.noCache,
13037
+ existingEntitiesPath: input.existingEntitiesPath,
13038
+ cachedComponents: cachedNames
13039
+ },
13040
+ {
13041
+ onStderr: (chunk) => {
13042
+ const components = applyGenerateStderr(chunk, progress.components);
13043
+ if (components !== progress.components) update({ components });
13044
+ }
13045
+ }
13046
+ );
13047
+ if (result.exitCode !== 0) return fail2("generate components", result.stderr.trim() || "Unknown error");
13048
+ const parsed = parseGenerateResult(result, accepted.length);
13049
+ generatedSessionId = parsed.generateSessionId ?? input.sessionId;
13050
+ generatedCount = parsed.generatedCount;
13051
+ }
13052
+ let plan;
13053
+ try {
13054
+ plan = await deps.prepareMapTokens(input, generatedSessionId);
13055
+ } catch (error) {
13056
+ return fail2("map tokens", errorMessage3(error));
13057
+ }
13058
+ update({ mapTokensEligible: plan.eligible });
13059
+ if (plan.eligible) {
13060
+ update({ mapTokens: "running" });
13061
+ const mapped = await deps.runMapTokens({
13062
+ sessionId: generatedSessionId,
13063
+ agent: input.agent,
13064
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
13065
+ promptOverrides: input.promptOverrides,
13066
+ noCache: input.noCache,
13067
+ existingEntitiesPath: input.existingEntitiesPath
13068
+ });
13069
+ if (mapped.exitCode !== 0) return fail2("map tokens", mapped.stderr.trim() || "Unknown error");
13070
+ }
13071
+ update({ mapTokens: "complete" });
13072
+ return {
13073
+ ok: true,
13074
+ generation: {
13075
+ route: "review",
13076
+ sessionId: generatedSessionId,
13077
+ acceptedCount: accepted.length,
13078
+ generatedCount,
13079
+ mapTokensEligible: plan.eligible
13080
+ }
13081
+ };
13082
+ }
13083
+ function cacheCheckFor(input) {
13084
+ return {
13085
+ sessionId: input.sessionId,
13086
+ tokensPath: input.tokensPath,
13087
+ agent: input.agent,
13088
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
13089
+ promptOverrides: input.promptOverrides,
13090
+ existingEntitiesPath: input.existingEntitiesPath,
13091
+ noCache: input.noCache
13092
+ };
13093
+ }
13094
+ var realDeps3, fail2, errorMessage3;
13095
+ var init_run2 = __esm({
13096
+ "packages/experience-design-system-cli/src/tui/import/steps/08-generation/run.ts"() {
13097
+ "use strict";
13098
+ init_src5();
13099
+ init_logic9();
13100
+ init_cache_check();
13101
+ init_logic10();
13102
+ init_map_tokens();
13103
+ init_processes2();
13104
+ init_save_decisions();
13105
+ realDeps3 = {
13106
+ checkAgentAuth: checkAgentAuth2,
13107
+ saveDecisions,
13108
+ checkCache: checkGenerationCache,
13109
+ spawnGenerate,
13110
+ prepareMapTokens,
13111
+ runMapTokens: runMapTokens2
13112
+ };
13113
+ fail2 = (step, message) => ({ ok: false, step, message });
13114
+ errorMessage3 = (error) => error instanceof Error ? error.message : String(error);
13115
+ }
13116
+ });
13117
+
13118
+ // packages/experience-design-system-cli/src/tui/import/steps/08-generation/use-generation.ts
13119
+ import { useEffect as useEffect9, useRef as useRef6, useState as useState14 } from "react";
13120
+ function useGeneration(input) {
13121
+ const [state, setState] = useState14();
13122
+ const current = useRef6();
13123
+ useEffect9(() => {
13124
+ current.current = input;
13125
+ if (!input) {
13126
+ setState(void 0);
13127
+ return;
13128
+ }
13129
+ setState({ status: "running", progress: initialProgress2() });
13130
+ void runGeneration(input, (progress) => {
13131
+ if (current.current === input) setState({ status: "running", progress });
13132
+ }).then((result) => {
13133
+ if (current.current === input) setState({ status: "done", result });
13134
+ });
13135
+ return () => {
13136
+ if (current.current === input) current.current = void 0;
13137
+ };
13138
+ }, [input]);
13139
+ return state;
13140
+ }
13141
+ var init_use_generation = __esm({
13142
+ "packages/experience-design-system-cli/src/tui/import/steps/08-generation/use-generation.ts"() {
13143
+ "use strict";
13144
+ init_logic10();
13145
+ init_run2();
13146
+ }
13147
+ });
13148
+
12502
13149
  // packages/experience-design-system-types/dist/src/handoff/index.js
12503
13150
  import * as z5 from "zod/mini";
12504
13151
  function serializeHandoff(handoff) {
12505
13152
  return JSON.stringify(handoff);
12506
13153
  }
12507
- var HANDOFF_ENV, NonEmpty, TokensSchema, ExtractionSchema, ScopeSchema, ImportHandoffSchema;
13154
+ var HANDOFF_ENV, NonEmpty, TokensSchema, ExtractionSchema, GenerationSchema, ImportHandoffSchema;
12508
13155
  var init_handoff = __esm({
12509
13156
  "packages/experience-design-system-types/dist/src/handoff/index.js"() {
12510
13157
  "use strict";
@@ -12529,33 +13176,42 @@ var init_handoff = __esm({
12529
13176
  /** The only phases the scope gate can start from. */
12530
13177
  compositionPhase: z5.enum(["done", "cache-hit"])
12531
13178
  });
12532
- ScopeSchema = z5.object({
12533
- /** The components the user kept at the scope gate. The wizard saves these, then generates them. */
12534
- accepted: z5.array(z5.string()),
12535
- /** Everything else at the gate, which counts as rejected. */
12536
- rejected: z5.array(z5.string()),
12537
- /** Slot edges the user removed at the gate. The child stays accepted; only that parent stops allowing it. */
12538
- excludedSlotEdges: z5._default(z5.array(z5.object({ parent: z5.string(), child: z5.string() })), []),
12539
- /**
12540
- * Components the generation cache already holds, found by the check that ran while the gate was open and which has
12541
- * finished (and restored them) before the wizard starts. Empty when the cache is off or the check failed.
12542
- */
12543
- cachedNames: z5.array(z5.string())
12544
- });
13179
+ GenerationSchema = z5.discriminatedUnion("route", [
13180
+ /** At least one component was accepted: the definitions were generated and the wizard opens the review screen. */
13181
+ z5.object({
13182
+ route: z5.literal("review"),
13183
+ /** The session the generated definitions are in. The review screen opens it, and saving and pushing read it. */
13184
+ sessionId: NonEmpty,
13185
+ /** How many components the user accepted at the scope gate. */
13186
+ acceptedCount: z5.number(),
13187
+ /** How many definitions were generated, which can differ from the accepted count. */
13188
+ generatedCount: z5.number(),
13189
+ /**
13190
+ * Whether token mapping was worth running (there were design props that are tokens, and tokens to map them from).
13191
+ * The step count the wizard shows depends on it.
13192
+ */
13193
+ mapTokensEligible: z5.boolean()
13194
+ }),
13195
+ /** Nothing was accepted: nothing is generated and the wizard goes straight to the push flow, as it always did. */
13196
+ z5.object({ route: z5.literal("push"), acceptedCount: z5.literal(0) })
13197
+ ]);
12545
13198
  ImportHandoffSchema = z5.object({
12546
13199
  /** The user skipped the credentials screen, so nothing is fetched from or pushed to Contentful. */
12547
13200
  credentialsSkipped: z5.boolean(),
12548
13201
  tokens: TokensSchema,
12549
13202
  /** Present once the CLI has run the extraction stage; the wizard then starts at the scope gate. */
12550
13203
  extraction: z5.optional(ExtractionSchema),
12551
- /** Present once the user has confirmed the scope gate; the wizard then saves the decisions and starts generating. */
12552
- scope: z5.optional(ScopeSchema)
13204
+ /**
13205
+ * Present once the CLI has shown the scope gate, saved the decisions and generated the definitions; the wizard then
13206
+ * starts at the review screen (or goes straight to pushing when nothing was accepted).
13207
+ */
13208
+ generation: z5.optional(GenerationSchema)
12553
13209
  });
12554
13210
  }
12555
13211
  });
12556
13212
 
12557
13213
  // packages/experience-design-system-cli/src/tui/import/spawn-v1-import.ts
12558
- import { spawn as spawn9 } from "node:child_process";
13214
+ import { spawn as spawn10 } from "node:child_process";
12559
13215
  function buildArgs2(options) {
12560
13216
  const args = ["import"];
12561
13217
  if (options.projectPath) {
@@ -12574,7 +13230,7 @@ async function spawnV1Import(options = {}) {
12574
13230
  const cliPath = findLegacyCliPath();
12575
13231
  const args = buildArgs2(options);
12576
13232
  return new Promise((resolvePromise) => {
12577
- const child = spawn9("node", [cliPath, ...args], {
13233
+ const child = spawn10("node", [cliPath, ...args], {
12578
13234
  stdio: "inherit",
12579
13235
  env: buildEnv(options)
12580
13236
  });
@@ -12600,7 +13256,7 @@ function getTerminalHandle() {
12600
13256
  return process.stdin._handle;
12601
13257
  }
12602
13258
  async function stopReadingTerminal() {
12603
- await new Promise((resolve10) => setImmediate(resolve10));
13259
+ await new Promise((resolve12) => setImmediate(resolve12));
12604
13260
  const handle = getTerminalHandle();
12605
13261
  if (!handle?.readStop) return;
12606
13262
  handle.reading = false;
@@ -12638,9 +13294,9 @@ var init_debug_mode_store = __esm({
12638
13294
  });
12639
13295
 
12640
13296
  // packages/experience-design-system-cli/src/tui/debug-store.ts
12641
- import { mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
13297
+ import { mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
12642
13298
  import { existsSync as existsSync6, readdirSync as readdirSync2 } from "node:fs";
12643
- import { join as join13 } from "node:path";
13299
+ import { join as join14 } from "node:path";
12644
13300
  function generateRunId() {
12645
13301
  const now = /* @__PURE__ */ new Date();
12646
13302
  const pad = (n) => String(n).padStart(2, "0");
@@ -12665,7 +13321,7 @@ function generateSessionId3() {
12665
13321
  return `${today}-session-${maxSeq + 1}`;
12666
13322
  }
12667
13323
  function sessionDebugDir() {
12668
- return join13(debugSessionsDir2(), SESSION_ID);
13324
+ return join14(debugSessionsDir2(), SESSION_ID);
12669
13325
  }
12670
13326
  function currentDebugSessionDir() {
12671
13327
  return sessionDebugDir();
@@ -12710,10 +13366,10 @@ async function finishDebugRun({
12710
13366
  const durationMs = Date.now() - run2.startedAt;
12711
13367
  const content = renderMarkdown(run2, { outputs: redact(outputs), status, exitMethod, durationMs });
12712
13368
  const flowSegments = run2.flow.split("/");
12713
- const dir = join13(sessionDebugDir(), ...flowSegments);
12714
- await mkdir3(dir, { recursive: true });
13369
+ const dir = join14(sessionDebugDir(), ...flowSegments);
13370
+ await mkdir4(dir, { recursive: true });
12715
13371
  const filename = nextAttemptFilename(dir, run2.menuOption);
12716
- await writeFile3(join13(dir, filename), content, { mode: 384 });
13372
+ await writeFile4(join14(dir, filename), content, { mode: 384 });
12717
13373
  }
12718
13374
  function nextAttemptFilename(dir, menuOption) {
12719
13375
  const today = datePrefix();
@@ -12767,7 +13423,7 @@ var init_debug_store = __esm({
12767
13423
  SESSION_ID = generateSessionId3();
12768
13424
  void isDebugModeEnabled().then((enabled) => {
12769
13425
  if (!enabled) return void 0;
12770
- return mkdir3(sessionDebugDir(), { recursive: true });
13426
+ return mkdir4(sessionDebugDir(), { recursive: true });
12771
13427
  });
12772
13428
  process.once("uncaughtException", (err) => {
12773
13429
  void handleCrash().finally(() => {
@@ -12819,21 +13475,21 @@ var init_help_info = __esm({
12819
13475
  });
12820
13476
 
12821
13477
  // packages/experience-design-system-cli/src/tui/help/PageContainer.tsx
12822
- import { useEffect as useEffect9, useState as useState14 } from "react";
13478
+ import { useEffect as useEffect10, useState as useState15 } from "react";
12823
13479
  import { Box as Box21, Text as Text23, useInput as useInput9 } from "ink";
12824
- import { Fragment as Fragment5, jsx as jsx25, jsxs as jsxs22 } from "react/jsx-runtime";
13480
+ import { Fragment as Fragment5, jsx as jsx26, jsxs as jsxs22 } from "react/jsx-runtime";
12825
13481
  function Section({ title, rows }) {
12826
13482
  return /* @__PURE__ */ jsxs22(Box21, { flexDirection: "column", children: [
12827
- /* @__PURE__ */ jsx25(Text23, { bold: true, color: PALETTE.accent, children: title }),
13483
+ /* @__PURE__ */ jsx26(Text23, { bold: true, color: PALETTE.accent, children: title }),
12828
13484
  rows.map((row) => /* @__PURE__ */ jsxs22(Box21, { gap: 1, children: [
12829
- /* @__PURE__ */ jsx25(Box21, { width: 14, flexShrink: 0, children: /* @__PURE__ */ jsx25(Text23, { color: PALETTE.muted, children: row.label }) }),
12830
- /* @__PURE__ */ jsx25(Text23, { children: row.value })
13485
+ /* @__PURE__ */ jsx26(Box21, { width: 14, flexShrink: 0, children: /* @__PURE__ */ jsx26(Text23, { color: PALETTE.muted, children: row.label }) }),
13486
+ /* @__PURE__ */ jsx26(Text23, { children: row.value })
12831
13487
  ] }, row.label))
12832
13488
  ] });
12833
13489
  }
12834
13490
  function HelpScreen({ onDone }) {
12835
- const [info, setInfo] = useState14();
12836
- useEffect9(() => {
13491
+ const [info, setInfo] = useState15();
13492
+ useEffect10(() => {
12837
13493
  startDebugRun({ flow: "help", step: "01-help", menuOption: "Help", inputs: {} });
12838
13494
  void readHelpInfo().then(setInfo);
12839
13495
  }, []);
@@ -12852,13 +13508,13 @@ function HelpScreen({ onDone }) {
12852
13508
  }
12853
13509
  });
12854
13510
  return /* @__PURE__ */ jsxs22(Box21, { flexDirection: "column", paddingX: 2, paddingY: 1, gap: 1, children: [
12855
- /* @__PURE__ */ jsx25(Text23, { bold: true, children: "Help" }),
13511
+ /* @__PURE__ */ jsx26(Text23, { bold: true, children: "Help" }),
12856
13512
  info ? /* @__PURE__ */ jsxs22(Fragment5, { children: [
12857
- /* @__PURE__ */ jsx25(Section, { title: "Where things are stored", rows: info.storage }),
12858
- /* @__PURE__ */ jsx25(Section, { title: "Troubleshooting", rows: info.troubleshooting }),
12859
- /* @__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." })
12860
- ] }) : /* @__PURE__ */ jsx25(Text23, { color: PALETTE.accent, children: "Loading..." }),
12861
- /* @__PURE__ */ jsx25(
13513
+ /* @__PURE__ */ jsx26(Section, { title: "Where things are stored", rows: info.storage }),
13514
+ /* @__PURE__ */ jsx26(Section, { title: "Troubleshooting", rows: info.troubleshooting }),
13515
+ /* @__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." })
13516
+ ] }) : /* @__PURE__ */ jsx26(Text23, { color: PALETTE.accent, children: "Loading..." }),
13517
+ /* @__PURE__ */ jsx26(
12862
13518
  ControlHints,
12863
13519
  {
12864
13520
  hints: [
@@ -12880,14 +13536,14 @@ var init_PageContainer2 = __esm({
12880
13536
  });
12881
13537
 
12882
13538
  // packages/experience-design-system-cli/src/tui/settings/PageContainer.tsx
12883
- import { useState as useState15 } from "react";
13539
+ import { useState as useState16 } from "react";
12884
13540
  import { Box as Box22, Text as Text24, useInput as useInput10 } from "ink";
12885
- import { jsx as jsx26, jsxs as jsxs23 } from "react/jsx-runtime";
13541
+ import { jsx as jsx27, jsxs as jsxs23 } from "react/jsx-runtime";
12886
13542
  function SettingsScreen({
12887
13543
  onNavigate,
12888
13544
  onBack
12889
13545
  }) {
12890
- const [focusIdx, setFocusIdx] = useState15(0);
13546
+ const [focusIdx, setFocusIdx] = useState16(0);
12891
13547
  const items = [
12892
13548
  { label: "Configuration", screen: "settings-configuration" },
12893
13549
  { label: "Opt-in Analytics", screen: "settings-opt-in-analytics" },
@@ -12914,14 +13570,14 @@ function SettingsScreen({
12914
13570
  }
12915
13571
  });
12916
13572
  return /* @__PURE__ */ jsxs23(Box22, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
12917
- /* @__PURE__ */ jsx26(Text24, { bold: true, children: "Settings" }),
12918
- /* @__PURE__ */ jsx26(Text24, { children: " " }),
13573
+ /* @__PURE__ */ jsx27(Text24, { bold: true, children: "Settings" }),
13574
+ /* @__PURE__ */ jsx27(Text24, { children: " " }),
12919
13575
  items.map((item, i) => /* @__PURE__ */ jsxs23(Text24, { color: i === focusIdx ? "cyan" : void 0, children: [
12920
13576
  i === focusIdx ? "> " : " ",
12921
13577
  item.label
12922
13578
  ] }, item.label)),
12923
- /* @__PURE__ */ jsx26(Text24, { children: " " }),
12924
- /* @__PURE__ */ jsx26(
13579
+ /* @__PURE__ */ jsx27(Text24, { children: " " }),
13580
+ /* @__PURE__ */ jsx27(
12925
13581
  ControlHints,
12926
13582
  {
12927
13583
  hints: [
@@ -12982,10 +13638,10 @@ var init_config_store = __esm({
12982
13638
  });
12983
13639
 
12984
13640
  // packages/experience-design-system-cli/src/tui/settings/contentful-configuration/ContentfulConfigScreen.tsx
12985
- import { useEffect as useEffect10, useState as useState16 } from "react";
13641
+ import { useEffect as useEffect11, useState as useState17 } from "react";
12986
13642
  import { Box as Box23, Text as Text25, useInput as useInput11 } from "ink";
12987
13643
  import TextInput4 from "ink-text-input";
12988
- import { Fragment as Fragment6, jsx as jsx27, jsxs as jsxs24 } from "react/jsx-runtime";
13644
+ import { Fragment as Fragment6, jsx as jsx28, jsxs as jsxs24 } from "react/jsx-runtime";
12989
13645
  function debugFields(config) {
12990
13646
  return {
12991
13647
  space_id: config?.spaceId ?? "",
@@ -12997,14 +13653,14 @@ function debugFields(config) {
12997
13653
  };
12998
13654
  }
12999
13655
  function ConfigurationScreen({ onDone }) {
13000
- const [stage, setStage] = useState16("loading");
13001
- const [config, setConfig] = useState16(null);
13002
- const [activeField, setActiveField] = useState16("spaceId");
13003
- const [notice, setNotice] = useState16(null);
13004
- const [lastSaved, setLastSaved] = useState16(null);
13005
- const [editing, setEditing] = useState16(false);
13006
- const [valueBeforeEdit, setValueBeforeEdit] = useState16("");
13007
- useEffect10(() => {
13656
+ const [stage, setStage] = useState17("loading");
13657
+ const [config, setConfig] = useState17(null);
13658
+ const [activeField, setActiveField] = useState17("spaceId");
13659
+ const [notice, setNotice] = useState17(null);
13660
+ const [lastSaved, setLastSaved] = useState17(null);
13661
+ const [editing, setEditing] = useState17(false);
13662
+ const [valueBeforeEdit, setValueBeforeEdit] = useState17("");
13663
+ useEffect11(() => {
13008
13664
  readCredentials().then((cfg) => {
13009
13665
  setConfig(cfg);
13010
13666
  setStage("form");
@@ -13082,25 +13738,25 @@ function ConfigurationScreen({ onDone }) {
13082
13738
  });
13083
13739
  if (stage === "loading") {
13084
13740
  return /* @__PURE__ */ jsxs24(Box23, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
13085
- /* @__PURE__ */ jsx27(Text25, { bold: true, children: "Configuration" }),
13086
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
13087
- /* @__PURE__ */ jsx27(Text25, { color: PALETTE.accent, children: "Loading..." })
13741
+ /* @__PURE__ */ jsx28(Text25, { bold: true, children: "Configuration" }),
13742
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
13743
+ /* @__PURE__ */ jsx28(Text25, { color: PALETTE.accent, children: "Loading..." })
13088
13744
  ] });
13089
13745
  }
13090
13746
  return /* @__PURE__ */ jsxs24(Box23, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
13091
- /* @__PURE__ */ jsx27(Text25, { bold: true, children: "Configuration" }),
13092
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
13093
- /* @__PURE__ */ jsx27(Box23, { flexDirection: "column", children: FIELD_ORDER.map((field) => {
13747
+ /* @__PURE__ */ jsx28(Text25, { bold: true, children: "Configuration" }),
13748
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
13749
+ /* @__PURE__ */ jsx28(Box23, { flexDirection: "column", children: FIELD_ORDER.map((field) => {
13094
13750
  const isActive = activeField === field;
13095
13751
  const value = fieldValue(field);
13096
13752
  const display = field === "cmaToken" ? "\u2022".repeat(value.length) : value;
13097
13753
  return /* @__PURE__ */ jsxs24(Box23, { gap: 1, children: [
13098
- /* @__PURE__ */ jsx27(Text25, { color: isActive ? PALETTE.accent : void 0, children: isActive ? "\u276F" : " " }),
13754
+ /* @__PURE__ */ jsx28(Text25, { color: isActive ? PALETTE.accent : void 0, children: isActive ? "\u276F" : " " }),
13099
13755
  /* @__PURE__ */ jsxs24(Text25, { bold: isActive, children: [
13100
13756
  FIELD_LABELS[field],
13101
13757
  ":"
13102
13758
  ] }),
13103
- isActive && editing ? /* @__PURE__ */ jsx27(
13759
+ isActive && editing ? /* @__PURE__ */ jsx28(
13104
13760
  TextInput4,
13105
13761
  {
13106
13762
  value,
@@ -13108,19 +13764,19 @@ function ConfigurationScreen({ onDone }) {
13108
13764
  onSubmit: () => setEditing(false),
13109
13765
  mask: field === "cmaToken" ? "\u2022" : void 0
13110
13766
  }
13111
- ) : /* @__PURE__ */ jsx27(Text25, { children: display || /* @__PURE__ */ jsx27(Text25, { color: PALETTE.muted, children: "(empty)" }) })
13767
+ ) : /* @__PURE__ */ jsx28(Text25, { children: display || /* @__PURE__ */ jsx28(Text25, { color: PALETTE.muted, children: "(empty)" }) })
13112
13768
  ] }, field);
13113
13769
  }) }),
13114
13770
  notice && /* @__PURE__ */ jsxs24(Fragment6, { children: [
13115
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
13771
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
13116
13772
  /* @__PURE__ */ jsxs24(Text25, { color: notice.kind === "success" ? PALETTE.success : PALETTE.error, children: [
13117
13773
  notice.kind === "success" ? "\u2713" : "\u2717",
13118
13774
  " ",
13119
13775
  notice.text
13120
13776
  ] })
13121
13777
  ] }),
13122
- /* @__PURE__ */ jsx27(Text25, { children: " " }),
13123
- /* @__PURE__ */ jsx27(
13778
+ /* @__PURE__ */ jsx28(Text25, { children: " " }),
13779
+ /* @__PURE__ */ jsx28(
13124
13780
  ControlHints,
13125
13781
  {
13126
13782
  hints: editing ? [
@@ -13188,13 +13844,13 @@ var init_analytics_store = __esm({
13188
13844
  });
13189
13845
 
13190
13846
  // packages/experience-design-system-cli/src/tui/settings/opt-in-analytics/screen.tsx
13191
- import { useEffect as useEffect11, useState as useState17 } from "react";
13847
+ import { useEffect as useEffect12, useState as useState18 } from "react";
13192
13848
  import { Box as Box24, Text as Text26, useInput as useInput12 } from "ink";
13193
- import { Fragment as Fragment7, jsx as jsx28, jsxs as jsxs25 } from "react/jsx-runtime";
13849
+ import { Fragment as Fragment7, jsx as jsx29, jsxs as jsxs25 } from "react/jsx-runtime";
13194
13850
  function OptInAnalyticsScreen({ onDone }) {
13195
- const [loading, setLoading] = useState17(true);
13196
- const [enabled, setEnabled] = useState17(true);
13197
- useEffect11(() => {
13851
+ const [loading, setLoading] = useState18(true);
13852
+ const [enabled, setEnabled] = useState18(true);
13853
+ useEffect12(() => {
13198
13854
  readAnalyticsSetting().then((setting) => {
13199
13855
  setEnabled(setting.enabled);
13200
13856
  setLoading(false);
@@ -13222,20 +13878,20 @@ function OptInAnalyticsScreen({ onDone }) {
13222
13878
  }
13223
13879
  });
13224
13880
  return /* @__PURE__ */ jsxs25(Box24, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
13225
- /* @__PURE__ */ jsx28(Text26, { bold: true, children: "Settings \u203A Opt-in Analytics" }),
13226
- /* @__PURE__ */ jsx28(Text26, { children: " " }),
13227
- loading ? /* @__PURE__ */ jsx28(Text26, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs25(Fragment7, { children: [
13881
+ /* @__PURE__ */ jsx29(Text26, { bold: true, children: "Settings \u203A Opt-in Analytics" }),
13882
+ /* @__PURE__ */ jsx29(Text26, { children: " " }),
13883
+ loading ? /* @__PURE__ */ jsx29(Text26, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs25(Fragment7, { children: [
13228
13884
  /* @__PURE__ */ jsxs25(Text26, { children: [
13229
13885
  "Share anonymous usage data:",
13230
13886
  " ",
13231
- /* @__PURE__ */ jsx28(Text26, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
13887
+ /* @__PURE__ */ jsx29(Text26, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
13232
13888
  ] }),
13233
- /* @__PURE__ */ jsx28(Text26, { children: " " }),
13234
- /* @__PURE__ */ jsx28(Text26, { color: PALETTE.muted, children: "Shares which CLI commands are used and where imports succeed or fail." }),
13235
- /* @__PURE__ */ jsx28(Text26, { color: PALETTE.muted, children: "Never includes source code, file paths, credentials, or authored content." })
13889
+ /* @__PURE__ */ jsx29(Text26, { children: " " }),
13890
+ /* @__PURE__ */ jsx29(Text26, { color: PALETTE.muted, children: "Shares which CLI commands are used and where imports succeed or fail." }),
13891
+ /* @__PURE__ */ jsx29(Text26, { color: PALETTE.muted, children: "Never includes source code, file paths, credentials, or authored content." })
13236
13892
  ] }),
13237
- /* @__PURE__ */ jsx28(Text26, { children: " " }),
13238
- /* @__PURE__ */ jsx28(
13893
+ /* @__PURE__ */ jsx29(Text26, { children: " " }),
13894
+ /* @__PURE__ */ jsx29(
13239
13895
  ControlHints,
13240
13896
  {
13241
13897
  hints: [
@@ -13246,7 +13902,7 @@ function OptInAnalyticsScreen({ onDone }) {
13246
13902
  )
13247
13903
  ] });
13248
13904
  }
13249
- var init_screen8 = __esm({
13905
+ var init_screen9 = __esm({
13250
13906
  "packages/experience-design-system-cli/src/tui/settings/opt-in-analytics/screen.tsx"() {
13251
13907
  "use strict";
13252
13908
  init_home_theme();
@@ -13257,12 +13913,12 @@ var init_screen8 = __esm({
13257
13913
  });
13258
13914
 
13259
13915
  // packages/experience-design-system-cli/src/tui/upgrade/PageContainer.tsx
13260
- import { useEffect as useEffect12, useState as useState18 } from "react";
13916
+ import { useEffect as useEffect13, useState as useState19 } from "react";
13261
13917
  import { Box as Box25, Text as Text27, useInput as useInput13 } from "ink";
13262
- import { jsx as jsx29, jsxs as jsxs26 } from "react/jsx-runtime";
13918
+ import { jsx as jsx30, jsxs as jsxs26 } from "react/jsx-runtime";
13263
13919
  function UpgradeScreen({ onDone }) {
13264
- const [upgradeCheck, setUpgradeCheck] = useState18();
13265
- useEffect12(() => {
13920
+ const [upgradeCheck, setUpgradeCheck] = useState19();
13921
+ useEffect13(() => {
13266
13922
  startDebugRun({
13267
13923
  flow: "upgrade",
13268
13924
  step: "01-upgrade",
@@ -13283,10 +13939,10 @@ function UpgradeScreen({ onDone }) {
13283
13939
  }
13284
13940
  });
13285
13941
  return /* @__PURE__ */ jsxs26(Box25, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
13286
- /* @__PURE__ */ jsx29(Text27, { bold: true, children: "Upgrade" }),
13287
- /* @__PURE__ */ jsx29(Text27, { children: " " }),
13942
+ /* @__PURE__ */ jsx30(Text27, { bold: true, children: "Upgrade" }),
13943
+ /* @__PURE__ */ jsx30(Text27, { children: " " }),
13288
13944
  renderBody(upgradeCheck),
13289
- /* @__PURE__ */ jsx29(Text27, { children: " " }),
13945
+ /* @__PURE__ */ jsx30(Text27, { children: " " }),
13290
13946
  /* @__PURE__ */ jsxs26(Text27, { bold: true, color: PALETTE.accent, children: [
13291
13947
  FOCUS_MARKER,
13292
13948
  " Go Back"
@@ -13295,10 +13951,10 @@ function UpgradeScreen({ onDone }) {
13295
13951
  }
13296
13952
  function renderBody(upgradeCheck) {
13297
13953
  if (!upgradeCheck) {
13298
- return /* @__PURE__ */ jsx29(Text27, { color: PALETTE.muted, children: "Checking for updates\u2026" });
13954
+ return /* @__PURE__ */ jsx30(Text27, { color: PALETTE.muted, children: "Checking for updates\u2026" });
13299
13955
  }
13300
13956
  if (upgradeCheck.status === "error") {
13301
- return /* @__PURE__ */ jsx29(Text27, { color: PALETTE.warning, children: "Couldn't check for updates \u2014 check your network connection and try again." });
13957
+ return /* @__PURE__ */ jsx30(Text27, { color: PALETTE.warning, children: "Couldn't check for updates \u2014 check your network connection and try again." });
13302
13958
  }
13303
13959
  if (upgradeCheck.status === "up-to-date") {
13304
13960
  return /* @__PURE__ */ jsxs26(Text27, { color: PALETTE.success, children: [
@@ -13321,8 +13977,8 @@ function renderBody(upgradeCheck) {
13321
13977
  ] }),
13322
13978
  "). Exit this program, cd into the root of your local clone of contentful/experience-design-system-sdk-public, then run:"
13323
13979
  ] }),
13324
- /* @__PURE__ */ jsx29(Text27, { children: " " }),
13325
- /* @__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)) })
13980
+ /* @__PURE__ */ jsx30(Text27, { children: " " }),
13981
+ /* @__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)) })
13326
13982
  ] });
13327
13983
  }
13328
13984
  var UPGRADE_COMMANDS;
@@ -13337,13 +13993,13 @@ var init_PageContainer4 = __esm({
13337
13993
  });
13338
13994
 
13339
13995
  // packages/experience-design-system-cli/src/tui/settings/debug-mode/screen.tsx
13340
- import { useEffect as useEffect13, useState as useState19 } from "react";
13996
+ import { useEffect as useEffect14, useState as useState20 } from "react";
13341
13997
  import { Box as Box26, Text as Text28, useInput as useInput14 } from "ink";
13342
- import { jsx as jsx30, jsxs as jsxs27 } from "react/jsx-runtime";
13998
+ import { jsx as jsx31, jsxs as jsxs27 } from "react/jsx-runtime";
13343
13999
  function DebugModeScreen({ onDone }) {
13344
- const [loading, setLoading] = useState19(true);
13345
- const [enabled, setEnabled] = useState19(true);
13346
- useEffect13(() => {
14000
+ const [loading, setLoading] = useState20(true);
14001
+ const [enabled, setEnabled] = useState20(true);
14002
+ useEffect14(() => {
13347
14003
  readDebugModeSetting().then((setting) => {
13348
14004
  setEnabled(setting.enabled);
13349
14005
  setLoading(false);
@@ -13371,15 +14027,15 @@ function DebugModeScreen({ onDone }) {
13371
14027
  }
13372
14028
  });
13373
14029
  return /* @__PURE__ */ jsxs27(Box26, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
13374
- /* @__PURE__ */ jsx30(Text28, { bold: true, children: "Settings \u203A Debug Mode" }),
13375
- /* @__PURE__ */ jsx30(Text28, { children: " " }),
13376
- loading ? /* @__PURE__ */ jsx30(Text28, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs27(Text28, { children: [
14030
+ /* @__PURE__ */ jsx31(Text28, { bold: true, children: "Settings \u203A Debug Mode" }),
14031
+ /* @__PURE__ */ jsx31(Text28, { children: " " }),
14032
+ loading ? /* @__PURE__ */ jsx31(Text28, { color: PALETTE.muted, children: "Loading\u2026" }) : /* @__PURE__ */ jsxs27(Text28, { children: [
13377
14033
  "Debug logging:",
13378
14034
  " ",
13379
- /* @__PURE__ */ jsx30(Text28, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
14035
+ /* @__PURE__ */ jsx31(Text28, { bold: true, color: enabled ? PALETTE.success : PALETTE.muted, children: enabled ? "On" : "Off" })
13380
14036
  ] }),
13381
- /* @__PURE__ */ jsx30(Text28, { children: " " }),
13382
- /* @__PURE__ */ jsx30(
14037
+ /* @__PURE__ */ jsx31(Text28, { children: " " }),
14038
+ /* @__PURE__ */ jsx31(
13383
14039
  ControlHints,
13384
14040
  {
13385
14041
  hints: [
@@ -13390,7 +14046,7 @@ function DebugModeScreen({ onDone }) {
13390
14046
  )
13391
14047
  ] });
13392
14048
  }
13393
- var init_screen9 = __esm({
14049
+ var init_screen10 = __esm({
13394
14050
  "packages/experience-design-system-cli/src/tui/settings/debug-mode/screen.tsx"() {
13395
14051
  "use strict";
13396
14052
  init_home_theme();
@@ -13405,20 +14061,20 @@ var app_exports = {};
13405
14061
  __export(app_exports, {
13406
14062
  runApp: () => runApp
13407
14063
  });
13408
- import { join as join14 } from "node:path";
13409
- import { useEffect as useEffect14, useState as useState20 } from "react";
13410
- import { Fragment as Fragment8, jsx as jsx31 } from "react/jsx-runtime";
14064
+ import { join as join15 } from "node:path";
14065
+ import { useEffect as useEffect15, useState as useState21 } from "react";
14066
+ import { Fragment as Fragment8, jsx as jsx32 } from "react/jsx-runtime";
13411
14067
  function App({ importOptions, onLaunchImport, importExitCode }) {
13412
14068
  const returnedFromImport = importExitCode !== void 0;
13413
- const [screen, setScreen] = useState20(returnedFromImport ? "import" : "start");
13414
- const [showImportResult, setShowImportResult] = useState20(returnedFromImport);
13415
- const [projectPath, setProjectPath] = useState20();
13416
- const [tokensPath, setTokensPath] = useState20();
13417
- const [scannedFiles, setScannedFiles] = useState20();
13418
- const [pendingLaunch, setPendingLaunch] = useState20();
13419
- const [extractionRun, setExtractionRun] = useState20();
14069
+ const [screen, setScreen] = useState21(returnedFromImport ? "import" : "start");
14070
+ const [showImportResult, setShowImportResult] = useState21(returnedFromImport);
14071
+ const [projectPath, setProjectPath] = useState21();
14072
+ const [tokensPath, setTokensPath] = useState21();
14073
+ const [scannedFiles, setScannedFiles] = useState21();
14074
+ const [pendingLaunch, setPendingLaunch] = useState21();
14075
+ const [extractionRun, setExtractionRun] = useState21();
13420
14076
  const extraction = useExtraction(extractionRun?.input);
13421
- const [scopeRun, setScopeRun] = useState20();
14077
+ const [scopeRun, setScopeRun] = useState21();
13422
14078
  const scopeFlow = useScopeGateFlow(
13423
14079
  scopeRun && {
13424
14080
  sessionId: scopeRun.extraction.sessionId,
@@ -13433,8 +14089,10 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13433
14089
  }
13434
14090
  }
13435
14091
  );
13436
- const [importDefaults, setImportDefaults] = useState20();
13437
- useEffect14(() => {
14092
+ const [generationInput, setGenerationInput] = useState21();
14093
+ const generation = useGeneration(generationInput);
14094
+ const [importDefaults, setImportDefaults] = useState21();
14095
+ useEffect15(() => {
13438
14096
  if (screen !== "import") {
13439
14097
  setImportDefaults(void 0);
13440
14098
  return;
@@ -13452,7 +14110,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13452
14110
  const launch = { projectPath: projectPath2, tokens, filePaths, ...importOptions };
13453
14111
  const state = await inspectTokens({
13454
14112
  rawTokensPath: tokens,
13455
- outDir: join14(resolveUserPath(projectPath2), ".contentful"),
14113
+ outDir: join15(resolveUserPath(projectPath2), ".contentful"),
13456
14114
  cache: importOptions.cache
13457
14115
  });
13458
14116
  if (state.kind === "cached") {
@@ -13470,8 +14128,11 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13470
14128
  void startExtraction(pending.launch, tokenStrategy, pending.credentials);
13471
14129
  };
13472
14130
  const startExtraction = async (launch, tokenStrategy, credentials) => {
13473
- const { agent, agentModel } = resolveAgentChoice(launch.agent, await readSettings2());
14131
+ const settings = await readSettings2();
14132
+ const { agent, agentModel } = resolveAgentChoice(launch.agent, settings);
14133
+ const generatePromptPath = typeof settings.generatePromptPath === "string" ? settings.generatePromptPath : void 0;
13474
14134
  setExtractionRun({
14135
+ ...generatePromptPath ? { generatePromptPath } : {},
13475
14136
  // the wizard gets the same agent, so its later steps use what the stage used
13476
14137
  launch: { ...launch, agent: agentModel ? `${agent}:${agentModel}` : agent },
13477
14138
  credentialsSkipped: credentials.skipped,
@@ -13488,25 +14149,44 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13488
14149
  }
13489
14150
  });
13490
14151
  };
13491
- useEffect14(() => {
14152
+ useEffect15(() => {
13492
14153
  if (!extractionRun || extraction?.status !== "done" || !extraction.result.ok) return;
13493
14154
  setExtractionRun(void 0);
13494
14155
  setScopeRun({ ...extractionRun, extraction: extraction.result.extraction });
13495
14156
  }, [extraction, extractionRun]);
13496
- useEffect14(() => {
13497
- if (!scopeRun || scopeFlow?.status !== "confirmed") return;
14157
+ useEffect15(() => {
14158
+ if (!scopeRun || scopeFlow?.status !== "confirmed" || generationInput) return;
14159
+ const { extraction: produced, input, generatePromptPath } = scopeRun;
14160
+ setGenerationInput({
14161
+ sessionId: produced.sessionId,
14162
+ decisions: scopeFlow.decisions,
14163
+ cachedNames: scopeFlow.cachedNames,
14164
+ tokensPath: produced.tokensPath,
14165
+ tokenSessionId: produced.tokenSessionId,
14166
+ existingEntitiesPath: produced.existingEntitiesPath,
14167
+ agent: input.agent,
14168
+ ...input.agentModel ? { agentModel: input.agentModel } : {},
14169
+ promptOverrides: input.promptOverrides,
14170
+ noCache: input.noCache,
14171
+ hasTokens: produced.tokensPath !== "",
14172
+ ...generatePromptPath ? { generatePromptPath } : {}
14173
+ });
14174
+ }, [scopeFlow, scopeRun, generationInput]);
14175
+ useEffect15(() => {
14176
+ if (!scopeRun || generation?.status !== "done" || !generation.result.ok) return;
13498
14177
  const { launch, credentialsSkipped, tokenStrategy, extraction: produced } = scopeRun;
13499
14178
  setScopeRun(void 0);
14179
+ setGenerationInput(void 0);
13500
14180
  onLaunchImport?.({
13501
14181
  ...launch,
13502
14182
  handoff: {
13503
14183
  credentialsSkipped,
13504
14184
  tokens: { strategy: tokenStrategy },
13505
14185
  extraction: produced,
13506
- scope: scopeFlow.scope
14186
+ generation: generation.result.generation
13507
14187
  }
13508
14188
  });
13509
- }, [scopeFlow, scopeRun]);
14189
+ }, [generation, scopeRun]);
13510
14190
  const goToStart = () => setScreen("start");
13511
14191
  const goToSettings = () => setScreen("settings");
13512
14192
  const resetImport = () => {
@@ -13516,6 +14196,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13516
14196
  setPendingLaunch(void 0);
13517
14197
  setExtractionRun(void 0);
13518
14198
  setScopeRun(void 0);
14199
+ setGenerationInput(void 0);
13519
14200
  };
13520
14201
  const finishImportResult = () => {
13521
14202
  setShowImportResult(false);
@@ -13528,13 +14209,13 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13528
14209
  };
13529
14210
  switch (screen) {
13530
14211
  case "import":
13531
- if (showImportResult) return /* @__PURE__ */ jsx31(ImportScreen, { exitCode: importExitCode, onDone: finishImportResult });
13532
- if (importDefaults === void 0) return /* @__PURE__ */ jsx31(Fragment8, {});
14212
+ if (showImportResult) return /* @__PURE__ */ jsx32(ImportScreen, { exitCode: importExitCode, onDone: finishImportResult });
14213
+ if (importDefaults === void 0) return /* @__PURE__ */ jsx32(Fragment8, {});
13533
14214
  if (projectPath === void 0) {
13534
- return /* @__PURE__ */ jsx31(WelcomeScreen, { onContinue: setProjectPath, onQuit: leaveImport, initialPath: importDefaults.componentDir });
14215
+ return /* @__PURE__ */ jsx32(WelcomeScreen, { onContinue: setProjectPath, onQuit: leaveImport, initialPath: importDefaults.componentDir });
13535
14216
  }
13536
14217
  if (tokensPath === void 0) {
13537
- return /* @__PURE__ */ jsx31(
14218
+ return /* @__PURE__ */ jsx32(
13538
14219
  TokenInputScreen,
13539
14220
  {
13540
14221
  initialPath: importDefaults.tokenFile,
@@ -13544,7 +14225,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13544
14225
  );
13545
14226
  }
13546
14227
  if (scannedFiles === void 0) {
13547
- return /* @__PURE__ */ jsx31(
14228
+ return /* @__PURE__ */ jsx32(
13548
14229
  PathValidationScreen,
13549
14230
  {
13550
14231
  projectPath,
@@ -13556,10 +14237,10 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13556
14237
  }
13557
14238
  if (extractionRun) {
13558
14239
  if (extraction?.status === "done" && !extraction.result.ok) {
13559
- return /* @__PURE__ */ jsx31(ErrorStep, { stepName: extraction.result.step, message: extraction.result.message, onExit: leaveImport });
14240
+ return /* @__PURE__ */ jsx32(ErrorStep, { stepName: extraction.result.step, message: extraction.result.message, onExit: leaveImport });
13560
14241
  }
13561
14242
  if (extraction?.status === "running") {
13562
- return /* @__PURE__ */ jsx31(
14243
+ return /* @__PURE__ */ jsx32(
13563
14244
  ExtractionScreen,
13564
14245
  {
13565
14246
  progress: extraction.progress,
@@ -13568,14 +14249,14 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13568
14249
  }
13569
14250
  );
13570
14251
  }
13571
- return /* @__PURE__ */ jsx31(Fragment8, {});
14252
+ return /* @__PURE__ */ jsx32(Fragment8, {});
13572
14253
  }
13573
14254
  if (scopeRun && scopeFlow) {
13574
14255
  if (scopeFlow.status === "failed") {
13575
- return /* @__PURE__ */ jsx31(ErrorStep, { stepName: "scope gate", message: scopeFlow.message, onExit: leaveImport });
14256
+ return /* @__PURE__ */ jsx32(ErrorStep, { stepName: "scope gate", message: scopeFlow.message, onExit: leaveImport });
13576
14257
  }
13577
14258
  if (scopeFlow.status === "deciding") {
13578
- return /* @__PURE__ */ jsx31(
14259
+ return /* @__PURE__ */ jsx32(
13579
14260
  ScopeGateScreen,
13580
14261
  {
13581
14262
  components: scopeFlow.load.components,
@@ -13584,19 +14265,31 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13584
14265
  }
13585
14266
  );
13586
14267
  }
13587
- const numbers = stepNumbers({ hasRawTokens: scopeRun.input.rawTokensPath !== "" });
13588
- return /* @__PURE__ */ jsx31(
13589
- RunningStep,
13590
- {
13591
- stepNumber: numbers.stepNumber + 1,
13592
- totalSteps: numbers.totalSteps,
13593
- title: "Preparing",
13594
- description: "Checking which components are already generated..."
13595
- }
13596
- );
14268
+ if (generation?.status === "done" && !generation.result.ok) {
14269
+ return /* @__PURE__ */ jsx32(ErrorStep, { stepName: generation.result.step, message: generation.result.message, onExit: leaveImport });
14270
+ }
14271
+ if (generation?.status === "running") {
14272
+ const hasRawTokens = scopeRun.input.rawTokensPath !== "";
14273
+ const counted = stepNumbers({
14274
+ hasRawTokens,
14275
+ mapTokensEligible: generation.progress.mapTokensEligible
14276
+ });
14277
+ return /* @__PURE__ */ jsx32(
14278
+ GenerationScreen,
14279
+ {
14280
+ progress: generation.progress,
14281
+ agent: scopeRun.input.agent,
14282
+ acceptedCount: scopeFlow.decisions.accepted.length,
14283
+ hasTokens: scopeRun.extraction.tokensPath !== "",
14284
+ stepNumber: hasRawTokens ? 4 : 3,
14285
+ totalSteps: counted.totalSteps
14286
+ }
14287
+ );
14288
+ }
14289
+ return /* @__PURE__ */ jsx32(Fragment8, {});
13597
14290
  }
13598
14291
  if (pendingLaunch?.cached) {
13599
- return /* @__PURE__ */ jsx31(
14292
+ return /* @__PURE__ */ jsx32(
13600
14293
  TokenReuseScreen,
13601
14294
  {
13602
14295
  tokensPath: pendingLaunch.cached.tokensPath,
@@ -13607,7 +14300,7 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13607
14300
  }
13608
14301
  );
13609
14302
  }
13610
- return /* @__PURE__ */ jsx31(
14303
+ return /* @__PURE__ */ jsx32(
13611
14304
  CredentialsScreen,
13612
14305
  {
13613
14306
  initial: importDefaults.credentials,
@@ -13616,25 +14309,25 @@ function App({ importOptions, onLaunchImport, importExitCode }) {
13616
14309
  }
13617
14310
  );
13618
14311
  case "help":
13619
- return /* @__PURE__ */ jsx31(HelpScreen, { onDone: goToStart });
14312
+ return /* @__PURE__ */ jsx32(HelpScreen, { onDone: goToStart });
13620
14313
  case "upgrade":
13621
- return /* @__PURE__ */ jsx31(UpgradeScreen, { onDone: goToStart });
14314
+ return /* @__PURE__ */ jsx32(UpgradeScreen, { onDone: goToStart });
13622
14315
  case "settings":
13623
- return /* @__PURE__ */ jsx31(SettingsScreen, { onNavigate: setScreen, onBack: goToStart });
14316
+ return /* @__PURE__ */ jsx32(SettingsScreen, { onNavigate: setScreen, onBack: goToStart });
13624
14317
  case "settings-configuration":
13625
- return /* @__PURE__ */ jsx31(ConfigurationScreen, { onDone: goToSettings });
14318
+ return /* @__PURE__ */ jsx32(ConfigurationScreen, { onDone: goToSettings });
13626
14319
  case "settings-opt-in-analytics":
13627
- return /* @__PURE__ */ jsx31(OptInAnalyticsScreen, { onDone: goToSettings });
14320
+ return /* @__PURE__ */ jsx32(OptInAnalyticsScreen, { onDone: goToSettings });
13628
14321
  case "settings-debug-mode":
13629
- return /* @__PURE__ */ jsx31(DebugModeScreen, { onDone: goToSettings });
14322
+ return /* @__PURE__ */ jsx32(DebugModeScreen, { onDone: goToSettings });
13630
14323
  case "start":
13631
- return /* @__PURE__ */ jsx31(HomeScreen, { onNavigate: setScreen });
14324
+ return /* @__PURE__ */ jsx32(HomeScreen, { onNavigate: setScreen });
13632
14325
  }
13633
14326
  }
13634
14327
  async function renderUntilImportRequestedOrExit(renderApp, importOptions, importExitCode) {
13635
14328
  let requestedImport;
13636
14329
  const instance = renderApp(
13637
- /* @__PURE__ */ jsx31(
14330
+ /* @__PURE__ */ jsx32(
13638
14331
  App,
13639
14332
  {
13640
14333
  importOptions,
@@ -13675,6 +14368,8 @@ var init_app = __esm({
13675
14368
  init_use_extraction();
13676
14369
  init_screen7();
13677
14370
  init_use_scope_gate_flow();
14371
+ init_screen8();
14372
+ init_use_generation();
13678
14373
  init_logic8();
13679
14374
  init_resolve_user_path();
13680
14375
  init_spawn_v1_import();
@@ -13682,9 +14377,9 @@ var init_app = __esm({
13682
14377
  init_PageContainer2();
13683
14378
  init_PageContainer3();
13684
14379
  init_ContentfulConfigScreen();
13685
- init_screen8();
13686
- init_PageContainer4();
13687
14380
  init_screen9();
14381
+ init_PageContainer4();
14382
+ init_screen10();
13688
14383
  init_config_store();
13689
14384
  CLEAR_SCREEN = "\x1B[2J\x1B[H";
13690
14385
  }
@@ -13692,7 +14387,7 @@ var init_app = __esm({
13692
14387
 
13693
14388
  // packages/experience-design-system-cli/program.ts
13694
14389
  import { readFileSync as readFileSync5 } from "node:fs";
13695
- import { join as join15 } from "node:path";
14390
+ import { join as join16 } from "node:path";
13696
14391
  import { Command } from "commander";
13697
14392
 
13698
14393
  // packages/experience-design-system-cli/src/legacy/run-legacy.ts
@@ -13770,14 +14465,14 @@ function runDevWatch(args) {
13770
14465
  process.stderr.write("--watch only works from a checkout of the repo (scripts/dev.mjs is not in the package).\n");
13771
14466
  return Promise.resolve(1);
13772
14467
  }
13773
- return new Promise((resolve10) => {
14468
+ return new Promise((resolve12) => {
13774
14469
  const child = spawn2(process.execPath, [script, ...args], { stdio: "inherit" });
13775
14470
  process.on("SIGINT", () => void 0);
13776
- child.on("exit", (code) => resolve10(code ?? 0));
14471
+ child.on("exit", (code) => resolve12(code ?? 0));
13777
14472
  child.on("error", (err) => {
13778
14473
  process.stderr.write(`${err.message}
13779
14474
  `);
13780
- resolve10(1);
14475
+ resolve12(1);
13781
14476
  });
13782
14477
  });
13783
14478
  }
@@ -13802,7 +14497,7 @@ function registerImportCommand(program, openTui) {
13802
14497
  init_package_root();
13803
14498
  var pkg = JSON.parse(
13804
14499
  readFileSync5(
13805
- join15(findPackageRoot(import.meta.url, "@contentful/experience-design-system-cli"), "package.json"),
14500
+ join16(findPackageRoot(import.meta.url, "@contentful/experience-design-system-cli"), "package.json"),
13806
14501
  "utf8"
13807
14502
  )
13808
14503
  );
@@ -13821,21 +14516,21 @@ function createProgram() {
13821
14516
  init_config();
13822
14517
  init_package_root();
13823
14518
  import { existsSync as existsSync7 } from "node:fs";
13824
- import { mkdir as mkdir4, readFile as readFile6, rename as rename2, rmdir, unlink } from "node:fs/promises";
13825
- import { dirname as dirname7, join as join16 } from "node:path";
14519
+ import { mkdir as mkdir5, readFile as readFile7, rename as rename2, rmdir, unlink } from "node:fs/promises";
14520
+ import { dirname as dirname7, join as join17 } from "node:path";
13826
14521
  var PACKAGE_NAME4 = "@contentful/experience-design-system-cli";
13827
14522
  async function readJson(path5) {
13828
14523
  try {
13829
- return JSON.parse(await readFile6(path5, "utf8"));
14524
+ return JSON.parse(await readFile7(path5, "utf8"));
13830
14525
  } catch {
13831
14526
  return void 0;
13832
14527
  }
13833
14528
  }
13834
14529
  async function migrateOldConfig() {
13835
14530
  try {
13836
- const oldCredentials = join16(oldConfigDir2(), "credentials.json");
13837
- const oldRuns = join16(oldConfigDir2(), "runs.json");
13838
- const oldDebugMode = join16(
14531
+ const oldCredentials = join17(oldConfigDir2(), "credentials.json");
14532
+ const oldRuns = join17(oldConfigDir2(), "runs.json");
14533
+ const oldDebugMode = join17(
13839
14534
  findPackageRoot(import.meta.url, PACKAGE_NAME4),
13840
14535
  ".contentful",
13841
14536
  "config",
@@ -13848,7 +14543,7 @@ async function migrateOldConfig() {
13848
14543
  if (Object.keys(migrated).length > 0) await updateSettings2({ ...migrated, ...await readSettings2() });
13849
14544
  if (existsSync7(oldRuns)) {
13850
14545
  if (!existsSync7(runsFilePath2())) {
13851
- await mkdir4(dirname7(runsFilePath2()), { recursive: true });
14546
+ await mkdir5(dirname7(runsFilePath2()), { recursive: true });
13852
14547
  await rename2(oldRuns, runsFilePath2());
13853
14548
  } else {
13854
14549
  await unlink(oldRuns);