@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.
- package/assets/api.js +2 -1
- package/assets/app.css +612 -1
- package/assets/app.js +89 -13
- package/assets/bar-fit.js +91 -0
- package/assets/commands.js +27 -4
- package/assets/dialog.css +125 -0
- package/assets/dialog.js +191 -0
- package/assets/fields/lookup-source.js +5 -2
- package/assets/fields/lookup.js +3 -2
- package/assets/i18n.js +13 -2
- package/assets/icons.js +18 -0
- package/assets/index.html +1 -0
- package/assets/journeys/compare.js +225 -0
- package/assets/journeys/expressions.js +89 -0
- package/assets/journeys/index.js +7 -0
- package/assets/journeys/run.js +152 -0
- package/assets/journeys/steps.js +163 -0
- package/assets/journeys-code.js +193 -0
- package/assets/journeys-dialog-model.js +172 -0
- package/assets/journeys-dialogs.js +301 -0
- package/assets/journeys-model.js +259 -0
- package/assets/journeys-runs.js +109 -0
- package/assets/journeys-session.js +135 -0
- package/assets/journeys-view.js +961 -0
- package/assets/journeys.js +962 -0
- package/assets/locales/ar-journeys.js +468 -0
- package/assets/locales/ar.js +2 -0
- package/assets/locales/cs-journeys.js +468 -0
- package/assets/locales/cs.js +2 -0
- package/assets/locales/da-journeys.js +465 -0
- package/assets/locales/da.js +2 -0
- package/assets/locales/de-journeys.js +465 -0
- package/assets/locales/de.js +2 -0
- package/assets/locales/el-journeys.js +465 -0
- package/assets/locales/el.js +2 -0
- package/assets/locales/en-journeys.js +467 -0
- package/assets/locales/en.js +2 -0
- package/assets/locales/es-journeys.js +467 -0
- package/assets/locales/es.js +2 -0
- package/assets/locales/fa-journeys.js +465 -0
- package/assets/locales/fa.js +2 -0
- package/assets/locales/fi-journeys.js +465 -0
- package/assets/locales/fi.js +2 -0
- package/assets/locales/fr-journeys.js +467 -0
- package/assets/locales/fr.js +2 -0
- package/assets/locales/he-journeys.js +468 -0
- package/assets/locales/he.js +2 -0
- package/assets/locales/hi-journeys.js +465 -0
- package/assets/locales/hi.js +2 -0
- package/assets/locales/id-journeys.js +466 -0
- package/assets/locales/id.js +2 -0
- package/assets/locales/it-journeys.js +467 -0
- package/assets/locales/it.js +2 -0
- package/assets/locales/ja-journeys.js +466 -0
- package/assets/locales/ja.js +2 -0
- package/assets/locales/ko-journeys.js +465 -0
- package/assets/locales/ko.js +2 -0
- package/assets/locales/nb-journeys.js +465 -0
- package/assets/locales/nb.js +2 -0
- package/assets/locales/nl-journeys.js +465 -0
- package/assets/locales/nl.js +2 -0
- package/assets/locales/pl-journeys.js +468 -0
- package/assets/locales/pl.js +2 -0
- package/assets/locales/pt-BR-journeys.js +467 -0
- package/assets/locales/pt-BR.js +2 -0
- package/assets/locales/pt-PT-journeys.js +467 -0
- package/assets/locales/pt-PT.js +2 -0
- package/assets/locales/ru-journeys.js +468 -0
- package/assets/locales/ru.js +2 -0
- package/assets/locales/sv-journeys.js +465 -0
- package/assets/locales/sv.js +2 -0
- package/assets/locales/th-journeys.js +466 -0
- package/assets/locales/th.js +2 -0
- package/assets/locales/tr-journeys.js +468 -0
- package/assets/locales/tr.js +2 -0
- package/assets/locales/uk-journeys.js +468 -0
- package/assets/locales/uk.js +2 -0
- package/assets/locales/vi-journeys.js +466 -0
- package/assets/locales/vi.js +2 -0
- package/assets/locales/zh-Hans-journeys.js +466 -0
- package/assets/locales/zh-Hans.js +2 -0
- package/assets/locales/zh-Hant-journeys.js +466 -0
- package/assets/locales/zh-Hant.js +2 -0
- package/assets/manifest.json +349 -104
- package/assets/markdown.js +27 -2
- package/assets/request-editor.js +7 -1
- package/assets/result-states.js +2 -2
- package/assets/results.js +41 -14
- package/assets/router.js +25 -1
- package/assets/seeded-menu.js +2 -1
- package/assets/shortcuts-sheet.js +3 -1
- package/assets/shortcuts.js +6 -0
- package/assets/sidebar.js +54 -5
- package/assets/signin.js +6 -3
- package/assets/styles.css +8 -2
- package/assets/toast.js +29 -0
- package/assets/vendor/arazzo-runtime-expression.js +136 -0
- package/assets/vendor/json-pointer.js +48 -0
- package/assets/vendor/jsonpath-rfc9535.js +15 -0
- package/assets/view.js +11 -3
- package/assets/views.css +7 -0
- package/dist/index.d.ts +7 -3
- package/dist/index.js +217 -26
- package/dist/journey-builder.d.ts +178 -0
- package/dist/journey-builder.js +169 -0
- package/dist/journeys.d.ts +24 -0
- package/dist/journeys.js +157 -0
- package/dist/node-http.d.ts +2 -0
- package/dist/node-http.js +17 -0
- package/dist/sessions.d.ts +43 -0
- package/dist/sessions.js +145 -0
- package/dist/statements.js +2 -2
- package/dist/stores/tables.d.ts +213 -0
- package/dist/stores/tables.js +213 -0
- package/dist/types.d.ts +34 -2
- package/package.json +1 -1
package/assets/dialog.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// The workbench's own dialog (mocks v8, screens 160–167, m43–m45). The workbench never opens a
|
|
2
|
+
// native browser dialog (confirm, alert, prompt): every question or notice is this one component,
|
|
3
|
+
// so it can list what will happen instead of one line of text.
|
|
4
|
+
//
|
|
5
|
+
// One shape: a tinted icon tile with the title and one sentence beside it, an optional list of
|
|
6
|
+
// consequences (rows of a name with a subtitle under it), the meta on the left of the footer and
|
|
7
|
+
// the actions on the right. On a phone it is a bottom sheet with the main action first.
|
|
8
|
+
//
|
|
9
|
+
// It is a native <dialog> opened with showModal(), so the page behind it is inert and focus stays
|
|
10
|
+
// inside. Focus starts on the safe action (Cancel, Keep running, Stay as…); Esc, the close button
|
|
11
|
+
// and a swipe down on a phone resolve null; the committing action needs the chord it shows (never
|
|
12
|
+
// plain Enter, which acts on whatever has focus); focus returns to the opener.
|
|
13
|
+
import { esc, icon, method } from './components.js';
|
|
14
|
+
import { t } from './i18n.js';
|
|
15
|
+
import { matchesShortcut, shortcutAttrs, shortcutHint } from './shortcuts.js';
|
|
16
|
+
|
|
17
|
+
const entities = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" };
|
|
18
|
+
/** The plain text of a trusted HTML snippet, for a row's tooltip. */
|
|
19
|
+
export const plainText = html => String(html ?? '').replace(/<[^>]*>/g, '').replace(/&(?:amp|lt|gt|quot|#39);/g, entity => entities[entity]);
|
|
20
|
+
|
|
21
|
+
/** Text that stays left to right inside a right-to-left dialog: an address, a file name, a status code. */
|
|
22
|
+
export const ltr = text => `<bdi dir="ltr">${esc(text)}</bdi>`;
|
|
23
|
+
|
|
24
|
+
/** A round mark for a row: an icon, tinted for ok (a step that ran) or warn. */
|
|
25
|
+
export const dialogMark = (glyph, tone = '') => `<span class="dl-mark${tone ? ` is-${tone}` : ''}" aria-hidden="true">${icon(glyph, true)}</span>`;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* One row of a dialog's list: a mark, a name with a subtitle under it and an optional end. `name`
|
|
29
|
+
* is plain text, `code` (optional) a file or database name set beside it, `sub` trusted HTML. The
|
|
30
|
+
* full text is the row's tooltip, because on a desktop the line is clipped with an ellipsis.
|
|
31
|
+
*/
|
|
32
|
+
export function dialogRow({ mark, name, code = '', sub = '', end = '' }) {
|
|
33
|
+
const title = [code ? `${name} ${code}` : name, plainText(sub)].filter(Boolean).join('\n');
|
|
34
|
+
const codeHtml = code ? ` <bdi dir="ltr"><code>${esc(code)}</code></bdi>` : '';
|
|
35
|
+
return `<li class="dl-row">${mark}<span class="dl-text" title="${esc(title)}"><span class="dl-name">${esc(name)}${codeHtml}</span>${sub ? `<span class="dl-sub">${sub}</span>` : ''}</span>${end}</li>`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The list that holds rows. */
|
|
39
|
+
export const dialogList = rows => `<ul class="dl-list">${rows.join('')}</ul>`;
|
|
40
|
+
|
|
41
|
+
/** A label above a list, with an optional chip on its end (the environment). */
|
|
42
|
+
export const dialogLabel = (text, end = '') => `<p class="dl-label"><span>${esc(text)}</span>${end}</p>`;
|
|
43
|
+
|
|
44
|
+
/** A one-line reminder under a list. */
|
|
45
|
+
export const dialogHint = (glyph, text) => `<p class="dl-hint">${icon(glyph, true)}<span>${esc(text)}</span></p>`;
|
|
46
|
+
|
|
47
|
+
/** The environment chip: a dot, the environment's name and its database. */
|
|
48
|
+
export const dialogEnv = (environment, database) => !environment && !database ? '' :
|
|
49
|
+
`<span class="dl-env"><span class="dot" aria-hidden="true"></span>${esc(environment ?? '')}${database ? `<span class="dl-env-db">${ltr(database)}</span>` : ''}</span>`;
|
|
50
|
+
|
|
51
|
+
/** A footer note: an icon and a few words. */
|
|
52
|
+
export const dialogNote = (glyph, text) => `<span class="dl-foot-note">${icon(glyph, true)}${esc(text)}</span>`;
|
|
53
|
+
|
|
54
|
+
/** A row that offers an operation: its method, name and a line about it. Clicking it resolves `value`. */
|
|
55
|
+
export const dialogOffer = ({ value, httpMethod, name, sub }) =>
|
|
56
|
+
`<button class="dl-undo" type="button" data-dialog-value="${esc(value)}">${method(httpMethod)}<span class="dl-text" title="${esc([name, sub].filter(Boolean).join('\n'))}"><span class="dl-name" dir="auto">${esc(name)}</span>${sub ? `<span class="dl-sub" dir="auto">${esc(sub)}</span>` : ''}</span>${icon('arrow-right', true)}</button>`;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The action that has focus when the dialog opens: the one marked `focus`, else the first plain
|
|
60
|
+
* action (Cancel, Keep running), else the first. Committing actions never take it.
|
|
61
|
+
*/
|
|
62
|
+
export function initialAction(actions) {
|
|
63
|
+
const marked = actions.findIndex(action => action.focus);
|
|
64
|
+
if (marked >= 0) return marked;
|
|
65
|
+
const safe = actions.findIndex(action => !action.kind || action.kind === 'default');
|
|
66
|
+
return safe >= 0 ? safe : 0;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const kindClass = { primary: 'btn btn-primary btn-sm', danger: 'btn btn-sm dl-danger' };
|
|
70
|
+
|
|
71
|
+
/** The dialog's markup. `title`, `body`, `content` and `foot` are trusted HTML: callers escape data. */
|
|
72
|
+
export function dialogMarkup({ tone = 'neutral', glyph, head, title, body = '', content = '', foot = '', actions = [] }, id = 'dl') {
|
|
73
|
+
const first = initialAction(actions);
|
|
74
|
+
const buttons = actions.map((action, index) => `<button class="${kindClass[action.kind] ?? 'btn btn-sm'}" type="button" data-dialog-action="${index}"${index === first ? ' data-dialog-initial autofocus' : ''}${action.shortcut ? ` ${shortcutAttrs(action.shortcut)}` : ''}>${action.icon ? icon(action.icon, true) : ''}${esc(action.label)}${action.shortcut ? shortcutHint(action.shortcut) : ''}</button>`).join('');
|
|
75
|
+
return `<div class="dl dl-${tone}">
|
|
76
|
+
<span class="dl-grab" aria-hidden="true"></span>
|
|
77
|
+
<header class="dl-head">
|
|
78
|
+
${head || `<span class="dl-tile is-${tone}" aria-hidden="true">${icon(glyph, false)}</span>`}
|
|
79
|
+
<div class="dl-titles"><h2 id="${id}-t">${title}</h2>${body ? `<p id="${id}-d">${body}</p>` : ''}</div>
|
|
80
|
+
<button class="btn btn-ghost btn-icon btn-sm dl-close" type="button" data-dialog-close aria-label="${esc(t('dialog.close'))}" title="${esc(t('dialog.closeTip'))}">${icon('x', true)}</button>
|
|
81
|
+
</header>
|
|
82
|
+
${content ? `<div class="dl-body">${content}</div>` : ''}
|
|
83
|
+
<footer class="dl-foot"><span class="dl-meta">${foot}</span><span class="dl-actions">${buttons}</span></footer>
|
|
84
|
+
</div>`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The value of the action whose chord `event` is, if any. Only a shown chord commits; plain Enter never does. */
|
|
88
|
+
export function actionForKey(actions, event) {
|
|
89
|
+
const hit = actions.find(action => action.shortcut && matchesShortcut(action.shortcut, event));
|
|
90
|
+
return hit ? { value: hit.value ?? null } : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The index Tab or Shift+Tab moves to among `count` focusable controls, wrapping at both ends. */
|
|
94
|
+
export function nextFocus(count, current, backwards) {
|
|
95
|
+
if (!count) return -1;
|
|
96
|
+
if (current < 0) return backwards ? count - 1 : 0;
|
|
97
|
+
return (current + (backwards ? -1 : 1) + count) % count;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
|
101
|
+
let counter = 0;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Opens a dialog and resolves to the chosen action's `value`, or null when it was dismissed (Esc,
|
|
105
|
+
* the close button, a swipe down on a phone). `actions` is `[{ label, kind: 'primary' | 'danger' |
|
|
106
|
+
* 'default', value, icon, shortcut (a shortcuts.js id), focus }]`. `role` is alertdialog for a
|
|
107
|
+
* warning or something that can't be undone.
|
|
108
|
+
*/
|
|
109
|
+
export function openDialog(spec) {
|
|
110
|
+
const doc = globalThis.document;
|
|
111
|
+
const opener = doc.activeElement;
|
|
112
|
+
const id = `dl-${++counter}`;
|
|
113
|
+
const tone = spec.tone ?? 'neutral';
|
|
114
|
+
const host = doc.createElement('dialog');
|
|
115
|
+
host.className = 'dl-host';
|
|
116
|
+
host.setAttribute('role', tone === 'danger' || tone === 'warn' ? 'alertdialog' : 'dialog');
|
|
117
|
+
host.setAttribute('aria-modal', 'true');
|
|
118
|
+
host.setAttribute('aria-labelledby', `${id}-t`);
|
|
119
|
+
if (spec.body) host.setAttribute('aria-describedby', `${id}-d`);
|
|
120
|
+
host.innerHTML = dialogMarkup({ ...spec, tone }, id);
|
|
121
|
+
doc.body.append(host);
|
|
122
|
+
const actions = spec.actions ?? [];
|
|
123
|
+
|
|
124
|
+
return new Promise(resolve => {
|
|
125
|
+
let done = false;
|
|
126
|
+
const finish = value => {
|
|
127
|
+
if (done) return;
|
|
128
|
+
done = true;
|
|
129
|
+
host.close?.();
|
|
130
|
+
host.remove();
|
|
131
|
+
if (opener?.isConnected && typeof opener.focus === 'function') opener.focus({ preventScroll: true });
|
|
132
|
+
resolve(value);
|
|
133
|
+
};
|
|
134
|
+
host.addEventListener('cancel', event => { event.preventDefault(); finish(null); });
|
|
135
|
+
host.addEventListener('close', () => finish(null));
|
|
136
|
+
host.addEventListener('click', event => {
|
|
137
|
+
const target = event.target;
|
|
138
|
+
if (target.closest?.('[data-dialog-close]')) return finish(null);
|
|
139
|
+
const offer = target.closest?.('[data-dialog-value]');
|
|
140
|
+
if (offer) return finish(offer.dataset.dialogValue);
|
|
141
|
+
const button = target.closest?.('[data-dialog-action]');
|
|
142
|
+
if (button) finish(actions[Number(button.dataset.dialogAction)]?.value ?? null);
|
|
143
|
+
});
|
|
144
|
+
host.addEventListener('keydown', event => {
|
|
145
|
+
// The workbench's own shortcuts (Send, search, J and K…) stay quiet while a question is open.
|
|
146
|
+
event.stopPropagation();
|
|
147
|
+
if (event.key === 'Escape') { event.preventDefault(); finish(null); return; }
|
|
148
|
+
const chord = actionForKey(actions, event);
|
|
149
|
+
if (chord) { event.preventDefault(); finish(chord.value); return; }
|
|
150
|
+
if (event.key === 'Tab') {
|
|
151
|
+
const controls = [...host.querySelectorAll(FOCUSABLE)];
|
|
152
|
+
const to = nextFocus(controls.length, controls.indexOf(doc.activeElement), event.shiftKey);
|
|
153
|
+
if (to >= 0) { event.preventDefault(); controls[to].focus(); }
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
swipeToClose(host, () => finish(null));
|
|
157
|
+
host.showModal();
|
|
158
|
+
host.querySelector('[data-dialog-initial]')?.focus();
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** On a phone, dragging the sheet down from its handle or heading dismisses it, like the Cancel it shows. */
|
|
163
|
+
function swipeToClose(host, dismiss) {
|
|
164
|
+
let start = null;
|
|
165
|
+
const card = () => host.querySelector('.dl');
|
|
166
|
+
host.addEventListener('pointerdown', event => {
|
|
167
|
+
if (event.pointerType === 'mouse' || !event.target.closest?.('.dl-grab, .dl-head')) return;
|
|
168
|
+
start = { y: event.clientY, time: event.timeStamp };
|
|
169
|
+
});
|
|
170
|
+
host.addEventListener('pointermove', event => {
|
|
171
|
+
if (!start) return;
|
|
172
|
+
const delta = Math.max(0, event.clientY - start.y);
|
|
173
|
+
const sheet = card();
|
|
174
|
+
if (sheet) { sheet.style.transition = 'none'; sheet.style.transform = `translateY(${delta}px)`; }
|
|
175
|
+
});
|
|
176
|
+
const release = event => {
|
|
177
|
+
if (!start) return;
|
|
178
|
+
const delta = event.clientY - start.y;
|
|
179
|
+
const fast = delta / Math.max(1, event.timeStamp - start.time) > 0.6;
|
|
180
|
+
start = null;
|
|
181
|
+
const sheet = card();
|
|
182
|
+
if (sheet) { sheet.style.transition = ''; sheet.style.transform = ''; }
|
|
183
|
+
if (delta > 96 || (fast && delta > 32)) dismiss();
|
|
184
|
+
};
|
|
185
|
+
host.addEventListener('pointerup', release);
|
|
186
|
+
host.addEventListener('pointercancel', () => {
|
|
187
|
+
start = null;
|
|
188
|
+
const sheet = card();
|
|
189
|
+
if (sheet) { sheet.style.transition = ''; sheet.style.transform = ''; }
|
|
190
|
+
});
|
|
191
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { localizeDateTimes } from '../i18n.js';
|
|
2
|
+
|
|
1
3
|
const read = (item, key) => item && Object.hasOwn(item, key) ? item[key] : undefined;
|
|
2
4
|
|
|
3
5
|
/** Resolve lookup URLs within the mounted application and use the current user's session. */
|
|
@@ -18,8 +20,9 @@ export function lookupOption(metadata, item) {
|
|
|
18
20
|
if (value === undefined || value === null || typeof value === 'object') return undefined;
|
|
19
21
|
return {
|
|
20
22
|
value,
|
|
21
|
-
|
|
22
|
-
|
|
23
|
+
// An ISO date-time in a name or detail reads as a local short date-time; the value is untouched.
|
|
24
|
+
label: localizeDateTimes(read(item, metadata.labelField || 'name') ?? value),
|
|
25
|
+
detail: ((detail) => typeof detail === 'string' ? localizeDateTimes(detail) : detail)(read(item, metadata.detailField || 'detail')),
|
|
23
26
|
status: read(item, metadata.statusField || 'status'),
|
|
24
27
|
// A short code at the end of the row, such as the account's currency.
|
|
25
28
|
end: typeof read(item, metadata.endField || 'currency') === 'string' ? read(item, metadata.endField || 'currency') : undefined,
|
package/assets/fields/lookup.js
CHANGED
|
@@ -174,8 +174,9 @@ export function lookupControl(context, metadata, schema, path, id, required, lab
|
|
|
174
174
|
}
|
|
175
175
|
refresh();
|
|
176
176
|
renderSelection();
|
|
177
|
-
// The status line counts the records once they're known (unless an error has taken it over
|
|
178
|
-
|
|
177
|
+
// The status line counts the records once they're known (unless an error has taken it over, or a
|
|
178
|
+
// journey step says where the bound value came from).
|
|
179
|
+
const hint = control.closest?.('.field:not([data-bound])')?.querySelector(':scope > .assist:not(.is-error):not(.is-generated) .field-hint');
|
|
179
180
|
if (hint) { hint.innerHTML = control.lookupStatus(); hint.dataset.base = hint.innerHTML; }
|
|
180
181
|
}
|
|
181
182
|
|
package/assets/i18n.js
CHANGED
|
@@ -183,8 +183,8 @@ export const formatDecimal = (n, digits = 2) =>
|
|
|
183
183
|
formatNumber(n, { minimumFractionDigits: digits, maximumFractionDigits: digits });
|
|
184
184
|
export const formatMoney = (n, currency = 'EUR') => formatNumber(n, { style: 'currency', currency });
|
|
185
185
|
/** Units in the locale's short form, such as "84 ms" or "1.2 kB". */
|
|
186
|
-
export const formatUnit = (n, unit, digits = 0) =>
|
|
187
|
-
formatNumber(n, { style: 'unit', unit, unitDisplay:
|
|
186
|
+
export const formatUnit = (n, unit, digits = 0, display = 'short') =>
|
|
187
|
+
formatNumber(n, { style: 'unit', unit, unitDisplay: display, maximumFractionDigits: digits });
|
|
188
188
|
/** Bytes as B, kB or MB in the locale's short form. */
|
|
189
189
|
export function formatBytes(bytes) {
|
|
190
190
|
// Intl spells out "byte"; the short symbol B reads better next to kB.
|
|
@@ -204,6 +204,17 @@ export const formatTime = value =>
|
|
|
204
204
|
new Intl.DateTimeFormat(active.locale, { hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(new Date(value));
|
|
205
205
|
export const formatDateTime = value =>
|
|
206
206
|
new Intl.DateTimeFormat(active.locale, { dateStyle: 'medium', timeStyle: 'medium' }).format(new Date(value));
|
|
207
|
+
/** Items strung together without "and": "7 rows, 3 documents, 1 email". */
|
|
208
|
+
export const formatCommaList = items =>
|
|
209
|
+
new Intl.ListFormat(active.locale, { style: 'short', type: 'unit' }).format(items.map(String));
|
|
210
|
+
export const formatShortDateTime = value =>
|
|
211
|
+
new Intl.DateTimeFormat(active.locale, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value));
|
|
212
|
+
const ISO_DATE_TIME = /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})\b/g;
|
|
213
|
+
/** Text with each ISO 8601 date-time (with a zone, as an API sends it) shown as a local short date-time. */
|
|
214
|
+
export const localizeDateTimes = text => String(text ?? '').replace(ISO_DATE_TIME, match => {
|
|
215
|
+
const time = new Date(match);
|
|
216
|
+
return Number.isNaN(time.getTime()) ? match : formatShortDateTime(time);
|
|
217
|
+
});
|
|
207
218
|
export const formatList = (items, type = 'conjunction') =>
|
|
208
219
|
new Intl.ListFormat(active.locale, { style: 'long', type }).format(items.map(String));
|
|
209
220
|
export const formatRelativeDays = days =>
|
package/assets/icons.js
CHANGED
|
@@ -80,6 +80,24 @@
|
|
|
80
80
|
// v6: data stores (Preview unavailable and the write guard).
|
|
81
81
|
'flask-off': '<path d="M9 3h6"/><path d="M10 3v4.5M14 3v6l2.2 4.1"/><path d="M8.6 11.4 4.5 18.5A1.7 1.7 0 0 0 6 21h12a1.7 1.7 0 0 0 .9-.25"/><path d="M3 3l18 18"/>',
|
|
82
82
|
ban: '<circle cx="12" cy="12" r="9"/><path d="m5.7 5.7 12.6 12.6"/>',
|
|
83
|
+
// v7: journeys (the mode switch, the progress rail, comparison findings and run summaries).
|
|
84
|
+
route: '<circle cx="6" cy="19" r="2.5"/><circle cx="18" cy="5" r="2.5"/><path d="M8.5 19H16a3.5 3.5 0 0 0 0-7H8a3.5 3.5 0 0 1 0-7h7.5"/>',
|
|
85
|
+
'circle-x': '<circle cx="12" cy="12" r="9"/><path d="m9 9 6 6M15 9l-6 6"/>',
|
|
86
|
+
'circle-dashed': '<path d="M10.1 3.2a9 9 0 0 1 3.8 0M17.6 4.9a9 9 0 0 1 2.7 2.7M20.8 10.1a9 9 0 0 1 0 3.8M19.1 17.6a9 9 0 0 1-2.7 2.7M13.9 20.8a9 9 0 0 1-3.8 0M6.4 19.1a9 9 0 0 1-2.7-2.7M3.2 13.9a9 9 0 0 1 0-3.8M4.9 6.4a9 9 0 0 1 2.7-2.7"/>',
|
|
87
|
+
play: '<path d="M7.5 4.8v14.4L19 12z"/>',
|
|
88
|
+
forward: '<path d="M4 5.5v13l7.5-6.5zM12.5 5.5v13L20 12z"/>',
|
|
89
|
+
bind: '<path d="M5 4v7a4 4 0 0 0 4 4h10"/><path d="m15 11 4 4-4 4"/>',
|
|
90
|
+
'badge-check': '<path d="M12 2.8l2.3 1.7 2.8-.2.9 2.7 2.4 1.5-.9 2.7.9 2.7-2.4 1.5-.9 2.7-2.8-.2L12 21.2l-2.3-1.7-2.8.2-.9-2.7-2.4-1.5.9-2.7-.9-2.7 2.4-1.5.9-2.7 2.8.2z"/><path d="m9 12 2 2 4-4"/>',
|
|
91
|
+
download: '<path d="M12 4v11M7 10l5 5 5-5M5 20h14"/>',
|
|
92
|
+
bot: '<rect x="4.5" y="8" width="15" height="11" rx="3"/><path d="M12 4v4M9.5 13v1M14.5 13v1"/>',
|
|
93
|
+
'file-code': '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5M10 12.5l-2 2 2 2M14 12.5l2 2-2 2"/>',
|
|
94
|
+
ne: '<path d="M5 9.5h14M5 14.5h14M15.5 5l-7 14"/>',
|
|
95
|
+
'minus-circle': '<circle cx="12" cy="12" r="9"/><path d="M8 12h8"/>',
|
|
96
|
+
'plus-circle': '<circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/>',
|
|
97
|
+
skip: '<circle cx="12" cy="12" r="9"/><path d="M9 8.5v7M10.5 12 15 8.5v7z"/>',
|
|
98
|
+
'shield-check': '<path d="M12 3 4 6v6c0 4.5 3.4 8.3 8 9 4.6-.7 8-4.5 8-9V6l-8-3z"/><path d="m9 12 2 2 4-4"/>',
|
|
99
|
+
// v8: the workbench's own dialogs (Stop run).
|
|
100
|
+
stop: '<rect x="6" y="6" width="12" height="12" rx="2"/>',
|
|
83
101
|
};
|
|
84
102
|
document.body.insertAdjacentHTML('afterbegin',
|
|
85
103
|
'<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">' +
|
package/assets/index.html
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
<link rel="stylesheet" href="styles.css" />
|
|
10
10
|
<link rel="stylesheet" href="views.css" />
|
|
11
11
|
<link rel="stylesheet" href="app.css" />
|
|
12
|
+
<link rel="stylesheet" href="dialog.css" />
|
|
12
13
|
</head>
|
|
13
14
|
<body>
|
|
14
15
|
<!-- The loading shell mirrors the final layout (mock 39), so nothing jumps when the spec arrives. -->
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// Comparing a step's captured writes and effects with its expectations (journeys.md, "Comparing
|
|
2
|
+
// and reporting"): nothing in Arazzo or a runtime-expression library knows about this, since it's
|
|
3
|
+
// entirely Sendproof's own companion-document format, so this module is all our own code. It
|
|
4
|
+
// resolves expected values (literals, runtime expressions, and the `type`/`pattern`/`from,to`
|
|
5
|
+
// matchers) with expressions.js, matches each expected write to a captured change by store,
|
|
6
|
+
// table or collection, op and key, applies approved differences, and produces one finding per
|
|
7
|
+
// expected write, extra change and expected effect.
|
|
8
|
+
import { evaluate, interpolate } from './expressions.js';
|
|
9
|
+
|
|
10
|
+
/** MongoDB changes arrive as Extended JSON ({ "$date": … }, { "$oid": … }, { "$numberLong": … });
|
|
11
|
+
* compare them as the plain values they stand for, so a date matches `date-time` and a number
|
|
12
|
+
* matches its literal. Anything else is returned as it is. */
|
|
13
|
+
function plainValue(value) {
|
|
14
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
|
|
15
|
+
const keys = Object.keys(value);
|
|
16
|
+
if (keys.length !== 1) return value;
|
|
17
|
+
const [name] = keys;
|
|
18
|
+
const inner = value[name];
|
|
19
|
+
if (name === '$date') {
|
|
20
|
+
if (typeof inner === 'string') return inner;
|
|
21
|
+
const millis = typeof inner === 'number' ? inner : Number(inner?.$numberLong);
|
|
22
|
+
return Number.isFinite(millis) ? new Date(millis).toISOString() : value;
|
|
23
|
+
}
|
|
24
|
+
if (name === '$oid' && typeof inner === 'string') return inner;
|
|
25
|
+
if (['$numberInt', '$numberLong', '$numberDouble', '$numberDecimal'].includes(name) && typeof inner === 'string') {
|
|
26
|
+
const number = Number(inner);
|
|
27
|
+
return Number.isFinite(number) ? number : value;
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const resolveScalar = (value, context) => (typeof value === 'string' && value.startsWith('$') ? evaluate(value, context) : value);
|
|
33
|
+
|
|
34
|
+
/** A raw expectation value as one of: a matcher ({type}, {pattern} or {from,to}), a runtime
|
|
35
|
+
* expression, or a literal. `from`/`to` and matcher fields are themselves literal-or-expression. */
|
|
36
|
+
function describeExpected(raw, context) {
|
|
37
|
+
if (raw !== null && typeof raw === 'object' && !Array.isArray(raw) && ('type' in raw || 'pattern' in raw || 'from' in raw || 'to' in raw)) {
|
|
38
|
+
if ('from' in raw || 'to' in raw) return { matcher: 'changed', from: resolveScalar(raw.from, context), to: resolveScalar(raw.to, context) };
|
|
39
|
+
if ('pattern' in raw) return { matcher: 'pattern', pattern: raw.pattern };
|
|
40
|
+
return { matcher: 'type', type: raw.type };
|
|
41
|
+
}
|
|
42
|
+
if (typeof raw === 'string' && raw.startsWith('$')) return { matcher: 'expression', expression: raw, value: evaluate(raw, context) };
|
|
43
|
+
return { matcher: 'literal', value: raw };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
47
|
+
const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
48
|
+
|
|
49
|
+
function matchesType(type, actual) {
|
|
50
|
+
switch (type) {
|
|
51
|
+
case 'string': return typeof actual === 'string';
|
|
52
|
+
case 'number': return typeof actual === 'number';
|
|
53
|
+
case 'integer': return typeof actual === 'number' && Number.isInteger(actual);
|
|
54
|
+
case 'boolean': return typeof actual === 'boolean';
|
|
55
|
+
case 'uuid': return typeof actual === 'string' && UUID.test(actual);
|
|
56
|
+
case 'date-time': return typeof actual === 'string' && DATE_TIME.test(actual) && !Number.isNaN(Date.parse(actual));
|
|
57
|
+
case 'any': return actual !== undefined;
|
|
58
|
+
default: return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const looseEqual = (a, b) => a === b || (a != null && b != null && JSON.stringify(a) === JSON.stringify(b));
|
|
63
|
+
|
|
64
|
+
/** Whether `actual` (with `before`, for a "changed" matcher) satisfies a described expectation. */
|
|
65
|
+
function matches(descriptor, rawActual, rawBefore) {
|
|
66
|
+
const actual = plainValue(rawActual);
|
|
67
|
+
const before = plainValue(rawBefore);
|
|
68
|
+
switch (descriptor.matcher) {
|
|
69
|
+
case 'literal':
|
|
70
|
+
case 'expression': return looseEqual(actual, descriptor.value);
|
|
71
|
+
case 'type': return matchesType(descriptor.type, actual);
|
|
72
|
+
case 'pattern': return typeof actual === 'string' && new RegExp(descriptor.pattern).test(actual);
|
|
73
|
+
case 'changed': return looseEqual(before, descriptor.from) && looseEqual(actual, descriptor.to);
|
|
74
|
+
default: return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const displayExpected = descriptor => (descriptor.matcher === 'changed' ? { from: descriptor.from, to: descriptor.to }
|
|
79
|
+
: descriptor.matcher === 'pattern' ? { pattern: descriptor.pattern } : descriptor.matcher === 'type' ? { type: descriptor.type }
|
|
80
|
+
: descriptor.value);
|
|
81
|
+
|
|
82
|
+
/** The target an approved-difference record names: the store/table (and field, for a `value`
|
|
83
|
+
* difference); `kind` is `value`, `missing` or `extra`, matching the finding it covers. An
|
|
84
|
+
* expired record (per `clock`) covers nothing, whatever else matches. */
|
|
85
|
+
function findApproved(approved, target, kind, expected, actual, clock) {
|
|
86
|
+
const now = clock();
|
|
87
|
+
return approved.find(record => record.kind === kind
|
|
88
|
+
// A record names its target the way the write does: a SQL table, a document collection or a key.
|
|
89
|
+
&& record.target?.store === target.store
|
|
90
|
+
&& (record.target?.table ?? record.target?.collection ?? record.target?.key) === target.table
|
|
91
|
+
&& (target.field === undefined || record.target?.field === target.field)
|
|
92
|
+
&& !(record.expires && new Date(record.expires) < now)
|
|
93
|
+
&& (record.expected === undefined || looseEqual(record.expected, expected))
|
|
94
|
+
&& (record.actual === undefined || looseEqual(record.actual, actual)));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The write's target name and, when it has one, its resolved row key. Redis-style writes name
|
|
98
|
+
* their target with a bare `key` string/expression instead of `table`/`collection`, and have no
|
|
99
|
+
* separate row key: the whole write is the one record at that key. */
|
|
100
|
+
function describeTarget(write, context) {
|
|
101
|
+
// A key is often a template with embedded expressions ("quote:{$steps.priceCart.outputs.quoteId}").
|
|
102
|
+
if (typeof write.key === 'string') return { target: interpolate(write.key, context), key: undefined };
|
|
103
|
+
const target = write.table ?? write.collection;
|
|
104
|
+
if (!write.key) return { target, key: undefined };
|
|
105
|
+
return { target, key: Object.fromEntries(Object.entries(write.key).map(([field, value]) => [field, resolveScalar(value, context)])) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether a `Db` log entry (`{ level: "Db", db: { system, operation, target } }`) is the command a
|
|
109
|
+
* write expects: the same store, the same operation (case-insensitive) and the same target (a
|
|
110
|
+
* Redis key, or a collection or table). */
|
|
111
|
+
function dbEntryMatches(entry, store, target, op) {
|
|
112
|
+
const db = entry?.level === 'Db' ? entry.db : undefined;
|
|
113
|
+
return !!db && db.system === store && String(db.operation ?? '').toLowerCase() === String(op ?? '').toLowerCase() && db.target === target;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const keyMatches =(resolvedKey, changeKey) => Object.entries(resolvedKey).every(([field, value]) => looseEqual(plainValue(changeKey?.[field]), value));
|
|
117
|
+
|
|
118
|
+
const findingId = (kind, index) => `${kind}:${index}`;
|
|
119
|
+
|
|
120
|
+
/** Compares one expected write against the change it matches, field by field, applying approved
|
|
121
|
+
* differences. `change` is null for a write nothing matched (a "missing" finding). */
|
|
122
|
+
function compareWrite(write, change, target, key, context, approved, clock, index) {
|
|
123
|
+
const base = { store: write.store, target, op: write.op, key };
|
|
124
|
+
if (!change) {
|
|
125
|
+
const approvedRecord = findApproved(approved, { store: write.store, table: target }, 'missing', undefined, undefined, clock);
|
|
126
|
+
return { id: findingId('missing', index), kind: approvedRecord ? 'approved' : 'missing', ...base, fields: [], record: approvedRecord?.id };
|
|
127
|
+
}
|
|
128
|
+
const fields = Object.entries(write.values ?? {}).map(([name, raw]) => {
|
|
129
|
+
const descriptor = describeExpected(raw, context);
|
|
130
|
+
const actual = change.after?.[name];
|
|
131
|
+
const before = change.before?.[name];
|
|
132
|
+
if (matches(descriptor, actual, before)) return { name, state: 'match', expected: displayExpected(descriptor), actual, source: descriptor.matcher };
|
|
133
|
+
const approvedRecord = findApproved(approved, { store: write.store, table: target, field: name }, 'value', displayExpected(descriptor), actual, clock);
|
|
134
|
+
if (approvedRecord) return { name, state: 'approved', expected: displayExpected(descriptor), actual, source: descriptor.matcher, record: approvedRecord.id };
|
|
135
|
+
return { name, state: 'differs', expected: displayExpected(descriptor), actual, source: descriptor.matcher };
|
|
136
|
+
});
|
|
137
|
+
const bad = fields.filter(field => field.state === 'differs');
|
|
138
|
+
const kind = bad.length ? 'differs' : fields.some(field => field.state === 'approved') ? 'approved' : 'match';
|
|
139
|
+
return { id: findingId('write', index), kind, ...base, fields };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** An effect's data field against an expectation: a list (an email's `to`, `cc`) matches a single
|
|
143
|
+
* expected value when one of its entries does, as hosts report recipients as arrays. */
|
|
144
|
+
function matchesEffectField(descriptor, actual) {
|
|
145
|
+
if (matches(descriptor, actual)) return true;
|
|
146
|
+
return Array.isArray(actual) && !Array.isArray(descriptor.value) && actual.some(item => matches(descriptor, item));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function compareEffect(expectedEffect, actualEffects, claimed, context, approved, clock, index) {
|
|
150
|
+
const field = (effect, name) => effect.data?.[name] ?? effect[name];
|
|
151
|
+
const toDescriptor = expectedEffect.to !== undefined ? describeExpected(expectedEffect.to, context) : undefined;
|
|
152
|
+
const candidates = actualEffects.map((effect, position) => ({ effect, position })).filter(({ effect, position }) =>
|
|
153
|
+
!claimed.has(position) && effect.kind === expectedEffect.kind && (!toDescriptor || matchesEffectField(toDescriptor, field(effect, 'to'))));
|
|
154
|
+
const chosen = candidates[0];
|
|
155
|
+
const base = { store: 'effect', target: expectedEffect.kind, op: 'send', key: undefined };
|
|
156
|
+
if (!chosen) return { id: findingId('effect', index), kind: 'missing', ...base, fields: [] };
|
|
157
|
+
claimed.add(chosen.position);
|
|
158
|
+
const fields = Object.entries(expectedEffect).filter(([name]) => name !== 'kind').map(([name, raw]) => {
|
|
159
|
+
const descriptor = describeExpected(raw, context);
|
|
160
|
+
const actual = field(chosen.effect, name);
|
|
161
|
+
if (matchesEffectField(descriptor, actual)) return { name, state: 'match', expected: displayExpected(descriptor), actual, source: descriptor.matcher };
|
|
162
|
+
return { name, state: 'differs', expected: displayExpected(descriptor), actual, source: descriptor.matcher };
|
|
163
|
+
});
|
|
164
|
+
const kind = fields.some(f => f.state === 'differs') ? 'differs' : 'match';
|
|
165
|
+
return { id: findingId('effect', index), kind, ...base, fields };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Compares one step's captured `changes` and `effects` with its `expected` writes and effects
|
|
170
|
+
* (journeys.md's expectations document, "writes" and "effects" arrays). `store` is the SQL
|
|
171
|
+
* system id (e.g. "sqlite"): a captured change with no `store` field is that database. `ignore`
|
|
172
|
+
* lists `{ store?, table }` pairs excused from `unlisted`. `logs` are the step's log entries: an
|
|
173
|
+
* expected write no change matches is also matched against its `Db` entries (store, op, key). `clock` (default the real clock) ages
|
|
174
|
+
* approved-difference records. Returns `{ verdict: 'passed' | 'passed-approved' | 'failed',
|
|
175
|
+
* findings }`; a finding's `record`, when set, is the approved-difference id it used.
|
|
176
|
+
*/
|
|
177
|
+
export function compareStep({ expected = {}, changes = [], effects = [], logs = [], context = {}, approved = [], ignore = [], unlisted = 'fail', store, clock = () => new Date() } = {}) {
|
|
178
|
+
const writes = expected.writes ?? [];
|
|
179
|
+
const expectedEffects = expected.effects ?? [];
|
|
180
|
+
const claimedChanges = new Set();
|
|
181
|
+
const claimedLogs = new Set();
|
|
182
|
+
const findings = [];
|
|
183
|
+
|
|
184
|
+
writes.forEach((write, index) => {
|
|
185
|
+
const { target, key } = describeTarget(write, context);
|
|
186
|
+
const candidates = changes
|
|
187
|
+
.map((change, position) => ({ change, position }))
|
|
188
|
+
.filter(({ change, position }) => !claimedChanges.has(position)
|
|
189
|
+
&& (change.store ?? store) === write.store && change.table === target && change.operation === write.op);
|
|
190
|
+
const chosen = key ? candidates.find(({ change }) => keyMatches(key, change.key)) : candidates[0];
|
|
191
|
+
if (chosen) claimedChanges.add(chosen.position);
|
|
192
|
+
// A traced Send records data-store commands only as Db log entries (spec/data-stores.md): no
|
|
193
|
+
// change matched, so look for the command itself. The log carries no values, so a command
|
|
194
|
+
// match checks the store, target and operation only.
|
|
195
|
+
const logged = chosen ? undefined : logs
|
|
196
|
+
.map((entry, position) => ({ entry, position }))
|
|
197
|
+
.find(({ entry, position }) => !claimedLogs.has(position) && dbEntryMatches(entry, write.store, target, write.op));
|
|
198
|
+
if (logged) {
|
|
199
|
+
claimedLogs.add(logged.position);
|
|
200
|
+
findings.push({ id: findingId('write', index), kind: 'match', store: write.store, target, op: write.op, key, fields: [], via: 'log' });
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
findings.push(compareWrite(write, chosen?.change ?? null, target, key, context, approved, clock, index));
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
changes.forEach((change, position) => {
|
|
207
|
+
if (claimedChanges.has(position)) return;
|
|
208
|
+
const effectiveStore = change.store ?? store;
|
|
209
|
+
if (ignore.some(rule => (rule.store ?? store) === effectiveStore && rule.table === change.table)) return;
|
|
210
|
+
if (unlisted !== 'fail') return;
|
|
211
|
+
const approvedRecord = findApproved(approved, { store: effectiveStore, table: change.table }, 'extra', undefined, undefined, clock);
|
|
212
|
+
findings.push({
|
|
213
|
+
id: findingId('extra', position), kind: approvedRecord ? 'approved' : 'extra',
|
|
214
|
+
store: effectiveStore, target: change.table, op: change.operation, key: change.key, fields: [], record: approvedRecord?.id,
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
const claimedEffects = new Set();
|
|
219
|
+
expectedEffects.forEach((expectedEffect, index) => findings.push(compareEffect(expectedEffect, effects, claimedEffects, context, approved, clock, index)));
|
|
220
|
+
|
|
221
|
+
const bad = findings.some(finding => finding.kind === 'differs' || finding.kind === 'missing' || finding.kind === 'extra');
|
|
222
|
+
const hasApproved = findings.some(finding => finding.kind === 'approved' || finding.fields.some(field => field.state === 'approved'));
|
|
223
|
+
const verdict = bad ? 'failed' : hasApproved ? 'passed-approved' : 'passed';
|
|
224
|
+
return { verdict, findings };
|
|
225
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Arazzo 1.1 runtime expressions, over two vendored libraries (ui/vendor/, both Apache-2.0):
|
|
2
|
+
// @swaggerexpert/arazzo-runtime-expression parses, validates and extracts the expressions, and
|
|
3
|
+
// its interpolate() splices a resolved value into a template string; @swaggerexpert/json-pointer
|
|
4
|
+
// evaluates the "#/a/b" suffix on $request.body and $response.body. Neither library knows what a
|
|
5
|
+
// Sendproof run context looks like, so this module is only that: a resolver over their parsed
|
|
6
|
+
// trees, for $inputs, $steps.<id>.outputs, $response.body (with the pointer), $response.header,
|
|
7
|
+
// $statusCode, $request.* and $url/$method.
|
|
8
|
+
import { extract, interpolate as interpolateTemplate, parse, test as isRuntimeExpression } from '../vendor/arazzo-runtime-expression.js';
|
|
9
|
+
import { evaluate as evaluatePointer } from '../vendor/json-pointer.js';
|
|
10
|
+
|
|
11
|
+
function readPath(object, dottedPath) {
|
|
12
|
+
let value = object;
|
|
13
|
+
for (const key of dottedPath.split('.')) {
|
|
14
|
+
if (value == null) return undefined;
|
|
15
|
+
value = value[key];
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function lookupHeader(headers, name) {
|
|
21
|
+
if (!headers) return undefined;
|
|
22
|
+
if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
|
|
23
|
+
const key = Object.keys(headers).find(candidate => candidate.toLowerCase() === name.toLowerCase());
|
|
24
|
+
return key === undefined ? undefined : headers[key];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A pointer into a body that doesn't have that shape (missing, the wrong type, no such index)
|
|
28
|
+
* resolves to undefined, the same as any other expression with nothing to read: a step whose
|
|
29
|
+
* response is an unexpected error, say, shouldn't throw just because its outputs don't apply. */
|
|
30
|
+
function readPointer(body, pointer) {
|
|
31
|
+
try { return evaluatePointer(body, pointer); } catch { return undefined; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** $request.* or $response.* : header, query, path or body (optionally with a JSON Pointer). */
|
|
35
|
+
function resolveMessage(message, reference) {
|
|
36
|
+
switch (reference.type) {
|
|
37
|
+
case 'HeaderReference': return lookupHeader(message?.headers, reference.token);
|
|
38
|
+
case 'QueryReference': return message?.query?.[reference.name];
|
|
39
|
+
case 'PathReference': return message?.path?.[reference.name];
|
|
40
|
+
case 'BodyReference': {
|
|
41
|
+
const body = message?.body;
|
|
42
|
+
return reference.jsonPointer ? readPointer(body, reference.jsonPointer.value) : body;
|
|
43
|
+
}
|
|
44
|
+
default: return undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Resolves one parsed expression tree (the `tree` from the vendored parse()) against a run
|
|
49
|
+
* context: { inputs, steps: { [stepId]: { outputs } }, workflows, request, response }. */
|
|
50
|
+
function resolveTree(tree, context) {
|
|
51
|
+
switch (tree.type) {
|
|
52
|
+
case 'StatusCodeExpression': return context.response?.statusCode;
|
|
53
|
+
case 'UrlExpression': return context.request?.url;
|
|
54
|
+
case 'MethodExpression': return context.request?.method;
|
|
55
|
+
case 'InputsExpression': return readPath(context.inputs, tree.name);
|
|
56
|
+
case 'StepsExpression': return readPath(context.steps?.[tree.stepId]?.[tree.field], tree.outputName);
|
|
57
|
+
case 'WorkflowsExpression': return readPath(context.workflows?.[tree.workflowId]?.[tree.field], tree.fieldName);
|
|
58
|
+
case 'RequestExpression': return resolveMessage(context.request, tree.source.reference);
|
|
59
|
+
case 'ResponseExpression': return resolveMessage(context.response, tree.source.reference);
|
|
60
|
+
default: return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A bare `$…` expression (as used for a whole parameter, body or matcher value): $inputs.x,
|
|
65
|
+
* $steps.id.outputs.x, $response.body#/ptr, $response.header.Name, $statusCode, $request.*.
|
|
66
|
+
* A value that isn't a runtime expression (doesn't start with "$") passes through unchanged. */
|
|
67
|
+
export function evaluate(expression, context = {}) {
|
|
68
|
+
if (typeof expression !== 'string' || !expression.startsWith('$')) return expression;
|
|
69
|
+
const { result, tree } = parse(expression);
|
|
70
|
+
if (!result.success || !tree) throw new RangeError(`Not a runtime expression: ${expression}`);
|
|
71
|
+
return resolveTree(tree, context);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const isWholeExpression = value => typeof value === 'string' && value.startsWith('$') && isRuntimeExpression(value);
|
|
75
|
+
const hasEmbeddedExpression = value => typeof value === 'string' && extract(value, { strict: false }).length > 0;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Interpolates one value against a run context, deeply: a string that is itself a whole
|
|
79
|
+
* expression (no surrounding braces) evaluates to its raw, possibly non-string, value; a
|
|
80
|
+
* "{$expr}" span embedded in a longer string is substituted, stringified, in place; arrays and
|
|
81
|
+
* plain objects are walked; everything else (including a plain literal string) passes through.
|
|
82
|
+
*/
|
|
83
|
+
export function interpolate(value, context = {}) {
|
|
84
|
+
if (Array.isArray(value)) return value.map(item => interpolate(item, context));
|
|
85
|
+
if (value !== null && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, interpolate(inner, context)]));
|
|
86
|
+
if (isWholeExpression(value)) return evaluate(value, context);
|
|
87
|
+
if (hasEmbeddedExpression(value)) return interpolateTemplate(value, expression => evaluate(expression, context), { strict: false });
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// The journey engine's public API (journeys-build.md, Contract 3). Pure ES modules, no DOM, no
|
|
2
|
+
// fetch: runnable in the browser and in Node 22. @sendproof/cli copies this directory into its
|
|
3
|
+
// package at build.
|
|
4
|
+
export { evaluate, interpolate } from './expressions.js';
|
|
5
|
+
export { bindStep, checkCriteria, stepOutputs } from './steps.js';
|
|
6
|
+
export { compareStep } from './compare.js';
|
|
7
|
+
export { createRun, recordStep, skipRun, exportRun, toJUnit } from './run.js';
|