@contentful/experience-design-system-cli 2.32.1-dev-build-23e5797.0 → 2.32.1-dev-build-4052dd5.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 (24) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/index.js +570 -341
  3. package/dist/src/session/core/cdf/cdf-mappers.d.ts +3 -0
  4. package/dist/src/session/core/components/derive-component-id.d.ts +1 -0
  5. package/dist/src/session/core/components/hash-component-shape.d.ts +5 -0
  6. package/dist/src/session/core/shared/index-rows-by-key.d.ts +1 -0
  7. package/dist/src/session/core/tokens/build-dtcg-groups.d.ts +12 -0
  8. package/dist/src/session/core/tokens/build-dtcg-tokens.d.ts +3 -0
  9. package/dist/src/session/core/tokens/hash-token-content.d.ts +1 -0
  10. package/dist/src/session/db.d.ts +17 -50
  11. package/dist/src/session/repositories/sessions/read.d.ts +11 -0
  12. package/dist/src/session/repositories/sessions/write.d.ts +3 -0
  13. package/dist/src/session/repositories/shared/with-transaction.d.ts +2 -0
  14. package/dist/src/session/repositories/steps/read.d.ts +2 -0
  15. package/dist/src/session/repositories/steps/write.d.ts +5 -0
  16. package/dist/src/session/repositories/tokens/read.d.ts +15 -0
  17. package/dist/src/session/repositories/tokens/write.d.ts +16 -0
  18. package/dist/src/session/services/session-resolver.d.ts +9 -0
  19. package/dist/src/session/services/tokens/apply-tool-calls.d.ts +8 -0
  20. package/dist/src/session/services/tokens/replace-raw-prop-token-paths.d.ts +3 -0
  21. package/dist/src/session/services/tokens/replace-raw-token-name-paths.d.ts +3 -0
  22. package/dist/src/session/services/tokens/store-dtcg-tokens.d.ts +3 -0
  23. package/package.json +6 -6
  24. /package/dist/src/session/{command.d.ts → cli.d.ts} +0 -0
package/dist/src/index.js CHANGED
@@ -8472,6 +8472,230 @@ var init_terminal_capabilities = __esm({
8472
8472
  }
8473
8473
  });
8474
8474
 
8475
+ // packages/experience-design-system-cli/src/session/source-excerpt.ts
8476
+ function escapeForRegExp(value) {
8477
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8478
+ }
8479
+ function identifierPattern(name) {
8480
+ return new RegExp(`(?<![A-Za-z0-9_$])${escapeForRegExp(name)}(?![A-Za-z0-9_$])`);
8481
+ }
8482
+ function excerptAroundNames(text, names, maxChars, contextLines = 6) {
8483
+ if (text.length <= maxChars) return { content: text, usesNotShown: [] };
8484
+ const patterns = names.filter((name) => name.length > 0).map((name) => ({ name, pattern: identifierPattern(name) }));
8485
+ const lines = text.split("\n");
8486
+ const windows = [];
8487
+ lines.forEach((line, index) => {
8488
+ const mentioned = patterns.filter(({ pattern }) => pattern.test(line)).map(({ name }) => name);
8489
+ if (mentioned.length === 0) return;
8490
+ const start = Math.max(0, index - contextLines);
8491
+ const end = Math.min(lines.length - 1, index + contextLines);
8492
+ const last = windows[windows.length - 1];
8493
+ if (last && start <= last.end + 1) {
8494
+ last.end = Math.max(last.end, end);
8495
+ for (const name of mentioned) last.names.add(name);
8496
+ } else {
8497
+ windows.push({ start, end, names: new Set(mentioned) });
8498
+ }
8499
+ });
8500
+ if (windows.length === 0) {
8501
+ return { content: `${text.slice(0, maxChars)}
8502
+ ${TRUNCATED_MARKER}`, usesNotShown: [] };
8503
+ }
8504
+ const lastWindowFor = /* @__PURE__ */ new Map();
8505
+ for (const window of windows) for (const name of window.names) lastWindowFor.set(name, window);
8506
+ const kept = [];
8507
+ const cut = /* @__PURE__ */ new Set();
8508
+ let used = 0;
8509
+ for (const window of [...windows].reverse()) {
8510
+ const chunk = lines.slice(window.start, window.end + 1).join("\n");
8511
+ const separator = kept.length > 0 ? `
8512
+ ${ELLIPSIS_MARKER}
8513
+ ` : "";
8514
+ if (used + separator.length + chunk.length > maxChars) {
8515
+ if (kept.length === 0) {
8516
+ const head = chunk.slice(0, maxChars);
8517
+ kept.push({ window, text: head });
8518
+ used += head.length;
8519
+ for (const name of window.names) {
8520
+ if (lastWindowFor.get(name) === window && !identifierPattern(name).test(head)) cut.add(name);
8521
+ }
8522
+ continue;
8523
+ }
8524
+ for (const name of window.names) {
8525
+ if (lastWindowFor.get(name) === window) cut.add(name);
8526
+ }
8527
+ continue;
8528
+ }
8529
+ kept.push({ window, text: chunk });
8530
+ used += separator.length + chunk.length;
8531
+ }
8532
+ kept.sort((a, b) => a.window.start - b.window.start);
8533
+ const parts = kept.map((entry, index) => (index > 0 ? `
8534
+ ${ELLIPSIS_MARKER}
8535
+ ` : "") + entry.text);
8536
+ const usesNotShown = names.filter((name, index) => cut.has(name) && names.indexOf(name) === index);
8537
+ return { content: `${parts.join("")}
8538
+ ${TRUNCATED_MARKER}`, usesNotShown };
8539
+ }
8540
+ var ELLIPSIS_MARKER, TRUNCATED_MARKER;
8541
+ var init_source_excerpt = __esm({
8542
+ "packages/experience-design-system-cli/src/session/source-excerpt.ts"() {
8543
+ "use strict";
8544
+ ELLIPSIS_MARKER = "/* \u2026 */";
8545
+ TRUNCATED_MARKER = "/* truncated */";
8546
+ }
8547
+ });
8548
+
8549
+ // packages/experience-design-system-cli/src/session/core/components/derive-component-id.ts
8550
+ import { createHash } from "node:crypto";
8551
+ function deriveComponentId(name, source) {
8552
+ return createHash("sha256").update(`${name}:${source}`).digest("hex").slice(0, 12);
8553
+ }
8554
+ var init_derive_component_id = __esm({
8555
+ "packages/experience-design-system-cli/src/session/core/components/derive-component-id.ts"() {
8556
+ "use strict";
8557
+ }
8558
+ });
8559
+
8560
+ // packages/experience-design-system-cli/src/session/core/cdf/cdf-mappers.ts
8561
+ function mapContentfulTypeToCdfType(contentfulType) {
8562
+ switch (contentfulType.toLowerCase()) {
8563
+ case "string":
8564
+ case "text":
8565
+ return "string";
8566
+ case "richtext":
8567
+ return "richtext";
8568
+ case "media":
8569
+ return "media";
8570
+ case "link":
8571
+ return "link";
8572
+ case "enum":
8573
+ case "symbol":
8574
+ return "enum";
8575
+ case "token":
8576
+ return "token";
8577
+ case "boolean":
8578
+ return "boolean";
8579
+ default:
8580
+ return "string";
8581
+ }
8582
+ }
8583
+ function resolveCdfCategory(contentfulCategory, propName, contentProps, designProps) {
8584
+ if (contentfulCategory && VALID_CATEGORIES2.includes(contentfulCategory)) {
8585
+ return contentfulCategory;
8586
+ }
8587
+ if (contentProps.has(propName)) return "content";
8588
+ if (designProps.has(propName)) return "design";
8589
+ return "state";
8590
+ }
8591
+ var VALID_CATEGORIES2;
8592
+ var init_cdf_mappers = __esm({
8593
+ "packages/experience-design-system-cli/src/session/core/cdf/cdf-mappers.ts"() {
8594
+ "use strict";
8595
+ VALID_CATEGORIES2 = ["content", "design", "state"];
8596
+ }
8597
+ });
8598
+
8599
+ // packages/experience-design-system-cli/src/session/core/shared/index-rows-by-key.ts
8600
+ function indexRowsByKey(items, key) {
8601
+ const map = /* @__PURE__ */ new Map();
8602
+ for (const item of items) {
8603
+ const k = key(item);
8604
+ let arr = map.get(k);
8605
+ if (!arr) {
8606
+ arr = [];
8607
+ map.set(k, arr);
8608
+ }
8609
+ arr.push(item);
8610
+ }
8611
+ return map;
8612
+ }
8613
+ var init_index_rows_by_key = __esm({
8614
+ "packages/experience-design-system-cli/src/session/core/shared/index-rows-by-key.ts"() {
8615
+ "use strict";
8616
+ }
8617
+ });
8618
+
8619
+ // packages/experience-design-system-cli/src/session/repositories/sessions/read.ts
8620
+ function getSessionById(db, sessionId2) {
8621
+ const row = db.prepare("SELECT id FROM sessions WHERE id = ?").get(sessionId2);
8622
+ return row ?? null;
8623
+ }
8624
+ function getLatestCompletedSessionForCommand(db, command) {
8625
+ const row = db.prepare(
8626
+ `SELECT s.id FROM sessions s
8627
+ JOIN steps st ON st.session_id = s.id
8628
+ WHERE st.command = ? AND st.status = 'complete'
8629
+ ORDER BY st.started_at DESC, st.id DESC
8630
+ LIMIT 1`
8631
+ ).get(command);
8632
+ return row?.id ?? null;
8633
+ }
8634
+ var init_read = __esm({
8635
+ "packages/experience-design-system-cli/src/session/repositories/sessions/read.ts"() {
8636
+ "use strict";
8637
+ }
8638
+ });
8639
+
8640
+ // packages/experience-design-system-cli/src/session/repositories/sessions/write.ts
8641
+ function createSession(db, id, name, timestamp) {
8642
+ db.prepare("INSERT INTO sessions (id, name, created_at, updated_at) VALUES (?, ?, ?, ?)").run(
8643
+ id,
8644
+ name,
8645
+ timestamp,
8646
+ timestamp
8647
+ );
8648
+ }
8649
+ function updateSessionTimestamp(db, sessionId2, timestamp) {
8650
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(timestamp, sessionId2);
8651
+ }
8652
+ var init_write = __esm({
8653
+ "packages/experience-design-system-cli/src/session/repositories/sessions/write.ts"() {
8654
+ "use strict";
8655
+ }
8656
+ });
8657
+
8658
+ // packages/experience-design-system-cli/src/session/repositories/steps/read.ts
8659
+ function getSessionIdForStep(db, stepId) {
8660
+ const row = db.prepare("SELECT session_id FROM steps WHERE id = ?").get(stepId);
8661
+ return row?.session_id ?? null;
8662
+ }
8663
+ var init_read2 = __esm({
8664
+ "packages/experience-design-system-cli/src/session/repositories/steps/read.ts"() {
8665
+ "use strict";
8666
+ }
8667
+ });
8668
+
8669
+ // packages/experience-design-system-cli/src/session/repositories/steps/write.ts
8670
+ function updatePendingStepsToInterrupted(db, sessionId2, command, timestamp) {
8671
+ db.prepare(
8672
+ `UPDATE steps SET status = 'interrupted', completed_at = ?, updated_at = ?
8673
+ WHERE session_id = ? AND command = ? AND status = 'pending'`
8674
+ ).run(timestamp, timestamp, sessionId2, command);
8675
+ }
8676
+ function createPendingStep(db, sessionId2, command, inputs, timestamp) {
8677
+ const result = db.prepare(
8678
+ `INSERT INTO steps (session_id, command, status, started_at, inputs, outputs, updated_at)
8679
+ VALUES (?, ?, 'pending', ?, ?, '{}', ?)`
8680
+ ).run(sessionId2, command, timestamp, JSON.stringify(inputs), timestamp);
8681
+ return Number(result.lastInsertRowid);
8682
+ }
8683
+ function updateStepStatus(db, stepId, status, outputs, error, timestamp) {
8684
+ db.prepare(`UPDATE steps SET status = ?, completed_at = ?, outputs = ?, error = ?, updated_at = ? WHERE id = ?`).run(
8685
+ status,
8686
+ timestamp,
8687
+ JSON.stringify(outputs),
8688
+ error,
8689
+ timestamp,
8690
+ stepId
8691
+ );
8692
+ }
8693
+ var init_write2 = __esm({
8694
+ "packages/experience-design-system-cli/src/session/repositories/steps/write.ts"() {
8695
+ "use strict";
8696
+ }
8697
+ });
8698
+
8475
8699
  // packages/experience-design-system-cli/src/session/session-id.ts
8476
8700
  var session_id_exports = {};
8477
8701
  __export(session_id_exports, {
@@ -8696,77 +8920,292 @@ var init_session_id = __esm({
8696
8920
  }
8697
8921
  });
8698
8922
 
8699
- // packages/experience-design-system-cli/src/session/source-excerpt.ts
8700
- function escapeForRegExp(value) {
8701
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8923
+ // packages/experience-design-system-cli/src/session/services/session-resolver.ts
8924
+ function getOrCreateSessionForCommand(db, sessionFlag, sessionName, _hints) {
8925
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8926
+ if (sessionFlag === "new" || sessionFlag === void 0) {
8927
+ const id = generateSessionId();
8928
+ createSession(db, id, sessionName ?? null, now);
8929
+ return { sessionId: id, isNew: true, isResumed: false };
8930
+ }
8931
+ if (!getSessionById(db, sessionFlag)) {
8932
+ throw new Error(`session '${sessionFlag}' not found. Run 'session list' to see active sessions.`);
8933
+ }
8934
+ return { sessionId: sessionFlag, isNew: false, isResumed: false };
8702
8935
  }
8703
- function identifierPattern(name) {
8704
- return new RegExp(`(?<![A-Za-z0-9_$])${escapeForRegExp(name)}(?![A-Za-z0-9_$])`);
8936
+ var init_session_resolver = __esm({
8937
+ "packages/experience-design-system-cli/src/session/services/session-resolver.ts"() {
8938
+ "use strict";
8939
+ init_session_id();
8940
+ init_read();
8941
+ init_write();
8942
+ }
8943
+ });
8944
+
8945
+ // packages/experience-design-system-cli/src/session/core/tokens/build-dtcg-groups.ts
8946
+ function buildDtcgGroups(groupRows, tokenRows) {
8947
+ return groupRows.map((r) => {
8948
+ const prefix = `${r.path}.`;
8949
+ const tokenIds = tokenRows.filter((t) => t.path.startsWith(prefix) && !t.path.slice(prefix.length).includes(".")).map((t) => t.path);
8950
+ const g = { path: r.path, tokenIds };
8951
+ if (r.description !== null) g.$description = r.description;
8952
+ return g;
8953
+ });
8705
8954
  }
8706
- function excerptAroundNames(text, names, maxChars, contextLines = 6) {
8707
- if (text.length <= maxChars) return { content: text, usesNotShown: [] };
8708
- const patterns = names.filter((name) => name.length > 0).map((name) => ({ name, pattern: identifierPattern(name) }));
8709
- const lines = text.split("\n");
8710
- const windows = [];
8711
- lines.forEach((line, index) => {
8712
- const mentioned = patterns.filter(({ pattern }) => pattern.test(line)).map(({ name }) => name);
8713
- if (mentioned.length === 0) return;
8714
- const start = Math.max(0, index - contextLines);
8715
- const end = Math.min(lines.length - 1, index + contextLines);
8716
- const last = windows[windows.length - 1];
8717
- if (last && start <= last.end + 1) {
8718
- last.end = Math.max(last.end, end);
8719
- for (const name of mentioned) last.names.add(name);
8720
- } else {
8721
- windows.push({ start, end, names: new Set(mentioned) });
8722
- }
8955
+ var init_build_dtcg_groups = __esm({
8956
+ "packages/experience-design-system-cli/src/session/core/tokens/build-dtcg-groups.ts"() {
8957
+ "use strict";
8958
+ }
8959
+ });
8960
+
8961
+ // packages/experience-design-system-cli/src/session/core/tokens/build-dtcg-tokens.ts
8962
+ function buildDtcgTokens(tokenRows) {
8963
+ return tokenRows.map((r) => {
8964
+ const t = {
8965
+ path: r.path,
8966
+ $type: r.type,
8967
+ $value: JSON.parse(r.value)
8968
+ };
8969
+ if (r.description !== null) t.$description = r.description;
8970
+ return t;
8971
+ });
8972
+ }
8973
+ var init_build_dtcg_tokens = __esm({
8974
+ "packages/experience-design-system-cli/src/session/core/tokens/build-dtcg-tokens.ts"() {
8975
+ "use strict";
8976
+ }
8977
+ });
8978
+
8979
+ // packages/experience-design-system-cli/src/session/repositories/tokens/read.ts
8980
+ function getDtcgTokensForSession(db, sessionId2) {
8981
+ const groupRows = db.prepare("SELECT path, description FROM raw_token_groups WHERE session_id = ? ORDER BY path").all(sessionId2).map((row) => ({
8982
+ path: String(row.path),
8983
+ description: row.description === null ? null : String(row.description)
8984
+ }));
8985
+ const tokenRows = db.prepare("SELECT path, type, value, description FROM raw_tokens WHERE session_id = ? ORDER BY path").all(sessionId2).map((row) => ({
8986
+ path: String(row.path),
8987
+ type: String(row.type),
8988
+ value: String(row.value),
8989
+ description: row.description === null ? null : String(row.description)
8990
+ }));
8991
+ return {
8992
+ groups: buildDtcgGroups(groupRows, tokenRows),
8993
+ tokens: buildDtcgTokens(tokenRows)
8994
+ };
8995
+ }
8996
+ function getRawTokenNamePaths(db, sessionId2) {
8997
+ const rows = db.prepare("SELECT raw_name, path FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId2);
8998
+ return Object.fromEntries(rows.map((row) => [String(row.raw_name), String(row.path)]));
8999
+ }
9000
+ function getRawTokenNamePathRows(db, sessionId2) {
9001
+ return db.prepare("SELECT raw_name, path, source FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId2).map((row) => ({
9002
+ rawName: String(row.raw_name),
9003
+ path: String(row.path),
9004
+ source: String(row.source)
9005
+ }));
9006
+ }
9007
+ var init_read3 = __esm({
9008
+ "packages/experience-design-system-cli/src/session/repositories/tokens/read.ts"() {
9009
+ "use strict";
9010
+ init_build_dtcg_groups();
9011
+ init_build_dtcg_tokens();
9012
+ }
9013
+ });
9014
+
9015
+ // packages/experience-design-system-cli/src/session/core/components/hash-component-shape.ts
9016
+ import { createHash as createHash2 } from "node:crypto";
9017
+ function hashComponentShape(component) {
9018
+ const payload = {
9019
+ framework: component.framework,
9020
+ name: component.name,
9021
+ source: component.source,
9022
+ props: component.props.map((p) => ({
9023
+ name: p.name,
9024
+ type: p.type
9025
+ })),
9026
+ slots: component.slots.map((s) => ({
9027
+ name: s.name,
9028
+ isDefault: s.isDefault,
9029
+ allowedComponents: [...s.allowedComponents ?? []].sort()
9030
+ }))
9031
+ };
9032
+ return createHash2("sha256").update(JSON.stringify(payload)).digest("hex");
9033
+ }
9034
+ var init_hash_component_shape = __esm({
9035
+ "packages/experience-design-system-cli/src/session/core/components/hash-component-shape.ts"() {
9036
+ "use strict";
9037
+ }
9038
+ });
9039
+
9040
+ // packages/experience-design-system-cli/src/session/core/tokens/hash-token-content.ts
9041
+ import { createHash as createHash3 } from "node:crypto";
9042
+ function hashTokenContent(rawTokenContent) {
9043
+ return createHash3("sha256").update(rawTokenContent.trim()).digest("hex");
9044
+ }
9045
+ var init_hash_token_content = __esm({
9046
+ "packages/experience-design-system-cli/src/session/core/tokens/hash-token-content.ts"() {
9047
+ "use strict";
9048
+ }
9049
+ });
9050
+
9051
+ // packages/experience-design-system-cli/src/session/repositories/tokens/write.ts
9052
+ function deleteRawTokensForSession(db, sessionId2) {
9053
+ db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(sessionId2);
9054
+ db.prepare("DELETE FROM raw_tokens WHERE session_id = ?").run(sessionId2);
9055
+ }
9056
+ function createRawTokenGroups(db, sessionId2, groups) {
9057
+ const insertGroup = db.prepare(`INSERT INTO raw_token_groups (session_id, path, description) VALUES (?, ?, ?)`);
9058
+ for (const group of groups) {
9059
+ insertGroup.run(sessionId2, group.path, group.$description ?? null);
9060
+ }
9061
+ }
9062
+ function createRawTokens(db, sessionId2, tokens) {
9063
+ const insertToken = db.prepare(
9064
+ `INSERT INTO raw_tokens (session_id, path, type, value, description) VALUES (?, ?, ?, ?, ?)`
9065
+ );
9066
+ for (const token of tokens) {
9067
+ insertToken.run(sessionId2, token.path, token.$type, JSON.stringify(token.$value), token.$description ?? null);
9068
+ }
9069
+ }
9070
+ function upsertRawToken(db, sessionId2, call) {
9071
+ db.prepare(
9072
+ `INSERT INTO raw_tokens (session_id, path, type, value, description) VALUES (?, ?, ?, ?, ?)
9073
+ ON CONFLICT(session_id, path) DO UPDATE SET type = excluded.type, value = excluded.value, description = excluded.description`
9074
+ ).run(sessionId2, call.path, call.type, JSON.stringify(call.value), call.description ?? null);
9075
+ }
9076
+ function upsertRawTokenGroup(db, sessionId2, call) {
9077
+ db.prepare(
9078
+ `INSERT INTO raw_token_groups (session_id, path, description) VALUES (?, ?, ?)
9079
+ ON CONFLICT(session_id, path) DO UPDATE SET description = excluded.description`
9080
+ ).run(sessionId2, call.path, call.description ?? null);
9081
+ }
9082
+ function updateRawTokenNamePaths(db, sessionId2, tokenNamePaths, source) {
9083
+ const entries = Object.entries(tokenNamePaths);
9084
+ const deletePaths = db.prepare("DELETE FROM raw_token_name_paths WHERE session_id = ? AND source = ?");
9085
+ const insertPath = db.prepare(
9086
+ "INSERT OR IGNORE INTO raw_token_name_paths (session_id, raw_name, path, source) VALUES (?, ?, ?, ?)"
9087
+ );
9088
+ const deleteAutomaticByName = db.prepare(
9089
+ "DELETE FROM raw_token_name_paths WHERE session_id = ? AND raw_name = ? AND source = 'automatic'"
9090
+ );
9091
+ deletePaths.run(sessionId2, source);
9092
+ for (const [rawName, path] of entries) {
9093
+ if (source === "manual") deleteAutomaticByName.run(sessionId2, rawName);
9094
+ insertPath.run(sessionId2, rawName, path, source);
9095
+ }
9096
+ }
9097
+ function updateRawPropTokenPaths(db, sessionId2, componentId, propName, paths, source) {
9098
+ db.prepare(
9099
+ `DELETE FROM raw_prop_token_paths
9100
+ WHERE session_id = ? AND component_id = ? AND prop_name = ?`
9101
+ ).run(sessionId2, componentId, propName);
9102
+ const insertPath = db.prepare(
9103
+ `INSERT INTO raw_prop_token_paths (session_id, component_id, prop_name, source, position, path)
9104
+ VALUES (?, ?, ?, ?, ?, ?)`
9105
+ );
9106
+ paths.forEach((path, position) => {
9107
+ insertPath.run(sessionId2, componentId, propName, source, position, path);
9108
+ });
9109
+ }
9110
+ var init_write3 = __esm({
9111
+ "packages/experience-design-system-cli/src/session/repositories/tokens/write.ts"() {
9112
+ "use strict";
9113
+ }
9114
+ });
9115
+
9116
+ // packages/experience-design-system-cli/src/session/repositories/shared/with-transaction.ts
9117
+ function withTransaction(db, fn) {
9118
+ db.exec("BEGIN");
9119
+ try {
9120
+ const result = fn();
9121
+ db.exec("COMMIT");
9122
+ return result;
9123
+ } catch (e) {
9124
+ db.exec("ROLLBACK");
9125
+ throw e;
9126
+ }
9127
+ }
9128
+ var init_with_transaction = __esm({
9129
+ "packages/experience-design-system-cli/src/session/repositories/shared/with-transaction.ts"() {
9130
+ "use strict";
9131
+ }
9132
+ });
9133
+
9134
+ // packages/experience-design-system-cli/src/session/services/tokens/store-dtcg-tokens.ts
9135
+ function storeDtcgTokens(db, sessionId2, groups, tokens) {
9136
+ const now = (/* @__PURE__ */ new Date()).toISOString();
9137
+ withTransaction(db, () => {
9138
+ deleteRawTokensForSession(db, sessionId2);
9139
+ createRawTokenGroups(db, sessionId2, groups);
9140
+ createRawTokens(db, sessionId2, tokens);
9141
+ updateSessionTimestamp(db, sessionId2, now);
8723
9142
  });
8724
- if (windows.length === 0) {
8725
- return { content: `${text.slice(0, maxChars)}
8726
- ${TRUNCATED_MARKER}`, usesNotShown: [] };
9143
+ }
9144
+ var init_store_dtcg_tokens = __esm({
9145
+ "packages/experience-design-system-cli/src/session/services/tokens/store-dtcg-tokens.ts"() {
9146
+ "use strict";
9147
+ init_write();
9148
+ init_write3();
9149
+ init_with_transaction();
8727
9150
  }
8728
- const lastWindowFor = /* @__PURE__ */ new Map();
8729
- for (const window of windows) for (const name of window.names) lastWindowFor.set(name, window);
8730
- const kept = [];
8731
- const cut = /* @__PURE__ */ new Set();
8732
- let used = 0;
8733
- for (const window of [...windows].reverse()) {
8734
- const chunk = lines.slice(window.start, window.end + 1).join("\n");
8735
- const separator = kept.length > 0 ? `
8736
- ${ELLIPSIS_MARKER}
8737
- ` : "";
8738
- if (used + separator.length + chunk.length > maxChars) {
8739
- if (kept.length === 0) {
8740
- const head = chunk.slice(0, maxChars);
8741
- kept.push({ window, text: head });
8742
- used += head.length;
8743
- for (const name of window.names) {
8744
- if (lastWindowFor.get(name) === window && !identifierPattern(name).test(head)) cut.add(name);
8745
- }
8746
- continue;
8747
- }
8748
- for (const name of window.names) {
8749
- if (lastWindowFor.get(name) === window) cut.add(name);
9151
+ });
9152
+
9153
+ // packages/experience-design-system-cli/src/session/services/tokens/apply-tool-calls.ts
9154
+ function applyTokenToolCalls(db, sessionId2, calls, incomingWarnings) {
9155
+ const now = (/* @__PURE__ */ new Date()).toISOString();
9156
+ const warnings = [...incomingWarnings];
9157
+ let tokens = 0;
9158
+ let groups = 0;
9159
+ withTransaction(db, () => {
9160
+ for (const call of calls) {
9161
+ if (call.tool === "set_token") {
9162
+ upsertRawToken(db, sessionId2, call);
9163
+ tokens++;
9164
+ } else if (call.tool === "set_group") {
9165
+ upsertRawTokenGroup(db, sessionId2, call);
9166
+ groups++;
8750
9167
  }
8751
- continue;
8752
9168
  }
8753
- kept.push({ window, text: chunk });
8754
- used += separator.length + chunk.length;
9169
+ updateSessionTimestamp(db, sessionId2, now);
9170
+ });
9171
+ return { tokens, groups, warnings };
9172
+ }
9173
+ var init_apply_tool_calls = __esm({
9174
+ "packages/experience-design-system-cli/src/session/services/tokens/apply-tool-calls.ts"() {
9175
+ "use strict";
9176
+ init_write();
9177
+ init_write3();
9178
+ init_with_transaction();
8755
9179
  }
8756
- kept.sort((a, b) => a.window.start - b.window.start);
8757
- const parts = kept.map((entry, index) => (index > 0 ? `
8758
- ${ELLIPSIS_MARKER}
8759
- ` : "") + entry.text);
8760
- const usesNotShown = names.filter((name, index) => cut.has(name) && names.indexOf(name) === index);
8761
- return { content: `${parts.join("")}
8762
- ${TRUNCATED_MARKER}`, usesNotShown };
9180
+ });
9181
+
9182
+ // packages/experience-design-system-cli/src/session/services/tokens/replace-raw-token-name-paths.ts
9183
+ function replaceRawTokenNamePaths(db, sessionId2, tokenNamePaths, source = "automatic") {
9184
+ withTransaction(db, () => {
9185
+ updateRawTokenNamePaths(db, sessionId2, tokenNamePaths, source);
9186
+ updateSessionTimestamp(db, sessionId2, (/* @__PURE__ */ new Date()).toISOString());
9187
+ });
8763
9188
  }
8764
- var ELLIPSIS_MARKER, TRUNCATED_MARKER;
8765
- var init_source_excerpt = __esm({
8766
- "packages/experience-design-system-cli/src/session/source-excerpt.ts"() {
9189
+ var init_replace_raw_token_name_paths = __esm({
9190
+ "packages/experience-design-system-cli/src/session/services/tokens/replace-raw-token-name-paths.ts"() {
8767
9191
  "use strict";
8768
- ELLIPSIS_MARKER = "/* \u2026 */";
8769
- TRUNCATED_MARKER = "/* truncated */";
9192
+ init_write3();
9193
+ init_write();
9194
+ init_with_transaction();
9195
+ }
9196
+ });
9197
+
9198
+ // packages/experience-design-system-cli/src/session/services/tokens/replace-raw-prop-token-paths.ts
9199
+ function replaceRawPropTokenPaths(db, sessionId2, componentId, propName, paths, source) {
9200
+ withTransaction(db, () => {
9201
+ updateRawPropTokenPaths(db, sessionId2, componentId, propName, paths, source);
9202
+ });
9203
+ }
9204
+ var init_replace_raw_prop_token_paths = __esm({
9205
+ "packages/experience-design-system-cli/src/session/services/tokens/replace-raw-prop-token-paths.ts"() {
9206
+ "use strict";
9207
+ init_write3();
9208
+ init_with_transaction();
8770
9209
  }
8771
9210
  });
8772
9211
 
@@ -8777,11 +9216,11 @@ __export(cache_keys_exports, {
8777
9216
  hashFile: () => hashFile,
8778
9217
  hashPromptForSkill: () => hashPromptForSkill
8779
9218
  });
8780
- import { createHash } from "node:crypto";
9219
+ import { createHash as createHash4 } from "node:crypto";
8781
9220
  import { readFile as readFile6 } from "node:fs/promises";
8782
9221
  import { resolve as resolve6 } from "node:path";
8783
9222
  function hashContent(content) {
8784
- return createHash("sha256").update(content).digest("hex");
9223
+ return createHash4("sha256").update(content).digest("hex");
8785
9224
  }
8786
9225
  async function hashFile(filePath) {
8787
9226
  const content = await readFile6(filePath, "utf8");
@@ -8803,7 +9242,7 @@ var init_cache_keys = __esm({
8803
9242
  import { DatabaseSync } from "node:sqlite";
8804
9243
  import { mkdirSync, readFileSync as readFileSync5 } from "node:fs";
8805
9244
  import { readFile as readFile7 } from "node:fs/promises";
8806
- import { createHash as createHash2 } from "node:crypto";
9245
+ import { createHash as createHash5 } from "node:crypto";
8807
9246
  import { homedir } from "node:os";
8808
9247
  import { dirname as dirname7, resolve as resolve7 } from "node:path";
8809
9248
  function getPipelineDbPath() {
@@ -9070,57 +9509,6 @@ function applyDbMigrations(db) {
9070
9509
  `);
9071
9510
  }
9072
9511
  }
9073
- function replaceRawTokenNamePaths(db, sessionId2, tokenNamePaths, source = "automatic") {
9074
- const entries = Object.entries(tokenNamePaths);
9075
- const deletePaths = db.prepare("DELETE FROM raw_token_name_paths WHERE session_id = ? AND source = ?");
9076
- const insertPath = db.prepare(
9077
- "INSERT OR IGNORE INTO raw_token_name_paths (session_id, raw_name, path, source) VALUES (?, ?, ?, ?)"
9078
- );
9079
- const deleteAutomaticByName = db.prepare(
9080
- "DELETE FROM raw_token_name_paths WHERE session_id = ? AND raw_name = ? AND source = 'automatic'"
9081
- );
9082
- db.exec("BEGIN");
9083
- try {
9084
- deletePaths.run(sessionId2, source);
9085
- for (const [rawName, path] of entries) {
9086
- if (source === "manual") deleteAutomaticByName.run(sessionId2, rawName);
9087
- insertPath.run(sessionId2, rawName, path, source);
9088
- }
9089
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run((/* @__PURE__ */ new Date()).toISOString(), sessionId2);
9090
- db.exec("COMMIT");
9091
- } catch (e) {
9092
- db.exec("ROLLBACK");
9093
- throw e;
9094
- }
9095
- }
9096
- function loadRawTokenNamePaths(db, sessionId2) {
9097
- const rows = db.prepare("SELECT raw_name, path FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId2);
9098
- return Object.fromEntries(rows.map((row) => [row.raw_name, row.path]));
9099
- }
9100
- function loadRawTokenNamePathRows(db, sessionId2) {
9101
- return db.prepare("SELECT raw_name, path, source FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId2).map((row) => ({ rawName: row.raw_name, path: row.path, source: row.source }));
9102
- }
9103
- function replaceRawPropTokenPaths(db, sessionId2, componentId, propName, paths, source) {
9104
- const deletePaths = db.prepare(
9105
- `DELETE FROM raw_prop_token_paths
9106
- WHERE session_id = ? AND component_id = ? AND prop_name = ?`
9107
- );
9108
- const insertPath = db.prepare(
9109
- `INSERT INTO raw_prop_token_paths (session_id, component_id, prop_name, source, position, path)
9110
- VALUES (?, ?, ?, ?, ?, ?)`
9111
- );
9112
- db.exec("BEGIN");
9113
- try {
9114
- deletePaths.run(sessionId2, componentId, propName);
9115
- paths.forEach((path, position) => {
9116
- insertPath.run(sessionId2, componentId, propName, source, position, path);
9117
- });
9118
- db.exec("COMMIT");
9119
- } catch (e) {
9120
- db.exec("ROLLBACK");
9121
- throw e;
9122
- }
9123
- }
9124
9512
  function loadComponentReviewMetadata(db, sessionId2, componentName) {
9125
9513
  const compRow = db.prepare(`SELECT component_id, source, source_path FROM raw_components WHERE session_id = ? AND name = ?`).get(sessionId2, componentName);
9126
9514
  if (!compRow) return null;
@@ -9334,39 +9722,18 @@ function applyToolCalls(db, sessionId2, componentId, componentName, calls, incom
9334
9722
  }
9335
9723
  return { classified, excluded, slots, warnings };
9336
9724
  }
9337
- function getOrCreateSession(db, sessionFlag, sessionName, _hints) {
9338
- const now = (/* @__PURE__ */ new Date()).toISOString();
9339
- if (sessionFlag === "new" || sessionFlag === void 0) {
9340
- const id = generateSessionId();
9341
- db.prepare("INSERT INTO sessions (id, name, created_at, updated_at) VALUES (?, ?, ?, ?)").run(
9342
- id,
9343
- sessionName ?? null,
9344
- now,
9345
- now
9346
- );
9347
- return { sessionId: id, isNew: true, isResumed: false };
9348
- }
9349
- const existing = db.prepare("SELECT id FROM sessions WHERE id = ?").get(sessionFlag);
9350
- if (!existing) {
9351
- throw new Error(`session '${sessionFlag}' not found. Run 'session list' to see active sessions.`);
9352
- }
9353
- return { sessionId: sessionFlag, isNew: false, isResumed: false };
9725
+ function getOrCreateSession(db, sessionFlag, sessionName, hints) {
9726
+ return getOrCreateSessionForCommand(db, sessionFlag, sessionName, hints);
9354
9727
  }
9355
9728
  function createStep(db, sessionId2, command, inputs) {
9356
9729
  const now = (/* @__PURE__ */ new Date()).toISOString();
9357
9730
  db.exec("BEGIN");
9358
9731
  try {
9359
- db.prepare(
9360
- `UPDATE steps SET status = 'interrupted', completed_at = ?, updated_at = ?
9361
- WHERE session_id = ? AND command = ? AND status = 'pending'`
9362
- ).run(now, now, sessionId2, command);
9363
- const result = db.prepare(
9364
- `INSERT INTO steps (session_id, command, status, started_at, inputs, outputs, updated_at)
9365
- VALUES (?, ?, 'pending', ?, ?, '{}', ?)`
9366
- ).run(sessionId2, command, now, JSON.stringify(inputs), now);
9367
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId2);
9732
+ updatePendingStepsToInterrupted(db, sessionId2, command, now);
9733
+ const stepId = createPendingStep(db, sessionId2, command, inputs, now);
9734
+ updateSessionTimestamp(db, sessionId2, now);
9368
9735
  db.exec("COMMIT");
9369
- return Number(result.lastInsertRowid);
9736
+ return stepId;
9370
9737
  } catch (e) {
9371
9738
  db.exec("ROLLBACK");
9372
9739
  throw e;
@@ -9376,12 +9743,10 @@ function updateStep(db, stepId, status, outputs, error) {
9376
9743
  const now = (/* @__PURE__ */ new Date()).toISOString();
9377
9744
  db.exec("BEGIN");
9378
9745
  try {
9379
- const step = db.prepare("SELECT session_id FROM steps WHERE id = ?").get(stepId);
9380
- db.prepare(
9381
- `UPDATE steps SET status = ?, completed_at = ?, outputs = ?, error = ?, updated_at = ? WHERE id = ?`
9382
- ).run(status, now, JSON.stringify(outputs), error ?? null, now, stepId);
9383
- if (step) {
9384
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, step.session_id);
9746
+ const stepSessionId = getSessionIdForStep(db, stepId);
9747
+ updateStepStatus(db, stepId, status, outputs, error ?? null, now);
9748
+ if (stepSessionId) {
9749
+ updateSessionTimestamp(db, stepSessionId, now);
9385
9750
  }
9386
9751
  db.exec("COMMIT");
9387
9752
  } catch (e) {
@@ -9579,10 +9944,10 @@ function loadRawComponents(db, sessionId2, allowedNames) {
9579
9944
  `SELECT component_id, slot_name, position, allowed_component
9580
9945
  FROM raw_slot_allowed_components WHERE session_id = ? ORDER BY component_id, slot_name, position`
9581
9946
  ).all(sessionId2);
9582
- const propsByComponent = groupBy(props, (p) => p.component_id);
9583
- const allowedValuesByProp = groupBy(allowedValues, (av) => `${av.component_id}::${av.prop_name}`);
9584
- const slotsByComponent = groupBy(slots, (s) => s.component_id);
9585
- const allowedComponentsBySlot = groupBy(allowedComponents, (ac) => `${ac.component_id}::${ac.slot_name}`);
9947
+ const propsByComponent = indexRowsByKey(props, (p) => p.component_id);
9948
+ const allowedValuesByProp = indexRowsByKey(allowedValues, (av) => `${av.component_id}::${av.prop_name}`);
9949
+ const slotsByComponent = indexRowsByKey(slots, (s) => s.component_id);
9950
+ const allowedComponentsBySlot = indexRowsByKey(allowedComponents, (ac) => `${ac.component_id}::${ac.slot_name}`);
9586
9951
  return components.map(
9587
9952
  (c2) => ({
9588
9953
  component_id: c2.component_id,
@@ -9808,22 +10173,6 @@ function parseReviewReasons(raw) {
9808
10173
  return [];
9809
10174
  }
9810
10175
  }
9811
- function groupBy(items, key) {
9812
- const map = /* @__PURE__ */ new Map();
9813
- for (const item of items) {
9814
- const k = key(item);
9815
- let arr = map.get(k);
9816
- if (!arr) {
9817
- arr = [];
9818
- map.set(k, arr);
9819
- }
9820
- arr.push(item);
9821
- }
9822
- return map;
9823
- }
9824
- function deriveComponentId(name, source) {
9825
- return createHash2("sha256").update(`${name}:${source}`).digest("hex").slice(0, 12);
9826
- }
9827
10176
  function storeCDFComponents(db, sessionId2, components) {
9828
10177
  const now = (/* @__PURE__ */ new Date()).toISOString();
9829
10178
  const updateComp = db.prepare(
@@ -9916,7 +10265,7 @@ function storeCDFComponents(db, sessionId2, components) {
9916
10265
  }
9917
10266
  }
9918
10267
  } else {
9919
- const componentId = createHash2("sha256").update(`${key}:generated`).digest("hex").slice(0, 12);
10268
+ const componentId = deriveComponentId(key, "generated");
9920
10269
  db.prepare(
9921
10270
  `INSERT INTO raw_components (session_id, component_id, name, source, framework, extracted_at, status, description)
9922
10271
  VALUES (?, ?, ?, '', 'react', ?, 'generated', ?)`
@@ -9994,15 +10343,15 @@ function loadCDFComponents(db, sessionId2) {
9994
10343
  `SELECT component_id, prop_name, position, path
9995
10344
  FROM raw_prop_token_paths WHERE session_id = ? ORDER BY component_id, prop_name, position`
9996
10345
  ).all(sessionId2);
9997
- const resolvedDefaultPaths = loadRawTokenNamePaths(db, sessionId2);
10346
+ const resolvedDefaultPaths = getRawTokenNamePaths(db, sessionId2);
9998
10347
  const tokenTypeByPath = new Map(
9999
10348
  db.prepare("SELECT path, type FROM raw_tokens WHERE session_id = ?").all(sessionId2).map((token) => [token.path, token.type])
10000
10349
  );
10001
- const propsByComponent = groupBy(props, (p) => p.component_id);
10002
- const allowedValuesByProp = groupBy(allowedValues, (av) => `${av.component_id}::${av.prop_name}`);
10003
- const slotsByComponent = groupBy(slots, (s) => s.component_id);
10004
- const allowedComponentsBySlot = groupBy(allowedComponents, (ac) => `${ac.component_id}::${ac.slot_name}`);
10005
- const tokenPathsByProp = groupBy(tokenPaths, (t) => `${t.component_id}::${t.prop_name}`);
10350
+ const propsByComponent = indexRowsByKey(props, (p) => p.component_id);
10351
+ const allowedValuesByProp = indexRowsByKey(allowedValues, (av) => `${av.component_id}::${av.prop_name}`);
10352
+ const slotsByComponent = indexRowsByKey(slots, (s) => s.component_id);
10353
+ const allowedComponentsBySlot = indexRowsByKey(allowedComponents, (ac) => `${ac.component_id}::${ac.slot_name}`);
10354
+ const tokenPathsByProp = indexRowsByKey(tokenPaths, (t) => `${t.component_id}::${t.prop_name}`);
10006
10355
  const toTokenPaths = (rows) => rows === void 0 ? void 0 : rows.map((r) => r.path);
10007
10356
  return components.map(({ component_id, name, description }) => {
10008
10357
  const compProps = propsByComponent.get(component_id) ?? [];
@@ -10067,8 +10416,8 @@ function loadScopeComponents(db, sessionId2) {
10067
10416
  `SELECT component_id, slot_name, position, allowed_component
10068
10417
  FROM raw_slot_allowed_components WHERE session_id = ? ORDER BY component_id, slot_name, position`
10069
10418
  ).all(sessionId2);
10070
- const slotsByComponent = groupBy(slotRows, (s) => s.component_id);
10071
- const allowedBySlot = groupBy(allowedRows, (a) => `${a.component_id}::${a.slot_name}`);
10419
+ const slotsByComponent = indexRowsByKey(slotRows, (s) => s.component_id);
10420
+ const allowedBySlot = indexRowsByKey(allowedRows, (a) => `${a.component_id}::${a.slot_name}`);
10072
10421
  return rows.map((r) => {
10073
10422
  const reviewReasons = parseReviewReasons(r.review_reasons);
10074
10423
  const nonAuthorableReason = reviewReasons.find((reason) => reason.startsWith("non-authorable:"));
@@ -10106,91 +10455,8 @@ function applyScopeDecisions(db, sessionId2, decisions) {
10106
10455
  }
10107
10456
  db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId2);
10108
10457
  }
10109
- function storeDTCGTokens(db, sessionId2, groups, tokens) {
10110
- const now = (/* @__PURE__ */ new Date()).toISOString();
10111
- db.exec("BEGIN");
10112
- try {
10113
- db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(sessionId2);
10114
- db.prepare("DELETE FROM raw_tokens WHERE session_id = ?").run(sessionId2);
10115
- const insertGroup = db.prepare(`INSERT INTO raw_token_groups (session_id, path, description) VALUES (?, ?, ?)`);
10116
- for (const group of groups) {
10117
- insertGroup.run(sessionId2, group.path, group.$description ?? null);
10118
- }
10119
- const insertToken = db.prepare(
10120
- `INSERT INTO raw_tokens (session_id, path, type, value, description) VALUES (?, ?, ?, ?, ?)`
10121
- );
10122
- for (const token of tokens) {
10123
- insertToken.run(sessionId2, token.path, token.$type, JSON.stringify(token.$value), token.$description ?? null);
10124
- }
10125
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId2);
10126
- db.exec("COMMIT");
10127
- } catch (e) {
10128
- db.exec("ROLLBACK");
10129
- throw e;
10130
- }
10131
- }
10132
- function applyTokenToolCalls(db, sessionId2, calls, incomingWarnings) {
10133
- const now = (/* @__PURE__ */ new Date()).toISOString();
10134
- const warnings = [...incomingWarnings];
10135
- let tokens = 0;
10136
- let groups = 0;
10137
- const upsertToken = db.prepare(
10138
- `INSERT INTO raw_tokens (session_id, path, type, value, description) VALUES (?, ?, ?, ?, ?)
10139
- ON CONFLICT(session_id, path) DO UPDATE SET type = excluded.type, value = excluded.value, description = excluded.description`
10140
- );
10141
- const upsertGroup = db.prepare(
10142
- `INSERT INTO raw_token_groups (session_id, path, description) VALUES (?, ?, ?)
10143
- ON CONFLICT(session_id, path) DO UPDATE SET description = excluded.description`
10144
- );
10145
- db.exec("BEGIN");
10146
- try {
10147
- for (const call of calls) {
10148
- if (call.tool === "set_token") {
10149
- upsertToken.run(sessionId2, call.path, call.type, JSON.stringify(call.value), call.description ?? null);
10150
- tokens++;
10151
- } else if (call.tool === "set_group") {
10152
- upsertGroup.run(sessionId2, call.path, call.description ?? null);
10153
- groups++;
10154
- }
10155
- }
10156
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId2);
10157
- db.exec("COMMIT");
10158
- } catch (e) {
10159
- db.exec("ROLLBACK");
10160
- throw e;
10161
- }
10162
- return { tokens, groups, warnings };
10163
- }
10164
- function loadDTCGTokens(db, sessionId2) {
10165
- const groupRows = db.prepare("SELECT path, description FROM raw_token_groups WHERE session_id = ? ORDER BY path").all(sessionId2);
10166
- const tokenRows = db.prepare("SELECT path, type, value, description FROM raw_tokens WHERE session_id = ? ORDER BY path").all(sessionId2);
10167
- const groups = groupRows.map((r) => {
10168
- const prefix = `${r.path}.`;
10169
- const tokenIds = tokenRows.filter((t) => t.path.startsWith(prefix) && !t.path.slice(prefix.length).includes(".")).map((t) => t.path);
10170
- const g = { path: r.path, tokenIds };
10171
- if (r.description !== null) g.$description = r.description;
10172
- return g;
10173
- });
10174
- const tokens = tokenRows.map((r) => {
10175
- const t = {
10176
- path: r.path,
10177
- $type: r.type,
10178
- $value: JSON.parse(r.value)
10179
- };
10180
- if (r.description !== null) t.$description = r.description;
10181
- return t;
10182
- });
10183
- return { groups, tokens };
10184
- }
10185
10458
  function findLatestSessionForCommand(db, command) {
10186
- const row = db.prepare(
10187
- `SELECT s.id FROM sessions s
10188
- JOIN steps st ON st.session_id = s.id
10189
- WHERE st.command = ? AND st.status = 'complete'
10190
- ORDER BY st.started_at DESC, st.id DESC
10191
- LIMIT 1`
10192
- ).get(command);
10193
- return row?.id ?? null;
10459
+ return getLatestCompletedSessionForCommand(db, command);
10194
10460
  }
10195
10461
  function seedCDFFromPreviewResponse(db, sessionId2, removedItems) {
10196
10462
  if (removedItems.length === 0) return 0;
@@ -10207,14 +10473,8 @@ function seedCDFFromPreviewResponse(db, sessionId2, removedItems) {
10207
10473
  const contentProps = new Set(item.contentProperties);
10208
10474
  const designProps = new Set(item.designProperties);
10209
10475
  for (const [propName, propSummary] of Object.entries(item.fullProperties)) {
10210
- const cdfType = mapServerTypeToCDFType(propSummary.type);
10211
- if (!cdfType) continue;
10212
- let cdfCategory = propSummary.category || null;
10213
- if (!cdfCategory || !["content", "design", "state"].includes(cdfCategory)) {
10214
- if (contentProps.has(propName)) cdfCategory = "content";
10215
- else if (designProps.has(propName)) cdfCategory = "design";
10216
- else cdfCategory = "state";
10217
- }
10476
+ const cdfType = mapContentfulTypeToCdfType(propSummary.type);
10477
+ const cdfCategory = resolveCdfCategory(propSummary.category, propName, contentProps, designProps);
10218
10478
  const result = updateStmt.run(cdfType, cdfCategory, sessionId2, localComponent.component_id, propName);
10219
10479
  totalSeeded += Number(result.changes);
10220
10480
  }
@@ -10244,14 +10504,8 @@ function seedDefaultsFromChangedItems(db, sessionId2, changedItems) {
10244
10504
  const result2 = updateDefaultStmt.run(defaultStr, sessionId2, localComponent.component_id, propName);
10245
10505
  totalSeeded += Number(result2.changes);
10246
10506
  }
10247
- const cdfType = mapServerTypeToCDFType(propSummary.type);
10248
- if (!cdfType) continue;
10249
- let cdfCategory = propSummary.category || null;
10250
- if (!cdfCategory || !["content", "design", "state"].includes(cdfCategory)) {
10251
- if (contentProps.has(propName)) cdfCategory = "content";
10252
- else if (designProps.has(propName)) cdfCategory = "design";
10253
- else cdfCategory = "state";
10254
- }
10507
+ const cdfType = mapContentfulTypeToCdfType(propSummary.type);
10508
+ const cdfCategory = resolveCdfCategory(propSummary.category, propName, contentProps, designProps);
10255
10509
  const result = updateCDFStmt.run(cdfType, cdfCategory, sessionId2, localComponent.component_id, propName);
10256
10510
  totalSeeded += Number(result.changes);
10257
10511
  }
@@ -10275,48 +10529,6 @@ function backfillUnclassifiedProps(db, sessionId2) {
10275
10529
  ).run(sessionId2, sessionId2);
10276
10530
  return Number(withCategory.changes) + Number(withoutCategory.changes);
10277
10531
  }
10278
- function mapServerTypeToCDFType(serverType) {
10279
- switch (serverType.toLowerCase()) {
10280
- case "string":
10281
- case "text":
10282
- return "string";
10283
- case "richtext":
10284
- return "richtext";
10285
- case "media":
10286
- return "media";
10287
- case "link":
10288
- return "link";
10289
- case "enum":
10290
- case "symbol":
10291
- return "enum";
10292
- case "token":
10293
- return "token";
10294
- case "boolean":
10295
- return "boolean";
10296
- default:
10297
- return "string";
10298
- }
10299
- }
10300
- function computeComponentInputHash(component) {
10301
- const payload = {
10302
- framework: component.framework,
10303
- name: component.name,
10304
- source: component.source,
10305
- props: component.props.map((p) => ({
10306
- name: p.name,
10307
- type: p.type
10308
- })),
10309
- slots: component.slots.map((s) => ({
10310
- name: s.name,
10311
- isDefault: s.isDefault,
10312
- allowedComponents: [...s.allowedComponents ?? []].sort()
10313
- }))
10314
- };
10315
- return createHash2("sha256").update(JSON.stringify(payload)).digest("hex");
10316
- }
10317
- function computeTokenInputHash(rawTokenContent) {
10318
- return createHash2("sha256").update(rawTokenContent.trim()).digest("hex");
10319
- }
10320
10532
  function computeMapTokensInputHash(db, sessionId2, componentSourceRefs = []) {
10321
10533
  const props = db.prepare(
10322
10534
  `SELECT rc.name AS component_name, rp.name AS prop_name, rp.cdf_token_kind, rp.default_value
@@ -10346,7 +10558,7 @@ function computeMapTokensInputHash(db, sessionId2, componentSourceRefs = []) {
10346
10558
  usesNotShown: [...ref.usesNotShown ?? []].sort()
10347
10559
  }))
10348
10560
  };
10349
- return createHash2("sha256").update(JSON.stringify(payload)).digest("hex");
10561
+ return createHash5("sha256").update(JSON.stringify(payload)).digest("hex");
10350
10562
  }
10351
10563
  function lookupCache(db, inputHash, entityType, entityId, promptHash = "") {
10352
10564
  const row = db.prepare(
@@ -10654,8 +10866,25 @@ var SCHEMA, MAX_COMPONENT_SOURCE_CHARS, MAX_SIBLING_FILES, MAX_SIBLING_SNIPPET_C
10654
10866
  var init_db = __esm({
10655
10867
  "packages/experience-design-system-cli/src/session/db.ts"() {
10656
10868
  "use strict";
10657
- init_session_id();
10658
10869
  init_source_excerpt();
10870
+ init_derive_component_id();
10871
+ init_cdf_mappers();
10872
+ init_index_rows_by_key();
10873
+ init_read();
10874
+ init_write();
10875
+ init_read2();
10876
+ init_write2();
10877
+ init_session_resolver();
10878
+ init_read3();
10879
+ init_derive_component_id();
10880
+ init_hash_component_shape();
10881
+ init_hash_token_content();
10882
+ init_cdf_mappers();
10883
+ init_read3();
10884
+ init_store_dtcg_tokens();
10885
+ init_apply_tool_calls();
10886
+ init_replace_raw_token_name_paths();
10887
+ init_replace_raw_prop_token_paths();
10659
10888
  SCHEMA = `
10660
10889
  PRAGMA journal_mode = WAL;
10661
10890
  PRAGMA foreign_keys = ON;
@@ -10932,11 +11161,11 @@ var init_persistence = __esm({
10932
11161
  });
10933
11162
 
10934
11163
  // packages/experience-design-system-cli/src/analyze/select/parser.ts
10935
- import { createHash as createHash3 } from "node:crypto";
11164
+ import { createHash as createHash6 } from "node:crypto";
10936
11165
  import { access as access2 } from "node:fs/promises";
10937
11166
  import { isAbsolute, relative, resolve as resolve9 } from "node:path";
10938
11167
  function createComponentId(name, resolvedSourcePath) {
10939
- const sourceHash = createHash3("sha256").update(`${name}:${resolvedSourcePath}`).digest("hex").slice(0, 12);
11168
+ const sourceHash = createHash6("sha256").update(`${name}:${resolvedSourcePath}`).digest("hex").slice(0, 12);
10940
11169
  return `${name}-${sourceHash}`;
10941
11170
  }
10942
11171
  async function resolveComponentSourcePath(source, reviewRoot) {
@@ -17364,7 +17593,7 @@ var init_save_conflict = __esm({
17364
17593
  });
17365
17594
 
17366
17595
  // packages/experience-design-system-cli/src/runs/fingerprint.ts
17367
- import { createHash as createHash4 } from "node:crypto";
17596
+ import { createHash as createHash7 } from "node:crypto";
17368
17597
  import { readFile as readFile24, stat as stat5 } from "node:fs/promises";
17369
17598
  import { resolve as resolve23 } from "node:path";
17370
17599
  function rowField(row, key) {
@@ -17372,7 +17601,7 @@ function rowField(row, key) {
17372
17601
  return typeof v === "string" ? v : null;
17373
17602
  }
17374
17603
  function sha256Hex(buf) {
17375
- return createHash4("sha256").update(buf).digest("hex");
17604
+ return createHash7("sha256").update(buf).digest("hex");
17376
17605
  }
17377
17606
  async function buildSourceFingerprint(opts) {
17378
17607
  const rows = opts.db.prepare("SELECT name, source_path FROM raw_components WHERE session_id = ?").all(opts.extractSessionId);
@@ -24861,7 +25090,7 @@ function GenerateReviewStep({
24861
25090
  try {
24862
25091
  cdfComponents = loadCDFComponents(db, extractSessionId);
24863
25092
  cycles = loadSlotCycles(db, extractSessionId);
24864
- tokens = loadDTCGTokens(db, tokenSessionId ?? extractSessionId).tokens.map((token) => ({
25093
+ tokens = getDtcgTokensForSession(db, tokenSessionId ?? extractSessionId).tokens.map((token) => ({
24865
25094
  path: token.path,
24866
25095
  kind: token.$type
24867
25096
  }));
@@ -26749,7 +26978,7 @@ function AtomicGenerateReviewStep({
26749
26978
  let tokens = [];
26750
26979
  try {
26751
26980
  cdfComponents = loadCDFComponents(db, extractSessionId);
26752
- tokens = loadDTCGTokens(db, tokenSessionId ?? extractSessionId).tokens.map((token) => ({
26981
+ tokens = getDtcgTokensForSession(db, tokenSessionId ?? extractSessionId).tokens.map((token) => ({
26753
26982
  path: token.path,
26754
26983
  kind: token.$type
26755
26984
  }));
@@ -28098,7 +28327,7 @@ If you are using AWS Bedrock, run:
28098
28327
  copyTokensFromCache(db, state.tokenSessionId, sessionId2);
28099
28328
  } else if (!state.tokenSessionId && state.tokensPath) {
28100
28329
  const tokens = await readTokensFromPath("tokens", state.tokensPath);
28101
- storeDTCGTokens(db, sessionId2, [], tokens);
28330
+ storeDtcgTokens(db, sessionId2, [], tokens);
28102
28331
  }
28103
28332
  const cdfEntries = loadCDFComponents(db, sessionId2);
28104
28333
  mappablePropCount = cdfEntries.reduce(
@@ -28107,7 +28336,7 @@ If you are using AWS Bedrock, run:
28107
28336
  ).length,
28108
28337
  0
28109
28338
  );
28110
- rawTokenCount = loadDTCGTokens(db, sessionId2).tokens.length;
28339
+ rawTokenCount = getDtcgTokensForSession(db, sessionId2).tokens.length;
28111
28340
  } finally {
28112
28341
  db.close();
28113
28342
  }
@@ -30731,7 +30960,7 @@ async function selectAllComponents(agent, model, components, verbose, skillPathO
30731
30960
  try {
30732
30961
  for (let i = 0; i < components.length; i++) {
30733
30962
  const candidate = components[i];
30734
- const compHash = computeComponentInputHash(candidate.component);
30963
+ const compHash = hashComponentShape(candidate.component);
30735
30964
  const hit = lookupSelectCache(db, compHash, promptHash, cliVersion2);
30736
30965
  if (hit) {
30737
30966
  const finalColor = hit.decision === "accepted" ? c.green : c.red;
@@ -30805,7 +31034,7 @@ async function selectAllComponents(agent, model, components, verbose, skillPathO
30805
31034
  const r = results[i];
30806
31035
  if (!r || r.failed || !r.decision) continue;
30807
31036
  const candidate = components[i];
30808
- const compHash = computeComponentInputHash(candidate.component);
31037
+ const compHash = hashComponentShape(candidate.component);
30809
31038
  storeSelectCache(db, compHash, promptHash, cliVersion2, r.decision, r.reason ?? null);
30810
31039
  }
30811
31040
  } finally {
@@ -32751,7 +32980,7 @@ function printFallbackInstructions(options) {
32751
32980
  async function runOneComponent(agent, model, db, sessionId2, component, tokensInline, tokenMapInline, index, total, verbose, noCache, skillPathOverride, promptHash, existingContentfulEntities, existingTokensInline) {
32752
32981
  const pos = c.dim(`[${index + 1}/${total}]`);
32753
32982
  if (!noCache) {
32754
- const inputHash = computeComponentInputHash(component);
32983
+ const inputHash = hashComponentShape(component);
32755
32984
  const cached = lookupCache(db, inputHash, "component", component.component_id, promptHash);
32756
32985
  if (cached) {
32757
32986
  copyComponentFromCache(db, cached.sourceSessionId, sessionId2, component.component_id);
@@ -32874,7 +33103,7 @@ ${outputBuf}`);
32874
33103
  }
32875
33104
  const applied = applyToolCalls(db, sessionId2, component.component_id, component.name, calls, warnings);
32876
33105
  if (!noCache) {
32877
- const inputHash = computeComponentInputHash(component);
33106
+ const inputHash = hashComponentShape(component);
32878
33107
  storeCache(db, inputHash, "component", component.component_id, sessionId2, false, promptHash);
32879
33108
  }
32880
33109
  return {
@@ -33171,7 +33400,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
33171
33400
  } else if (skill === "tokens") {
33172
33401
  const noCache = opts.cache === false || process.env.EDS_NO_CACHE === "1";
33173
33402
  const tokenInputContent = rawTokensInline ?? "";
33174
- const tokenInputHash = computeTokenInputHash(tokenInputContent);
33403
+ const tokenInputHash = hashTokenContent(tokenInputContent);
33175
33404
  const db = openPipelineDb();
33176
33405
  try {
33177
33406
  let resolvedSessionId = opts.session;
@@ -33329,7 +33558,7 @@ function registerGenerateCommand(program) {
33329
33558
  // packages/experience-design-system-cli/src/program.ts
33330
33559
  init_command();
33331
33560
 
33332
- // packages/experience-design-system-cli/src/session/command.ts
33561
+ // packages/experience-design-system-cli/src/session/cli.ts
33333
33562
  init_db();
33334
33563
 
33335
33564
  // packages/experience-design-system-cli/src/session/stats.ts
@@ -33533,7 +33762,7 @@ function migrateImportDb(db, _now) {
33533
33762
  }
33534
33763
  }
33535
33764
 
33536
- // packages/experience-design-system-cli/src/session/command.ts
33765
+ // packages/experience-design-system-cli/src/session/cli.ts
33537
33766
  function parseDuration(str) {
33538
33767
  const m = /^(\d+)([dwmy])$/.exec(str);
33539
33768
  if (!m) return null;
@@ -34195,7 +34424,7 @@ function registerPrintCommand(program) {
34195
34424
  const db = openPipelineDb();
34196
34425
  let result;
34197
34426
  try {
34198
- result = loadDTCGTokens(db, sessionId2);
34427
+ result = getDtcgTokensForSession(db, sessionId2);
34199
34428
  } finally {
34200
34429
  db.close();
34201
34430
  }
@@ -34545,7 +34774,7 @@ async function runMapTokens(opts) {
34545
34774
  tokenLeaves
34546
34775
  );
34547
34776
  const manualMappings = new Map(
34548
- loadRawTokenNamePathRows(db, sessionId2).filter((row) => row.source === "manual").map((row) => [row.rawName, row.path])
34777
+ getRawTokenNamePathRows(db, sessionId2).filter((row) => row.source === "manual").map((row) => [row.rawName, row.path])
34549
34778
  );
34550
34779
  const automaticMappings = {};
34551
34780
  const defaultDiagnostics = [
@@ -34580,7 +34809,7 @@ ${defaultDiagnostics.map((diagnostic) => ` ${diagnostic}`).join("\n")}
34580
34809
  (count, { entry }) => count + Object.values(entry.$properties ?? {}).filter((prop) => prop.$type === "token" && prop.$category === "design").length,
34581
34810
  0
34582
34811
  );
34583
- const { groups, tokens } = loadDTCGTokens(db, sessionId2);
34812
+ const { groups, tokens } = getDtcgTokensForSession(db, sessionId2);
34584
34813
  const tokenCount = tokens.length;
34585
34814
  if (mappablePropCount === 0 || tokenCount === 0) {
34586
34815
  process.stdout.write(
@@ -35065,7 +35294,7 @@ async function runPipeline(opts, progressWriter, cliPathOverride) {
35065
35294
  }
35066
35295
  if (extractSessionId && opts.tokens) {
35067
35296
  const tokens = await readTokensFromPath("--tokens", opts.tokens);
35068
- storeDTCGTokens(db, extractSessionId, [], tokens);
35297
+ storeDtcgTokens(db, extractSessionId, [], tokens);
35069
35298
  }
35070
35299
  const mapTokensLabel = stepLabel("Mapping design tokens");
35071
35300
  const hasGeneratedComponents = extractSessionId !== null && loadCDFComponents(db, extractSessionId).length > 0;