@sendproof/core 0.1.0-alpha.1 → 0.1.0-alpha.2

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 (116) hide show
  1. package/assets/api.js +2 -1
  2. package/assets/app.css +612 -1
  3. package/assets/app.js +89 -13
  4. package/assets/bar-fit.js +91 -0
  5. package/assets/commands.js +27 -4
  6. package/assets/dialog.css +125 -0
  7. package/assets/dialog.js +191 -0
  8. package/assets/fields/lookup-source.js +5 -2
  9. package/assets/fields/lookup.js +3 -2
  10. package/assets/i18n.js +13 -2
  11. package/assets/icons.js +18 -0
  12. package/assets/index.html +1 -0
  13. package/assets/journeys/compare.js +225 -0
  14. package/assets/journeys/expressions.js +89 -0
  15. package/assets/journeys/index.js +7 -0
  16. package/assets/journeys/run.js +152 -0
  17. package/assets/journeys/steps.js +163 -0
  18. package/assets/journeys-code.js +193 -0
  19. package/assets/journeys-dialog-model.js +172 -0
  20. package/assets/journeys-dialogs.js +301 -0
  21. package/assets/journeys-model.js +259 -0
  22. package/assets/journeys-runs.js +109 -0
  23. package/assets/journeys-session.js +135 -0
  24. package/assets/journeys-view.js +961 -0
  25. package/assets/journeys.js +962 -0
  26. package/assets/locales/ar-journeys.js +468 -0
  27. package/assets/locales/ar.js +2 -0
  28. package/assets/locales/cs-journeys.js +468 -0
  29. package/assets/locales/cs.js +2 -0
  30. package/assets/locales/da-journeys.js +465 -0
  31. package/assets/locales/da.js +2 -0
  32. package/assets/locales/de-journeys.js +465 -0
  33. package/assets/locales/de.js +2 -0
  34. package/assets/locales/el-journeys.js +465 -0
  35. package/assets/locales/el.js +2 -0
  36. package/assets/locales/en-journeys.js +467 -0
  37. package/assets/locales/en.js +2 -0
  38. package/assets/locales/es-journeys.js +467 -0
  39. package/assets/locales/es.js +2 -0
  40. package/assets/locales/fa-journeys.js +465 -0
  41. package/assets/locales/fa.js +2 -0
  42. package/assets/locales/fi-journeys.js +465 -0
  43. package/assets/locales/fi.js +2 -0
  44. package/assets/locales/fr-journeys.js +467 -0
  45. package/assets/locales/fr.js +2 -0
  46. package/assets/locales/he-journeys.js +468 -0
  47. package/assets/locales/he.js +2 -0
  48. package/assets/locales/hi-journeys.js +465 -0
  49. package/assets/locales/hi.js +2 -0
  50. package/assets/locales/id-journeys.js +466 -0
  51. package/assets/locales/id.js +2 -0
  52. package/assets/locales/it-journeys.js +467 -0
  53. package/assets/locales/it.js +2 -0
  54. package/assets/locales/ja-journeys.js +466 -0
  55. package/assets/locales/ja.js +2 -0
  56. package/assets/locales/ko-journeys.js +465 -0
  57. package/assets/locales/ko.js +2 -0
  58. package/assets/locales/nb-journeys.js +465 -0
  59. package/assets/locales/nb.js +2 -0
  60. package/assets/locales/nl-journeys.js +465 -0
  61. package/assets/locales/nl.js +2 -0
  62. package/assets/locales/pl-journeys.js +468 -0
  63. package/assets/locales/pl.js +2 -0
  64. package/assets/locales/pt-BR-journeys.js +467 -0
  65. package/assets/locales/pt-BR.js +2 -0
  66. package/assets/locales/pt-PT-journeys.js +467 -0
  67. package/assets/locales/pt-PT.js +2 -0
  68. package/assets/locales/ru-journeys.js +468 -0
  69. package/assets/locales/ru.js +2 -0
  70. package/assets/locales/sv-journeys.js +465 -0
  71. package/assets/locales/sv.js +2 -0
  72. package/assets/locales/th-journeys.js +466 -0
  73. package/assets/locales/th.js +2 -0
  74. package/assets/locales/tr-journeys.js +468 -0
  75. package/assets/locales/tr.js +2 -0
  76. package/assets/locales/uk-journeys.js +468 -0
  77. package/assets/locales/uk.js +2 -0
  78. package/assets/locales/vi-journeys.js +466 -0
  79. package/assets/locales/vi.js +2 -0
  80. package/assets/locales/zh-Hans-journeys.js +466 -0
  81. package/assets/locales/zh-Hans.js +2 -0
  82. package/assets/locales/zh-Hant-journeys.js +466 -0
  83. package/assets/locales/zh-Hant.js +2 -0
  84. package/assets/manifest.json +349 -104
  85. package/assets/markdown.js +27 -2
  86. package/assets/request-editor.js +7 -1
  87. package/assets/result-states.js +2 -2
  88. package/assets/results.js +41 -14
  89. package/assets/router.js +25 -1
  90. package/assets/seeded-menu.js +2 -1
  91. package/assets/shortcuts-sheet.js +3 -1
  92. package/assets/shortcuts.js +6 -0
  93. package/assets/sidebar.js +54 -5
  94. package/assets/signin.js +6 -3
  95. package/assets/styles.css +8 -2
  96. package/assets/toast.js +29 -0
  97. package/assets/vendor/arazzo-runtime-expression.js +136 -0
  98. package/assets/vendor/json-pointer.js +48 -0
  99. package/assets/vendor/jsonpath-rfc9535.js +15 -0
  100. package/assets/view.js +11 -3
  101. package/assets/views.css +7 -0
  102. package/dist/index.d.ts +7 -3
  103. package/dist/index.js +217 -26
  104. package/dist/journey-builder.d.ts +178 -0
  105. package/dist/journey-builder.js +169 -0
  106. package/dist/journeys.d.ts +24 -0
  107. package/dist/journeys.js +157 -0
  108. package/dist/node-http.d.ts +2 -0
  109. package/dist/node-http.js +17 -0
  110. package/dist/sessions.d.ts +43 -0
  111. package/dist/sessions.js +145 -0
  112. package/dist/statements.js +2 -2
  113. package/dist/stores/tables.d.ts +213 -0
  114. package/dist/stores/tables.js +213 -0
  115. package/dist/types.d.ts +34 -2
  116. package/package.json +1 -1
@@ -0,0 +1,962 @@
1
+ // Journeys mode (docs/plans/journeys.md; mocks v7, screens 132–151, m32–m40). The controller
2
+ // app.js wires in: the mode switch, the journeys sidebar and its rail, the overview, runs step by
3
+ // step and to the end in Preview (one Preview session per run, rewound when a step runs again,
4
+ // ended when the run finishes or is cancelled) and in Send (traced Sends), each step on its
5
+ // operation's own Try it screen with its bound fields marked, the Expected tab and the
6
+ // comparison, the summary, Run all, and the runs kept in this browser.
7
+ //
8
+ // The journey engine (ui/journeys/) binds steps, checks criteria and compares writes; this file
9
+ // only runs it against the host and draws what it says. Nothing here exists, and nothing in the
10
+ // workbench changes, unless capabilities list journeys or Preview sessions.
11
+ import { createRun, exportRun, recordStep, toJUnit, bindStep } from './journeys/index.js';
12
+ import { fixedValues, inputControls, journeysEnabled, journeyGroups, loadJourneys, inputUsage } from './journeys-model.js';
13
+ import { findingCounts, lastStatusOf, loadRuns, saveRun, recentRuns, tallyEnvelope } from './journeys-runs.js';
14
+ import { endHeldSessions, openSession, SESSION_HEADER, sessionGone } from './journeys-session.js';
15
+ import { changeFacts, changeRef, refForId } from './journeys-dialog-model.js';
16
+ import { showToast } from './toast.js';
17
+ import { confirmEndRun, confirmPersonaSwitch, confirmSendRun, confirmSessionEnded, confirmSessionOpenFailed, confirmStopSend } from './journeys-dialogs.js';
18
+ import { draftApprovedDifference, expectWritesCode, refsFor } from './journeys-code.js';
19
+ import * as view from './journeys-view.js';
20
+ import { encodeRequestBody, execute, makeRequest } from './api.js';
21
+ import { createSchemaForm } from './schema.js';
22
+ import { copyText } from './copy.js';
23
+ import { esc, icon } from './components.js';
24
+ import { current, formatNumber, t } from './i18n.js';
25
+ import { opKey } from './operations.js';
26
+ import { personasProvider } from './personas.js';
27
+ import { sqlSystem } from './stores.js';
28
+ import { captured } from './result-states.js';
29
+ import { shortcutAttrs, shortcutHint } from './shortcuts.js';
30
+
31
+ /** Steps whose writes go to a store this host didn't hook (or a Send that wasn't traced) can't be compared. */
32
+ function uncheckedReason(write, capabilities, traced) {
33
+ if (!traced) return t('jr.unchecked.noTrace');
34
+ const system = write.store;
35
+ const sql = sqlSystem(capabilities);
36
+ const hooked = system === sql || system === 'sql' || (capabilities.dataStores ?? []).some(store => store.system === system);
37
+ return hooked ? null : t('jr.unchecked.notHooked', { store: system });
38
+ }
39
+
40
+ /**
41
+ * The expectations a step can be compared with on this host: writes to stores it didn't hook,
42
+ * and everything after an untraced Send, become "Not checked" findings instead of "Missing".
43
+ */
44
+ export function checkableExpectations(expectations, journeyId, capabilities, { traced = true } = {}) {
45
+ const copy = structuredClone(expectations ?? {});
46
+ const unchecked = {};
47
+ const steps = copy.journeys?.[journeyId]?.steps ?? {};
48
+ for (const [stepId, expected] of Object.entries(steps)) {
49
+ const kept = [];
50
+ for (const [index, write] of (expected.writes ?? []).entries()) {
51
+ const reason = uncheckedReason(write, capabilities, traced);
52
+ if (reason) (unchecked[stepId] ??= []).push({ id: `unchecked:${index}`, kind: 'unchecked', store: write.store, target: write.table ?? write.collection ?? write.key, op: write.op, key: undefined, fields: [], note: reason });
53
+ else kept.push(write);
54
+ }
55
+ expected.writes = kept;
56
+ if (!traced && expected.effects?.length) {
57
+ for (const [index, effect] of expected.effects.entries()) (unchecked[stepId] ??= []).push({ id: `unchecked-effect:${index}`, kind: 'unchecked', store: 'effect', target: effect.kind, op: 'send', fields: [], note: t('jr.unchecked.noTrace') });
58
+ expected.effects = [];
59
+ }
60
+ }
61
+ return { expectations: copy, unchecked };
62
+ }
63
+
64
+ /** The value a request field holds at a binding's target ("path.id", "body/items/0/sku"). */
65
+ function valueAt(target, { paramValues = {}, body }) {
66
+ const param = /^(path|query|header|cookie)\.(.+)$/.exec(target);
67
+ if (param) return paramValues[`${param[1]}:${param[2]}`];
68
+ const tokens = target.replace(/^body\/?/, '').split('/').filter(Boolean).map(token => token.replace(/~1/g, '/').replace(/~0/g, '~'));
69
+ return tokens.reduce((node, key) => node == null ? undefined : node[key], body);
70
+ }
71
+
72
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null) || String(a ?? '') === String(b ?? '');
73
+
74
+ export function createJourneys({ state, $, basePath, results, openOperation, navigate, announce, refreshIdentity, storage = globalThis.localStorage }) {
75
+ const j = {
76
+ status: 'idle', journeys: [], sources: [], problems: [], open: null, view: 'overview', live: null, filter: 'all',
77
+ summaryOpen: -1, runTab: 'approved', inputs: {}, lastSpec: null, lastJourneys: null, runningAll: false, loadedFor: null, opening: false,
78
+ };
79
+ let inputsForm = null;
80
+
81
+ const enabled = () => journeysEnabled(state.cap);
82
+ const journey = id => j.journeys.find(item => item.id === id);
83
+ const runs = () => loadRuns(storage, state.documentUrl);
84
+ const lastStatus = id => {
85
+ if (j.live?.journey.id === id && j.live.run.status !== 'running') return j.live.run.status;
86
+ return lastStatusOf(recentRuns(runs(), id));
87
+ };
88
+ const stepRoute = () => state.route?.kind === 'jstep';
89
+ const liveStep = () => stepRoute() && j.live && j.live.journey.id === state.route.journey ? j.live.journey.steps.findIndex(step => step.stepId === state.route.step) : -1;
90
+
91
+ /* ---------- Loading ---------- */
92
+
93
+ async function load() {
94
+ if (!enabled() || j.loadedFor === state.documentUrl) return;
95
+ j.loadedFor = state.documentUrl;
96
+ // A session this tab opened before it was closed or crashed still holds the store: end it, unless a run here owns it.
97
+ if (state.cap.previewSessions === true && !j.live && !j.runningAll && !j.opening) endHeldSessions();
98
+ j.status = 'loading';
99
+ const fetchJson = async url => {
100
+ const response = await fetch(new URL(url, location.href), { credentials: 'include', redirect: 'error' });
101
+ if (!response.ok) throw new Error(t('jr.loadStatus', { status: response.status, url }));
102
+ return response.json();
103
+ };
104
+ try {
105
+ const loaded = await loadJourneys({ capabilities: state.cap, document: state.doc, ops: state.ops, fetchJson });
106
+ Object.assign(j, loaded, { status: 'ready' });
107
+ } catch (error) {
108
+ Object.assign(j, { journeys: [], problems: [{ message: error.message }], status: 'ready' });
109
+ }
110
+ if (state.mode === 'journeys') {
111
+ // The route may name a journey that has just loaded: show it in place of the skeleton.
112
+ if (state.route?.kind === 'journeys' || state.route?.kind === 'journey') navigate(state.route, { replace: true, focus: false });
113
+ else navigate(state.route, { replace: true, focus: false });
114
+ }
115
+ }
116
+
117
+ /* ---------- Routes ---------- */
118
+
119
+ /**
120
+ * Makes `state` show a journey route. Returns the route really shown. The step of a run opens
121
+ * its operation's own screen (state.view 'try'); the overview and a run's summary use the
122
+ * reading panes.
123
+ */
124
+ function applyRoute(route) {
125
+ state.mode = 'journeys';
126
+ j.lastJourneys = route;
127
+ if (j.status !== 'ready') { state.view = 'journey'; return route; }
128
+ if (route.kind === 'journeys') {
129
+ const id = j.open && journey(j.open) ? j.open : j.journeys[0]?.id;
130
+ state.view = 'journey';
131
+ if (!id) return route;
132
+ j.open = id;
133
+ return { kind: 'journey', journey: id };
134
+ }
135
+ const target = journey(route.journey);
136
+ if (!target) { state.view = 'journey'; j.open = j.journeys[0]?.id ?? null; return j.open ? { kind: 'journey', journey: j.open } : { kind: 'journeys' }; }
137
+ if (j.open !== target.id) j.filter = 'all';
138
+ j.open = target.id;
139
+ if (route.kind === 'journey') { state.view = 'journey'; return route; }
140
+ if (route.kind === 'jrun') {
141
+ const stored = route.run === j.live?.run.runId ? j.live.run : recentRuns(runs(), target.id).find(run => run.runId === route.run);
142
+ if (!stored) { state.view = 'journey'; return { kind: 'journey', journey: target.id }; }
143
+ j.summary = stored;
144
+ state.view = 'jrun';
145
+ return route;
146
+ }
147
+ // A step: of the open run, or of a stored run reviewed from its summary.
148
+ const index = target.steps.findIndex(step => step.stepId === route.step);
149
+ if (index < 0 || !target.steps[index].op) { state.view = 'journey'; return { kind: 'journey', journey: target.id }; }
150
+ if (!j.live || j.live.journey.id !== target.id) {
151
+ const stored = j.summary?.journeyId === target.id ? j.summary : recentRuns(runs(), target.id)[0];
152
+ if (!stored) { state.view = 'journey'; return { kind: 'journey', journey: target.id }; }
153
+ j.live = { journey: target, run: stored, review: true, envelopes: [], responses: [], contentTypes: [], drafts: [], results: [] };
154
+ }
155
+ // The editor marks bound fields as it draws, so the step is the current route before it does.
156
+ state.route = route;
157
+ showStep(index);
158
+ state.view = 'try';
159
+ return route;
160
+ }
161
+
162
+ /** Opens step `index` of the live run on its operation's screen, with its bound values. */
163
+ function showStep(index) {
164
+ const live = j.live;
165
+ const step = live.journey.steps[index];
166
+ const draft = live.drafts[index];
167
+ let paramValues, body;
168
+ if (draft) ({ paramValues, body } = structuredClone(draft));
169
+ else {
170
+ const bound = bindStep(step.def, contextFor(live.run));
171
+ paramValues = {};
172
+ for (const [where, values] of [['path', bound.path], ['query', bound.query], ['header', bound.headers]]) {
173
+ for (const [name, value] of Object.entries(values)) if (value !== undefined) paramValues[`${where}:${name}`] = value;
174
+ }
175
+ ({ body } = bound);
176
+ }
177
+ live.index = index;
178
+ openOperation(step.op, paramValues, body);
179
+ // The step's result, when it ran in this run, stays on its screen.
180
+ state.result = live.results[index] ?? null;
181
+ state.resultTab = 'Expected';
182
+ }
183
+
184
+ /** The runtime-expression context of a run: its inputs and each step's outputs so far. */
185
+ function contextFor(run) {
186
+ return { inputs: run.inputs ?? {}, steps: Object.fromEntries((run.steps ?? []).filter(step => step.status !== 'pending' && step.status !== 'skipped').map(step => [step.stepId, { outputs: step.outputs ?? {} }])) };
187
+ }
188
+
189
+ /* ---------- Mode ---------- */
190
+
191
+ function switchMode(mode) {
192
+ if (!enabled()) return;
193
+ if (mode === state.mode) return;
194
+ if (mode === 'journeys') {
195
+ j.lastSpec = state.route;
196
+ navigate(j.lastJourneys ?? { kind: 'journeys' });
197
+ } else {
198
+ navigate(j.lastSpec ?? { kind: 'overview' });
199
+ }
200
+ }
201
+
202
+ /** Marks the current mode in every mode switch (top bar and drawer). */
203
+ function markMode() {
204
+ for (const item of document.querySelectorAll('[data-mode]')) {
205
+ if (item.dataset.mode === (state.mode === 'journeys' ? 'journeys' : 'spec')) item.setAttribute('aria-current', 'page');
206
+ else item.removeAttribute('aria-current');
207
+ }
208
+ document.querySelector('.app')?.classList.toggle('jm', state.mode === 'journeys');
209
+ }
210
+
211
+ /* ---------- Sidebar provider ---------- */
212
+
213
+ const sidebarProvider = {
214
+ active: () => state.mode === 'journeys',
215
+ filterable: () => j.status === 'ready' && j.journeys.length > 0,
216
+ head: () => view.sidebarHead({ journeys: j.journeys, loading: j.status !== 'ready', sources: j.sources }),
217
+ names: () => j.journeys.map(item => item.name),
218
+ groupKeys: () => journeyGroups(j.journeys).map(([name, , inferred]) => inferred ? '__inferred' : name),
219
+ list(query, isCollapsed) {
220
+ if (j.status !== 'ready') return view.journeysNavLoading();
221
+ if (!j.journeys.length) return view.journeysNavEmpty();
222
+ const live = j.live && !j.live.review ? j.live : j.live?.review && stepRoute() ? j.live : null;
223
+ return view.journeysNav({
224
+ journeys: j.journeys, query, open: j.open, run: live?.journey.id === j.open ? live.run : null,
225
+ here: live?.journey.id === j.open && stepRoute() ? liveStep() : -1, running: live?.running ?? -1, lastStatus, isCollapsed,
226
+ });
227
+ },
228
+ foot: allCollapsed => view.journeysFoot({ disabled: j.status !== 'ready' || !j.journeys.length, allCollapsed: allCollapsed(sidebarProvider.groupKeys()), runningAll: j.runningAll }),
229
+ };
230
+
231
+ /* ---------- Reading views: overview, summary, empty, loading ---------- */
232
+
233
+ function renderReading(main, aside) {
234
+ inputsForm?.destroy?.();
235
+ inputsForm = null;
236
+ const target = j.open && journey(j.open);
237
+ if (j.status !== 'ready') { main.innerHTML = view.loadingMain(); aside.innerHTML = view.loadingAside(); return; }
238
+ if (!target) {
239
+ main.innerHTML = view.emptyMain({ apiName: state.cap.apiName, dotnet: state.cap.binding?.language === 'dotnet' || !state.cap.binding });
240
+ aside.innerHTML = view.emptyAside();
241
+ return;
242
+ }
243
+ if (state.view === 'jrun') { renderSummary(main, aside, target, j.summary); return; }
244
+ const stored = recentRuns(runs(), target.id);
245
+ const body = j.view === 'arazzo' ? view.arazzoView(target) : `<div class="form j7-body">
246
+ <h2 class="section-label j7-sl"><span>${esc(t('jr.steps'))}</span><span class="rule" aria-hidden="true"></span></h2>
247
+ ${view.stepsTimeline(target)}
248
+ ${target.inputs?.properties && Object.keys(target.inputs.properties).length ? `<h2 class="section-label j7-sl"><span>${esc(t('jr.inputs'))}</span><span class="rule" aria-hidden="true"></span>${target.definedIn?.type ? `<span class="j7-sl-end">${esc(t('jr.from'))} <bdi dir="ltr"><code>${esc(target.definedIn.type.replace(/Journey$/, 'Inputs'))}</code></bdi></span>` : ''}</h2>
249
+ <div class="j7-inputs" data-journey-inputs></div>` : ''}
250
+ ${target.outputs.length || target.steps.length ? `<h2 class="section-label j7-sl"><span>${esc(t('jr.endsWith'))}</span><span class="rule" aria-hidden="true"></span></h2>${view.endsWith(target)}` : ''}
251
+ </div>`;
252
+ main.innerHTML = `${view.overviewContext(target, j.view)}<div class="pane-scroll">${view.overviewHead(target, { capabilities: state.cap })}${body}</div>
253
+ <div class="actionbar j7-actions">${view.overviewBar(target, { previewSessions: state.cap.previewSessions === true, opening: j.opening })}</div>`;
254
+ aside.innerHTML = view.overviewAside(target, stored);
255
+ const holder = main.querySelector('[data-journey-inputs]');
256
+ if (holder) renderInputs(holder, target);
257
+ }
258
+
259
+ /** The journey's inputs as the workbench's real fields, each saying which steps use it. */
260
+ function renderInputs(holder, target) {
261
+ const values = j.inputs[target.id] ??= Object.fromEntries(Object.entries(target.inputs.properties).filter(([, schema]) => schema.default !== undefined).map(([name, schema]) => [name, structuredClone(schema.default)]));
262
+ // An input bound to a step field with a lookup, an enum or a format uses that field's control.
263
+ const controls = inputControls(target, state.doc);
264
+ // Inputs keep their own names as labels, and each has a value (its default), so none reads as optional.
265
+ const schema = { ...target.inputs, required: target.inputs.required ?? Object.keys(target.inputs.properties),
266
+ properties: Object.fromEntries(Object.entries(target.inputs.properties).map(([name, property]) => [name, { title: name, ...controls[name], ...property }])) };
267
+ inputsForm = createSchemaForm({
268
+ container: holder, schema, document: state.doc, value: values, name: 'inputs', flattenRoot: true, basePath,
269
+ lookupCache: state.lookupCache ??= new Map(), actor: state.cap.identity?.name, signedIn: !!state.cap.identity?.name,
270
+ onChange: value => { j.inputs[target.id] = value; },
271
+ });
272
+ const usage = inputUsage(target);
273
+ for (const field of holder.querySelectorAll('[data-schema-path]')) {
274
+ const path = JSON.parse(field.dataset.schemaPath);
275
+ if (path.length !== 1) continue;
276
+ const hint = field.querySelector(':scope > .assist .field-hint');
277
+ if (hint) { hint.textContent = view.usedIn(usage[path[0]]); hint.dataset.base = hint.innerHTML; }
278
+ }
279
+ }
280
+
281
+ function renderSummary(main, aside, target, run) {
282
+ main.innerHTML = `${view.summaryMain(target, run, { capabilities: state.cap, open: j.summaryOpen })}
283
+ <div class="actionbar j7-actions">${view.summaryBar(target, run, { previewSessions: state.cap.previewSessions === true, opening: j.opening })}</div>`;
284
+ const inputs = Object.entries(run.inputs ?? {});
285
+ const inputsHtml = inputs.length ? `<dl class="j7-inputs-list">${inputs.map(([name, value]) => `<div><dt dir="ltr">${esc(name)}</dt><dd><bdi dir="ltr"><code>${esc(view.display(value))}</code></bdi></dd></div>`).join('')}</dl>` : `<p class="faint">${esc(t('jr.noInputs'))}</p>`;
286
+ aside.innerHTML = view.summaryAside(target, run, { tab: j.runTab, inputsHtml });
287
+ }
288
+
289
+ /* ---------- A step on its operation's screen ---------- */
290
+
291
+ /** The context bar and strip of a step; app.js draws the rest of Try it. */
292
+ function stepChrome() {
293
+ const index = liveStep();
294
+ const strip = $('#journey-strip');
295
+ if (index < 0) { if (strip) { strip.hidden = true; strip.innerHTML = ''; } return null; }
296
+ const live = j.live;
297
+ if (strip) { strip.hidden = false; strip.innerHTML = view.stepStrip(live.journey, live.run, index, { capabilities: state.cap, end: live.review ? '' : endRunButton(), sessionEnded: !!live.ending }); }
298
+ return view.stepContext(live.journey, index);
299
+ }
300
+ const endRunButton = () => `<button type="button" class="btn btn-ghost btn-icon btn-xs j7-end" data-action="journey-end-run" aria-label="${esc(t('jr.endRun'))}" title="${esc(t('jr.endRunTip'))}">${icon('x', true)}</button>`;
301
+
302
+ /** After the request editor draws: chips on bound fields, their status lines, bound URL tokens. */
303
+ function decorateStep() {
304
+ const index = liveStep();
305
+ if (index < 0) return;
306
+ const live = j.live;
307
+ const step = live.journey.steps[index];
308
+ const bound = bindStep(step.def, contextFor(live.run)).bound;
309
+ // Values the journey sets itself: parameters, and top-level body fields (nested ones sit inside a group).
310
+ const fixed = fixedValues(step.def).filter(item => !item.target.startsWith('body/') || item.target.split('/').length === 2).map(item => ({ ...item, from: 'fixed' }));
311
+ for (const binding of [...bound, ...fixed]) {
312
+ const field = fieldFor(binding.target);
313
+ if (!field || field.querySelector('.bind7')) continue;
314
+ field.dataset.bound = '';
315
+ const end = field.querySelector(':scope > .label > .end');
316
+ end?.insertAdjacentHTML('beforebegin', view.bindChip(binding, live.journey));
317
+ const hint = field.querySelector(':scope > .assist .field-hint');
318
+ if (hint) { hint.innerHTML = view.bindStatus(binding); hint.dataset.base = hint.innerHTML; }
319
+ }
320
+ for (const binding of bound.filter(item => item.target.startsWith('path.'))) {
321
+ const token = document.querySelector(`.urlbar [data-path-param="${CSS.escape(binding.target.slice(5))}"]`);
322
+ if (token && !token.classList.contains('is-bound7')) {
323
+ token.classList.add('is-bound7');
324
+ // The token's own glyph gives way to the bind arrow: the value comes from an earlier step.
325
+ const glyph = token.querySelector('svg');
326
+ if (glyph) glyph.outerHTML = icon('bind', true); else token.insertAdjacentHTML('afterbegin', icon('bind', true));
327
+ token.title = view.display(binding.value) || binding.expression;
328
+ }
329
+ }
330
+ }
331
+
332
+ function fieldFor(target) {
333
+ const param = /^(path|query|header|cookie)\.(.+)$/.exec(target);
334
+ if (param) return document.querySelector(`#editor [data-parameter-name="${CSS.escape(param[2])}"] [data-schema-path]`);
335
+ const tokens = target.replace(/^body\/?/, '').split('/').filter(Boolean);
336
+ const candidates = [JSON.stringify(tokens), JSON.stringify(tokens.map(token => /^\d+$/.test(token) ? Number(token) : token))];
337
+ return [...document.querySelectorAll('#editor [data-schema-path]')].find(node => candidates.includes(node.dataset.schemaPath)) ?? null;
338
+ }
339
+
340
+ /** How many bound values the person changed on this step's screen. */
341
+ function editedTargets(index) {
342
+ const live = j.live;
343
+ const step = live.journey.steps[index];
344
+ const bound = bindStep(step.def, contextFor(live.run)).bound;
345
+ return bound.filter(binding => !same(valueAt(binding.target, { paramValues: state.paramValues, body: state.body }), binding.value)).map(binding => binding.target);
346
+ }
347
+
348
+ /** The hooks results.js asks for on a journey step: the bar, the Expected tab, the run options. */
349
+ function hooks() {
350
+ const index = liveStep();
351
+ if (index < 0) return null;
352
+ const live = j.live;
353
+ const step = live.journey.steps[index];
354
+ const result = live.run.steps[index];
355
+ const ran = result && !['pending', 'skipped'].includes(result.status);
356
+ const problems = ran ? findingCounts(result).problems : 0;
357
+ const stopped = ran && ['refused', 'blocked'].includes(result.status);
358
+ const expectedCount = (step.expected?.writes?.length ?? 0) + (step.expected?.effects?.length ?? 0) + (step.def.successCriteria?.length ?? 0);
359
+ return {
360
+ bar: () => view.stepBar(live.journey, live.run, index, { running: live.running ?? -1, edited: live.review ? 0 : editedTargets(index).length, opening: j.opening, canPreview: live.run.mode !== 'send' || step.op.method !== 'GET' }),
361
+ idleHead: () => `<strong class="j7-rh-t">${esc(t('jr.stepN', { n: formatNumber(index + 1) }))}</strong><span class="metric">${esc(t('jr.rail.notRun'))}</span><span class="spacer"></span>`,
362
+ plainHead: true,
363
+ headExtra: () => live.review || live.run.mode === 'send' ? '' : `<button type="button" class="btn btn-ghost btn-icon btn-sm j7-rerun" data-action="preview" aria-label="${esc(t('jr.rerun', { n: formatNumber(index + 1) }))}" title="${esc(t('jr.rerun', { n: formatNumber(index + 1) }))}">${icon('refresh', true)}</button>`,
364
+ resultBar: (shown, { running }) => {
365
+ const text = running ? t('bar.runningShort') : shown?.finishedAt
366
+ ? t(shown.preview ? 'jr.rb.previewed' : 'jr.rb.sent', { time: new Intl.DateTimeFormat(current().locale, { hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(new Date(shown.finishedAt)), run: live.run.runId.slice(0, 4) })
367
+ : live.review ? t('jr.rb.review', { run: live.run.runId.slice(0, 4) }) : index > 0 && live.run.steps[index - 1]?.at ? t(live.run.mode === 'send' ? 'jr.rb.prevSent' : 'jr.rb.prevPreviewed', { n: formatNumber(index), time: new Intl.DateTimeFormat(current().locale, { hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(new Date(live.run.steps[index - 1].at)) }) : t(live.run.mode === 'send' ? 'jr.rb.sendRun' : 'jr.rb.held');
368
+ // Once the session is gone nothing is held any more, so the bar must not say so.
369
+ const gone = live.ending && live.run.mode === 'preview' && !running && !shown?.finishedAt;
370
+ const shownText = gone ? t('jr.rb.ended') : text;
371
+ return `<span class="bar-text is-fit" title="${esc(shownText)}">${icon(gone ? 'undo' : shown ? (shown.preview ? 'undo' : 'send') : 'clock', true, gone ? 'i-dir' : '')}<span>${esc(shownText)}</span></span>
372
+ <button type="button" class="btn btn-ghost btn-sm" data-action="history" ${shortcutAttrs('history')}>${icon('history', true)}${esc(t('shell.history'))}${shortcutHint('history')}</button>`;
373
+ },
374
+ expected: {
375
+ label: t('jr.expected'), count: expectedCount, flag: stopped ? t('jr.stopped') : problems ? t('jr.problems', { n: problems }) : undefined,
376
+ render: () => !ran ? view.expectList(live.journey, index, { capabilities: state.cap })
377
+ : stopped ? view.stoppedView(live.journey, index, { ...live.run, responses: live.responses, envelopes: live.envelopes, contentTypes: live.contentTypes }, { capabilities: state.cap, leftBehind: leftBehind(index), undo: undoFor(index) })
378
+ : view.comparison(live.journey, index, { ...live.run, envelopes: live.envelopes }, { filter: j.filter, capabilities: state.cap }),
379
+ loading: () => `<div class="result-body" aria-hidden="true"><div class="vd7"><span class="sk vd7-ico"></span><div class="vd7-text"><span class="sk sk-line" style="inline-size:9rem"></span><span class="sk sk-line" style="inline-size:16rem;margin-block-start:0.5rem"></span></div></div>${[0, 1].map(() => '<span class="sk" style="display:block;block-size:9rem;border-radius:var(--r-lg)"></span>').join('')}</div>`,
380
+ },
381
+ run: preview => live.review ? null : ({
382
+ headers: preview && live.run.mode === 'preview' && live.session ? live.session.header() : {},
383
+ allowPreview: preview && live.run.mode === 'preview',
384
+ skipConfirm: live.run.mode === 'send',
385
+ observedSend: state.cap.observedSend === true,
386
+ onResult: (result, { preview: wasPreview }) => record(index, result, { preview: wasPreview, edited: editedTargets(index) }),
387
+ onError: error => {
388
+ live.running = -1;
389
+ // The session timed out while the person was away, or the host ended it: say so, and end the run.
390
+ if (live.run.mode === 'preview' && sessionGone(error)) { sessionEnded(live); return; }
391
+ refresh();
392
+ },
393
+ }),
394
+ };
395
+ }
396
+
397
+ /** What earlier steps of a Send run committed: one line per change, with the step that made it. */
398
+ function leftBehind(index) {
399
+ const live = j.live;
400
+ if (live.run.mode !== 'send') return [];
401
+ const rows = [];
402
+ // Every Send that committed, including an earlier attempt at a step sent again.
403
+ for (const { step, envelope } of live.sent ?? []) {
404
+ for (const change of envelope.changes ?? []) {
405
+ const after = change.after ?? change.before ?? {};
406
+ const detail = after.Number ?? after.number ?? after.Status ?? after.status ?? Object.values(change.key ?? {})[0];
407
+ const { ref, field } = changeRef(change);
408
+ rows.push({ step, store: change.store || sqlSystem(state.cap), target: change.table, op: change.operation, detail, ref, facts: changeFacts(change, field) });
409
+ }
410
+ for (const effect of envelope.effects ?? []) rows.push({ step, store: 'effect', target: effect.kind, op: effect.kind, detail: effect.description });
411
+ }
412
+ return rows;
413
+ }
414
+
415
+ /** The operation that undoes what a stopped Send left: a cancel on the first resource an earlier step created. */
416
+ function undoFor(index) {
417
+ const live = j.live;
418
+ if (live.run.mode !== 'send') return null;
419
+ for (let i = index - 1; i >= 0; i--) {
420
+ const created = live.journey.steps[i].op;
421
+ if (!created || created.method !== 'POST') continue;
422
+ const id = Object.values(live.run.steps[i].outputs ?? {})[0];
423
+ const base = created.path.replace(/\/$/, '');
424
+ const cancel = state.ops.find(op => op.method === 'POST' && op.path.startsWith(`${base}/{`) && /\/(cancel|void|refund)/i.test(op.path));
425
+ if (cancel) return { op: cancel, index: state.ops.indexOf(cancel), value: id, ref: refForId((live.sent ?? []).flatMap(item => item.envelope.changes ?? []), id), param: /\{([^}]+)\}/.exec(cancel.path)?.[1], step: i + 1 };
426
+ }
427
+ return null;
428
+ }
429
+
430
+ /** What a stopped Send run left and how to undo it, kept with the run so its summary can still show it. */
431
+ function leftOver(live) {
432
+ if (live.run.mode !== 'send') return {};
433
+ const left = leftBehind();
434
+ if (!left.length) return {};
435
+ const undo = undoFor(live.run.steps.length);
436
+ return { left, ...(undo ? { undo: { id: opKey(undo.op), method: undo.op.method, title: undo.op.title || undo.op.operation?.summary || undo.op.path, param: undo.param, value: undo.value, ref: undo.ref, step: undo.step } } : {}) };
437
+ }
438
+
439
+ /* ---------- Running ---------- */
440
+
441
+ /**
442
+ * Starts a run of the open journey in `mode`, opening its Preview session, and shows step 1.
443
+ * A Preview that can't open says why in a dialog, which can try again.
444
+ */
445
+ async function startRun(mode) {
446
+ if (j.opening) return;
447
+ const failure = await beginRun(mode);
448
+ if (failure && (await openFailed(failure)) === true) await startRun(mode);
449
+ }
450
+
451
+ /** Resolves to the error that stopped a Preview session opening, or nothing. */
452
+ async function beginRun(mode) {
453
+ const target = journey(j.open);
454
+ if (!target) return;
455
+ if (mode === 'preview' && (target.sendOnly || state.cap.previewSessions !== true)) return;
456
+ if (mode === 'send' && !(await confirmSend(target))) return;
457
+ // While the session opens the bars show it (journeys-view.js, `opening`): a re-render, such as the persona sign-in's, keeps it.
458
+ if (mode === 'preview') { j.opening = true; refresh(); announce(t('jr.opening')); }
459
+ let started = false;
460
+ try {
461
+ await endLive();
462
+ await signInAs(target);
463
+ const inputs = structuredClone(j.inputs[target.id] ?? defaults(target));
464
+ const traced = mode === 'preview' || state.cap.observedSend === true;
465
+ const { expectations, unchecked } = checkableExpectations(target.expectations, target.id, state.cap, { traced });
466
+ const run = createRun({ journey: target.def, expectations, mode, inputs, persona: target.runAs ?? state.cap.identity?.name ?? null, store: sqlSystem(state.cap) });
467
+ Object.assign(run, { by: state.cap.identity?.name ?? null, tally: { stores: {}, effects: 0 } });
468
+ const live = { journey: target, run, mode, unchecked, envelopes: [], responses: [], contentTypes: [], drafts: [], results: [], sessionSteps: [], running: -1, started: performance.now(), lastActivity: Date.now() };
469
+ if (mode === 'preview') {
470
+ try { live.session = await openSession(); } catch (error) { return error; }
471
+ }
472
+ j.live = live;
473
+ started = true;
474
+ // Opened: the step draws as ready, not as still opening.
475
+ j.opening = false;
476
+ navigate({ kind: 'jstep', journey: target.id, step: target.steps[0].stepId });
477
+ } finally {
478
+ const wasOpening = j.opening;
479
+ j.opening = false;
480
+ // A run that opened navigates, which draws the step; one that didn't goes back to the journey, whose run has ended.
481
+ if (wasOpening && !started) { if (stepRoute()) navigate({ kind: 'journey', journey: target.id }); else refresh(); }
482
+ }
483
+ }
484
+
485
+ /** A Preview session that couldn't open: the busy store, or any other problem, as a dialog. Resolves true to try again. */
486
+ const openFailed = error => confirmSessionOpenFailed({ error, capabilities: state.cap });
487
+
488
+ const defaults = target => Object.fromEntries(Object.entries(target.inputs?.properties ?? {}).filter(([, schema]) => schema.default !== undefined).map(([name, schema]) => [name, schema.default]));
489
+
490
+ /** A Send run asks once, before anything is sent: what each store keeps, in which environment (dialogs v8). */
491
+ async function confirmSend(target) {
492
+ return (await confirmSendRun({
493
+ journey: target, capabilities: state.cap, inputs: j.inputs[target.id] ?? defaults(target),
494
+ preview: !target.sendOnly && state.cap.previewSessions === true,
495
+ })) === true;
496
+ }
497
+
498
+ /** The steps a run has run so far (not pending, not skipped). */
499
+ const stepsRun = run => run.steps.filter(step => !['pending', 'skipped'].includes(step.status)).length;
500
+
501
+ /** The held Preview session of the live run, when it holds steps: ending it would roll them back. */
502
+ const heldSteps = () => {
503
+ const live = j.live;
504
+ return live && !live.review && live.run.mode === 'preview' && live.run.status === 'running' && live.session && !live.session.ended ? stepsRun(live.run) : 0;
505
+ };
506
+
507
+ /**
508
+ * Ending the live run asks first when that throws something away: a Preview run's held steps
509
+ * roll back; a Send run's earlier steps keep what they wrote, and the run won't finish. While it
510
+ * asks, Run to end waits before its next step, so the answer is about the run as it is.
511
+ * Resolves `{ go, undo }`: whether to end the run, and the undo operation if the person chose it.
512
+ */
513
+ async function confirmEnd() {
514
+ const live = j.live;
515
+ if (!live || live.review || live.run.status !== 'running' || !stepsRun(live.run)) return { go: true };
516
+ const send = live.run.mode === 'send';
517
+ const left = send ? leftBehind() : [];
518
+ if (send && !left.length) return { go: true };
519
+ live.hold = new Promise(resolve => { live.release = resolve; });
520
+ try {
521
+ if (!send) return { go: (await confirmEndRun({ journey: live.journey, run: live.run, envelopes: live.envelopes, heldMs: Math.round(performance.now() - live.started), capabilities: state.cap })) === true };
522
+ const next = live.run.steps.findIndex(step => step.status === 'pending');
523
+ const undo = undoFor(next < 0 ? live.run.steps.length : next);
524
+ const choice = await confirmStopSend({ journey: live.journey, run: live.run, left, undo, capabilities: state.cap });
525
+ return { go: choice === true || choice === 'undo', undo: choice === 'undo' ? undo : null };
526
+ } finally {
527
+ live.release();
528
+ live.hold = null;
529
+ }
530
+ }
531
+
532
+ /** Switching persona ends a held Preview session. Asks first, and rolls it back when confirmed; resolves whether to go on. */
533
+ async function confirmPersona(user) {
534
+ const held = heldSteps();
535
+ if (!held) return true;
536
+ const live = j.live;
537
+ const choice = await confirmPersonaSwitch({ journey: live.journey, from: state.cap.identity, to: user, held, document: state.doc });
538
+ if (choice !== true) return false;
539
+ await endLive();
540
+ return true;
541
+ }
542
+
543
+ /** The held session ended on its own: say what is safe, then end the run, and start it again if asked. */
544
+ async function sessionEnded(live) {
545
+ if (live.ending) return;
546
+ live.ending = true;
547
+ live.running = -1;
548
+ const journeyId = live.journey.id;
549
+ const noticed = Date.now();
550
+ // The step that found the session gone goes back to not run: the failed request isn't a result,
551
+ // so its raw error ("Request failed … HTTP 404") doesn't stay on screen behind the notice.
552
+ if (state.result?.error) { state.result = undefined; state.resultTab = 'Expected'; }
553
+ refresh();
554
+ // The run's steps stay on screen behind the notice; the run ends (and is kept as stopped) when it closes.
555
+ const again = await confirmSessionEnded({ journey: live.journey, run: live.run, capabilities: state.cap, idleSeconds: live.session?.idleTimeoutSeconds, lastActivity: live.lastActivity, now: noticed });
556
+ if (j.live === live) await endLive();
557
+ navigate({ kind: 'journey', journey: journeyId });
558
+ if (again === true) await startRun('preview');
559
+ }
560
+
561
+ /** A journey that runs as a persona signs in as it first, through the personas source, so its session is that persona's. */
562
+ async function signInAs(target, { notify = true } = {}) {
563
+ const provider = personasProvider(state.cap);
564
+ if (!target.runAs || !provider) return;
565
+ try {
566
+ const list = await (await fetch(provider.url, { credentials: 'include', redirect: 'error' })).json();
567
+ const user = Array.isArray(list) ? list.find(item => item.email === target.runAs) : null;
568
+ if (!user || user.name === state.cap.identity?.name) return;
569
+ const response = await fetch(`${provider.url.replace(/\/$/, '')}/${encodeURIComponent(user.email)}`, { method: 'POST', credentials: 'include', redirect: 'error' });
570
+ if (response.ok) {
571
+ await refreshIdentity();
572
+ // The sign-in is silent by design; this says it happened, so the byline and the next requests aren't a surprise.
573
+ if (notify) showToast(t('jr.signedInAs', { name: user.name }), { glyph: 'user' });
574
+ }
575
+ } catch { /* The run goes ahead as whoever is signed in; the byline says who. */ }
576
+ }
577
+
578
+ /** Records one step's result in the run; rewinds or ends the session as the run requires. */
579
+ function record(index, result, { preview, edited = [], onScreen = true }) {
580
+ const live = j.live;
581
+ if (!live || live.review) return;
582
+ const step = live.journey.steps[index];
583
+ const envelope = { changes: result.changes ?? [], effects: result.effects ?? [], logs: result.logs ?? [], blocked: result.blocked };
584
+ const response = { statusCode: result.status, body: result.body, headers: result.headers };
585
+ if (preview && live.run.mode === 'send') {
586
+ // Previewing a step of a Send run on its own shows its result but records nothing.
587
+ return;
588
+ }
589
+ if (preview) { live.session?.record(result); live.lastActivity = Date.now(); }
590
+ const traced = preview || captured(result);
591
+ const recorded = recordStep(live.run, step.stepId, { response, envelope: traced ? envelope : {}, durationMs: result.duration });
592
+ // Stores this host doesn't hook, or an untraced Send, give "Not checked" in place of Missing.
593
+ const unchecked = new Map((live.unchecked[step.stepId] ?? []).map(item => [item.id, item]));
594
+ if (!traced) {
595
+ for (const [i, write] of (step.expected?.writes ?? []).entries()) unchecked.set(`unchecked:${i}`, { id: `unchecked:${i}`, kind: 'unchecked', store: write.store, target: write.table ?? write.collection ?? write.key, op: write.op, fields: [], note: t('jr.unchecked.noTrace') });
596
+ recorded.findings = [];
597
+ }
598
+ recorded.findings.push(...unchecked.values());
599
+ // A traced Send carries the stores it hooks as changes (SQL, MongoDB in a transaction) or as
600
+ // `Db` log entries (Redis and the other stores' commands), and compareStep matches both, so a
601
+ // write that's still missing for a hooked store really is missing. Stores this host doesn't
602
+ // hook were already turned into Not checked above.
603
+ const bad = recorded.findings.some(finding => ['differs', 'missing', 'extra'].includes(finding.kind));
604
+ if (recorded.status === 'failed' && !bad && recorded.criteria.every(criterion => criterion.passed)) {
605
+ recorded.status = 'passed';
606
+ recorded.verdict = recorded.findings.some(finding => finding.kind === 'approved' || finding.fields?.some(field => field.state === 'approved')) ? 'passed-approved' : 'passed';
607
+ }
608
+ if (live.run.status === 'failed' && live.run.steps.every(item => item.status === 'passed')) live.run.status = 'passed';
609
+ Object.assign(recorded, { at: new Date().toISOString(), edited, preview: !!preview });
610
+ live.envelopes[index] = envelope;
611
+ if (!preview && (envelope.changes.length || envelope.effects.length)) (live.sent ??= []).push({ step: index + 1, envelope });
612
+ live.responses[index] = result.body;
613
+ live.contentTypes[index] = Object.entries(result.headers ?? {}).find(([name]) => name.toLowerCase() === 'content-type')?.[1];
614
+ live.results[index] = result;
615
+ // The form is this step's only when it was on screen; a step Run to end sent from its bindings
616
+ // reopens with those, not with the form of the step that was showing.
617
+ if (onScreen) live.drafts[index] = { paramValues: structuredClone(state.paramValues ?? {}), body: structuredClone(state.body) };
618
+ else delete live.drafts[index];
619
+ live.run.tally = tallyEnvelope(live.run.tally, traced ? envelope : {});
620
+ if (live.run.status !== 'running') finishRun();
621
+ refresh();
622
+ }
623
+
624
+ /** Before a step that ran already runs again: rewind the session to before it and forget later steps. */
625
+ async function prepareRerun(index) {
626
+ const live = j.live;
627
+ const already = live.run.steps[index].status !== 'pending' && live.run.steps[index].status !== 'skipped';
628
+ if (!already && live.run.status === 'running') return true;
629
+ if (live.run.status !== 'running') {
630
+ // A finished Preview run's session has rolled back: start the run again. A Send run that
631
+ // stopped carries on from the step it stopped at; what earlier steps committed stays.
632
+ if (live.run.mode === 'preview') { await startRun('preview'); return false; }
633
+ Object.assign(live.run, { status: 'running', finishedAt: null, durationMs: null });
634
+ }
635
+ if (live.run.mode === 'preview' && live.session) {
636
+ const sessionStep = live.run.steps.slice(0, index).filter(step => step.status === 'passed' || step.status === 'failed').length + 1;
637
+ try { await live.session.rewind(sessionStep); } catch (error) {
638
+ if (sessionGone(error)) sessionEnded(live); else showProblem(error.message);
639
+ return false;
640
+ }
641
+ }
642
+ for (let i = index; i < live.run.steps.length; i++) {
643
+ Object.assign(live.run.steps[i], { status: 'pending', httpStatus: null, durationMs: null, criteria: [], outputs: {}, findings: [], verdict: null, bound: null });
644
+ if (i > index) { live.results[i] = undefined; live.envelopes[i] = undefined; }
645
+ }
646
+ live.run.tally = live.envelopes.slice(0, index).reduce((tally, envelope) => tallyEnvelope(tally, envelope), { stores: {}, effects: 0 });
647
+ return true;
648
+ }
649
+
650
+ /** Preview or Send the current step from its screen. */
651
+ async function runStep(preview) {
652
+ const index = liveStep();
653
+ const live = j.live;
654
+ if (index < 0 || !live) return false;
655
+ if (live.review) { await startRun(live.run.mode === 'send' || live.journey.sendOnly ? 'send' : 'preview'); return true; }
656
+ if (live.run.mode === 'preview' && !preview) return true;
657
+ if (live.run.mode === 'send' && preview && live.journey.steps[index].op.method === 'GET') return true;
658
+ if (!(preview && live.run.mode === 'send') && !(await prepareRerun(index))) return true;
659
+ await results.run(preview);
660
+ return true;
661
+ }
662
+
663
+ /** "Preview step 5" after step 4: open the next step and preview it. */
664
+ async function runNext() {
665
+ const index = liveStep();
666
+ const next = j.live?.journey.steps[index + 1];
667
+ if (!next) return;
668
+ navigate({ kind: 'jstep', journey: j.live.journey.id, step: next.stepId });
669
+ await results.run(j.live.run.mode !== 'send');
670
+ }
671
+
672
+ /** The request a step sends when it runs without its screen (Run to end, Run all). */
673
+ function boundRequest(step, run) {
674
+ const bound = bindStep(step.def, contextFor(run));
675
+ const parameters = step.op.parameters.map(parameter => ({ ...parameter, value: { path: bound.path, query: bound.query, header: bound.headers }[parameter.in]?.[parameter.name] }));
676
+ const headers = {};
677
+ return makeRequest(step.op, parameters, encodeRequestBody(bound.body, step.def.requestBody?.contentType || 'application/json', headers), headers, basePath);
678
+ }
679
+
680
+ /** Runs the rest of the live run without stopping at each screen, then shows the summary or the stop. */
681
+ async function runToEnd() {
682
+ const live = j.live;
683
+ const from = liveStep();
684
+ if (!live || live.review || from < 0) return;
685
+ if (!(await prepareRerun(from))) return;
686
+ for (let index = from; index < live.journey.steps.length && live.run.status === 'running'; index++) {
687
+ // An open "End run?" question holds the run before its next step, so what it says stays true.
688
+ await live.hold;
689
+ if (live.run.status !== 'running') break;
690
+ const step = live.journey.steps[index];
691
+ if (live.run.steps[index].status !== 'pending') continue;
692
+ live.running = index;
693
+ refresh();
694
+ let result;
695
+ try {
696
+ const request = index === from ? readRequest() : boundRequest(step, live.run);
697
+ if (live.run.mode === 'preview' && live.session) request.headers.set(SESSION_HEADER, live.session.id);
698
+ result = await execute(request, live.run.mode === 'preview', basePath, undefined, { observedSend: live.run.mode === 'send' && state.cap.observedSend === true });
699
+ result.finishedAt = Date.now();
700
+ } catch (error) {
701
+ live.running = -1;
702
+ if (live.run.mode === 'preview' && sessionGone(error)) { sessionEnded(live); return; }
703
+ showProblem(error.message);
704
+ refresh();
705
+ return;
706
+ }
707
+ record(index, result, { preview: live.run.mode === 'preview', edited: index === from ? editedTargets(index) : [], onScreen: index === from });
708
+ }
709
+ live.running = -1;
710
+ if (j.live !== live) return;
711
+ const stoppedAt = live.run.steps.findIndex(step => ['refused', 'blocked'].includes(step.status) || (step.status === 'failed' && live.run.status === 'stopped'));
712
+ if (live.run.status === 'stopped' && stoppedAt >= 0) navigate({ kind: 'jstep', journey: live.journey.id, step: live.journey.steps[stoppedAt].stepId });
713
+ else navigate({ kind: 'jrun', journey: live.journey.id, run: live.run.runId });
714
+ }
715
+
716
+ /** The current screen's request, as Send or Preview would make it. */
717
+ let readRequest = () => { throw new Error('No request'); };
718
+
719
+ /** Runs and the end of a run: the session rolls back, the run is kept in this browser. */
720
+ function finishRun() {
721
+ const live = j.live;
722
+ live.session?.end();
723
+ live.run.durationMs = view.runTime(live.run);
724
+ const stored = { ...exportRun(live.run), by: live.run.by, tally: live.run.tally, ...(live.run.status === 'stopped' ? leftOver(live) : {}) };
725
+ saveRun(storage, state.documentUrl, stored);
726
+ announce(t('jr.finished', { name: live.journey.name, verdict: view.runVerdict(live.run).short }));
727
+ }
728
+
729
+ /** Ends the live run (Cancel, a new run, leaving): rolls its session back. A partial run is kept as stopped. */
730
+ async function endLive({ keep = true } = {}) {
731
+ const live = j.live;
732
+ if (!live || live.review) { j.live = null; return; }
733
+ if (live.run.status === 'running') {
734
+ const ran = live.run.steps.some(step => step.status !== 'pending');
735
+ for (const step of live.run.steps) if (step.status === 'pending') step.status = 'skipped';
736
+ live.run.status = 'stopped';
737
+ live.run.finishedAt = new Date().toISOString();
738
+ if (keep && ran) { live.run.durationMs = view.runTime(live.run); saveRun(storage, state.documentUrl, { ...exportRun(live.run), by: live.run.by, tally: live.run.tally, ...leftOver(live), cancelled: true }); }
739
+ }
740
+ await live.session?.end();
741
+ j.live = null;
742
+ }
743
+
744
+ /** Run all: previews every journey that can Preview, one after another, each in its own session. */
745
+ async function runAll() {
746
+ if (j.runningAll || state.cap.previewSessions !== true) return;
747
+ j.runningAll = true;
748
+ refresh();
749
+ let passed = 0, failed = 0;
750
+ // Inferred journeys carry no inputs or expectations: they're a starting point to fill in, not a check.
751
+ for (const target of j.journeys.filter(item => !item.sendOnly && !item.inferred && item.steps.every(step => step.op))) {
752
+ await signInAs(target, { notify: false });
753
+ const inputs = structuredClone(j.inputs[target.id] ?? defaults(target));
754
+ const { expectations, unchecked } = checkableExpectations(target.expectations, target.id, state.cap);
755
+ const run = createRun({ journey: target.def, expectations, mode: 'preview', inputs, persona: target.runAs, store: sqlSystem(state.cap) });
756
+ Object.assign(run, { by: state.cap.identity?.name ?? null, tally: { stores: {}, effects: 0 } });
757
+ let session;
758
+ while (!session) {
759
+ try { session = await openSession(); } catch (error) { if (await openFailed(error) !== true) break; }
760
+ }
761
+ if (!session) break;
762
+ for (const [index, step] of target.steps.entries()) {
763
+ if (run.status !== 'running') break;
764
+ try {
765
+ const request = boundRequest(step, run);
766
+ request.headers.set(SESSION_HEADER, session.id);
767
+ const result = await execute(request, true, basePath);
768
+ session.record(result);
769
+ const envelope = { changes: result.changes ?? [], effects: result.effects ?? [], logs: result.logs ?? [], blocked: result.blocked };
770
+ const recorded = recordStep(run, step.stepId, { response: { statusCode: result.status, body: result.body, headers: result.headers }, envelope, durationMs: result.duration });
771
+ recorded.findings.push(...(unchecked[step.stepId] ?? []));
772
+ recorded.at = new Date().toISOString();
773
+ run.tally = tallyEnvelope(run.tally, envelope);
774
+ } catch (error) {
775
+ for (const item of run.steps.slice(index)) if (item.status === 'pending') item.status = 'skipped';
776
+ run.status = 'stopped';
777
+ run.finishedAt = new Date().toISOString();
778
+ break;
779
+ }
780
+ }
781
+ await session.end();
782
+ run.durationMs = view.runTime(run);
783
+ saveRun(storage, state.documentUrl, { ...exportRun(run), by: run.by, tally: run.tally });
784
+ if (run.status === 'passed') passed++; else failed++;
785
+ refresh();
786
+ }
787
+ j.runningAll = false;
788
+ refresh();
789
+ announce(t('jr.allDone', { passed: formatNumber(passed), failed: formatNumber(failed) }));
790
+ }
791
+
792
+ /* ---------- Drafts and copies ---------- */
793
+
794
+ async function draft(button) {
795
+ const live = j.live;
796
+ const index = liveStep();
797
+ if (!live || index < 0) return;
798
+ const step = live.run.steps[index];
799
+ const finding = step.findings.find(item => item.id === button.dataset.finding);
800
+ if (!finding) return;
801
+ const fields = (finding.fields ?? []).filter(field => field.state === 'differs');
802
+ const field = fields.length ? fields[0] : undefined;
803
+ const { text } = draftApprovedDifference({ journey: live.journey, stepId: step.stepId, finding, field, approvedBy: '', sqlStore: sqlSystem(state.cap) });
804
+ await copyText(text, { button, what: t('jr.copy.draft') });
805
+ }
806
+
807
+ /** Copy as C# on the Database tab: this Preview's writes as an ExpectWrites block. */
808
+ async function copyCSharp(button) {
809
+ const result = state.result;
810
+ if (!result?.preview) return;
811
+ const index = liveStep();
812
+ const refs = index >= 0 ? refsFor(j.live.journey, j.live.run, index - 1) : [];
813
+ const stepVariable = index >= 0 ? j.live.journey.steps[index].stepId : 'step';
814
+ await copyText(expectWritesCode({ changes: result.changes ?? [], effects: result.effects ?? [], refs, stepVariable }), { button, what: t('jr.copy.csharp') });
815
+ }
816
+
817
+ function download(name, type, text) {
818
+ const url = URL.createObjectURL(new Blob([text], { type }));
819
+ const link = Object.assign(document.createElement('a'), { href: url, download: name });
820
+ document.body.append(link);
821
+ link.click();
822
+ link.remove();
823
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
824
+ }
825
+
826
+ function showProblem(message) {
827
+ const slot = document.querySelector('[data-request-announcement]');
828
+ if (slot) slot.textContent = message;
829
+ const bar = document.querySelector('.workspace > .pane:not([hidden]) .actionbar .status');
830
+ if (bar) bar.innerHTML = `${icon('alert', true)}<span>${esc(message)}</span>`;
831
+ }
832
+
833
+ /** Redraws what a run changes: the sidebar rail, the strip, the bar and the result pane (or the reading panes). */
834
+ let redraw = () => {};
835
+ function refresh() { redraw(); }
836
+
837
+ /* ---------- Events ---------- */
838
+
839
+ const actions = {
840
+ 'journey-preview-run': () => startRun('preview'),
841
+ 'journey-send-run': () => startRun('send'),
842
+ 'journey-run-to-end': () => runToEnd(),
843
+ 'journey-next-run': () => runNext(),
844
+ 'journey-summary': () => j.live && navigate({ kind: 'jrun', journey: j.live.journey.id, run: j.live.run.runId }),
845
+ 'journey-run-all': () => runAll(),
846
+ 'journey-end-run': async () => {
847
+ const id = j.live?.journey.id;
848
+ const { go, undo } = await confirmEnd();
849
+ if (!go) return;
850
+ await endLive();
851
+ if (undo) {
852
+ const parameters = undo.param && undo.value !== undefined ? { [`path:${undo.param}`]: undo.value } : {};
853
+ navigate({ kind: 'op', id: opKey(undo.op) }, { reset: parameters });
854
+ } else if (id) navigate({ kind: 'journey', journey: id });
855
+ },
856
+ 'journey-back': () => navigate({ kind: 'journey', journey: j.open }),
857
+ 'journey-step-prev': () => stepBy(-1),
858
+ 'journey-step-next': () => stepBy(1),
859
+ 'journey-view': button => { j.view = button.dataset.viewKind; refresh(); },
860
+ 'journey-draft': button => draft(button),
861
+ 'journey-copy-csharp': button => copyCSharp(button),
862
+ 'journey-copy-json': button => j.summary && copyText(JSON.stringify(exportRun(j.summary), null, 2), { button, what: t('jr.copy.run') }),
863
+ 'journey-junit': () => j.summary && download(`${j.summary.journeyId}-${j.summary.runId.slice(0, 8)}.xml`, 'application/xml', toJUnit(j.summary)),
864
+ 'journey-copy-output': button => copyText(button.dataset.copy, { button, what: t('jr.copy.output') }),
865
+ 'journey-copy-cli': button => copyText(button.dataset.copy, { button, what: t('jr.copy.command') }),
866
+ 'journey-copy-snippet': button => copyText(button.dataset.copy, { button, what: t('jr.copy.code') }),
867
+ 'journey-copy-prompt': button => copyText(button.dataset.copy, { button, what: t('jr.copy.prompt') }),
868
+ // From a stopped Send run's summary: the undo kept with the run, which opens its operation with the ID filled in.
869
+ 'journey-undo-run': button => {
870
+ const { undoOp, undoParam, undoValue } = button.dataset;
871
+ const parameters = undoParam && undoValue ? { [`path:${undoParam}`]: undoValue } : {};
872
+ navigate({ kind: 'op', id: undoOp }, { reset: parameters });
873
+ },
874
+ 'journey-undo': button => {
875
+ const undo = undoFor(liveStep());
876
+ if (!undo) return;
877
+ const parameters = undo.param && undo.value !== undefined ? { [`path:${undo.param}`]: undo.value } : {};
878
+ navigate({ kind: 'op', id: opKey(undo.op) }, { reset: parameters });
879
+ },
880
+ };
881
+
882
+ function stepBy(delta) {
883
+ const index = liveStep();
884
+ const next = j.live?.journey.steps[index + delta];
885
+ if (index < 0 || !next?.op) return;
886
+ if (!j.live.review) j.live.drafts[index] = { paramValues: structuredClone(state.paramValues ?? {}), body: structuredClone(state.body) };
887
+ navigate({ kind: 'jstep', journey: j.live.journey.id, step: next.stepId });
888
+ }
889
+
890
+ /** Clicks inside the workbench that belong to Journeys mode. Returns true when handled. */
891
+ function click(event) {
892
+ const plain = !(event.button || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey);
893
+ const mode = event.target.closest('[data-mode]');
894
+ if (mode && plain) { event.preventDefault(); switchMode(mode.dataset.mode); return true; }
895
+ if (!plain) return false;
896
+ const filter = event.target.closest('[data-cmp-filter]');
897
+ if (filter) { j.filter = filter.dataset.cmpFilter; results.renderResult(); document.querySelector(`[data-cmp-filter="${j.filter}"]`)?.focus(); return true; }
898
+ const runTab = event.target.closest('[data-run-tab]');
899
+ if (runTab) { j.runTab = runTab.dataset.runTab; refresh(); document.querySelector(`[data-run-tab="${j.runTab}"]`)?.focus(); return true; }
900
+ const summaryStep = event.target.closest('[data-summary-step]');
901
+ if (summaryStep) { event.preventDefault(); const index = Number(summaryStep.dataset.summaryStep); j.summaryOpen = j.summaryOpen === index ? -2 : index; refresh(); document.querySelector(`[data-summary-step="${index}"]`)?.focus(); return true; }
902
+ const ad = event.target.closest('[data-ad-jump]');
903
+ if (ad) { event.preventDefault(); document.getElementById(`ad-${ad.dataset.adJump}`)?.scrollIntoView({ block: 'nearest', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' }); return true; }
904
+ const stepLink = event.target.closest('[data-journey-step]');
905
+ if (stepLink) {
906
+ event.preventDefault();
907
+ const id = stepLink.closest('[data-journey]')?.dataset.journey ?? j.open;
908
+ if (stepLink.dataset.fromRun && j.live?.run.runId !== stepLink.dataset.fromRun) {
909
+ const stored = j.summary?.runId === stepLink.dataset.fromRun ? j.summary : null;
910
+ if (stored) j.live = { journey: journey(stored.journeyId), run: stored, review: true, envelopes: [], responses: [], contentTypes: [], drafts: [], results: [] };
911
+ }
912
+ if (!j.live || j.live.journey.id !== (id ?? j.open)) { navigate({ kind: 'journey', journey: j.open }); return true; }
913
+ navigate({ kind: 'jstep', journey: j.live.journey.id, step: stepLink.dataset.journeyStep });
914
+ return true;
915
+ }
916
+ const runLink = event.target.closest('[data-journey-run]');
917
+ if (runLink) { event.preventDefault(); j.summaryOpen = -1; navigate({ kind: 'jrun', journey: j.open, run: runLink.dataset.journeyRun }); return true; }
918
+ const item = event.target.closest('[data-journey]');
919
+ if (item && item.matches('a')) { event.preventDefault(); j.view = 'overview'; navigate({ kind: 'journey', journey: item.dataset.journey }); return true; }
920
+ const history = event.target.closest('.hr7-link');
921
+ if (history) { event.preventDefault(); const run = /\/run\/([^/]+)$/.exec(history.getAttribute('href'))?.[1]; if (run) { j.summaryOpen = -1; navigate({ kind: 'jrun', journey: j.open, run: decodeURIComponent(run) }); } return true; }
922
+ const button = event.target.closest('[data-action]');
923
+ if (button && actions[button.dataset.action]) { if (button.tagName === 'A') event.preventDefault(); actions[button.dataset.action](button); return true; }
924
+ return false;
925
+ }
926
+
927
+ // A closing page ends every session the tab holds (a live run's, or Run all's), so none is left to its idle timeout.
928
+ globalThis.addEventListener?.('pagehide', () => { endHeldSessions({ keepalive: true }); });
929
+
930
+ /** Arrow keys move along the comparison filter, a radio group (WAI-ARIA radio pattern). */
931
+ function keydown(event) {
932
+ const radio = event.target.closest?.('[data-cmp-filter]');
933
+ if (!radio || !['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) return false;
934
+ const radios = [...radio.closest('[role="radiogroup"]').querySelectorAll('[data-cmp-filter]:not(:disabled)')];
935
+ const rtl = document.documentElement.dir === 'rtl';
936
+ const step = ['ArrowDown', rtl ? 'ArrowLeft' : 'ArrowRight'].includes(event.key) ? 1 : -1;
937
+ const index = radios.indexOf(radio);
938
+ const next = event.key === 'Home' ? radios[0] : event.key === 'End' ? radios.at(-1) : radios[(index + step + radios.length) % radios.length];
939
+ event.preventDefault();
940
+ next?.click();
941
+ return true;
942
+ }
943
+
944
+ return {
945
+ enabled, load, applyRoute, renderReading, keydown, stepChrome, decorateStep, hooks, click, switchMode, markMode, runStep, runToEnd,
946
+ sidebar: sidebarProvider, endLive, confirmPersona,
947
+ /** The phone's pane switch names what each side holds: Journey | Runs, Summary | Differences, Step | Result. */
948
+ paneNames: view => view === 'journey' ? [t('jr.pane.journey'), t('jr.runs')] : view === 'jrun' ? [t('jr.pane.summary'), t('jr.pane.details')]
949
+ : liveStep() >= 0 ? [t('jr.pane.step'), t('shell.result')] : [t('shell.request'), t('shell.result')],
950
+ get mode() { return state.mode; },
951
+ get ready() { return j.status === 'ready'; },
952
+ /** True while Try it shows a journey step, so Preview and Send run it as a step. */
953
+ stepActive: () => liveStep() >= 0,
954
+ canRunToEnd: () => liveStep() >= 0 && !j.live.review && j.live.run.status === 'running',
955
+ stepBy,
956
+ setReadRequest(fn) { readRequest = fn; },
957
+ setRedraw(fn) { redraw = fn; },
958
+ copyCSharpButton: () => enabled() && state.result?.preview && state.result.changes?.length
959
+ ? `<button type="button" class="btn btn-sm" data-action="journey-copy-csharp" title="${esc(t('jr.copyCSharpTip'))}">${icon('code', true)}${esc(t('jr.copyCSharp'))}</button>` : '',
960
+ };
961
+
962
+ }