@extantape/payload-plugin-wizards 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 EXTANT APE
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,107 @@
1
- # Temporary Holding Version
1
+ # payload-plugin-wizards
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Wizards for Payload: gated step-by-step flows, one question per screen with Yes needed to go on, a video and text per step edited in the admin, and the answers checked on the server and recorded.
4
+
5
+ **Status:** early (0.x). 475 tests pass: 29 server tests on Payload 3.92 with an in-memory MongoDB, 13 on SQLite for blank text, 402 for the scope option, mostly run on MongoDB and SQLite, and 31 component tests in jsdom. It hasn't been tested on a real site, and nothing has run in a real browser.
6
+
7
+ ## What it does
8
+
9
+ - **Steps in the admin** (`guided-steps`): each has a flow, a key, a group, an order and a kind:
10
+ - **gate:** Yes needed to go on;
11
+ - **info:** Next;
12
+ - **choice:** options, any of which can stop the flow.
13
+
14
+ Each step also has its question, a text version, an optional video with required captions, a stop message, and active or not.
15
+ - Every step needs a question, and every gate and choice a stop message, which says what to do when the answer is No. Text that is only spaces doesn't count. A choice's options each need their own value and a label.
16
+ - A video has to be a video file, and its captions a WebVTT file.
17
+ - Each step's content hash covers what a person confirms (question, text, kind, options, stop message, video and captions) in the language they read it. It's worked out each time a step is read, so it can't go stale.
18
+ - Editors (`access.edit`, required) change steps. The public reads active ones only.
19
+ - **Flows are registered in code:** a list of slots, either your own code steps (finding a kit with the camera, choosing an animal) or a group of content steps. Other plugins register flows at `config.custom.wizardFlows` with no import, and a flow registered twice, or one that uses a group of steps twice, stops the site at start-up.
20
+ - **`flowSteps(payload, { flow, locale, req })`** gives the flow's slots, with active steps in order, for the page. A step whose question, stop message or an option label is blank in that language is left out and named in `blank`. With `localization.fallback: false`, an untranslated step is blank. Show an error instead of the flow when `blank` or `empty` has anything in it.
21
+ - **`<Wizard>`** (`./client`) shows one step per screen:
22
+ - focus on the question, "Step N of M", and Back;
23
+ - No shows the stop message and stays, and withdraws an earlier Yes on that step;
24
+ - video with captions, never autoplaying, and the text version always shown;
25
+ - your code steps rendered with `next` and `back`;
26
+ - a step with a blank question, stop message or option label shows an alert in place of the step, with no way to answer it;
27
+ - state in memory only.
28
+ - **The answers are checked on the server, not trusted.** Call `answersFor(payload, { flow, answers, req })` before acting. It refuses:
29
+ - a No, or a stopping choice;
30
+ - a step whose question, stop message or an option label is blank in the language asked for (`blankStep`), so nobody is recorded agreeing to text they weren't shown;
31
+ - a missing, extra or repeated step;
32
+ - a group of steps with no active step, so a safety group that was never seeded, is misspelled or was switched off never waves the flow through;
33
+ - any step whose wording changed since the screen loaded;
34
+ - a flow it doesn't know.
35
+
36
+ Pass the `locale` the person read. It returns the record to keep with your action: the language, each step's hash and question as the person read them, the answers, and the time. The hash identifies the full wording; the plugin keeps no copy of older wording, so keep versions on `guided-steps` if you need to show a past version in full. A client can't skip a gate by posting straight to your action.
37
+
38
+ ## Scope: one site's steps for one site
39
+
40
+ For a platform that runs several sites from one database. Unset, nothing changes: every caller sees every step, as in 0.1.0.
41
+
42
+ ```ts
43
+ wizardsPlugin({
44
+ flows,
45
+ access: { edit },
46
+ scope: {
47
+ where: ({ req }) => {
48
+ if (!req.user?.site) throw new Error('No site') // refuses plainly
49
+ return { site: { equals: req.user.site } }
50
+ },
51
+ indexWith: ['site'],
52
+ },
53
+ })
54
+ ```
55
+
56
+ - **`where`** runs on every call with the request. If it throws, the call is refused. A scope may use only `equals` and `in`. `equals` takes one non-empty string or number. `in` takes a non-empty list of them. The plugin refuses everything else at every depth, so a filter can't match everything by accident or mean one thing in memory and another in a database: any other operator (`not_equals`, `not_in`, `exists`, `like`, `contains` and the comparisons), an empty string, `null` or `undefined`, a list with an empty or null entry, an empty `and` or `or`, an empty `{}`, and anything that isn't a plain object. `and` and `or` can nest. Build `or` lists so that a user with no sites throws instead of producing `{ or: [] }`. If a user's site can be an object (a populated relationship), return its id. A host that wants every site leaves `scope` unset.
57
+ - **Reads:** the scope is ANDed with what the access rules already allow, so the REST API, GraphQL, count and the Local API with `overrideAccess: false` only see the caller's steps. `flowSteps` and `answersFor` take `req` and apply the scope themselves. With a scope set and no `req` they refuse (`answersFor` answers `noScope`) and never fall back to all sites.
58
+ - **Writes:** update and delete access are limited to the caller's steps. A create or update is checked at the database adapter, on the step exactly as it will be stored, after every field hook and every collection hook, including any your own plugins add. One that would leave the scope, including a move to another site, is refused with a 403 and nothing is written. That works the same with or without database transactions. The stored value of every field in the scope has to be a string or a number, so a missing, null, list or object value is refused. An update or a delete also reads the steps it would touch and refuses unless every one of them is inside the scope, so a call can't take another site's step into its own site or delete it. That covers `overrideAccess: true` calls and direct `db.updateOne`, `db.deleteOne` and `db.deleteMany` calls, and a `where` that matches steps on two sites is refused whole. A call with no `req` is refused. While a scope is set, `updateMany` and `upsert` on the adapter for the steps are refused, and so is `updateOne` with `upsert` set. A delete through the collection is also checked in `beforeDelete`. The stored-step check reads first and writes after, and the write is handed the scope in its `where`, so a step that moves to another site in between is not touched (the call then does nothing, or touches only the steps still in scope). The read uses the call's locale. A seeding script has to pass a `req` the hook accepts.
59
+ - **Plugin order:** the check wraps `db`, so set `db` in the config before this plugin and list `wizardsPlugin` last among the plugins that touch `db`. A plugin listed before it that wraps `create`, `updateOne` or `deleteOne` (or `deleteMany`) runs after the check, so its changes to those calls are not checked. At start-up the plugin looks at the adapter the site actually runs. If `find`, `create`, `updateOne`, `deleteOne`, `deleteMany`, `updateMany` or `upsert` is not the one this plugin wrapped (a later plugin put the original `db` back, or wrapped it again), the site refuses to start and the error says so.
60
+ - **`indexWith`** adds your field names to the unique index on flow + key. Sites that share step keys need it, because without it the index is flow + key alone, so a second site can't reuse a key. Even then a duplicate key is answered with a 400 "must be unique" without `indexWith`, including for a key that only another site uses, so the answer tells a caller that the key exists elsewhere. Set `indexWith` if that matters to you. You add the field yourself, in a plugin or config that runs after Wizards (`{ name: 'site', type: 'text', required: true, index: true }`, for example); naming a field that doesn't exist stops the site at start-up. If `scope` is set without `indexWith`, a warning is logged at start-up.
61
+ - **Videos and captions:** the file-type check when a step is saved, and the files `flowSteps` returns, are looked up as the caller (`overrideAccess: false`), so a site can't attach or show another site's files. Give your media collection its own site-based read access. A file the caller can't read shows as no video.
62
+ - **Per-site checks:** the group-with-no-active-step refusal runs inside the caller's scope. A site that never seeded its safety group is refused even when another site has one. The start-up checks (a flow registered twice, a group used twice) stay across the whole config.
63
+ - **Versions and drafts:** with a scope set, the steps collection can't have `versions` or `drafts` (autosave included). They write through adapter calls the scope check doesn't cover, and their reads aren't scoped. If a later plugin or your config turns them on, the site refuses to start. With no scope, nothing changes.
64
+ - **Limits:** Tested on MongoDB (replica set and standalone) and SQLite (with and without transactions).
65
+
66
+ ## On its own, and with others
67
+
68
+ **On its own:** Wizards needs only Payload, an `access.edit` rule, and an upload collection if your steps have videos (`media`, or `false` for none). Your site registers its flows in `flows` and renders its own code steps.
69
+
70
+ **Works with:**
71
+ - **Sample Kits:** with `adapters.wizards`, Sample Kits registers its `kit-activation` flow at `config.custom.wizardFlows` and checks the answers with `answersFor`.
72
+ - **Scan:** a code step can show Scan's `<CameraScanButton>`, for example to find a kit. Neither plugin imports the other.
73
+
74
+ **Family:** Wizards sits in the Fulfillment family, with Kitting, Restock, Sample Kits, Shipping, Scan, Labels, Custody and Sequences, though the families are a working draft and Fulfillment is due to be split into different groups.
75
+
76
+ ## Install
77
+
78
+ ```sh
79
+ npm install @extantape/payload-plugin-wizards
80
+ ```
81
+
82
+ ```ts
83
+ import { wizardsPlugin } from '@extantape/payload-plugin-wizards'
84
+
85
+ wizardsPlugin({
86
+ flows: { 'kit-activation': { slots: [{ code: 'find-kit' }, { steps: 'safety' }, { code: 'sampled' }] } },
87
+ access: { edit: ({ req }) => req.user?.role === 'editor' }, // required
88
+ media: 'media', // your upload collection for videos and captions, or false
89
+ })
90
+
91
+ // In your action, before doing anything:
92
+ const check = await answersFor(payload, { flow: 'kit-activation', answers, locale })
93
+ if (!check.ok) return refuse(check.problem)
94
+ await markSampled(kit, { confirmed: check.record })
95
+ ```
96
+
97
+ ## Commands
98
+
99
+ ```sh
100
+ npm test
101
+ npm run typecheck
102
+ npm run build
103
+ ```
104
+
105
+ ## License
106
+
107
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Text a person must read is there: a string that still has a letter, number, punctuation mark or symbol once the
3
+ * characters that draw nothing are removed. Spaces, control characters and lone combining marks don't count.
4
+ * Anything else counts as blank, including a missing value and an object (such as every language at once).
5
+ */
6
+ export declare const hasText: (v: unknown) => v is string;
7
+ /**
8
+ * Whether a step, as read in one language, lacks text a person is asked to agree to or be stopped by: the question
9
+ * (the title of an information step), the stop message of a gate or choice, or the label of any option of a choice.
10
+ * Such a step is never shown, answered or recorded.
11
+ */
12
+ export declare const isBlankStep: (s: {
13
+ kind?: unknown;
14
+ question?: unknown;
15
+ stopMessage?: unknown;
16
+ options?: unknown;
17
+ }) => boolean;
package/dist/blank.js ADDED
@@ -0,0 +1,18 @@
1
+ /** Characters that draw nothing: Unicode's default-ignorable code points, plus the braille blank (U+2800). */
2
+ const invisible = /[\p{Default_Ignorable_Code_Point}\u2800]/gu;
3
+ /** What counts as something to read: a letter, number, punctuation mark or symbol (emoji included). */
4
+ const readable = /[\p{L}\p{N}\p{P}\p{S}]/u;
5
+ /**
6
+ * Text a person must read is there: a string that still has a letter, number, punctuation mark or symbol once the
7
+ * characters that draw nothing are removed. Spaces, control characters and lone combining marks don't count.
8
+ * Anything else counts as blank, including a missing value and an object (such as every language at once).
9
+ */
10
+ export const hasText = (v) => typeof v === 'string' && readable.test(v.replace(invisible, ''));
11
+ /**
12
+ * Whether a step, as read in one language, lacks text a person is asked to agree to or be stopped by: the question
13
+ * (the title of an information step), the stop message of a gate or choice, or the label of any option of a choice.
14
+ * Such a step is never shown, answered or recorded.
15
+ */
16
+ export const isBlankStep = (s) => !hasText(s.question) ||
17
+ (s.kind !== 'info' && !hasText(s.stopMessage)) ||
18
+ (s.kind === 'choice' && !(Array.isArray(s.options) && s.options.every((o) => Boolean(o) && typeof o === 'object' && hasText(o.label))));
@@ -0,0 +1,48 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { Answer, Step } from '../types.js';
3
+ /** One screen of the flow, as the server's flowSteps() returns it. */
4
+ export type WizardSlot = {
5
+ code: string;
6
+ } | {
7
+ step: Step;
8
+ };
9
+ /** What a code step's renderer gets. */
10
+ export type CodeStepContext = {
11
+ /** Store `value` under `values[code]` (when given) and go to the next screen. */
12
+ next: (value?: unknown) => void;
13
+ /** Go to the previous screen. Does nothing on the first. */
14
+ back: () => void;
15
+ values: Record<string, unknown>;
16
+ answers: Answer[];
17
+ };
18
+ export type WizardResult = {
19
+ answers: Answer[];
20
+ values: Record<string, unknown>;
21
+ };
22
+ export type WizardLabels = {
23
+ yes: string;
24
+ no: string;
25
+ next: string;
26
+ back: string;
27
+ stepOf: (n: number, m: number) => string;
28
+ /** Shown when a code slot has no renderer. That's a bug in the site, not something the person can fix. */
29
+ missingCode: (code: string) => string;
30
+ /** Shown when onFinish throws or rejects. The buttons come back so the person can try again. */
31
+ finishFailed: string;
32
+ /** Shown instead of a step whose question, stop message or an option label is blank. There is no way to answer it. */
33
+ blankStep: string;
34
+ /** Visible marker on the option or button chosen earlier, so the choice isn't shown by color alone. */
35
+ chosen: string;
36
+ };
37
+ export type WizardProps = {
38
+ slots: WizardSlot[];
39
+ renderCode: Record<string, (ctx: CodeStepContext) => ReactNode>;
40
+ onFinish: (result: WizardResult) => void | Promise<void>;
41
+ labels?: Partial<WizardLabels>;
42
+ };
43
+ export declare const defaultLabels: WizardLabels;
44
+ /**
45
+ * A guided flow, one slot per screen. State lives in memory only: nothing is
46
+ * written to localStorage, sessionStorage or cookies.
47
+ */
48
+ export declare function Wizard({ slots, renderCode, onFinish, labels: labelOverrides, }: WizardProps): import("react").JSX.Element | null;
@@ -0,0 +1,135 @@
1
+ 'use client';
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useId, useRef, useState } from 'react';
4
+ import { isBlankStep } from '../blank.js';
5
+ export const defaultLabels = {
6
+ yes: 'Yes',
7
+ no: 'No',
8
+ next: 'Next',
9
+ back: 'Back',
10
+ stepOf: (n, m) => `Step ${n} of ${m}`,
11
+ missingCode: (code) => `This step ("${code}") can't be shown. Please contact the site.`,
12
+ finishFailed: "That didn't go through. Please try again.",
13
+ blankStep: "This step can't be shown in your language yet, so it can't be answered. Please contact the site.",
14
+ chosen: '(chosen)',
15
+ };
16
+ const buttonStyle = { minHeight: 44, minWidth: 44, padding: '0.5rem 1rem' };
17
+ function isCode(slot) {
18
+ return 'code' in slot;
19
+ }
20
+ /**
21
+ * A guided flow, one slot per screen. State lives in memory only: nothing is
22
+ * written to localStorage, sessionStorage or cookies.
23
+ */
24
+ export function Wizard({ slots, renderCode, onFinish, labels: labelOverrides, }) {
25
+ const labels = { ...defaultLabels, ...labelOverrides };
26
+ const baseId = useId();
27
+ const [index, setIndex] = useState(0);
28
+ // Answers keyed by slot index, so Back keeps them and answering again replaces them.
29
+ const [answers, setAnswers] = useState({});
30
+ const [values, setValues] = useState({});
31
+ const [stopMessage, setStopMessage] = useState('');
32
+ const [busy, setBusy] = useState(false);
33
+ const [done, setDone] = useState(false);
34
+ const [error, setError] = useState('');
35
+ const finishing = useRef(false);
36
+ const focusTarget = useRef(null);
37
+ const mounted = useRef(false);
38
+ // Move focus to the new screen's heading when the step changes. Not on first
39
+ // render, so the page doesn't jump to the wizard before the person gets there.
40
+ useEffect(() => {
41
+ if (!mounted.current) {
42
+ mounted.current = true;
43
+ return;
44
+ }
45
+ focusTarget.current?.focus();
46
+ }, [index]);
47
+ const ordered = (byIndex) => slots.flatMap((slot, i) => (!isCode(slot) && byIndex[i] ? [byIndex[i]] : []));
48
+ const advance = useCallback((nextAnswers, nextValues) => {
49
+ setStopMessage('');
50
+ setError('');
51
+ if (index < slots.length - 1) {
52
+ setIndex(index + 1);
53
+ return;
54
+ }
55
+ if (finishing.current)
56
+ return;
57
+ finishing.current = true;
58
+ setBusy(true);
59
+ const result = {
60
+ answers: slots.flatMap((slot, i) => (!isCode(slot) && nextAnswers[i] ? [nextAnswers[i]] : [])),
61
+ values: nextValues,
62
+ };
63
+ Promise.resolve()
64
+ .then(() => onFinish(result))
65
+ .then(() => setDone(true), () => {
66
+ finishing.current = false;
67
+ setBusy(false);
68
+ setError(labels.finishFailed);
69
+ });
70
+ }, [index, slots, onFinish, labels.finishFailed]);
71
+ const back = useCallback(() => {
72
+ if (busy || done || index === 0)
73
+ return;
74
+ setStopMessage('');
75
+ setError('');
76
+ setIndex(index - 1);
77
+ }, [busy, done, index]);
78
+ const record = (step, value) => {
79
+ if (isBlankStep(step))
80
+ return;
81
+ const nextAnswers = { ...answers, [index]: { key: step.key, hash: step.hash, value } };
82
+ setAnswers(nextAnswers);
83
+ advance(nextAnswers, values);
84
+ };
85
+ // No withdraws an earlier Yes on this step: it's no longer shown as chosen, and the flow can't finish with it.
86
+ const stop = (message) => {
87
+ setStopMessage(message);
88
+ setAnswers((current) => {
89
+ if (!(index in current))
90
+ return current;
91
+ const { [index]: _withdrawn, ...rest } = current;
92
+ return rest;
93
+ });
94
+ };
95
+ if (slots.length === 0)
96
+ return null;
97
+ const slot = slots[index];
98
+ if (!slot)
99
+ return null;
100
+ const disabled = busy || done;
101
+ const progressId = `${baseId}-progress`;
102
+ const headingId = `${baseId}-heading`;
103
+ const progress = labels.stepOf(index + 1, slots.length);
104
+ const blank = !isCode(slot) && isBlankStep(slot.step);
105
+ const alertText = blank ? labels.blankStep : error;
106
+ const backButton = index > 0 ? (_jsx("button", { type: "button", style: buttonStyle, onClick: back, disabled: disabled, className: "wizard-back", children: labels.back })) : null;
107
+ const liveRegions = (_jsxs(_Fragment, { children: [_jsx("div", { role: "status", "aria-live": "polite", className: "wizard-stop", children: stopMessage ? _jsx("p", { children: stopMessage }) : null }), _jsx("div", { role: "alert", className: "wizard-error", children: alertText ? _jsx("p", { children: alertText }) : null })] }));
108
+ if (isCode(slot)) {
109
+ const render = renderCode[slot.code];
110
+ const ctx = {
111
+ next: (value) => {
112
+ if (disabled)
113
+ return;
114
+ const nextValues = value === undefined ? values : { ...values, [slot.code]: value };
115
+ setValues(nextValues);
116
+ advance(answers, nextValues);
117
+ },
118
+ back,
119
+ values,
120
+ answers: ordered(answers),
121
+ };
122
+ return (_jsxs("section", { className: "wizard", "data-slot": slot.code, "aria-labelledby": progressId, "aria-busy": busy || undefined, tabIndex: -1, ref: (el) => {
123
+ focusTarget.current = el;
124
+ }, children: [_jsx("p", { id: progressId, className: "wizard-progress", children: progress }), render ? render(ctx) : _jsx("p", { className: "wizard-missing", children: labels.missingCode(slot.code) }), liveRegions, _jsx("div", { className: "wizard-nav", children: backButton })] }));
125
+ }
126
+ const step = slot.step;
127
+ const previous = answers[index]?.value;
128
+ if (blank)
129
+ return (_jsxs("section", { className: "wizard", "data-step": step.key, "aria-labelledby": progressId, children: [_jsx("p", { id: progressId, className: "wizard-progress", tabIndex: -1, ref: (el) => { focusTarget.current = el; }, children: progress }), liveRegions, _jsx("div", { className: "wizard-nav", children: backButton })] }));
130
+ return (_jsxs("section", { className: "wizard", "data-step": step.key, "aria-labelledby": headingId, "aria-busy": busy || undefined, children: [_jsx("p", { id: progressId, className: "wizard-progress", children: progress }), _jsx("h2", { id: headingId, tabIndex: -1, "aria-describedby": progressId, ref: (el) => {
131
+ focusTarget.current = el;
132
+ }, children: step.question }), step.video ? (
133
+ // Never autoplays; the person starts it. The text version below is always on the page.
134
+ _jsx("video", { controls: true, preload: "none", src: step.video.url, className: "wizard-video", children: _jsx("track", { kind: "captions", default: true, src: step.video.captionsUrl }) })) : null, step.body ? _jsx("p", { className: "wizard-body", children: step.body }) : null, step.kind === 'gate' ? (_jsxs("div", { className: "wizard-actions", role: "group", "aria-labelledby": headingId, children: [_jsxs("button", { type: "button", style: buttonStyle, disabled: disabled, "aria-pressed": previous === 'yes', onClick: () => record(step, 'yes'), children: [labels.yes, previous === 'yes' ? ` ${labels.chosen}` : null] }), _jsx("button", { type: "button", style: buttonStyle, disabled: disabled, onClick: () => stop(step.stopMessage), children: labels.no })] })) : null, step.kind === 'info' ? (_jsx("div", { className: "wizard-actions", children: _jsx("button", { type: "button", style: buttonStyle, disabled: disabled, onClick: () => record(step, 'seen'), children: labels.next }) })) : null, step.kind === 'choice' ? (_jsx("div", { className: "wizard-actions", role: "group", "aria-labelledby": headingId, children: step.options.map((option) => (_jsxs("button", { type: "button", style: buttonStyle, disabled: disabled, "aria-pressed": previous === option.value, onClick: () => (option.stops ? stop(step.stopMessage) : record(step, option.value)), children: [option.label, previous === option.value ? ` ${labels.chosen}` : null] }, option.value))) })) : null, liveRegions, _jsx("div", { className: "wizard-nav", children: backButton })] }));
135
+ }
@@ -0,0 +1,3 @@
1
+ export { Wizard, defaultLabels } from './Wizard.js';
2
+ export type { CodeStepContext, WizardLabels, WizardProps, WizardResult, WizardSlot } from './Wizard.js';
3
+ export type { Answer, Step } from '../types.js';
@@ -0,0 +1,2 @@
1
+ 'use client';
2
+ export { Wizard, defaultLabels } from './Wizard.js';
@@ -0,0 +1,3 @@
1
+ export { wizardsPlugin } from './plugin.js';
2
+ export { answersFor, contentHash, flowSteps, flowsOf } from './steps.js';
3
+ export type { Answer, Flow, FlowRegistration, ScopeOption, Slot, Step, WizardRecord, WizardsOptions } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { wizardsPlugin } from './plugin.js';
2
+ export { answersFor, contentHash, flowSteps, flowsOf } from './steps.js';
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from 'payload';
2
+ import type { WizardsOptions } from './types.js';
3
+ /** Wizards: gated step-by-step flows, steps edited in the admin, and answers checked on the server. */
4
+ export declare const wizardsPlugin: (options: WizardsOptions) => Plugin;
package/dist/plugin.js ADDED
@@ -0,0 +1,26 @@
1
+ import { assertGuarded, flowsOf, guardDb, stepsCollection } from './steps.js';
2
+ /** Wizards: gated step-by-step flows, steps edited in the admin, and answers checked on the server. */
3
+ export const wizardsPlugin = (options) => (config) => {
4
+ const o = { scope: options.scope, slug: options.slug ?? 'guided-steps', flows: options.flows ?? {}, edit: options?.access?.edit, media: options.media === undefined ? 'media' : options.media, adminGroup: options.adminGroup ?? 'Wizards' };
5
+ if (o.scope && typeof o.scope.where !== 'function')
6
+ throw new Error('Wizards: `scope.where` must be a function.');
7
+ if (o.scope?.indexWith && !(Array.isArray(o.scope.indexWith) && o.scope.indexWith.every((f) => typeof f === 'string' && f)))
8
+ throw new Error('Wizards: `scope.indexWith` must be a list of field names.');
9
+ if (typeof o.edit !== 'function')
10
+ throw new Error('Wizards: give `access.edit`, saying who may change the steps.');
11
+ if (o.media && !(config.collections ?? []).some((c) => c.slug === o.media && c.upload))
12
+ throw new Error(`Wizards: "${o.media}" isn't an upload collection. Set \`media\`, or false for no videos.`);
13
+ return {
14
+ ...config,
15
+ db: guardDb(o, config.db),
16
+ custom: { ...config.custom, wizards: o },
17
+ collections: [...(config.collections ?? []), stepsCollection(o)],
18
+ onInit: async (payload) => {
19
+ flowsOf(payload);
20
+ assertGuarded(o, payload);
21
+ if (o.scope && !o.scope.indexWith?.length)
22
+ payload.logger.warn('Wizards: scope is set without indexWith, so two sites can’t use the same step key. Add indexWith (and the field) if sites share keys.');
23
+ await config.onInit?.(payload);
24
+ },
25
+ };
26
+ };
@@ -0,0 +1,83 @@
1
+ import { APIError } from 'payload';
2
+ import type { CollectionConfig, Config, Payload } from 'payload';
3
+ import type { Flow, Req, Resolved, Step, WizardRecord } from './types.js';
4
+ /** The scope could not be worked out, or a write or read falls outside it. Carries status 403. */
5
+ export declare class ScopeError extends APIError {
6
+ constructor(message: string);
7
+ }
8
+ /**
9
+ * Puts the scope check at the one place every save passes last: the database adapter's create and update, which
10
+ * receive the step exactly as it will be stored, after every field hook and every collection hook any plugin added,
11
+ * whatever the plugins do before the adapter is called. An update or delete also reads the stored steps and refuses
12
+ * unless every one is inside the scope, so a call can't move another site's step into its own site or delete it, and
13
+ * the write itself is handed the scope in its `where` (and no `id`), so a step that changes between the read and the
14
+ * write is still not touched. A bulk update or an upsert straight on the adapter is refused while a scope is set. A
15
+ * plugin that wraps `db` and is listed before this one runs after the check on `create`, `updateOne`, `deleteOne`
16
+ * and `deleteMany`, so its changes to those calls are not checked.
17
+ */
18
+ export declare const guardDb: (o: Resolved, db: Config["db"] | undefined) => Config["db"];
19
+ /**
20
+ * Start-up check with a scope set: the adapter the site actually runs must still carry this plugin's check (a plugin
21
+ * that puts back an earlier `config.db` removes it), and the steps must have no versions or drafts, which write
22
+ * through adapter calls the check does not cover.
23
+ */
24
+ export declare const assertGuarded: (o: Resolved, payload: Payload) => void;
25
+ /**
26
+ * What a person confirms, in the language they read it: question, body, kind, options, the stop message, and the
27
+ * video with its captions. Worked out each time a step is read in a locale, never stored, so it can't be stale or
28
+ * belong to another language.
29
+ */
30
+ export declare const contentHash: (s: {
31
+ question?: unknown;
32
+ body?: unknown;
33
+ kind?: unknown;
34
+ options?: unknown;
35
+ stopMessage?: unknown;
36
+ video?: unknown;
37
+ captions?: unknown;
38
+ }) => string;
39
+ export declare const stepsCollection: (o: Resolved) => CollectionConfig;
40
+ /** Every flow: the site's own and those other plugins registered at `config.custom.wizardFlows`. One owner each. */
41
+ export declare function flowsOf(payload: Payload): Record<string, Flow>;
42
+ /**
43
+ * The content steps of a flow, in slot order, as the client shows them, in the locale asked for. Only active steps.
44
+ * `empty` names any group of steps with no active step, and `blank` the key of any step left out because its
45
+ * question, its stop message or an option label is blank in that locale (with `fallback: false`, an untranslated
46
+ * step is blank). Either way the flow can't be passed until an editor fixes it.
47
+ */
48
+ export declare function flowSteps(payload: Payload, args: {
49
+ flow: string;
50
+ locale?: string;
51
+ req?: Req;
52
+ }): Promise<{
53
+ slots: ({
54
+ code: string;
55
+ } | {
56
+ step: Step;
57
+ })[];
58
+ empty: string[];
59
+ blank: string[];
60
+ }>;
61
+ /**
62
+ * Checks a flow's answers on the server before the owner acts. Fails closed: every active content step must be
63
+ * answered exactly once, with the wording the server has now in that locale (its hash), and every gate Yes and every
64
+ * choice a non-stopping option. A group of steps with no active step fails (`noSteps`): a safety group emptied by
65
+ * mistake never waves a flow through. A step whose question, stop message or option label is blank in that locale
66
+ * fails (`blankStep`), so nobody agrees to, or is recorded agreeing to, text they were never shown. A step changed since the screen loaded fails, and the person sees the new
67
+ * wording. Returns the record to store with the action: the locale, and for each step the hash and the question as
68
+ * the person read it, with the answer and the time. With a `scope` set, `req` is required and the check runs inside
69
+ * the caller's scope; without it the answer is `noScope`, never all sites.
70
+ */
71
+ export declare function answersFor(payload: Payload, args: {
72
+ flow: string;
73
+ answers: unknown;
74
+ locale?: string;
75
+ req?: Req;
76
+ }): Promise<{
77
+ ok: true;
78
+ record: WizardRecord;
79
+ } | {
80
+ ok: false;
81
+ problem: 'noScope' | 'unknownFlow' | 'noSteps' | 'blankStep' | 'badAnswers' | 'missing' | 'extra' | 'changed' | 'notYes';
82
+ key?: string;
83
+ }>;
package/dist/steps.js ADDED
@@ -0,0 +1,452 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { APIError } from 'payload';
3
+ import { hasText, isBlankStep } from './blank.js';
4
+ const configOf = (payload) => {
5
+ const o = payload.config.custom?.wizards;
6
+ if (!o)
7
+ throw new Error('Wizards: the plugin is not configured on this site.');
8
+ return o;
9
+ };
10
+ /** The scope could not be worked out, or a write or read falls outside it. Carries status 403. */
11
+ export class ScopeError extends APIError {
12
+ constructor(message) {
13
+ super(message, 403, undefined, true);
14
+ }
15
+ }
16
+ const isObject = (v) => {
17
+ if (!v || typeof v !== 'object' || Array.isArray(v))
18
+ return false;
19
+ const proto = Object.getPrototypeOf(v);
20
+ return proto === Object.prototype || proto === null;
21
+ };
22
+ /** A value a scope may compare to: a non-empty string or a finite number. Nothing else is allowed, so nothing can match everything. */
23
+ const scalar = (v) => (typeof v === 'string' && v !== '') || (typeof v === 'number' && Number.isFinite(v));
24
+ /**
25
+ * A scope is safe to apply only if it can't match everything by accident and means the same thing in memory and in
26
+ * every database. At every depth: `and` and `or` are non-empty arrays of scopes, and a field maps to a non-empty
27
+ * object of `equals` (one non-empty string or finite number) and `in` (a non-empty list of them). Any other operator,
28
+ * an empty or null value and anything not recognized is refused. Plain objects only. A deliberate match-all is the
29
+ * host's own choice, made without the scope option.
30
+ */
31
+ const validScope = (w) => {
32
+ if (!isObject(w))
33
+ return false;
34
+ const keys = Object.keys(w);
35
+ if (!keys.length)
36
+ return false;
37
+ return keys.every((k) => {
38
+ const v = w[k];
39
+ if (k === 'and' || k === 'or')
40
+ return Array.isArray(v) && v.length > 0 && v.every(validScope);
41
+ if (!isObject(v))
42
+ return false;
43
+ const ops = Object.keys(v);
44
+ return ops.length > 0 && ops.every((op) => (op === 'equals' ? scalar(v[op]) : op === 'in' ? Array.isArray(v[op]) && v[op].length > 0 && v[op].every(scalar) : false));
45
+ });
46
+ };
47
+ const pathValue = (doc, path) => path.split('.').reduce((acc, k) => (acc && typeof acc === 'object' ? acc[k] : undefined), doc);
48
+ /**
49
+ * Whether a document (as it will be saved) matches a validated scope. A stored value that isn't a string or a number
50
+ * (an object, a list, null, nothing) matches nothing, so a write the databases would read differently is refused.
51
+ */
52
+ const matches = (doc, w) => Object.entries(w).every(([k, v]) => {
53
+ if (k === 'and')
54
+ return v.every((x) => matches(doc, x));
55
+ if (k === 'or')
56
+ return v.some((x) => matches(doc, x));
57
+ const raw = pathValue(doc, k);
58
+ if (typeof raw !== 'string' && typeof raw !== 'number')
59
+ return false;
60
+ const val = String(raw);
61
+ return Object.entries(v).every(([op, arg]) => (op === 'equals' ? val === String(arg) : op === 'in' ? arg.map(String).includes(val) : false));
62
+ });
63
+ /**
64
+ * The caller's scope: `null` when the host set none (0.1.0 behavior), otherwise its `where`. Fails closed: no
65
+ * request, a hook that throws, or anything that isn't a valid scope raises ScopeError.
66
+ */
67
+ const scopeOf = async (o, req) => {
68
+ if (!o.scope)
69
+ return null;
70
+ if (!req)
71
+ throw new ScopeError('Wizards: a scope is set, so this call needs `req`.');
72
+ let w;
73
+ try {
74
+ w = await o.scope.where({ req: req });
75
+ }
76
+ catch {
77
+ throw new ScopeError('Wizards: the scope hook threw, so the call is refused.');
78
+ }
79
+ if (!validScope(w))
80
+ throw new ScopeError('Wizards: the scope hook must return a non-empty filter that uses only `equals` and `in`, with non-empty string or number values, so the call is refused.');
81
+ return w;
82
+ };
83
+ /** An access result with the scope ANDed in. `false` stays false; a failing scope refuses. */
84
+ const withScope = async (o, req, result) => {
85
+ if (result === false)
86
+ return false;
87
+ let scope;
88
+ try {
89
+ scope = await scopeOf(o, req);
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ if (!scope)
95
+ return result;
96
+ return result === true ? scope : { and: [result, scope] };
97
+ };
98
+ /** Refuses, before anything is saved, a step that would sit outside the caller's scope. */
99
+ const checkWrite = (next, scope) => {
100
+ if (!matches(next, scope))
101
+ throw new ScopeError('This step would be outside your scope.');
102
+ };
103
+ /** The adapter functions this plugin put its check in, so start-up can tell whether a later plugin took them out. */
104
+ const guarded = new WeakSet();
105
+ const checked = ['create', 'updateOne', 'deleteOne', 'deleteMany'];
106
+ const refused = ['updateMany', 'upsert'];
107
+ /** Passed straight through, but marked: the stored-step check reads with `find`, so a later plugin that wraps it would be noticed. */
108
+ const watched = ['find'];
109
+ /** Whether an object has anything in it. */
110
+ const hasKeys = (w) => Boolean(w) && Object.keys(w).length > 0;
111
+ /**
112
+ * What the adapter will act on, worked out the way the adapters do: `updateOne` uses `id` when it is truthy and the
113
+ * `where` otherwise; `deleteOne` and `deleteMany` use only the `where` and ignore an `id`.
114
+ */
115
+ const targetOf = (name, a) => (name === 'updateOne' && a.id ? { id: { equals: a.id } } : a.where);
116
+ /**
117
+ * Reads the stored steps the call would touch and refuses unless every one of them is inside the scope. It reads in
118
+ * the locale the call uses, so a `where` on a localized field means the same here as in the write, and it reads with
119
+ * `find`, which every database allows inside a transaction.
120
+ */
121
+ const checkStored = async (adapter, o, a, target, scope) => {
122
+ const locale = a.locale ?? a.req?.locale;
123
+ const howMany = async (where) => (await adapter.find.call(adapter, { collection: o.slug, where, locale, limit: 0, pagination: false, select: { id: true }, req: a.req })).docs.length;
124
+ const base = hasKeys(target) ? target : {};
125
+ const all = await howMany(base);
126
+ if (all && (await howMany(hasKeys(target) ? { and: [base, scope] } : scope)) !== all)
127
+ throw new ScopeError('This step is outside your scope.');
128
+ };
129
+ /**
130
+ * Puts the scope check at the one place every save passes last: the database adapter's create and update, which
131
+ * receive the step exactly as it will be stored, after every field hook and every collection hook any plugin added,
132
+ * whatever the plugins do before the adapter is called. An update or delete also reads the stored steps and refuses
133
+ * unless every one is inside the scope, so a call can't move another site's step into its own site or delete it, and
134
+ * the write itself is handed the scope in its `where` (and no `id`), so a step that changes between the read and the
135
+ * write is still not touched. A bulk update or an upsert straight on the adapter is refused while a scope is set. A
136
+ * plugin that wraps `db` and is listed before this one runs after the check on `create`, `updateOne`, `deleteOne`
137
+ * and `deleteMany`, so its changes to those calls are not checked.
138
+ */
139
+ export const guardDb = (o, db) => {
140
+ if (!o.scope)
141
+ return db;
142
+ if (!db || typeof db.init !== 'function')
143
+ throw new Error('Wizards: a scope needs `db` set before this plugin, so the check can sit at the database.');
144
+ return {
145
+ ...db,
146
+ init: (args) => {
147
+ const adapter = db.init(args);
148
+ for (const name of watched) {
149
+ const original = adapter[name];
150
+ if (typeof original !== 'function')
151
+ throw new Error(`Wizards: the database adapter has no ${name}, so the scope can't be enforced.`);
152
+ const wrapped = function (a) {
153
+ return original.call(this, a);
154
+ };
155
+ guarded.add(wrapped);
156
+ adapter[name] = wrapped;
157
+ }
158
+ for (const name of checked) {
159
+ const original = adapter[name];
160
+ if (typeof original !== 'function')
161
+ throw new Error(`Wizards: the database adapter has no ${name}, so the scope can't be enforced.`);
162
+ const wrapped = async function (a) {
163
+ if (a?.collection !== o.slug)
164
+ return original.call(this, a);
165
+ const scope = await scopeOf(o, a.req);
166
+ if (!scope)
167
+ return original.call(this, a);
168
+ if (name === 'create') {
169
+ checkWrite((a.data ?? {}), scope);
170
+ return original.call(this, a);
171
+ }
172
+ if (name === 'updateOne') {
173
+ // An upsert inserts when nothing matches, so the stored-step check would have nothing to read. Refused like `upsert` itself.
174
+ if (a.upsert || a.options?.upsert)
175
+ throw new ScopeError('Wizards: an upsert on the steps is refused while a scope is set.');
176
+ checkWrite((a.data ?? {}), scope);
177
+ }
178
+ const target = targetOf(name, a);
179
+ await checkStored(adapter, o, a, target, scope);
180
+ const { id: _id, ...rest } = a;
181
+ return original.call(this, { ...rest, where: hasKeys(target) ? { and: [target, scope] } : scope });
182
+ };
183
+ guarded.add(wrapped);
184
+ adapter[name] = wrapped;
185
+ }
186
+ for (const name of refused) {
187
+ const original = adapter[name];
188
+ if (typeof original !== 'function')
189
+ continue;
190
+ const wrapped = async function (a) {
191
+ if (a?.collection === o.slug)
192
+ throw new ScopeError(`Wizards: ${name} on the steps is refused while a scope is set.`);
193
+ return original.call(this, a);
194
+ };
195
+ guarded.add(wrapped);
196
+ adapter[name] = wrapped;
197
+ }
198
+ return adapter;
199
+ },
200
+ };
201
+ };
202
+ /**
203
+ * Start-up check with a scope set: the adapter the site actually runs must still carry this plugin's check (a plugin
204
+ * that puts back an earlier `config.db` removes it), and the steps must have no versions or drafts, which write
205
+ * through adapter calls the check does not cover.
206
+ */
207
+ export const assertGuarded = (o, payload) => {
208
+ if (!o.scope)
209
+ return;
210
+ const db = payload.db;
211
+ for (const name of [...watched, ...checked, ...refused]) {
212
+ const fn = db[name];
213
+ if (typeof fn === 'function' && !guarded.has(fn))
214
+ throw new Error(`Wizards: the database adapter's ${name} is not the one this plugin wrapped, so the scope isn't enforced. Another plugin replaced or re-wrapped \`db\`. Put \`wizardsPlugin\` last among the plugins that touch \`db\`.`);
215
+ }
216
+ const steps = payload.config.collections.find((c) => c.slug === o.slug);
217
+ if (steps?.versions)
218
+ throw new Error('Wizards: a scope is set, so the steps collection can\u2019t have versions or drafts. They write through adapter calls the scope check does not cover.');
219
+ };
220
+ /** Refuses, before the delete, a step outside the caller's scope. */
221
+ const beforeDelete = (o) => async ({ id, req }) => {
222
+ const scope = await scopeOf(o, req);
223
+ if (!scope)
224
+ return;
225
+ const { totalDocs } = await req.payload.count({ collection: o.slug, where: { and: [{ id: { equals: id } }, scope] }, overrideAccess: true, req });
226
+ if (!totalDocs)
227
+ throw new ScopeError('This step is outside your scope.');
228
+ };
229
+ /** A media file as the hash sees it: its id and when it last changed, so a swapped or replaced file counts as new. */
230
+ const fileOf = (v) => (v && typeof v === 'object' ? [String(v.id ?? ''), String(v.updatedAt ?? '')] : v ? [String(v), ''] : null);
231
+ /**
232
+ * What a person confirms, in the language they read it: question, body, kind, options, the stop message, and the
233
+ * video with its captions. Worked out each time a step is read in a locale, never stored, so it can't be stale or
234
+ * belong to another language.
235
+ */
236
+ export const contentHash = (s) => createHash('sha256')
237
+ .update(JSON.stringify([s.question ?? '', s.body ?? '', s.kind ?? '', s.options?.map((x) => { const o = x; return [o.value, o.label, Boolean(o.stops)]; }) ?? [], s.stopMessage ?? '', fileOf(s.video), fileOf(s.captions)]))
238
+ .digest('hex')
239
+ .slice(0, 24);
240
+ const idOf = (v) => (v && typeof v === 'object' ? v.id : v);
241
+ const beforeChange = (o) => async ({ data, originalDoc, req }) => {
242
+ const next = { ...originalDoc, ...data };
243
+ // The scope is checked later, at the database, once every hook has run.
244
+ if (next.video && !next.captions)
245
+ throw new Error('A step with a video needs its captions (a WebVTT file).');
246
+ if (next.kind === 'choice' && !(Array.isArray(next.options) && next.options.length >= 2))
247
+ throw new Error('A choice step needs at least two options.');
248
+ if (next.kind === 'choice') {
249
+ const values = next.options.map((x) => String(x?.value ?? ''));
250
+ // One value for a stopping and a going-on option would let the check accept either.
251
+ if (new Set(values).size !== values.length)
252
+ throw new Error('Each option in a choice step needs its own value.');
253
+ }
254
+ if (!hasText(next.question))
255
+ throw new Error('A step needs a question with words in it, in each language it is saved in.');
256
+ if (next.kind === 'choice' && !next.options.every((x) => hasText(x?.label)))
257
+ throw new Error('Each option in a choice step needs a label with words in it.');
258
+ if (next.kind !== 'info' && !hasText(next.stopMessage))
259
+ throw new Error('A gate or choice step needs a stop message: what to do when the answer is No.');
260
+ if (o.media && (next.video || next.captions)) {
261
+ const mime = async (v) => String((await req.payload.findByID({ collection: o.media, id: idOf(v), depth: 0, overrideAccess: !o.scope, req }).catch(() => null))?.mimeType ?? '');
262
+ if (next.video && !(await mime(next.video)).startsWith('video/'))
263
+ throw new Error('The video needs to be a video file.');
264
+ if (next.captions && !/^text\/(vtt|plain)$/.test(await mime(next.captions)))
265
+ throw new Error('The captions need to be a WebVTT (.vtt) file.');
266
+ }
267
+ return data;
268
+ };
269
+ export const stepsCollection = (o) => ({
270
+ slug: o.slug,
271
+ labels: { singular: 'Guided step', plural: 'Guided steps' },
272
+ admin: { group: o.adminGroup, useAsTitle: 'question', defaultColumns: ['flow', 'group', 'order', 'question', 'active'] },
273
+ access: {
274
+ read: async (args) => withScope(o, args.req, (await o.edit(args)) === true ? true : { active: { equals: true } }),
275
+ create: async (args) => (await o.edit(args)) === true && (await withScope(o, args.req, true)) !== false,
276
+ update: async (args) => withScope(o, args.req, (await o.edit(args)) === true),
277
+ delete: async (args) => withScope(o, args.req, (await o.edit(args)) === true),
278
+ },
279
+ hooks: { beforeChange: [beforeChange(o)], beforeDelete: [beforeDelete(o)] },
280
+ indexes: [{ fields: ['flow', 'key', ...(o.scope?.indexWith ?? [])], unique: true }],
281
+ fields: [
282
+ { name: 'flow', type: 'text', required: true, index: true },
283
+ { name: 'key', type: 'text', required: true, admin: { description: 'Stable: answers name it. Don’t reuse a key for a different question.' } },
284
+ { name: 'group', type: 'text', required: true, admin: { description: 'The flow takes a group of steps in one place, such as "safety".' } },
285
+ { name: 'order', type: 'number', defaultValue: 100 },
286
+ { name: 'kind', type: 'select', required: true, defaultValue: 'gate', options: [{ label: 'Gate (Yes needed to go on)', value: 'gate' }, { label: 'Information (Next)', value: 'info' }, { label: 'Choice', value: 'choice' }] },
287
+ { name: 'question', type: 'text', required: true, localized: true },
288
+ { name: 'body', type: 'textarea', localized: true, admin: { description: 'The text version: everything the video says.' } },
289
+ ...(o.media
290
+ ? [
291
+ { name: 'video', type: 'upload', relationTo: o.media },
292
+ { name: 'captions', type: 'upload', relationTo: o.media, admin: { description: 'WebVTT captions. Required with a video.' } },
293
+ ]
294
+ : []),
295
+ {
296
+ name: 'options',
297
+ type: 'array',
298
+ admin: { condition: (d) => d?.kind === 'choice' },
299
+ fields: [
300
+ { name: 'value', type: 'text', required: true },
301
+ { name: 'label', type: 'text', required: true, localized: true },
302
+ { name: 'stops', type: 'checkbox', admin: { description: 'This answer stops the flow until changed.' } },
303
+ ],
304
+ },
305
+ { name: 'stopMessage', type: 'textarea', localized: true, admin: { description: 'What No says: what to do before going on.' } },
306
+ { name: 'active', type: 'checkbox', defaultValue: true, index: true },
307
+ ],
308
+ });
309
+ /** Every flow: the site's own and those other plugins registered at `config.custom.wizardFlows`. One owner each. */
310
+ export function flowsOf(payload) {
311
+ const o = configOf(payload);
312
+ const all = {};
313
+ const owner = {};
314
+ const add = (who, flows) => {
315
+ for (const [k, f] of Object.entries(flows ?? {})) {
316
+ if (owner[k])
317
+ throw new Error(`Wizards: the flow "${k}" is registered by both ${owner[k]} and ${who}.`);
318
+ if (!Array.isArray(f?.slots) || !f.slots.length)
319
+ throw new Error(`Wizards: the flow "${k}" from ${who} has no slots.`);
320
+ const groups = f.slots.flatMap((s) => ('steps' in s ? [s.steps] : []));
321
+ // A group in two slots would ask each step twice, and no answer could pass.
322
+ if (new Set(groups).size !== groups.length)
323
+ throw new Error(`Wizards: the flow "${k}" from ${who} uses a group of steps twice.`);
324
+ owner[k] = who;
325
+ all[k] = f;
326
+ }
327
+ };
328
+ add('the site', o.flows);
329
+ const regs = payload.config.custom?.wizardFlows;
330
+ for (const r of Array.isArray(regs) ? regs : [])
331
+ add(String(r?.owner ?? 'a plugin'), r?.flows);
332
+ return all;
333
+ }
334
+ const urlOf = (v) => (v && typeof v === 'object' && typeof v.url === 'string' ? v.url : null);
335
+ /**
336
+ * The content steps of a flow, in slot order, as the client shows them, in the locale asked for. Only active steps.
337
+ * `empty` names any group of steps with no active step, and `blank` the key of any step left out because its
338
+ * question, its stop message or an option label is blank in that locale (with `fallback: false`, an untranslated
339
+ * step is blank). Either way the flow can't be passed until an editor fixes it.
340
+ */
341
+ export async function flowSteps(payload, args) {
342
+ const o = configOf(payload);
343
+ const scope = await scopeOf(o, args.req);
344
+ const flows = flowsOf(payload);
345
+ const flow = Object.hasOwn(flows, args.flow) ? flows[args.flow] : null;
346
+ if (!flow)
347
+ throw new Error(`Wizards: no flow "${args.flow}".`);
348
+ const docs = (await payload.find({ collection: o.slug, where: { and: [{ flow: { equals: args.flow } }, { active: { equals: true } }, ...(scope ? [scope] : [])] }, sort: ['order', 'key'], pagination: false, depth: scope ? 0 : 1, overrideAccess: true, ...(args.locale ? { locale: args.locale } : {}) })).docs;
349
+ // With a scope, files are fetched as the caller, so another site's video and captions never reach this site's page.
350
+ if (scope) {
351
+ const asCaller = async (v) => (v ? (await payload.findByID({ collection: o.media, id: idOf(v), depth: 0, overrideAccess: false, req: args.req }).catch(() => null)) : null);
352
+ for (const d of docs) {
353
+ if (o.media) {
354
+ d.video = await asCaller(d.video);
355
+ d.captions = await asCaller(d.captions);
356
+ }
357
+ }
358
+ }
359
+ const out = [];
360
+ const empty = [];
361
+ const blank = [];
362
+ for (const slot of flow.slots) {
363
+ if ('code' in slot)
364
+ out.push({ code: slot.code });
365
+ else {
366
+ const group = docs.filter((x) => x.group === slot.steps);
367
+ if (!group.length)
368
+ empty.push(slot.steps);
369
+ for (const d of group) {
370
+ if (isBlankStep(d)) {
371
+ blank.push(String(d.key));
372
+ continue;
373
+ }
374
+ const video = urlOf(d.video);
375
+ const captions = urlOf(d.captions);
376
+ out.push({
377
+ step: {
378
+ key: d.key,
379
+ group: d.group,
380
+ kind: d.kind,
381
+ question: d.question,
382
+ body: d.body ?? '',
383
+ video: video && captions ? { url: video, captionsUrl: captions } : null,
384
+ options: (d.options ?? []).map((x) => ({ value: String(x.value), label: String(x.label), stops: Boolean(x.stops) })),
385
+ stopMessage: d.stopMessage ?? '',
386
+ hash: contentHash(d),
387
+ },
388
+ });
389
+ }
390
+ }
391
+ }
392
+ return { slots: out, empty, blank };
393
+ }
394
+ /**
395
+ * Checks a flow's answers on the server before the owner acts. Fails closed: every active content step must be
396
+ * answered exactly once, with the wording the server has now in that locale (its hash), and every gate Yes and every
397
+ * choice a non-stopping option. A group of steps with no active step fails (`noSteps`): a safety group emptied by
398
+ * mistake never waves a flow through. A step whose question, stop message or option label is blank in that locale
399
+ * fails (`blankStep`), so nobody agrees to, or is recorded agreeing to, text they were never shown. A step changed since the screen loaded fails, and the person sees the new
400
+ * wording. Returns the record to store with the action: the locale, and for each step the hash and the question as
401
+ * the person read it, with the answer and the time. With a `scope` set, `req` is required and the check runs inside
402
+ * the caller's scope; without it the answer is `noScope`, never all sites.
403
+ */
404
+ export async function answersFor(payload, args) {
405
+ let flow;
406
+ try {
407
+ flow = await flowSteps(payload, { flow: args.flow, locale: args.locale, req: args.req });
408
+ }
409
+ catch (e) {
410
+ if (e instanceof ScopeError)
411
+ return { ok: false, problem: 'noScope' };
412
+ return { ok: false, problem: 'unknownFlow' };
413
+ }
414
+ if (flow.empty.length)
415
+ return { ok: false, problem: 'noSteps', key: flow.empty[0] };
416
+ if (flow.blank.length)
417
+ return { ok: false, problem: 'blankStep', key: flow.blank[0] };
418
+ if (!Array.isArray(args.answers) || args.answers.some((a) => !a || typeof a !== 'object' || typeof a.key !== 'string' || typeof a.hash !== 'string' || typeof a.value !== 'string'))
419
+ return { ok: false, problem: 'badAnswers' };
420
+ const answers = args.answers;
421
+ const steps = flow.slots.flatMap((s) => ('step' in s ? [s.step] : []));
422
+ const byKey = new Map();
423
+ for (const a of answers)
424
+ byKey.set(a.key, [...(byKey.get(a.key) ?? []), a]);
425
+ for (const a of answers)
426
+ if (!steps.some((s) => s.key === a.key))
427
+ return { ok: false, problem: 'extra', key: a.key };
428
+ for (const s of steps) {
429
+ const given = byKey.get(s.key) ?? [];
430
+ if (given.length !== 1)
431
+ return { ok: false, problem: given.length ? 'extra' : 'missing', key: s.key };
432
+ const a = given[0];
433
+ if (isBlankStep(s))
434
+ return { ok: false, problem: 'blankStep', key: s.key };
435
+ if (a.hash !== s.hash)
436
+ return { ok: false, problem: 'changed', key: s.key };
437
+ if (s.kind === 'gate' && a.value !== 'yes')
438
+ return { ok: false, problem: 'notYes', key: s.key };
439
+ if (s.kind === 'info' && a.value !== 'seen')
440
+ return { ok: false, problem: 'notYes', key: s.key };
441
+ if (s.kind === 'choice') {
442
+ const opt = s.options.find((x) => x.value === a.value);
443
+ if (!opt || opt.stops)
444
+ return { ok: false, problem: 'notYes', key: s.key };
445
+ }
446
+ if (s.kind !== 'gate' && s.kind !== 'info' && s.kind !== 'choice')
447
+ return { ok: false, problem: 'notYes', key: s.key };
448
+ }
449
+ const localization = payload.config.localization;
450
+ const locale = args.locale || (localization ? localization.defaultLocale : null);
451
+ return { ok: true, record: { flow: args.flow, at: new Date().toISOString(), locale, answers: steps.map((s) => ({ key: s.key, hash: s.hash, value: byKey.get(s.key)[0].value, question: s.question })) } };
452
+ }
@@ -0,0 +1,86 @@
1
+ import type { Access, Payload, PayloadRequest, Where } from 'payload';
2
+ export type Req = Partial<PayloadRequest>;
3
+ /** A slot in a flow: a code step the site renders, or every active guided step in a group, in order. */
4
+ export type Slot = {
5
+ code: string;
6
+ } | {
7
+ steps: string;
8
+ };
9
+ export type Flow = {
10
+ slots: Slot[];
11
+ };
12
+ export type FlowRegistration = {
13
+ owner: string;
14
+ flows: Record<string, Flow>;
15
+ };
16
+ /** A content step as the client gets it. */
17
+ export type Step = {
18
+ key: string;
19
+ group: string;
20
+ kind: 'gate' | 'info' | 'choice';
21
+ question: string;
22
+ body: string;
23
+ video: {
24
+ url: string;
25
+ captionsUrl: string;
26
+ } | null;
27
+ options: {
28
+ value: string;
29
+ label: string;
30
+ stops: boolean;
31
+ }[];
32
+ stopMessage: string;
33
+ hash: string;
34
+ };
35
+ /** What the client sends for each content step it showed: the step, the wording it saw, and the answer. */
36
+ export type Answer = {
37
+ key: string;
38
+ hash: string;
39
+ value: string;
40
+ };
41
+ /** What to store with the owner's action: which wording, in which language, was confirmed, and when. */
42
+ export type WizardRecord = {
43
+ flow: string;
44
+ at: string;
45
+ locale: string | null;
46
+ answers: (Answer & {
47
+ question: string;
48
+ })[];
49
+ };
50
+ /**
51
+ * Limits every read and write of the steps to the caller's slice, such as one site. `where` runs for each call with
52
+ * the request and must return a non-empty plain object; anything else (a throw, `{}`, `null`, an array) refuses.
53
+ * `indexWith` adds the host's own field names (such as `site`) to the unique index on flow + key. The host adds
54
+ * those fields to the steps collection itself.
55
+ */
56
+ export type ScopeOption = {
57
+ where: (args: {
58
+ req: PayloadRequest;
59
+ }) => Where | Promise<Where>;
60
+ indexWith?: string[];
61
+ };
62
+ export type WizardsOptions = {
63
+ /** Unset keeps every step visible to every caller, as in 0.1.0. */
64
+ scope?: ScopeOption;
65
+ flows?: Record<string, Flow>;
66
+ /** Who edits the steps. Required; only an answer of exactly true counts. */
67
+ access: {
68
+ edit: Access;
69
+ };
70
+ /** The upload collection for videos and captions. Default 'media'; `false` for no videos. */
71
+ media?: string | false;
72
+ slug?: string;
73
+ adminGroup?: string;
74
+ };
75
+ export type Resolved = {
76
+ scope?: ScopeOption;
77
+ slug: string;
78
+ flows: Record<string, Flow>;
79
+ edit: Access;
80
+ media: string | false;
81
+ adminGroup: string;
82
+ };
83
+ export type Ctx = {
84
+ payload: Payload;
85
+ req?: Req;
86
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-wizards",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Wizards for Payload: gated step-by-step flows, one question per screen with Yes needed to go on, a video and text per step edited in the admin, and the answers checked on the server and recorded.",
5
+ "homepage": "https://github.com/ExtantApe/payload-plugin-wizards#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/ExtantApe/payload-plugin-wizards/issues"
8
+ },
9
+ "keywords": [
10
+ "payload",
11
+ "payload-plugin",
12
+ "payloadcms",
13
+ "forms",
14
+ "content",
15
+ "wizard",
16
+ "guided-steps",
17
+ "step-by-step",
18
+ "checklist",
19
+ "onboarding",
20
+ "accessibility"
21
+ ],
22
+ "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/ExtantApe/payload-plugin-wizards.git"
26
+ },
27
+ "type": "module",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ },
33
+ "./client": {
34
+ "types": "./dist/client/index.d.ts",
35
+ "import": "./dist/client/index.js"
36
+ }
37
+ },
38
+ "main": "./dist/index.js",
39
+ "types": "./dist/index.d.ts",
40
+ "files": [
41
+ "dist",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "engines": {
46
+ "node": ">=22"
47
+ },
48
+ "scripts": {
49
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
50
+ "typecheck": "tsc --noEmit",
51
+ "test": "vitest run",
52
+ "leak-check": "bash scripts/leak-check.sh",
53
+ "prepack": "npm run build",
54
+ "prepublishOnly": "npm run typecheck && npm test"
55
+ },
56
+ "peerDependencies": {
57
+ "payload": "^3.80.0",
58
+ "react": "^19.0.0"
59
+ },
60
+ "devDependencies": {
61
+ "@payloadcms/db-mongodb": "3.92.1",
62
+ "@payloadcms/db-sqlite": "3.92.1",
63
+ "@payloadcms/graphql": "3.92.1",
64
+ "@testing-library/react": "^16.3.3",
65
+ "@types/node": "^24.0.0",
66
+ "@types/react": "^19.3.0",
67
+ "@types/react-dom": "^19.3.0",
68
+ "graphql": "^16.14.2",
69
+ "jsdom": "^31.0.0",
70
+ "mongodb-memory-server": "^11.3.0",
71
+ "payload": "3.92.1",
72
+ "react": "^19.3.1",
73
+ "react-dom": "^19.3.1",
74
+ "typescript": "^5.9.0",
75
+ "vitest": "^3.2.0"
76
+ },
77
+ "peerDependenciesMeta": {
78
+ "react": {
79
+ "optional": true
80
+ }
81
+ }
82
+ }