@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.4
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/dist/actions.d.ts +7 -0
- package/dist/actions.js +21 -3
- package/dist/actions.test.js +8 -410
- package/dist/after.d.ts +28 -0
- package/dist/after.js +48 -0
- package/dist/after.test.js +58 -0
- package/dist/assets-static.d.ts +10 -1
- package/dist/assets-static.js +10 -2
- package/dist/base-path.js +4 -3
- package/dist/builtin-tags.d.ts +12 -0
- package/dist/builtin-tags.js +42 -0
- package/dist/builtin-tags.test.js +12 -0
- package/dist/cache-adapter.test.js +4 -203
- package/dist/cache-scope.d.ts +2 -0
- package/dist/cache.test.js +1 -197
- package/dist/cloudflare-workers.d.ts +2 -0
- package/dist/cloudflare-workers.js +27 -0
- package/dist/dev-overlay.d.ts +54 -3
- package/dist/dev-overlay.js +469 -76
- package/dist/dom.js +3 -1
- package/dist/events.test.js +2 -407
- package/dist/handler-html.test.js +1 -202
- package/dist/handler-routing.js +3 -0
- package/dist/handler-segments.d.ts +6 -0
- package/dist/handler-segments.js +16 -2
- package/dist/handler-segments.test.js +8 -200
- package/dist/head-tags.d.ts +9 -0
- package/dist/head-tags.js +85 -1
- package/dist/head-tags.test.js +18 -125
- package/dist/index.d.ts +1 -5
- package/dist/index.js +3 -0
- package/dist/inline-action-token.test.js +31 -0
- package/dist/jsx-svg-types.test.js +58 -0
- package/dist/jsx-types.d.ts +92 -1
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +384 -65
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router-lite.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +2 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/link-base-path.test.js +28 -0
- package/dist/node-server.test.js +1 -355
- package/dist/platform.d.ts +52 -0
- package/dist/platform.js +57 -0
- package/dist/platform.test.js +44 -0
- package/dist/router-nav.test.js +15 -444
- package/dist/router.js +39 -1
- package/dist/server-handler.d.ts +48 -0
- package/dist/server-handler.js +279 -17
- package/dist/server-handler.test.js +54 -388
- package/dist/server-renderer.test.js +0 -104
- package/dist/server.d.ts +15 -5
- package/dist/server.js +149 -22
- package/dist/server.test.js +52 -60
- package/dist/site-config.d.ts +13 -0
- package/dist/site-config.js +28 -0
- package/dist/site-config.test.js +30 -0
- package/dist/slot.d.ts +12 -0
- package/dist/slot.js +23 -0
- package/dist/slot.test.js +25 -0
- package/dist/ssr-core-behavior.test.js +3 -515
- package/dist/testing.d.ts +59 -0
- package/dist/testing.js +88 -0
- package/dist/testing.test.js +73 -0
- package/package.json +9 -1
- package/dist/action-context.test.js +0 -72
- package/dist/base-path.test.js +0 -88
- package/dist/class-component.test.js +0 -462
- package/dist/class-helpers.test.js +0 -169
- package/dist/context.test.js +0 -57
- package/dist/derived.test.js +0 -140
- package/dist/dev-overlay.test.js +0 -165
- package/dist/discrete.test.js +0 -100
- package/dist/dom.test.js +0 -39
- package/dist/effect-errors.test.d.ts +0 -1
- package/dist/effect-errors.test.js +0 -199
- package/dist/effects.test.d.ts +0 -1
- package/dist/effects.test.js +0 -485
- package/dist/handler-routing.test.d.ts +0 -1
- package/dist/handler-routing.test.js +0 -99
- package/dist/highlight-bind.test.d.ts +0 -1
- package/dist/highlight-bind.test.js +0 -124
- package/dist/highlight.test.d.ts +0 -1
- package/dist/highlight.test.js +0 -56
- package/dist/lanes.test.d.ts +0 -1
- package/dist/lanes.test.js +0 -59
- package/dist/list.test.d.ts +0 -1
- package/dist/list.test.js +0 -435
- package/dist/metadata.test.d.ts +0 -1
- package/dist/metadata.test.js +0 -167
- package/dist/navigation.test.d.ts +0 -1
- package/dist/navigation.test.js +0 -130
- package/dist/optimistic-lanes.test.d.ts +0 -1
- package/dist/optimistic-lanes.test.js +0 -45
- package/dist/patterns.test.d.ts +0 -1
- package/dist/patterns.test.js +0 -125
- package/dist/portal.test.d.ts +0 -1
- package/dist/portal.test.js +0 -99
- package/dist/react-effects.test.d.ts +0 -1
- package/dist/react-effects.test.js +0 -133
- package/dist/react-suspense.test.d.ts +0 -1
- package/dist/react-suspense.test.js +0 -194
- package/dist/react.test.d.ts +0 -1
- package/dist/react.test.js +0 -60
- package/dist/react19.test.d.ts +0 -1
- package/dist/react19.test.js +0 -176
- package/dist/reactivity-core.test.d.ts +0 -1
- package/dist/reactivity-core.test.js +0 -152
- package/dist/reconcile.test.d.ts +0 -1
- package/dist/reconcile.test.js +0 -110
- package/dist/refs.test.d.ts +0 -1
- package/dist/refs.test.js +0 -257
- package/dist/router-layout.test.d.ts +0 -1
- package/dist/router-layout.test.js +0 -249
- package/dist/router-slots.test.d.ts +0 -1
- package/dist/router-slots.test.js +0 -144
- package/dist/router-speculation.test.d.ts +0 -1
- package/dist/router-speculation.test.js +0 -25
- package/dist/router-styles.test.d.ts +0 -1
- package/dist/router-styles.test.js +0 -98
- package/dist/router.test.d.ts +0 -1
- package/dist/router.test.js +0 -36
- package/dist/server-async.test.d.ts +0 -1
- package/dist/server-async.test.js +0 -216
- package/dist/server-highlight.test.d.ts +0 -1
- package/dist/server-highlight.test.js +0 -32
- package/dist/signal-lanes.test.d.ts +0 -1
- package/dist/signal-lanes.test.js +0 -32
- package/dist/slots.test.d.ts +0 -1
- package/dist/slots.test.js +0 -187
- package/dist/snapshots.test.d.ts +0 -1
- package/dist/snapshots.test.js +0 -208
- package/dist/ssr-core.test.d.ts +0 -1
- package/dist/ssr-core.test.js +0 -324
- package/dist/static-memory.test.d.ts +0 -1
- package/dist/static-memory.test.js +0 -26
- package/dist/storage.test.d.ts +0 -1
- package/dist/storage.test.js +0 -46
- package/dist/suspense-actions.test.d.ts +0 -1
- package/dist/suspense-actions.test.js +0 -72
- package/dist/suspense.test.d.ts +0 -1
- package/dist/suspense.test.js +0 -556
- /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
- /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
- /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
- /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
- /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
- /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
- /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
- /package/dist/{discrete.test.d.ts → slot.test.d.ts} +0 -0
- /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
package/dist/actions.d.ts
CHANGED
|
@@ -93,6 +93,13 @@ interface RunnableAction {
|
|
|
93
93
|
(payload: unknown): unknown;
|
|
94
94
|
__krateRun?: (payload: unknown) => Promise<boolean>;
|
|
95
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* Drops the query of a native action URL: the no-JS leading args and return
|
|
98
|
+
* path are only for native posts. The one exception is the sealed closure
|
|
99
|
+
* token of an inline server action (`k1.` prefix), which the server needs to
|
|
100
|
+
* rebuild the values the function closed over.
|
|
101
|
+
*/
|
|
102
|
+
export declare function stripActionURL(url: string): string;
|
|
96
103
|
/**
|
|
97
104
|
* Runs a form action: sets the form status, invokes the action with the form
|
|
98
105
|
* data in an async transition, resets the form on success and reports errors.
|
package/dist/actions.js
CHANGED
|
@@ -390,10 +390,28 @@ function formDataFor(form, submitter) {
|
|
|
390
390
|
}
|
|
391
391
|
return fd;
|
|
392
392
|
}
|
|
393
|
-
|
|
394
|
-
|
|
393
|
+
/**
|
|
394
|
+
* Drops the query of a native action URL: the no-JS leading args and return
|
|
395
|
+
* path are only for native posts. The one exception is the sealed closure
|
|
396
|
+
* token of an inline server action (`k1.` prefix), which the server needs to
|
|
397
|
+
* rebuild the values the function closed over.
|
|
398
|
+
*/
|
|
399
|
+
export function stripActionURL(url) {
|
|
395
400
|
const i = url.indexOf('?');
|
|
396
|
-
|
|
401
|
+
if (i < 0)
|
|
402
|
+
return url;
|
|
403
|
+
const base = url.slice(0, i);
|
|
404
|
+
try {
|
|
405
|
+
const raw = new URLSearchParams(url.slice(i + 1)).get(ACTION_ARGS_FIELD);
|
|
406
|
+
const leading = raw ? JSON.parse(raw) : null;
|
|
407
|
+
if (Array.isArray(leading) && typeof leading[0] === 'string' && leading[0].startsWith('k1.')) {
|
|
408
|
+
return base + '?' + ACTION_ARGS_FIELD + '=' + encodeURIComponent(JSON.stringify([leading[0]]));
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
// not a token: strip like any native query
|
|
413
|
+
}
|
|
414
|
+
return base;
|
|
397
415
|
}
|
|
398
416
|
/**
|
|
399
417
|
* Runs a form action: sets the form status, invokes the action with the form
|
package/dist/actions.test.js
CHANGED
|
@@ -1,16 +1,5 @@
|
|
|
1
1
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
-
import {
|
|
3
|
-
import { krateOn } from './events.js';
|
|
4
|
-
import { ACTION_ARGS_FIELD, ServerActionError, __krateAction, __krateActionState, __krateBeginAction, __krateBindFormAction, __krateFormStatusMount, __krateOptimistic, getFormStatus, installActionForms, isServerAction, requestFormReset, setActionTransitionRunner, takeFlash, } from './actions.js';
|
|
5
|
-
function deferred() {
|
|
6
|
-
let resolve;
|
|
7
|
-
let reject;
|
|
8
|
-
const promise = new Promise((res, rej) => {
|
|
9
|
-
resolve = res;
|
|
10
|
-
reject = rej;
|
|
11
|
-
});
|
|
12
|
-
return { promise, resolve, reject };
|
|
13
|
-
}
|
|
2
|
+
import { ServerActionError, __krateAction, getFormStatus, installActionForms, isServerAction, setActionTransitionRunner, stripActionURL, } from './actions.js';
|
|
14
3
|
const tick = () => new Promise((r) => setTimeout(r, 0));
|
|
15
4
|
function makeForm(html) {
|
|
16
5
|
const host = document.createElement('div');
|
|
@@ -35,124 +24,6 @@ afterEach(() => {
|
|
|
35
24
|
setActionTransitionRunner(null);
|
|
36
25
|
});
|
|
37
26
|
describe('form actions', () => {
|
|
38
|
-
it('runs a client function action with the form data, without navigating, and resets after success', async () => {
|
|
39
|
-
const form = makeForm('<form><input name="title" value="initial"><button type="submit">Go</button></form>');
|
|
40
|
-
const input = form.querySelector('input');
|
|
41
|
-
input.value = 'typed';
|
|
42
|
-
const gate = deferred();
|
|
43
|
-
const seen = [];
|
|
44
|
-
__krateBindFormAction(form, () => async (fd) => {
|
|
45
|
-
seen.push(String(fd.get('title')));
|
|
46
|
-
await gate.promise;
|
|
47
|
-
});
|
|
48
|
-
submit(form);
|
|
49
|
-
expect(seen).toEqual(['typed']);
|
|
50
|
-
expect(form.getAttribute('data-krate-action-pending')).toBe('1');
|
|
51
|
-
expect(getFormStatus(form).pending).toBe(true);
|
|
52
|
-
expect(input.value).toBe('typed');
|
|
53
|
-
gate.resolve();
|
|
54
|
-
await tick();
|
|
55
|
-
expect(getFormStatus(form).pending).toBe(false);
|
|
56
|
-
expect(form.hasAttribute('data-krate-action-pending')).toBe(false);
|
|
57
|
-
expect(input.value).toBe('initial');
|
|
58
|
-
});
|
|
59
|
-
it('keeps fields when the action fails and reports the error', async () => {
|
|
60
|
-
const form = makeForm('<form><input name="a" value="x"></form>');
|
|
61
|
-
const input = form.querySelector('input');
|
|
62
|
-
input.value = 'kept';
|
|
63
|
-
const errors = [];
|
|
64
|
-
form.addEventListener('krate:action-error', (e) => {
|
|
65
|
-
errors.push(e.detail.error);
|
|
66
|
-
e.preventDefault();
|
|
67
|
-
});
|
|
68
|
-
__krateBindFormAction(form, () => async () => {
|
|
69
|
-
throw new Error('boom');
|
|
70
|
-
});
|
|
71
|
-
submit(form);
|
|
72
|
-
await tick();
|
|
73
|
-
expect(errors[0].message).toBe('boom');
|
|
74
|
-
expect(input.value).toBe('kept');
|
|
75
|
-
expect(getFormStatus(form).pending).toBe(false);
|
|
76
|
-
});
|
|
77
|
-
it('drops the no-JS POST target once a function is bound', () => {
|
|
78
|
-
const form = makeForm('<form action="/__krate/action/a1?__krate_args=%5B0%5D" method="post" data-krate-action><button formaction="/x" formmethod="post">b</button></form>');
|
|
79
|
-
const button = form.querySelector('button');
|
|
80
|
-
__krateBindFormAction(form, () => () => { });
|
|
81
|
-
__krateBindFormAction(button, () => () => { });
|
|
82
|
-
expect(form.hasAttribute('action') || form.hasAttribute('method') || form.hasAttribute('data-krate-action')).toBe(false);
|
|
83
|
-
expect(button.hasAttribute('formaction') || button.hasAttribute('formmethod')).toBe(false);
|
|
84
|
-
});
|
|
85
|
-
it('prefers a submit button formAction over the form action', async () => {
|
|
86
|
-
const form = makeForm('<form><button type="submit" name="op" value="b">B</button></form>');
|
|
87
|
-
const button = form.querySelector('button');
|
|
88
|
-
const calls = [];
|
|
89
|
-
__krateBindFormAction(form, () => () => calls.push('form'));
|
|
90
|
-
__krateBindFormAction(button, () => (fd) => calls.push('button:' + fd.get('op')));
|
|
91
|
-
submit(form, button);
|
|
92
|
-
await tick();
|
|
93
|
-
expect(calls).toEqual(['button:b']);
|
|
94
|
-
});
|
|
95
|
-
it('leaves forms without an action and native formaction buttons alone', () => {
|
|
96
|
-
const form = makeForm('<form action="/search"><button formaction="/other">x</button></form>');
|
|
97
|
-
const ev = new Event('submit', { bubbles: true, cancelable: true });
|
|
98
|
-
form.dispatchEvent(ev);
|
|
99
|
-
expect(ev.defaultPrevented).toBe(false);
|
|
100
|
-
});
|
|
101
|
-
it('does not run the action when onSubmit prevented the default', async () => {
|
|
102
|
-
const form = makeForm('<form></form>');
|
|
103
|
-
const fn = vi.fn();
|
|
104
|
-
__krateBindFormAction(form, () => fn);
|
|
105
|
-
form.addEventListener('submit', (e) => e.preventDefault());
|
|
106
|
-
submit(form);
|
|
107
|
-
await tick();
|
|
108
|
-
expect(fn).not.toHaveBeenCalled();
|
|
109
|
-
});
|
|
110
|
-
it('runs onSubmit through the React event system first; preventDefault cancels the action', async () => {
|
|
111
|
-
const form = makeForm('<form><button>Go</button></form>');
|
|
112
|
-
const order = [];
|
|
113
|
-
let cancel = true;
|
|
114
|
-
krateOn(form, 'onSubmit', (e) => {
|
|
115
|
-
order.push('onSubmit');
|
|
116
|
-
if (cancel)
|
|
117
|
-
e.preventDefault();
|
|
118
|
-
});
|
|
119
|
-
__krateBindFormAction(form, () => () => order.push('action'));
|
|
120
|
-
submit(form);
|
|
121
|
-
await tick();
|
|
122
|
-
expect(order).toEqual(['onSubmit']);
|
|
123
|
-
cancel = false;
|
|
124
|
-
submit(form);
|
|
125
|
-
await tick();
|
|
126
|
-
expect(order).toEqual(['onSubmit', 'onSubmit', 'action']);
|
|
127
|
-
});
|
|
128
|
-
it('restores controlled fields after the reset', async () => {
|
|
129
|
-
const form = makeForm('<form><input name="c" value="" data-kattr-value="k:1"><input name="u" value="d"></form>');
|
|
130
|
-
const [controlled, uncontrolled] = Array.from(form.querySelectorAll('input'));
|
|
131
|
-
controlled.value = 'signal value';
|
|
132
|
-
uncontrolled.value = 'typed';
|
|
133
|
-
__krateBindFormAction(form, () => async () => { });
|
|
134
|
-
submit(form);
|
|
135
|
-
await tick();
|
|
136
|
-
expect(controlled.value).toBe('signal value');
|
|
137
|
-
expect(uncontrolled.value).toBe('d');
|
|
138
|
-
});
|
|
139
|
-
it('requestFormReset waits for the pending action', async () => {
|
|
140
|
-
const form = makeForm('<form><input name="a" value="d"></form>');
|
|
141
|
-
const input = form.querySelector('input');
|
|
142
|
-
const gate = deferred();
|
|
143
|
-
__krateBindFormAction(form, () => async () => {
|
|
144
|
-
await gate.promise;
|
|
145
|
-
throw new Error('fail');
|
|
146
|
-
});
|
|
147
|
-
form.addEventListener('krate:action-error', (e) => e.preventDefault());
|
|
148
|
-
input.value = 'typed';
|
|
149
|
-
submit(form);
|
|
150
|
-
requestFormReset(form);
|
|
151
|
-
expect(input.value).toBe('typed');
|
|
152
|
-
gate.resolve();
|
|
153
|
-
await tick();
|
|
154
|
-
expect(input.value).toBe('d');
|
|
155
|
-
});
|
|
156
27
|
it('posts server action forms as multipart and does not reload', async () => {
|
|
157
28
|
const fetchMock = vi.fn(async () => jsonResponse({ ok: true, result: { saved: true } }));
|
|
158
29
|
vi.stubGlobal('fetch', fetchMock);
|
|
@@ -168,213 +39,17 @@ describe('form actions', () => {
|
|
|
168
39
|
expect(init.body.get('text')).toBe('hi');
|
|
169
40
|
expect(getFormStatus(form).pending).toBe(false);
|
|
170
41
|
});
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
it('is scoped to the parent form of the component', async () => {
|
|
174
|
-
document.body.innerHTML =
|
|
175
|
-
'<form id="a"><button id="ba">A</button></form><form id="b"><button id="bb">B</button></form>';
|
|
176
|
-
const formA = document.getElementById('a');
|
|
177
|
-
const statusA = [];
|
|
178
|
-
const pendingB = [];
|
|
179
|
-
__krateFormStatusMount(document.getElementById('ba'), { status: (s) => statusA.push(s) });
|
|
180
|
-
__krateFormStatusMount(document.getElementById('bb'), { pending: (p) => pendingB.push(p) });
|
|
181
|
-
const gate = deferred();
|
|
182
|
-
const action = async () => {
|
|
183
|
-
await gate.promise;
|
|
184
|
-
};
|
|
185
|
-
__krateBindFormAction(formA, () => action);
|
|
186
|
-
submit(formA);
|
|
187
|
-
const live = statusA[statusA.length - 1];
|
|
188
|
-
expect(live.pending).toBe(true);
|
|
189
|
-
expect(live.method).toBe('get');
|
|
190
|
-
expect(live.action).toBe(action);
|
|
191
|
-
expect(live.data).toBeInstanceOf(FormData);
|
|
192
|
-
expect(pendingB).toEqual([false]);
|
|
193
|
-
gate.resolve();
|
|
194
|
-
await tick();
|
|
195
|
-
expect(statusA[statusA.length - 1].pending).toBe(false);
|
|
196
|
-
expect(pendingB).toEqual([false]);
|
|
197
|
-
});
|
|
198
|
-
it('does not report the form the component itself renders', () => {
|
|
199
|
-
document.body.innerHTML = '<form id="self"></form>';
|
|
200
|
-
const seen = [];
|
|
201
|
-
__krateFormStatusMount(document.getElementById('self'), { pending: (p) => seen.push(p) });
|
|
202
|
-
expect(seen).toEqual([]);
|
|
203
|
-
});
|
|
204
|
-
});
|
|
205
|
-
describe('useActionState', () => {
|
|
206
|
-
it('queues calls sequentially and threads the previous state', async () => {
|
|
207
|
-
const [state, setState] = createSignal(0);
|
|
208
|
-
const [pending, setPending] = createSignal(false);
|
|
209
|
-
const gates = [deferred(), deferred(), deferred()];
|
|
210
|
-
const log = [];
|
|
211
|
-
let call = 0;
|
|
212
|
-
const dispatch = __krateActionState(async (prev, payload) => {
|
|
213
|
-
const i = call++;
|
|
214
|
-
log.push(`start ${i} prev=${prev} payload=${payload}`);
|
|
215
|
-
await gates[i].promise;
|
|
216
|
-
return prev + payload;
|
|
217
|
-
}, state, setState, setPending);
|
|
218
|
-
dispatch(1);
|
|
219
|
-
dispatch(10);
|
|
220
|
-
dispatch(100);
|
|
221
|
-
expect(pending()).toBe(true);
|
|
222
|
-
await tick();
|
|
223
|
-
expect(log).toEqual(['start 0 prev=0 payload=1']);
|
|
224
|
-
gates[0].resolve();
|
|
225
|
-
await tick();
|
|
226
|
-
expect(state()).toBe(1);
|
|
227
|
-
expect(log[1]).toBe('start 1 prev=1 payload=10');
|
|
228
|
-
gates[1].resolve();
|
|
229
|
-
await tick();
|
|
230
|
-
gates[2].resolve();
|
|
231
|
-
await tick();
|
|
232
|
-
expect(state()).toBe(111);
|
|
233
|
-
expect(pending()).toBe(false);
|
|
234
|
-
});
|
|
235
|
-
it('cancels queued calls when an action throws', async () => {
|
|
236
|
-
const [state, setState] = createSignal('a');
|
|
237
|
-
const [pending, setPending] = createSignal(false);
|
|
238
|
-
const runs = [];
|
|
239
|
-
const errors = [];
|
|
240
|
-
const onErr = (e) => {
|
|
241
|
-
errors.push(e.detail.error);
|
|
242
|
-
e.preventDefault();
|
|
243
|
-
};
|
|
244
|
-
document.addEventListener('krate:action-error', onErr);
|
|
245
|
-
const dispatch = __krateActionState(async (prev, payload) => {
|
|
246
|
-
runs.push(String(payload));
|
|
247
|
-
if (payload === 'bad')
|
|
248
|
-
throw new Error('nope');
|
|
249
|
-
return prev + payload;
|
|
250
|
-
}, state, setState, setPending);
|
|
251
|
-
dispatch('bad');
|
|
252
|
-
dispatch('next');
|
|
253
|
-
await tick();
|
|
254
|
-
await tick();
|
|
255
|
-
document.removeEventListener('krate:action-error', onErr);
|
|
256
|
-
expect(runs).toEqual(['bad']);
|
|
257
|
-
expect(state()).toBe('a');
|
|
258
|
-
expect(pending()).toBe(false);
|
|
259
|
-
expect(errors[0].message).toBe('nope');
|
|
260
|
-
});
|
|
261
|
-
it('works as a form action and resets the form after success', async () => {
|
|
262
|
-
const [state, setState] = createSignal([]);
|
|
263
|
-
const [, setPending] = createSignal(false);
|
|
264
|
-
const form = makeForm('<form><input name="todo" value=""></form>');
|
|
265
|
-
const input = form.querySelector('input');
|
|
266
|
-
const dispatch = __krateActionState(async (prev, fd) => [...prev, String(fd.get('todo'))], state, setState, setPending);
|
|
267
|
-
__krateBindFormAction(form, () => dispatch);
|
|
268
|
-
input.value = 'one';
|
|
269
|
-
submit(form);
|
|
270
|
-
await tick();
|
|
271
|
-
await tick();
|
|
272
|
-
expect(state()).toEqual(['one']);
|
|
273
|
-
expect(input.value).toBe('');
|
|
274
|
-
});
|
|
275
|
-
it('sends the previous state to a server action as the leading argument', async () => {
|
|
276
|
-
const fetchMock = vi.fn(async () => jsonResponse({ ok: true, result: 5 }));
|
|
42
|
+
it('keeps only the sealed closure token of an inline action in the posted URL', async () => {
|
|
43
|
+
const fetchMock = vi.fn(async () => jsonResponse({ ok: true, result: null }));
|
|
277
44
|
vi.stubGlobal('fetch', fetchMock);
|
|
278
|
-
const
|
|
279
|
-
const
|
|
280
|
-
const dispatch = __krateActionState(__krateAction('a9'), state, setState, setPending);
|
|
281
|
-
const fd = new FormData();
|
|
282
|
-
fd.set('n', '1');
|
|
283
|
-
dispatch(fd);
|
|
284
|
-
await tick();
|
|
285
|
-
await tick();
|
|
286
|
-
const init = fetchMock.mock.calls[0][1];
|
|
287
|
-
const body = init.body;
|
|
288
|
-
expect(JSON.parse(String(body.get(ACTION_ARGS_FIELD)))).toEqual([4]);
|
|
289
|
-
expect(body.get('n')).toBe('1');
|
|
290
|
-
expect(state()).toBe(5);
|
|
291
|
-
});
|
|
292
|
-
});
|
|
293
|
-
describe('useActionState flash from a native form post', () => {
|
|
294
|
-
const flash = (id, result) => btoa(JSON.stringify({ a: id, r: result })).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
295
|
-
afterEach(() => {
|
|
296
|
-
document.cookie = 'krate_flash=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT';
|
|
297
|
-
});
|
|
298
|
-
it('starts from the state the server returned to the redirected native post', () => {
|
|
299
|
-
document.cookie = 'krate_flash=' + flash('save', { errors: { name: 'required' } }) + '; Path=/';
|
|
300
|
-
const [state, setState] = createSignal({ errors: {} });
|
|
301
|
-
const [, setPending] = createSignal(false);
|
|
302
|
-
__krateActionState(__krateAction('save'), state, setState, setPending);
|
|
303
|
-
expect(state()).toEqual({ errors: { name: 'required' } });
|
|
304
|
-
// The flash is single use.
|
|
305
|
-
expect(document.cookie).not.toContain('krate_flash=' + flash('save', { errors: { name: 'required' } }));
|
|
306
|
-
const [again, setAgain] = createSignal('init');
|
|
307
|
-
__krateActionState(__krateAction('save'), again, setAgain, setPending);
|
|
308
|
-
expect(again()).toBe('init');
|
|
309
|
-
});
|
|
310
|
-
it('ignores a flash written for another action', () => {
|
|
311
|
-
document.cookie = 'krate_flash=' + flash('other', 'x') + '; Path=/';
|
|
312
|
-
const [state, setState] = createSignal('init');
|
|
313
|
-
const [, setPending] = createSignal(false);
|
|
314
|
-
__krateActionState(__krateAction('save'), state, setState, setPending);
|
|
315
|
-
expect(state()).toBe('init');
|
|
316
|
-
});
|
|
317
|
-
});
|
|
318
|
-
describe('useOptimistic', () => {
|
|
319
|
-
it('applies updates while an action is pending and reverts to the latest base', async () => {
|
|
320
|
-
const [base, setBase] = createSignal(['a']);
|
|
321
|
-
const [value, setValue] = createSignal(base());
|
|
322
|
-
const add = __krateOptimistic(base, setValue, (s, n) => [...s, n]);
|
|
323
|
-
const end = __krateBeginAction();
|
|
324
|
-
add('b');
|
|
325
|
-
add('c');
|
|
326
|
-
expect(value()).toEqual(['a', 'b', 'c']);
|
|
327
|
-
setBase(['a', 'x']);
|
|
328
|
-
await tick();
|
|
329
|
-
expect(value()).toEqual(['a', 'x', 'b', 'c']);
|
|
330
|
-
end();
|
|
331
|
-
expect(value()).toEqual(['a', 'x']);
|
|
332
|
-
});
|
|
333
|
-
it('drops an update made outside any action', async () => {
|
|
334
|
-
const [base] = createSignal(1);
|
|
335
|
-
const [value, setValue] = createSignal(base());
|
|
336
|
-
const add = __krateOptimistic(base, setValue);
|
|
337
|
-
add(2);
|
|
338
|
-
expect(value()).toBe(2);
|
|
339
|
-
await tick();
|
|
340
|
-
expect(value()).toBe(1);
|
|
341
|
-
});
|
|
342
|
-
it('keeps updates for a form action until it settles', async () => {
|
|
343
|
-
const [base, setBase] = createSignal(0);
|
|
344
|
-
const [value, setValue] = createSignal(base());
|
|
345
|
-
const add = __krateOptimistic(base, setValue, (s, n) => s + n);
|
|
346
|
-
const gate = deferred();
|
|
347
|
-
const form = makeForm('<form></form>');
|
|
348
|
-
__krateBindFormAction(form, () => async () => {
|
|
349
|
-
add(5);
|
|
350
|
-
await gate.promise;
|
|
351
|
-
setBase(1);
|
|
352
|
-
});
|
|
45
|
+
const args = encodeURIComponent(JSON.stringify(['k1.AbC_-123']));
|
|
46
|
+
const form = makeForm(`<form action="/__krate/action/a1?__krate_args=${args}&__krate_return=%2Fx" method="post" data-krate-action></form>`);
|
|
353
47
|
submit(form);
|
|
354
48
|
await tick();
|
|
355
|
-
expect(value()).toBe(5);
|
|
356
|
-
gate.resolve();
|
|
357
|
-
await tick();
|
|
358
|
-
await tick();
|
|
359
|
-
expect(value()).toBe(1);
|
|
360
|
-
});
|
|
361
|
-
it('uses a custom transition runner when one is installed', async () => {
|
|
362
|
-
const runs = [];
|
|
363
|
-
setActionTransitionRunner(async (fn) => {
|
|
364
|
-
runs.push(1);
|
|
365
|
-
const end = __krateBeginAction();
|
|
366
|
-
try {
|
|
367
|
-
return await fn();
|
|
368
|
-
}
|
|
369
|
-
finally {
|
|
370
|
-
end();
|
|
371
|
-
}
|
|
372
|
-
});
|
|
373
|
-
const form = makeForm('<form></form>');
|
|
374
|
-
__krateBindFormAction(form, () => async () => { });
|
|
375
|
-
submit(form);
|
|
376
49
|
await tick();
|
|
377
|
-
|
|
50
|
+
const [url] = fetchMock.mock.calls[0];
|
|
51
|
+
expect(url.replace(/^https?:\/\/[^/]+/, '')).toBe(`/__krate/action/a1?__krate_args=${args}`);
|
|
52
|
+
expect(stripActionURL('/__krate/action/a2?__krate_args=%5B%7B%22n%22%3A1%7D%5D&__krate_return=%2Fx')).toBe('/__krate/action/a2');
|
|
378
53
|
});
|
|
379
54
|
});
|
|
380
55
|
describe('server action proxies', () => {
|
|
@@ -389,15 +64,6 @@ describe('server action proxies', () => {
|
|
|
389
64
|
expect(JSON.parse(String(init.body))).toEqual({ args: [{ n: 1 }] });
|
|
390
65
|
expect(init.headers['content-type']).toBe('application/json');
|
|
391
66
|
});
|
|
392
|
-
it('keeps bound arguments ahead of the call arguments', async () => {
|
|
393
|
-
const fetchMock = vi.fn(async () => jsonResponse({ ok: true, result: null }));
|
|
394
|
-
vi.stubGlobal('fetch', fetchMock);
|
|
395
|
-
const bound = __krateAction('a2').bind(null, 'id-7');
|
|
396
|
-
expect(isServerAction(bound)).toBe(true);
|
|
397
|
-
await bound('x');
|
|
398
|
-
const [, init] = fetchMock.mock.calls[0];
|
|
399
|
-
expect(JSON.parse(String(init.body))).toEqual({ args: ['id-7', 'x'] });
|
|
400
|
-
});
|
|
401
67
|
it('rejects with the structured error envelope', async () => {
|
|
402
68
|
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: false, error: { message: 'An error occurred', digest: 'd1' } }, 500)));
|
|
403
69
|
const err = (await __krateAction('a3')().catch((e) => e));
|
|
@@ -406,72 +72,4 @@ describe('server action proxies', () => {
|
|
|
406
72
|
expect(err.digest).toBe('d1');
|
|
407
73
|
expect(err.status).toBe(500);
|
|
408
74
|
});
|
|
409
|
-
it('follows a redirect from the response', async () => {
|
|
410
|
-
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: null, redirect: '/next' })));
|
|
411
|
-
const nav = vi.fn();
|
|
412
|
-
vi.stubGlobal('navigate', nav);
|
|
413
|
-
await __krateAction('a4')();
|
|
414
|
-
expect(nav).toHaveBeenCalledWith('/next');
|
|
415
|
-
});
|
|
416
|
-
it('keeps the previous useActionState state when the action redirects', async () => {
|
|
417
|
-
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: null, redirect: '/next' })));
|
|
418
|
-
vi.stubGlobal('navigate', vi.fn());
|
|
419
|
-
const proxy = __krateAction('a4b');
|
|
420
|
-
let state = { error: '' };
|
|
421
|
-
const dispatch = __krateActionState((prev, payload) => proxy(prev, payload), () => state, (next) => {
|
|
422
|
-
state = next;
|
|
423
|
-
}, () => { });
|
|
424
|
-
await dispatch.__krateRun(new FormData());
|
|
425
|
-
expect(state).toEqual({ error: '' });
|
|
426
|
-
});
|
|
427
|
-
it('ignores a null element when a form binding is detached', () => {
|
|
428
|
-
expect(() => __krateBindFormAction(null, () => () => { })).not.toThrow();
|
|
429
|
-
});
|
|
430
|
-
it('dispatches krate:revalidate when the action revalidated server caches', async () => {
|
|
431
|
-
const revalidation = { paths: [{ path: '/posts', type: 'page' }], tags: ['posts'] };
|
|
432
|
-
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: 1, revalidated: true, revalidation })));
|
|
433
|
-
const seen = [];
|
|
434
|
-
const onRevalidate = (e) => seen.push(e.detail);
|
|
435
|
-
window.addEventListener('krate:revalidate', onRevalidate);
|
|
436
|
-
try {
|
|
437
|
-
await expect(__krateAction('a5')()).resolves.toBe(1);
|
|
438
|
-
expect(seen).toEqual([revalidation]);
|
|
439
|
-
}
|
|
440
|
-
finally {
|
|
441
|
-
window.removeEventListener('krate:revalidate', onRevalidate);
|
|
442
|
-
}
|
|
443
|
-
});
|
|
444
|
-
it('does not dispatch krate:revalidate for actions that revalidated nothing', async () => {
|
|
445
|
-
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: null })));
|
|
446
|
-
const handler = vi.fn();
|
|
447
|
-
window.addEventListener('krate:revalidate', handler);
|
|
448
|
-
try {
|
|
449
|
-
await __krateAction('a6')();
|
|
450
|
-
expect(handler).not.toHaveBeenCalled();
|
|
451
|
-
}
|
|
452
|
-
finally {
|
|
453
|
-
window.removeEventListener('krate:revalidate', handler);
|
|
454
|
-
}
|
|
455
|
-
});
|
|
456
|
-
});
|
|
457
|
-
describe('takeFlash', () => {
|
|
458
|
-
const encode = (payload) => btoa(unescape(encodeURIComponent(JSON.stringify(payload)))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
459
|
-
afterEach(() => {
|
|
460
|
-
document.body.innerHTML = '';
|
|
461
|
-
document.cookie = 'krate_flash=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT';
|
|
462
|
-
});
|
|
463
|
-
it('reads the cookie for the matching action only', () => {
|
|
464
|
-
document.cookie = 'krate_flash=' + encode({ a: 'act1', r: { error: 'bad' } }) + '; Path=/';
|
|
465
|
-
expect(takeFlash('other')).toEqual({ found: false });
|
|
466
|
-
expect(takeFlash('act1')).toEqual({ found: true, value: { error: 'bad' } });
|
|
467
|
-
expect(takeFlash('act1')).toEqual({ found: false });
|
|
468
|
-
});
|
|
469
|
-
it('falls back to the notice the server rendered and removes it', () => {
|
|
470
|
-
document.body.innerHTML =
|
|
471
|
-
'<form><div data-krate-flash="' + encode({ a: 'act2', r: { error: 'server rendered' } }) + '" data-krate-action="act2">server rendered</div></form>';
|
|
472
|
-
expect(takeFlash('act1')).toEqual({ found: false });
|
|
473
|
-
expect(document.querySelector('[data-krate-flash]')).not.toBeNull();
|
|
474
|
-
expect(takeFlash('act2')).toEqual({ found: true, value: { error: 'server rendered' } });
|
|
475
|
-
expect(document.querySelector('[data-krate-flash]')).toBeNull();
|
|
476
|
-
});
|
|
477
75
|
});
|
package/dist/after.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export type AfterTask = (() => unknown) | PromiseLike<unknown>;
|
|
2
|
+
export declare function after(task: AfterTask): void;
|
|
3
|
+
/** Runs and clears a scope's after() tasks in order; each failure is logged. */
|
|
4
|
+
export declare function runAfterTasks(scope: {
|
|
5
|
+
after?: Array<() => unknown>;
|
|
6
|
+
}): Promise<void>;
|
|
7
|
+
/** request.cookies on an API route's Request, shaped like Next's RequestCookies (read-only). */
|
|
8
|
+
export interface KrateRequestCookies {
|
|
9
|
+
get(name: string): {
|
|
10
|
+
name: string;
|
|
11
|
+
value: string;
|
|
12
|
+
} | undefined;
|
|
13
|
+
getAll(name?: string): Array<{
|
|
14
|
+
name: string;
|
|
15
|
+
value: string;
|
|
16
|
+
}>;
|
|
17
|
+
has(name: string): boolean;
|
|
18
|
+
}
|
|
19
|
+
/** request.nextUrl: the request URL plus Next's basePath and clone(). */
|
|
20
|
+
export interface KrateNextURL extends URL {
|
|
21
|
+
readonly basePath: string;
|
|
22
|
+
clone(): KrateNextURL;
|
|
23
|
+
}
|
|
24
|
+
/** The Request an API route handler receives: a web Request with Next-style cookies and nextUrl. */
|
|
25
|
+
export type KrateRequest = Request & {
|
|
26
|
+
readonly cookies: KrateRequestCookies;
|
|
27
|
+
readonly nextUrl: KrateNextURL;
|
|
28
|
+
};
|
package/dist/after.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `after(task)` mirrors `next/server`'s `after()`: it schedules work that runs
|
|
3
|
+
* once the response has been sent (logging, analytics, cache warming). Inside
|
|
4
|
+
* an API route the task is queued on the request and the server runs it after
|
|
5
|
+
* the response is flushed, in registration order. Errors are logged, never
|
|
6
|
+
* sent to the client. Where no request is active (the embedded runtime, tests)
|
|
7
|
+
* the task runs on a later microtask turn, right after the handler settles.
|
|
8
|
+
* On a serverless target the task is also handed to the platform's waitUntil
|
|
9
|
+
* (the Worker's ctx.waitUntil on cloudflare), so it outlives the response.
|
|
10
|
+
*/
|
|
11
|
+
import { currentRevalidateScope } from './cache-scope.js';
|
|
12
|
+
import { platformWaitUntil } from './platform.js';
|
|
13
|
+
function toThunk(task) {
|
|
14
|
+
if (typeof task === 'function')
|
|
15
|
+
return task;
|
|
16
|
+
if (task && typeof task.then === 'function')
|
|
17
|
+
return () => task;
|
|
18
|
+
throw new TypeError('after() expects a function or a promise');
|
|
19
|
+
}
|
|
20
|
+
export function after(task) {
|
|
21
|
+
const thunk = toThunk(task);
|
|
22
|
+
const scope = currentRevalidateScope();
|
|
23
|
+
if (scope) {
|
|
24
|
+
(scope.after || (scope.after = [])).push(thunk);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const run = Promise.resolve()
|
|
28
|
+
.then(thunk)
|
|
29
|
+
.catch((err) => console.error(`[krate] after() task failed: ${(err && err.stack) || err}`));
|
|
30
|
+
// Serverless platforms stop the instance once the response is sent unless
|
|
31
|
+
// waitUntil keeps it alive.
|
|
32
|
+
platformWaitUntil(run);
|
|
33
|
+
}
|
|
34
|
+
/** Runs and clears a scope's after() tasks in order; each failure is logged. */
|
|
35
|
+
export async function runAfterTasks(scope) {
|
|
36
|
+
const tasks = scope.after;
|
|
37
|
+
if (!tasks || tasks.length === 0)
|
|
38
|
+
return;
|
|
39
|
+
scope.after = [];
|
|
40
|
+
for (const t of tasks) {
|
|
41
|
+
try {
|
|
42
|
+
await t();
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
console.error(`[krate] after() task failed: ${(err && err.stack) || err}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { after, runAfterTasks } from './after.js';
|
|
4
|
+
const STORE_KEY = Symbol.for('krate.revalidate.store');
|
|
5
|
+
afterEach(() => {
|
|
6
|
+
delete globalThis[STORE_KEY];
|
|
7
|
+
});
|
|
8
|
+
describe('after()', () => {
|
|
9
|
+
it('queues tasks on the request scope instead of running them', async () => {
|
|
10
|
+
const store = new AsyncLocalStorage();
|
|
11
|
+
globalThis[STORE_KEY] = store;
|
|
12
|
+
const scope = { kind: 'api', paths: [], tags: [] };
|
|
13
|
+
const ran = [];
|
|
14
|
+
store.run(scope, () => {
|
|
15
|
+
after(() => ran.push('fn'));
|
|
16
|
+
after(Promise.resolve().then(() => ran.push('promise')));
|
|
17
|
+
});
|
|
18
|
+
expect(scope.after).toHaveLength(2);
|
|
19
|
+
await Promise.resolve();
|
|
20
|
+
expect(ran).toEqual(['promise']);
|
|
21
|
+
await runAfterTasks(scope);
|
|
22
|
+
expect(ran).toEqual(['promise', 'fn']);
|
|
23
|
+
expect(scope.after).toEqual([]);
|
|
24
|
+
});
|
|
25
|
+
it('keeps running later tasks when one throws', async () => {
|
|
26
|
+
const err = vi.spyOn(console, 'error').mockImplementation(() => { });
|
|
27
|
+
const scope = {
|
|
28
|
+
kind: 'api',
|
|
29
|
+
paths: [],
|
|
30
|
+
tags: [],
|
|
31
|
+
after: [
|
|
32
|
+
() => {
|
|
33
|
+
throw new Error('boom');
|
|
34
|
+
},
|
|
35
|
+
() => {
|
|
36
|
+
ran = true;
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
};
|
|
40
|
+
let ran = false;
|
|
41
|
+
await runAfterTasks(scope);
|
|
42
|
+
expect(ran).toBe(true);
|
|
43
|
+
expect(err).toHaveBeenCalledOnce();
|
|
44
|
+
err.mockRestore();
|
|
45
|
+
});
|
|
46
|
+
it('runs on a later turn when no request is active', async () => {
|
|
47
|
+
let ran = false;
|
|
48
|
+
after(() => {
|
|
49
|
+
ran = true;
|
|
50
|
+
});
|
|
51
|
+
expect(ran).toBe(false);
|
|
52
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
53
|
+
expect(ran).toBe(true);
|
|
54
|
+
});
|
|
55
|
+
it('rejects anything but a function or a promise', () => {
|
|
56
|
+
expect(() => after(42)).toThrow(TypeError);
|
|
57
|
+
});
|
|
58
|
+
});
|
package/dist/assets-static.d.ts
CHANGED
|
@@ -2,4 +2,13 @@ import type { StaticLayer } from "./server-handler.js";
|
|
|
2
2
|
export interface AssetFetcher {
|
|
3
3
|
fetch(request: Request): Promise<Response>;
|
|
4
4
|
}
|
|
5
|
-
export
|
|
5
|
+
export interface AssetsStaticOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Ask for a folder's index.html file by name. The generated wrangler config
|
|
8
|
+
* sets assets.html_handling to "none" for trailingSlash "ignore", so the
|
|
9
|
+
* platform no longer maps /x and /x/ to x/index.html or redirects between
|
|
10
|
+
* them; the layer does that mapping itself and both URLs serve the page.
|
|
11
|
+
*/
|
|
12
|
+
directoryIndex?: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function createAssetsStaticLayer(assets: AssetFetcher, options?: AssetsStaticOptions): StaticLayer;
|