@atscript/vue-wf 0.1.186 → 0.1.187

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.
@@ -1,9 +1,44 @@
1
1
  import { t as as_wf_finish_default } from "./as-wf-finish-DSlzLuDT.mjs";
2
- import { computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createVNode, defineComponent, guardReactiveProps, normalizeProps, onMounted, onUnmounted, openBlock, reactive, ref, renderSlot, shallowRef, toDisplayString, toRaw, unref, watch, withCtx } from "vue";
2
+ import { computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createVNode, defineComponent, getCurrentInstance, guardReactiveProps, normalizeProps, onMounted, onUnmounted, openBlock, reactive, ref, renderSlot, shallowRef, toDisplayString, toRaw, unref, watch, withCtx } from "vue";
3
3
  import { createFormData, createFormDef, deserializeServedType, getDeclaredFormActions } from "@atscript/ui";
4
4
  import { AS_UI_MESSAGES } from "@atscript/ui/messages";
5
5
  import { useAsTexts } from "@atscript/vue-form/locale";
6
6
  import { AsForm } from "@atscript/vue-form";
7
+ //#region src/session-run.ts
8
+ /**
9
+ * One `sessionStorage` entry. Never throws: no browser (SSR — Node 25+ has a
10
+ * process-wide `sessionStorage`, so `window` is the guard), disabled storage or
11
+ * a full quota read as nothing saved and fail the write — the run goes on in
12
+ * memory and only stops surviving a reload.
13
+ */
14
+ function sessionRunEntry(key) {
15
+ return {
16
+ load() {
17
+ try {
18
+ if (typeof window === "undefined") return void 0;
19
+ const value = JSON.parse(sessionStorage.getItem(key) ?? "null");
20
+ if (typeof value?.token !== "string" || !value.token) return void 0;
21
+ return typeof value.link === "string" ? {
22
+ link: value.link,
23
+ token: value.token
24
+ } : { token: value.token };
25
+ } catch {
26
+ return;
27
+ }
28
+ },
29
+ save(run) {
30
+ try {
31
+ if (typeof window === "undefined") return false;
32
+ if (run) sessionStorage.setItem(key, JSON.stringify(run));
33
+ else sessionStorage.removeItem(key);
34
+ return true;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+ };
40
+ }
41
+ //#endregion
7
42
  //#region src/use-wf-form.ts
8
43
  /**
9
44
  * A status with its own friendly text (`UI_WF_STATUS_<status>`: client errors
@@ -22,6 +57,18 @@ function servedTexts(data) {
22
57
  return (data?.inputRequired)?.payload?.$i18n;
23
58
  }
24
59
  /**
60
+ * A route pattern with its params filled in (`/projects/:id/setup` →
61
+ * `/projects/42/setup`), leaving out a param that holds the link, so the page
62
+ * stays the same when the link leaves the URL (`/invite/:token?` → `/invite`).
63
+ */
64
+ function fillRoutePattern(pattern, params, link) {
65
+ return pattern.replace(/:(\w+)(?:\([^)]*\))?[?*+]?/g, (_, name) => {
66
+ const value = params[name];
67
+ const text = Array.isArray(value) ? value.join("/") : typeof value === "string" ? value : "";
68
+ return text === link ? "" : text;
69
+ }).replace(/\/{2,}/g, "/").replace(/(.)\/$/, "$1");
70
+ }
71
+ /**
25
72
  * A `{ error }` answer as a `WfFormError`: a string is the message; an
26
73
  * object keeps its `message` / `status` / `code` and is the `body`.
27
74
  */
@@ -52,7 +99,18 @@ function useWfForm(options) {
52
99
  const finished = ref(false);
53
100
  /** Increments each time the form schema changes — used as :key on AsForm to force remount. */
54
101
  const formKey = ref(0);
55
- let token;
102
+ const persist = options.persistToken === "session";
103
+ const router = getCurrentInstance()?.appContext.config.globalProperties.$router;
104
+ const entry = persist && transport !== "cookie" ? sessionRunEntry(options.persistTokenKey ?? defaultRunKey()) : void 0;
105
+ let answeredLink;
106
+ let pendingLink;
107
+ /** Answered, but kept in the URL until the run is held elsewhere. */
108
+ let linkToDrop;
109
+ /** The link the current run started from — saved along with its token. */
110
+ let runLink;
111
+ /** Whether the last write of the entry went through (no entry: nothing to hold). */
112
+ let runSaved = true;
113
+ const token = ref(transport === "cookie" ? void 0 : startTokenFor(readInitialToken()));
56
114
  let lastRequestBody;
57
115
  let lastPayloadJson;
58
116
  let abortController;
@@ -70,34 +128,103 @@ function useWfForm(options) {
70
128
  };
71
129
  function readInitialToken() {
72
130
  if (options.initialToken) return options.initialToken;
73
- if (transport === "query") return new URLSearchParams(window.location.search).get(tokenName) ?? void 0;
131
+ if (transport === "query" && typeof window !== "undefined") return new URLSearchParams(window.location.search).get(tokenName) ?? void 0;
132
+ }
133
+ /**
134
+ * The token a start sends: the saved run's, when there is no link or the same
135
+ * link (it may have been renewed since); else the link until it is answered.
136
+ */
137
+ function startTokenFor(link) {
138
+ const run = entry?.load();
139
+ if (run && (!link || run.link === link)) {
140
+ runLink = run.link;
141
+ return run.token;
142
+ }
143
+ runLink = link;
144
+ return link !== answeredLink ? link : void 0;
145
+ }
146
+ /**
147
+ * `wf:<page>:<name>`: two pages running one workflow (an admin page, an
148
+ * invitee's link page; project 1's and project 2's setup) never share a run.
149
+ * The page is the route pattern with its params filled in except the link's
150
+ * (stable when a path-param link leaves the URL), else the pathname.
151
+ */
152
+ function defaultRunKey() {
153
+ const route = router?.currentRoute?.value;
154
+ const pattern = route?.matched?.[route.matched.length - 1]?.path;
155
+ return `wf:${pattern === void 0 ? typeof window === "undefined" ? "" : window.location.pathname : fillRoutePattern(pattern, route?.params ?? {}, readInitialToken())}:${options.name}`;
156
+ }
157
+ function setToken(next) {
158
+ if (transport === "cookie") return;
159
+ token.value = typeof next === "string" && next ? next : void 0;
160
+ if (entry) runSaved = entry.save(token.value ? {
161
+ link: runLink,
162
+ token: token.value
163
+ } : void 0);
164
+ }
165
+ /**
166
+ * After an answer: the link sent with the request is used up — except a refused
167
+ * request with cookie transport (no cookie was set: the link is still the only
168
+ * copy; a 410 means it is dead anyway). It leaves the URL once the run is held
169
+ * elsewhere: by the cookie, or by a saved entry (a failed save keeps it there).
170
+ */
171
+ function afterAnswer(usedLink, res) {
172
+ if (usedLink) if (transport === "cookie" && !res.ok && res.status !== 410) pendingLink = usedLink;
173
+ else {
174
+ answeredLink = usedLink;
175
+ linkToDrop = usedLink;
176
+ }
177
+ if (linkToDrop && (transport === "cookie" || runSaved)) {
178
+ const link = linkToDrop;
179
+ linkToDrop = void 0;
180
+ linkUsed(link);
181
+ }
182
+ }
183
+ /** The link is no longer needed: take it out of the URL. */
184
+ function linkUsed(link) {
185
+ if (options.onLinkUsed) {
186
+ try {
187
+ options.onLinkUsed();
188
+ } catch (err) {
189
+ if (import.meta.env?.DEV) console.error("[useWfForm] onLinkUsed threw:", err);
190
+ }
191
+ return;
192
+ }
193
+ if (!persist || typeof window === "undefined") return;
194
+ if (router) {
195
+ if (import.meta.env?.DEV) console.warn("[useWfForm] persistToken: the link token stays in the URL — pass `onLinkUsed` (`@link-used` on <AsWfForm>) and remove it with your router.");
196
+ return;
197
+ }
198
+ const url = new URL(window.location.href);
199
+ if (url.searchParams.get(tokenName) !== link) return;
200
+ url.searchParams.delete(tokenName);
201
+ history.replaceState(history.state, "", url);
74
202
  }
75
203
  function buildBody(payload) {
76
204
  const body = { ...payload };
77
- if (transport !== "cookie" && token) body[tokenName] = token;
205
+ if (token.value) body[tokenName] = token.value;
78
206
  return body;
79
207
  }
80
208
  function extractToken(data) {
81
- if (transport !== "cookie" && tokenName in data) token = data[tokenName];
209
+ if (tokenName in data) setToken(data[tokenName]);
210
+ }
211
+ /** The run is over for this client: a finish, or an outlet pause. */
212
+ function endRun(data, payload) {
213
+ finished.value = true;
214
+ response.value = data;
215
+ finishedPayload.value = payload;
216
+ formDef.value = null;
217
+ formData.value = null;
218
+ lastPayloadJson = void 0;
219
+ if (!(tokenName in data)) setToken(void 0);
82
220
  }
83
221
  function processResponse(data) {
84
- extractToken(data);
85
222
  if (data.finished) {
86
- finished.value = true;
87
- response.value = data;
88
- finishedPayload.value = data;
89
- formDef.value = null;
90
- formData.value = null;
91
- lastPayloadJson = void 0;
223
+ endRun(data, data);
92
224
  return;
93
225
  }
94
226
  if (data.sent === true || typeof data.outlet === "string") {
95
- finished.value = true;
96
- response.value = data;
97
- finishedPayload.value = null;
98
- formDef.value = null;
99
- formData.value = null;
100
- lastPayloadJson = void 0;
227
+ endRun(data, null);
101
228
  return;
102
229
  }
103
230
  if (data.error) {
@@ -123,7 +250,31 @@ function useWfForm(options) {
123
250
  finished.value = false;
124
251
  error.value = null;
125
252
  }
253
+ /** The request in flight (it settles, never rejects). */
254
+ let inFlight;
126
255
  async function post(body) {
256
+ const request = send(body);
257
+ inFlight = request;
258
+ try {
259
+ await request;
260
+ } finally {
261
+ if (inFlight === request) inFlight = void 0;
262
+ }
263
+ }
264
+ /**
265
+ * Cookie transport: a start sends `{ wfid }` with the cookie, and a cookie whose
266
+ * state an in-flight request has just consumed reads as no token — the server
267
+ * would start a second run (aborting the fetch does not stop the server). So a
268
+ * start waits for that request to settle instead of aborting it.
269
+ */
270
+ async function settleInFlight() {
271
+ const request = inFlight;
272
+ if (!request) return;
273
+ await request;
274
+ return settleInFlight();
275
+ }
276
+ const startWaits = () => transport === "cookie" && inFlight !== void 0;
277
+ async function send(body) {
127
278
  abortController?.abort();
128
279
  abortController = new AbortController();
129
280
  const { signal } = abortController;
@@ -142,10 +293,14 @@ function useWfForm(options) {
142
293
  signal,
143
294
  body: JSON.stringify(buildBody(body))
144
295
  });
296
+ const usedLink = pendingLink;
297
+ pendingLink = void 0;
145
298
  const data = await res.json().catch(() => null);
146
299
  if (!sendsLanguage) texts.merge(locale, servedTexts(data));
147
300
  if (data && typeof data === "object" && !Array.isArray(data)) extractToken(data);
301
+ afterAnswer(usedLink, res);
148
302
  if (!res.ok) {
303
+ if (res.status === 410 && entry && !runLink) entry.save(void 0);
149
304
  const errData = data;
150
305
  const failed = {
151
306
  message: errData?.message ?? errData?.error ?? friendlyMessageForStatus(res.status, t),
@@ -169,14 +324,17 @@ function useWfForm(options) {
169
324
  }
170
325
  }
171
326
  async function start(input) {
172
- const initialToken = readInitialToken();
173
- if (initialToken) token = initialToken;
174
- if (import.meta.env?.DEV && !initialToken && transport !== "query") {
327
+ if (startWaits()) await settleInFlight();
328
+ const link = readInitialToken();
329
+ const startToken = startTokenFor(link);
330
+ if (startToken) setToken(startToken);
331
+ pendingLink = link !== answeredLink ? link : void 0;
332
+ if (import.meta.env?.DEV && !link && transport !== "query") {
175
333
  if (new URLSearchParams(window.location.search).get(tokenName)) console.warn(`[useWfForm] URL contains ?${tokenName}=… but no \`initialToken\` was passed and \`tokenTransport\` is "${transport}". Workflow will start fresh instead of resuming the magic-link flow. Pass \`initial-token="route.query.${tokenName}"\` or set \`tokenTransport: "query"\`.`);
176
334
  }
177
335
  const body = { [wfidName]: options.name };
178
336
  if (input) body.input = { formData: input };
179
- if (initialToken) body[tokenName] = initialToken;
337
+ if (startToken && transport === "cookie") body[tokenName] = startToken;
180
338
  await post(body);
181
339
  }
182
340
  async function submit(data) {
@@ -192,6 +350,7 @@ function useWfForm(options) {
192
350
  } });
193
351
  }
194
352
  async function retry() {
353
+ if (lastRequestBody && wfidName in lastRequestBody && startWaits()) await settleInFlight();
195
354
  if (lastRequestBody) await post(lastRequestBody);
196
355
  }
197
356
  if (options.autoStart !== false) onMounted(() => start(options.input));
@@ -207,6 +366,7 @@ function useWfForm(options) {
207
366
  response,
208
367
  finishedPayload,
209
368
  error,
369
+ token,
210
370
  start,
211
371
  submit,
212
372
  action,
@@ -303,6 +463,18 @@ var as_wf_form_default = /* @__PURE__ */ defineComponent({
303
463
  initialToken: {
304
464
  type: String,
305
465
  required: false
466
+ },
467
+ persistToken: {
468
+ type: String,
469
+ required: false
470
+ },
471
+ persistTokenKey: {
472
+ type: String,
473
+ required: false
474
+ },
475
+ onLinkUsed: {
476
+ type: Function,
477
+ required: false
306
478
  }
307
479
  },
308
480
  emits: [
@@ -312,7 +484,8 @@ var as_wf_form_default = /* @__PURE__ */ defineComponent({
312
484
  "submit",
313
485
  "loading",
314
486
  "dismiss",
315
- "action"
487
+ "action",
488
+ "token"
316
489
  ],
317
490
  setup(__props, { expose: __expose, emit: __emit }) {
318
491
  const props = __props;
@@ -329,6 +502,7 @@ var as_wf_form_default = /* @__PURE__ */ defineComponent({
329
502
  watch([() => wf.formDef.value, () => wf.formContext.value], ([def, ctx]) => {
330
503
  if (def) emit("form", def, ctx);
331
504
  });
505
+ watch(() => wf.token.value, (v) => emit("token", v));
332
506
  const formActions = computed(() => {
333
507
  const def = wf.formDef.value;
334
508
  return def ? getDeclaredFormActions(def) : [];
@@ -1,2 +1,2 @@
1
- import { t as _default } from "./as-wf-form.vue-B4vJZta7.mjs";
1
+ import { t as _default } from "./as-wf-form.vue-23gylIsm.mjs";
2
2
  export { _default as default };
@@ -1,2 +1,2 @@
1
- import { t as as_wf_form_default } from "./as-wf-form-DEkBW0o_.mjs";
1
+ import { t as as_wf_form_default } from "./as-wf-form-CqpfnpJX.mjs";
2
2
  export { as_wf_form_default as default };
@@ -49,9 +49,39 @@ interface UseWfFormOptions {
49
49
  * outside `window.location.search` — e.g. encoded in a Vue Router path param
50
50
  * (`/invite/:token`) or pulled from app state. Included in the first request
51
51
  * so the server resumes the paused workflow instead of starting a new one.
52
- * Takes precedence over `tokenTransport: "query"` auto-detection.
52
+ * Takes precedence over `tokenTransport: "query"` auto-detection. `start()`
53
+ * sends it until a request carrying it is answered, or after its value
54
+ * changes; otherwise the run's current token (none once the run is over).
53
55
  */
54
56
  initialToken?: string;
57
+ /**
58
+ * `"session"`: keep the run's token in this tab's `sessionStorage` (one entry
59
+ * per workflow, `{ link, token }`), so a reload resumes the run while the
60
+ * token stays out of the URL and the history. The saved token wins over no
61
+ * link or the same link; a different link starts from itself. The entry is
62
+ * written on every token change and removed when the run is over (and on a
63
+ * `410` of a run that did not start from a link); storage errors leave the run
64
+ * in memory and the link in the URL. With cookie transport nothing is stored
65
+ * (the cookie survives a reload): only the link is dropped. Off by default.
66
+ */
67
+ persistToken?: "session";
68
+ /**
69
+ * `sessionStorage` key for `persistToken`. Default `wf:<page>:<name>`, the page
70
+ * being the Vue Router route pattern with its params filled in, except one
71
+ * holding the link (`/projects/42/setup`, `/invite`); else `location.pathname`,
72
+ * which cannot tell a path-param link apart (set the key there). Set it also
73
+ * for two runs of one workflow on a page.
74
+ */
75
+ persistTokenKey?: string;
76
+ /**
77
+ * Called once the link (`initialToken`, or the URL's with `tokenTransport:
78
+ * "query"`) is no longer needed: the server has answered it and the run is
79
+ * held elsewhere (the saved entry with `persistToken`, the cookie after a
80
+ * successful answer or a `410`). Remove the link from the URL here (e.g.
81
+ * `router.replace`). Without it, `persistToken` in an app with no Vue Router
82
+ * removes `?<tokenName>=` via `history.replaceState`.
83
+ */
84
+ onLinkUsed?: () => void;
55
85
  }
56
86
  /** A failed round-trip, as `error` holds it (and `AsWfForm` emits it). */
57
87
  interface WfFormError {
@@ -77,6 +107,15 @@ interface UseWfFormReturn {
77
107
  /** Typed envelope on finish — null while running, on outlet pause, or before first response. */
78
108
  finishedPayload: ShallowRef<WfFinished | null>;
79
109
  error: ShallowRef<unknown>;
110
+ /**
111
+ * The state token the next request sends: the start token (with
112
+ * `persistToken` the saved run's, else `initialToken` or the URL's with
113
+ * `tokenTransport: "query"`), then each answer's `wfs` —
114
+ * refused answers included. `undefined` once the run is over for this client:
115
+ * a finish, or an outlet pause whose answer carries no `wfs` (the token went
116
+ * out of band, e.g. in an email). Always `undefined` with cookie transport.
117
+ */
118
+ token: Readonly<Ref<string | undefined>>;
80
119
  start: (input?: Record<string, unknown>) => Promise<void>;
81
120
  submit: (data: unknown) => Promise<void>;
82
121
  action: (name: string) => Promise<void>;
@@ -358,6 +397,7 @@ declare const __VLS_base: vue.DefineComponent<AsWfFormProps, {
358
397
  finished: (response: unknown) => any;
359
398
  submit: (data: unknown) => any;
360
399
  loading: (isLoading: boolean) => any;
400
+ token: (token: string | undefined) => any;
361
401
  form: (def: FormDef, context?: Record<string, unknown> | undefined) => any;
362
402
  }, string, vue.PublicProps, Readonly<AsWfFormProps> & Readonly<{
363
403
  onDismiss?: (() => any) | undefined;
@@ -366,6 +406,7 @@ declare const __VLS_base: vue.DefineComponent<AsWfFormProps, {
366
406
  onFinished?: ((response: unknown) => any) | undefined;
367
407
  onSubmit?: ((data: unknown) => any) | undefined;
368
408
  onLoading?: ((isLoading: boolean) => any) | undefined;
409
+ onToken?: ((token: string | undefined) => any) | undefined;
369
410
  onForm?: ((def: FormDef, context?: Record<string, unknown> | undefined) => any) | undefined;
370
411
  }>, {
371
412
  tokenTransport: "body" | "cookie" | "query";
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { a as WfNext, i as WfMessage, n as WfButton, r as WfFinished, t as WfActionRequest } from "./index-C5MmoWFB.mjs";
2
- import { a as useWfForm, i as WfFormError, n as UseWfFormOptions, r as UseWfFormReturn, t as _default$1 } from "./as-wf-form.vue-B4vJZta7.mjs";
2
+ import { a as useWfForm, i as WfFormError, n as UseWfFormOptions, r as UseWfFormReturn, t as _default$1 } from "./as-wf-form.vue-23gylIsm.mjs";
3
3
  import { t as _default } from "./as-wf-finish.vue-BhXMooP3.mjs";
4
4
  export { _default as AsWfFinish, _default$1 as AsWfForm, type UseWfFormOptions, type UseWfFormReturn, type WfActionRequest, type WfButton, type WfFinished, type WfFormError, type WfMessage, type WfNext, useWfForm };
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { n as useWfForm, t as as_wf_form_default } from "./as-wf-form-DEkBW0o_.mjs";
1
+ import { n as useWfForm, t as as_wf_form_default } from "./as-wf-form-CqpfnpJX.mjs";
2
2
  import { t as as_wf_finish_default } from "./as-wf-finish-DSlzLuDT.mjs";
3
3
  export { as_wf_finish_default as AsWfFinish, as_wf_form_default as AsWfForm, useWfForm };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/vue-wf",
3
- "version": "0.1.186",
3
+ "version": "0.1.187",
4
4
  "description": "Workflow form integration for Vue 3 — HTTP round-trip loop driven by atscript type metadata",
5
5
  "keywords": [
6
6
  "atscript",
@@ -51,25 +51,25 @@
51
51
  "access": "public"
52
52
  },
53
53
  "dependencies": {
54
- "@atscript/ui": "^0.1.186"
54
+ "@atscript/ui": "^0.1.187"
55
55
  },
56
56
  "devDependencies": {
57
- "@atscript/core": "^0.2.19",
58
- "@atscript/typescript": "^0.2.19",
57
+ "@atscript/core": "^0.2.20",
58
+ "@atscript/typescript": "^0.2.20",
59
59
  "@vitejs/plugin-vue": "^6",
60
60
  "@vue/test-utils": "^2",
61
61
  "happy-dom": "^18",
62
- "unplugin-atscript": "^0.2.19",
62
+ "unplugin-atscript": "^0.2.20",
63
63
  "vitest": "npm:@voidzero-dev/vite-plus-test@0.1.14",
64
64
  "vue": "^3",
65
65
  "vue-tsc": "~3.2.9",
66
- "@atscript/moost-wf": "^0.1.186",
67
- "@atscript/vue-form": "^0.1.186"
66
+ "@atscript/moost-wf": "^0.1.187",
67
+ "@atscript/vue-form": "^0.1.187"
68
68
  },
69
69
  "peerDependencies": {
70
- "@atscript/typescript": "^0.2.19",
70
+ "@atscript/typescript": "^0.2.20",
71
71
  "vue": "^3",
72
- "@atscript/vue-form": "^0.1.186"
72
+ "@atscript/vue-form": "^0.1.187"
73
73
  },
74
74
  "scripts": {
75
75
  "build": "node ../../scripts/gen-exports.mjs && vp pack",