clarusjs 0.13.0 → 0.14.0
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/check/generate.js +42 -8
- package/dist/compiler/class-style.d.ts +1 -1
- package/dist/compiler/class-style.js +4 -0
- package/dist/compiler/emit-client.js +15 -1
- package/dist/compiler/emit-server.js +11 -4
- package/dist/compiler/html-expr.d.ts +10 -2
- package/dist/compiler/html-expr.js +28 -16
- package/dist/compiler/icon.d.ts +1 -1
- package/dist/compiler/icon.js +4 -0
- package/dist/compiler/index.js +10 -1
- package/dist/compiler/ir.d.ts +19 -0
- package/dist/compiler/ir.js +27 -1
- package/dist/compiler/lint.js +12 -1
- package/dist/compiler/parse.d.ts +24 -0
- package/dist/compiler/parse.js +66 -0
- package/dist/compiler/script.d.ts +10 -1
- package/dist/compiler/script.js +17 -3
- package/dist/fetch/index.d.ts +157 -3
- package/dist/fetch/index.js +135 -14
- package/dist/runtime/dom.d.ts +9 -0
- package/dist/runtime/dom.js +24 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/server.d.ts +12 -0
- package/dist/runtime/server.js +34 -1
- package/dist/server/handler.d.ts +1 -1
- package/dist/server/handler.js +5 -2
- package/dist/server/views.d.ts +1 -1
- package/dist/server/views.js +1 -1
- package/dist/vite/plugin.js +15 -2
- package/package.json +1 -1
|
@@ -15,13 +15,22 @@ export declare function scriptNames(code: string): Set<string>;
|
|
|
15
15
|
* Island scripts are bundled for the browser, so `node:` imports are a build error.
|
|
16
16
|
*/
|
|
17
17
|
/** Import statements (text and offset in `code`), and the body with them blanked out. */
|
|
18
|
-
export declare function splitImports(code: string, file: string, source: string, offset: number): {
|
|
18
|
+
export declare function splitImports(code: string, file: string, source: string, offset: number, server?: boolean): {
|
|
19
19
|
imports: {
|
|
20
20
|
text: string;
|
|
21
21
|
start: number;
|
|
22
22
|
}[];
|
|
23
23
|
body: string;
|
|
24
24
|
};
|
|
25
|
+
/**
|
|
26
|
+
* A `<script server>` (#430): its imports (hoisted to the server module, `node:` allowed: it never reaches a browser),
|
|
27
|
+
* the rest (run at the top of render), and whether it awaits at the top level (then render is async).
|
|
28
|
+
*/
|
|
29
|
+
export declare function serverScriptParts(code: string, file: string, source: string, offset: number): {
|
|
30
|
+
imports: string[];
|
|
31
|
+
body: string;
|
|
32
|
+
awaits: boolean;
|
|
33
|
+
};
|
|
25
34
|
/**
|
|
26
35
|
* Where type annotations go for type checking: `: any` after the untyped parameters of the script's own functions
|
|
27
36
|
* (declarations, `const f = (x) => …`, class methods) and of callbacks passed straight to them (`record((p) => …)`).
|
package/dist/compiler/script.js
CHANGED
|
@@ -184,14 +184,14 @@ function signalCall(init) {
|
|
|
184
184
|
const name = init.callee.name;
|
|
185
185
|
return name === 'state' || name === 'derived' || name === 'shared' ? name : undefined;
|
|
186
186
|
}
|
|
187
|
-
export function splitImports(code, file, source, offset) {
|
|
187
|
+
export function splitImports(code, file, source, offset, server = false) {
|
|
188
188
|
const imports = [];
|
|
189
189
|
let body = code;
|
|
190
190
|
for (const stmt of parseScript(code, file, source, offset).body) {
|
|
191
191
|
if (stmt.type !== 'ImportDeclaration')
|
|
192
192
|
continue;
|
|
193
193
|
const from = String(stmt.source.value);
|
|
194
|
-
if (from.startsWith('node:')) {
|
|
194
|
+
if (!server && from.startsWith('node:')) {
|
|
195
195
|
throw new ClarusError(`\`${from}\` can't be imported in an island script: the script is bundled for the browser`, file, source, offset + stmt.start);
|
|
196
196
|
}
|
|
197
197
|
imports.push({ text: code.slice(stmt.start, stmt.end), start: stmt.start });
|
|
@@ -199,6 +199,20 @@ export function splitImports(code, file, source, offset) {
|
|
|
199
199
|
}
|
|
200
200
|
return { imports, body };
|
|
201
201
|
}
|
|
202
|
+
export function serverScriptParts(code, file, source, offset) {
|
|
203
|
+
const ast = parseScript(code, file, source, offset);
|
|
204
|
+
const imports = [];
|
|
205
|
+
let body = code;
|
|
206
|
+
for (const stmt of ast.body) {
|
|
207
|
+
if (stmt.type.startsWith('Export'))
|
|
208
|
+
throw new ClarusError('a <script server> cannot export anything: its names are for the template', file, source, offset + stmt.start);
|
|
209
|
+
if (stmt.type !== 'ImportDeclaration')
|
|
210
|
+
continue;
|
|
211
|
+
imports.push(code.slice(stmt.start, stmt.end));
|
|
212
|
+
body = body.slice(0, stmt.start) + code.slice(stmt.start, stmt.end).replace(/[^\n]/g, ' ') + body.slice(stmt.end);
|
|
213
|
+
}
|
|
214
|
+
return { imports, body, awaits: !!topLevelAwait(ast) };
|
|
215
|
+
}
|
|
202
216
|
export function untypedParams(code) {
|
|
203
217
|
const ast = parseScript(code);
|
|
204
218
|
const isFn = (n) => !!n && (n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression');
|
|
@@ -254,7 +268,7 @@ export function analyzeScript(code, file, source, offset) {
|
|
|
254
268
|
}
|
|
255
269
|
const tla = topLevelAwait(ast);
|
|
256
270
|
if (tla)
|
|
257
|
-
throw new ClarusError("top
|
|
271
|
+
throw new ClarusError("an island's <script> can't await at the top level (the browser attaches it without waiting): await data on the server in a <script server>, or in the browser inside a function, such as a resource()'s fetcher or an event handler", file, source, offset + tla.start);
|
|
258
272
|
for (const stmt of ast.body) {
|
|
259
273
|
if (stmt.type.startsWith('Export')) {
|
|
260
274
|
throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
|
package/dist/fetch/index.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export type Resource<T> = {
|
|
|
11
11
|
readonly error: unknown;
|
|
12
12
|
/** Run now, aborting a run in flight. */
|
|
13
13
|
refetch(): Promise<void>;
|
|
14
|
+
/** Cancel the run in flight: back to idle, the value kept, no error and no callbacks (a cancel isn't a failure). */
|
|
15
|
+
abort(): void;
|
|
14
16
|
/** Set the shown value (e.g. optimistically, before a POST); the next run overwrites it. Keyed: its cache entry. */
|
|
15
17
|
mutate(value: T): void;
|
|
16
18
|
/** The first answer (`value`), or the first run's error. On the server, `initial`. In handlers, not top level. */
|
|
@@ -43,7 +45,49 @@ export type ResourceOptions<T> = {
|
|
|
43
45
|
stale?: number;
|
|
44
46
|
/** With `key`: keep an unshown answer this long (ms, default 5 min). */
|
|
45
47
|
keep?: number;
|
|
48
|
+
/** Fail a run (retries included) after this many ms, with a `TimeoutError`: an error, unlike `abort()`. */
|
|
49
|
+
timeout?: number;
|
|
50
|
+
} & Callbacks<T>;
|
|
51
|
+
/**
|
|
52
|
+
* What happens after a request settles, once per request (an event, so the same error twice is two calls; an effect
|
|
53
|
+
* on `error` is for state). A cancel calls none of them; with `retry`, after the last attempt. Browser only.
|
|
54
|
+
* @see https://clarusjs.com/guide/fetching#errors
|
|
55
|
+
*/
|
|
56
|
+
export type Callbacks<T, I = void> = {
|
|
57
|
+
/** It succeeded (an action's input second). Return `false` to skip `configure()`'s `onSuccess`. */
|
|
58
|
+
onSuccess?(value: T, input: I): unknown;
|
|
59
|
+
/** It failed (a timeout too). Return `false` to skip `configure()`'s `onError` (handled here). */
|
|
60
|
+
onError?(error: unknown, input: I): unknown;
|
|
61
|
+
/** After either, last: `(value, undefined)` or `(undefined, error)`. */
|
|
62
|
+
onSettled?(value: T | undefined, error: unknown, input: I): unknown;
|
|
63
|
+
/** Anything for `configure()`'s handlers: `{ success: 'Saved' }`, `{ silent: true }`. */
|
|
64
|
+
meta?: Record<string, unknown>;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Handlers for every resource and action on the page, after their own callbacks: toasts in one place.
|
|
68
|
+
* @see https://clarusjs.com/reference/fetch#configure
|
|
69
|
+
*/
|
|
70
|
+
export type Handlers = {
|
|
71
|
+
onSuccess?(value: unknown, ctx: {
|
|
72
|
+
meta: Record<string, unknown> | undefined;
|
|
73
|
+
}): void;
|
|
74
|
+
onError?(error: unknown, ctx: {
|
|
75
|
+
meta: Record<string, unknown> | undefined;
|
|
76
|
+
}): void;
|
|
46
77
|
};
|
|
78
|
+
/**
|
|
79
|
+
* Set the handlers every resource and action calls after its own callbacks (one place for toasts); replaces the
|
|
80
|
+
* previous ones. An instance's `meta` reaches them; its own callback returning `false` skips them.
|
|
81
|
+
* @example
|
|
82
|
+
* ```ts
|
|
83
|
+
* configure({
|
|
84
|
+
* onError: (e, { meta }) => { if (!meta?.silent) toast.error(String(e)) },
|
|
85
|
+
* onSuccess: (_, { meta }) => { if (meta?.success) toast(String(meta.success)) },
|
|
86
|
+
* })
|
|
87
|
+
* ```
|
|
88
|
+
* @see https://clarusjs.com/reference/fetch#configure
|
|
89
|
+
*/
|
|
90
|
+
export declare function configure(next: Handlers): void;
|
|
47
91
|
/**
|
|
48
92
|
* A fetcher's answer: a value, a promise of one, or undefined/null/false for "not ready" (a chain still waiting). An
|
|
49
93
|
* async fetcher resolving to undefined is "not ready" too. Signals it reads before its first `await` are tracked.
|
|
@@ -73,6 +117,55 @@ type Fetcher<T> = (ctx: {
|
|
|
73
117
|
* @see https://clarusjs.com/reference/fetch#resource
|
|
74
118
|
*/
|
|
75
119
|
export declare function resource<T>(fetcher: Fetcher<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
120
|
+
/**
|
|
121
|
+
* A one-off async call (delete, save, like): what `action()` gives. Its getters read signals.
|
|
122
|
+
* @see https://clarusjs.com/reference/fetch#action
|
|
123
|
+
*/
|
|
124
|
+
export type Action<I, R> = {
|
|
125
|
+
/** A call is in flight. */
|
|
126
|
+
readonly pending: boolean;
|
|
127
|
+
/** The last call's error (a timeout too, not a cancel), cleared when a call starts. */
|
|
128
|
+
readonly error: unknown;
|
|
129
|
+
/** The last successful call's answer, kept until the next success. */
|
|
130
|
+
readonly result: R | undefined;
|
|
131
|
+
/** Call it: resolves to the answer, or `undefined` if it failed or was cancelled. Never rejects. */
|
|
132
|
+
run(input: I): Promise<R | undefined>;
|
|
133
|
+
/** Call it, and reject if it fails or is cancelled (for try/catch and chains). */
|
|
134
|
+
runAsync(input: I): Promise<R>;
|
|
135
|
+
/** Cancel the call in flight: back to idle, no error, no callbacks. */
|
|
136
|
+
abort(): void;
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* `action()`'s options: `timeout`, `concurrency`, and the callbacks and `meta` a resource takes.
|
|
140
|
+
* @see https://clarusjs.com/reference/fetch#action
|
|
141
|
+
*/
|
|
142
|
+
export type ActionOptions<I, R> = {
|
|
143
|
+
/** Fail a call after this many ms, with a `TimeoutError`. */
|
|
144
|
+
timeout?: number;
|
|
145
|
+
/** A call while one runs: `'join'` (default) shares the one in flight (no double submit); `'latest'` cancels it. */
|
|
146
|
+
concurrency?: 'join' | 'latest';
|
|
147
|
+
} & Callbacks<R, I>;
|
|
148
|
+
/**
|
|
149
|
+
* A one-off async call from the browser (delete, save, like), with `pending`, `error` and `result` for the template.
|
|
150
|
+
* `run()` never rejects (the error lands in `error`, `onError` and `configure()`'s handler); `runAsync()` does. A
|
|
151
|
+
* call while one runs joins it; created in an island, the call is cancelled when the island goes away. On the server
|
|
152
|
+
* nothing runs.
|
|
153
|
+
*
|
|
154
|
+
* @param fn Gets the input and `{ signal }` (pass it on to `request()`); returns the answer or a promise of it.
|
|
155
|
+
* @param options `timeout`, `concurrency` (`'join'` or `'latest'`), `onSuccess` / `onError` / `onSettled`, `meta`.
|
|
156
|
+
* @example
|
|
157
|
+
* ```ts
|
|
158
|
+
* const remove = action((id: number, { signal }) => request(`/api/posts/${id}`, { method: 'DELETE', signal }), {
|
|
159
|
+
* meta: { success: 'Deleted' },
|
|
160
|
+
* onSuccess: () => invalidate(['posts']),
|
|
161
|
+
* })
|
|
162
|
+
* // <button (click)="remove.run(post.id)" [disabled]="remove.pending">Delete</button>
|
|
163
|
+
* ```
|
|
164
|
+
* @see https://clarusjs.com/reference/fetch#action
|
|
165
|
+
*/
|
|
166
|
+
export declare function action<I = void, R = unknown>(fn: (input: I, ctx: {
|
|
167
|
+
signal: AbortSignal;
|
|
168
|
+
}) => R | Promise<R>, options?: ActionOptions<I, R>): Action<I, R>;
|
|
76
169
|
/**
|
|
77
170
|
* Mark every cached answer whose key starts with `prefix` (element by element) as stale: the resources showing one
|
|
78
171
|
* fetch it again now, the others when next used. With no prefix: everything.
|
|
@@ -136,14 +229,75 @@ export declare function batch<T>(load: (keys: string[], ctx: {
|
|
|
136
229
|
max?: number;
|
|
137
230
|
}): Batch<T>;
|
|
138
231
|
/**
|
|
139
|
-
* `
|
|
140
|
-
*
|
|
232
|
+
* What `request()` reads from a response: by default from its `Content-Type` (JSON for `application/json` and
|
|
233
|
+
* `+json` types, text for `text/*` and XML, else a Blob; nothing for a 204), or as `as` says.
|
|
234
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
235
|
+
*/
|
|
236
|
+
export type ReadAs = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'response' | 'stream';
|
|
237
|
+
/**
|
|
238
|
+
* `request()`'s options: `fetch`'s, plus `body` (a plain object or array is sent as JSON), `as`, `parse` and `timeout`.
|
|
239
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
240
|
+
*/
|
|
241
|
+
export type RequestOptions = Omit<RequestInit, 'body'> & {
|
|
242
|
+
/** What `fetch` takes, or a plain object or array: sent as JSON, with `Content-Type: application/json` unless set. */
|
|
243
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null;
|
|
244
|
+
/** What to read from the response; by default its `Content-Type` decides. */
|
|
245
|
+
as?: ReadAs;
|
|
246
|
+
/** Your own reader per content type (`'application/x-ndjson'`, without parameters), ahead of the built-in ones. */
|
|
247
|
+
parse?: Record<string, (res: Response) => unknown>;
|
|
248
|
+
/** Abort after this many ms, with a `TimeoutError` (on top of `signal`). */
|
|
249
|
+
timeout?: number;
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* The error a non-2xx response throws: its `status`, and its body read like a success's (`data`).
|
|
253
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
254
|
+
*/
|
|
255
|
+
export type ResponseError = Error & {
|
|
256
|
+
status: number;
|
|
257
|
+
data: unknown;
|
|
258
|
+
};
|
|
259
|
+
/** What `request()` resolves to for each built-in `as` (without `parse`, which can read anything). */
|
|
260
|
+
type ReadResult = {
|
|
261
|
+
text: string;
|
|
262
|
+
blob: Blob;
|
|
263
|
+
arrayBuffer: ArrayBuffer;
|
|
264
|
+
formData: FormData;
|
|
265
|
+
response: Response;
|
|
266
|
+
stream: ReadableStream<Uint8Array> | null;
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* `fetch`, then the response read by its `Content-Type` (or as `as` says). A response that isn't 2xx throws an Error
|
|
270
|
+
* naming the URL and status, with `status` and the error body (`data`), so a resource's `retry` and `error` see it.
|
|
141
271
|
*
|
|
272
|
+
* @param options `fetch`'s options, plus `body` (a plain object or array goes as JSON), `as`, `parse`, `timeout`.
|
|
273
|
+
* @example
|
|
274
|
+
* ```ts
|
|
275
|
+
* const csv = await request<string>('/api/export', { as: 'text', timeout: 10_000 })
|
|
276
|
+
* await request(`/api/posts/${id}`, { method: 'PATCH', body: { title } })
|
|
277
|
+
* ```
|
|
278
|
+
* @see https://clarusjs.com/reference/fetch#request
|
|
279
|
+
*/
|
|
280
|
+
export declare function request<A extends keyof ReadResult>(url: string | URL, options: RequestOptions & {
|
|
281
|
+
as: A;
|
|
282
|
+
parse?: undefined;
|
|
283
|
+
}): Promise<ReadResult[A]>;
|
|
284
|
+
export declare function request<T = any>(url: string | URL, options?: RequestOptions): Promise<T>;
|
|
285
|
+
/**
|
|
286
|
+
* `request()` reading JSON whatever the `Content-Type`. A non-2xx response throws (with `status` and `data`).
|
|
142
287
|
* @example
|
|
143
288
|
* ```ts
|
|
144
289
|
* const me = resource(({ signal }) => json<User>('/api/me', { signal }))
|
|
145
290
|
* ```
|
|
146
291
|
* @see https://clarusjs.com/reference/fetch#json
|
|
147
292
|
*/
|
|
148
|
-
export declare
|
|
293
|
+
export declare const json: <T = any>(url: string | URL, options?: RequestOptions) => Promise<T>;
|
|
294
|
+
/**
|
|
295
|
+
* `request()` reading text whatever the `Content-Type`. A non-2xx response throws (with `status` and `data`).
|
|
296
|
+
* @example
|
|
297
|
+
* ```ts
|
|
298
|
+
* const readme = resource(({ signal }) => text('/README.md', { signal }))
|
|
299
|
+
* ```
|
|
300
|
+
* @see https://clarusjs.com/reference/fetch#text
|
|
301
|
+
*/
|
|
302
|
+
export declare const text: (url: string | URL, options?: RequestOptions) => Promise<string>;
|
|
149
303
|
export {};
|
package/dist/fetch/index.js
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
import { batch as group, effect, onDispose, state, untrack } from '../runtime/index.js';
|
|
2
2
|
import { browser } from '../runtime/env.js';
|
|
3
|
+
let handlers = {};
|
|
4
|
+
export function configure(next) {
|
|
5
|
+
handlers = next;
|
|
6
|
+
}
|
|
7
|
+
const call = (fn, ...args) => {
|
|
8
|
+
try {
|
|
9
|
+
return fn?.(...args);
|
|
10
|
+
}
|
|
11
|
+
catch (err) {
|
|
12
|
+
(globalThis.reportError ?? console.error)(err);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const settled = (o, ok, value, err, input) => {
|
|
16
|
+
const ctx = { meta: o.meta };
|
|
17
|
+
if (ok) {
|
|
18
|
+
if (call(o.onSuccess, value, input) !== false)
|
|
19
|
+
call(handlers.onSuccess, value, ctx);
|
|
20
|
+
}
|
|
21
|
+
else if (call(o.onError, err, input) !== false)
|
|
22
|
+
call(handlers.onError, err, ctx);
|
|
23
|
+
call(o.onSettled, ok ? value : undefined, ok ? undefined : err, input);
|
|
24
|
+
};
|
|
25
|
+
const within = (signal, ms) => (ms === undefined ? signal : AbortSignal.any([signal, AbortSignal.timeout(ms)]));
|
|
3
26
|
export function resource(fetcher, options = {}) {
|
|
4
27
|
const value = state(options.initial);
|
|
5
28
|
const loading = state(!browser && options.initial === undefined);
|
|
@@ -18,9 +41,10 @@ export function resource(fetcher, options = {}) {
|
|
|
18
41
|
const keyed = browser && !!options.key;
|
|
19
42
|
let entry;
|
|
20
43
|
let force = false;
|
|
44
|
+
let cancelled = -1;
|
|
21
45
|
const user = {
|
|
22
46
|
keep: options.keep ?? KEEP,
|
|
23
|
-
push: (v) => { if (!disposed)
|
|
47
|
+
push: (v, seq) => { if (!disposed && seq !== cancelled)
|
|
24
48
|
value.set(v); },
|
|
25
49
|
rerun: () => { if (stop)
|
|
26
50
|
tick.set(untrack(tick.get) + 1); },
|
|
@@ -51,11 +75,13 @@ export function resource(fetcher, options = {}) {
|
|
|
51
75
|
}
|
|
52
76
|
const run = () => {
|
|
53
77
|
tick.get();
|
|
78
|
+
cancelled = -1;
|
|
54
79
|
const forced = force;
|
|
55
80
|
force = false;
|
|
56
81
|
controller?.abort();
|
|
57
82
|
const id = ++runs;
|
|
58
83
|
const c = (controller = new AbortController());
|
|
84
|
+
const signal = within(c.signal, options.timeout);
|
|
59
85
|
let state = 'fetch';
|
|
60
86
|
let out;
|
|
61
87
|
inFetcher = true;
|
|
@@ -74,19 +100,19 @@ export function resource(fetcher, options = {}) {
|
|
|
74
100
|
else if (!forced && e.pending)
|
|
75
101
|
out = e.pending;
|
|
76
102
|
else {
|
|
77
|
-
const
|
|
78
|
-
const first = fetcher({ signal:
|
|
103
|
+
const rs = within(new AbortController().signal, options.timeout);
|
|
104
|
+
const first = fetcher({ signal: rs });
|
|
79
105
|
if (first === undefined || first === null || first === false)
|
|
80
106
|
state = 'not ready';
|
|
81
107
|
else
|
|
82
|
-
out =
|
|
108
|
+
out = track(e, retrying(first, () => fetcher({ signal: rs }), rs));
|
|
83
109
|
}
|
|
84
110
|
}
|
|
85
111
|
if (state === 'not ready')
|
|
86
112
|
join(undefined);
|
|
87
113
|
}
|
|
88
114
|
else {
|
|
89
|
-
out = fetcher({ signal
|
|
115
|
+
out = fetcher({ signal });
|
|
90
116
|
if (out === undefined || out === null || out === false)
|
|
91
117
|
state = 'not ready';
|
|
92
118
|
}
|
|
@@ -116,15 +142,19 @@ export function resource(fetcher, options = {}) {
|
|
|
116
142
|
loading.set(true);
|
|
117
143
|
busy = true;
|
|
118
144
|
const latest = () => id === runs && !disposed;
|
|
119
|
-
return (keyed ? out : retrying(out, () => fetcher({ signal
|
|
145
|
+
return (keyed ? Promise.race([out, aborted(signal)]) : retrying(out, () => fetcher({ signal }), signal)).then((v) => { if (latest()) {
|
|
120
146
|
if (!keyed && v !== undefined)
|
|
121
147
|
value.set(v);
|
|
122
148
|
loading.set(false);
|
|
123
149
|
busy = false;
|
|
124
|
-
|
|
150
|
+
if (v !== undefined)
|
|
151
|
+
settled(options, true, v, undefined);
|
|
152
|
+
} }, (e) => { if (latest()) {
|
|
153
|
+
const err = signal.aborted ? signal.reason : e;
|
|
125
154
|
error.set(err);
|
|
126
155
|
loading.set(false);
|
|
127
156
|
busy = false;
|
|
157
|
+
settled(options, false, undefined, err);
|
|
128
158
|
} });
|
|
129
159
|
});
|
|
130
160
|
};
|
|
@@ -176,6 +206,17 @@ export function resource(fetcher, options = {}) {
|
|
|
176
206
|
stop = effect(run);
|
|
177
207
|
return Promise.resolve().then(() => pending);
|
|
178
208
|
},
|
|
209
|
+
abort() {
|
|
210
|
+
if (!controller)
|
|
211
|
+
return;
|
|
212
|
+
runs++;
|
|
213
|
+
if (entry?.pending)
|
|
214
|
+
cancelled = entry.seq;
|
|
215
|
+
controller.abort();
|
|
216
|
+
controller = undefined;
|
|
217
|
+
busy = false;
|
|
218
|
+
loading.set(false);
|
|
219
|
+
},
|
|
179
220
|
mutate(v) { if (browser) {
|
|
180
221
|
if (entry)
|
|
181
222
|
store(entry, v, ++entry.seq);
|
|
@@ -195,6 +236,53 @@ export function resource(fetcher, options = {}) {
|
|
|
195
236
|
};
|
|
196
237
|
return self;
|
|
197
238
|
}
|
|
239
|
+
const aborted = (signal) => new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true }));
|
|
240
|
+
export function action(fn, options = {}) {
|
|
241
|
+
const pending = state(false);
|
|
242
|
+
const error = state(undefined);
|
|
243
|
+
const result = state(undefined);
|
|
244
|
+
let controller;
|
|
245
|
+
let current;
|
|
246
|
+
const abort = () => { controller?.abort(); controller = current = undefined; pending.set(false); };
|
|
247
|
+
if (browser)
|
|
248
|
+
onDispose(abort);
|
|
249
|
+
const runAsync = (input) => {
|
|
250
|
+
if (!browser)
|
|
251
|
+
return Promise.resolve(undefined);
|
|
252
|
+
if (current && options.concurrency !== 'latest')
|
|
253
|
+
return current;
|
|
254
|
+
abort();
|
|
255
|
+
const c = (controller = new AbortController());
|
|
256
|
+
const signal = within(c.signal, options.timeout);
|
|
257
|
+
const mine = () => controller === c;
|
|
258
|
+
const end = () => { controller = current = undefined; };
|
|
259
|
+
error.set(undefined);
|
|
260
|
+
const p = Promise.race([(async () => fn(input, { signal }))(), aborted(signal)]).then((v) => { if (mine()) {
|
|
261
|
+
end();
|
|
262
|
+
group(() => { result.set(v); pending.set(false); });
|
|
263
|
+
settled(options, true, v, undefined, input);
|
|
264
|
+
} return v; }, (e) => {
|
|
265
|
+
const err = signal.aborted ? signal.reason : e;
|
|
266
|
+
if (mine()) {
|
|
267
|
+
end();
|
|
268
|
+
group(() => { error.set(err); pending.set(false); });
|
|
269
|
+
settled(options, false, undefined, err, input);
|
|
270
|
+
}
|
|
271
|
+
throw err;
|
|
272
|
+
});
|
|
273
|
+
current = p;
|
|
274
|
+
pending.set(true);
|
|
275
|
+
return p;
|
|
276
|
+
};
|
|
277
|
+
return {
|
|
278
|
+
get pending() { return pending.get(); },
|
|
279
|
+
get error() { return error.get(); },
|
|
280
|
+
get result() { return result.get(); },
|
|
281
|
+
run: (input) => runAsync(input).catch(() => undefined),
|
|
282
|
+
runAsync,
|
|
283
|
+
abort,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
198
286
|
const KEEP = 5 * 60_000;
|
|
199
287
|
const cache = new Map();
|
|
200
288
|
const hash = (v) => JSON.stringify(v, (_, x) => (x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : x));
|
|
@@ -218,9 +306,9 @@ const store = (e, v, seq) => {
|
|
|
218
306
|
return;
|
|
219
307
|
Object.assign(e, { value: v, has: true, at: Date.now(), invalid: false });
|
|
220
308
|
for (const u of e.users)
|
|
221
|
-
u.push(v);
|
|
309
|
+
u.push(v, seq);
|
|
222
310
|
};
|
|
223
|
-
const
|
|
311
|
+
const track = (e, answer) => {
|
|
224
312
|
const seq = ++e.seq;
|
|
225
313
|
const p = answer.then((v) => { if (v !== undefined)
|
|
226
314
|
store(e, v, seq); return v; });
|
|
@@ -257,7 +345,7 @@ export function prefetch(key, fetcher) {
|
|
|
257
345
|
if (!browser)
|
|
258
346
|
return Promise.resolve();
|
|
259
347
|
const e = entryOf(key);
|
|
260
|
-
const p = e.has && !e.invalid ? Promise.resolve() : e.pending ??
|
|
348
|
+
const p = e.has && !e.invalid ? Promise.resolve() : e.pending ?? track(e, (async () => fetcher({ signal: new AbortController().signal }))());
|
|
261
349
|
release(e);
|
|
262
350
|
return p.then(() => { }, () => { });
|
|
263
351
|
}
|
|
@@ -302,11 +390,44 @@ export function batch(load, options = {}) {
|
|
|
302
390
|
},
|
|
303
391
|
};
|
|
304
392
|
}
|
|
305
|
-
|
|
393
|
+
const read = (res, as, parse) => {
|
|
394
|
+
const type = res.headers.get('content-type')?.split(';')[0].trim().toLowerCase() ?? '';
|
|
395
|
+
const own = parse?.[type];
|
|
396
|
+
if (own)
|
|
397
|
+
return own(res);
|
|
398
|
+
if (as === 'response')
|
|
399
|
+
return res;
|
|
400
|
+
if (as === 'stream')
|
|
401
|
+
return res.body;
|
|
402
|
+
if (as)
|
|
403
|
+
return res[as]();
|
|
404
|
+
if (res.status === 204)
|
|
405
|
+
return undefined;
|
|
406
|
+
if (type === 'application/json' || type.endsWith('+json'))
|
|
407
|
+
return res.json();
|
|
408
|
+
return type.startsWith('text/') || type.endsWith('xml') ? res.text() : res.blob();
|
|
409
|
+
};
|
|
410
|
+
export async function request(url, options = {}) {
|
|
411
|
+
const { as, parse, timeout, body, ...init } = options;
|
|
412
|
+
if (body !== undefined) {
|
|
413
|
+
const plain = body !== null && typeof body === 'object' && (Array.isArray(body) || [Object.prototype, null].includes(Object.getPrototypeOf(body)));
|
|
414
|
+
if (plain) {
|
|
415
|
+
const headers = new Headers(init.headers);
|
|
416
|
+
if (!headers.has('content-type'))
|
|
417
|
+
headers.set('content-type', 'application/json');
|
|
418
|
+
Object.assign(init, { body: JSON.stringify(body), headers });
|
|
419
|
+
}
|
|
420
|
+
else
|
|
421
|
+
init.body = body;
|
|
422
|
+
}
|
|
423
|
+
if (timeout !== undefined)
|
|
424
|
+
init.signal = AbortSignal.any([AbortSignal.timeout(timeout), ...(init.signal ? [init.signal] : [])]);
|
|
306
425
|
const res = await fetch(url, init);
|
|
307
426
|
if (!res.ok) {
|
|
308
|
-
await
|
|
309
|
-
throw Object.assign(new Error(`${url}: ${res.status} ${res.statusText}`.trim()), { status: res.status });
|
|
427
|
+
const data = await Promise.resolve().then(() => read(res, as === 'response' || as === 'stream' ? 'text' : undefined, parse)).catch(() => undefined);
|
|
428
|
+
throw Object.assign(new Error(`${url}: ${res.status} ${res.statusText}`.trim()), { status: res.status, data });
|
|
310
429
|
}
|
|
311
|
-
return res
|
|
430
|
+
return read(res, as, parse);
|
|
312
431
|
}
|
|
432
|
+
export const json = (url, options) => request(url, { ...options, as: 'json' });
|
|
433
|
+
export const text = (url, options) => request(url, { ...options, as: 'text' });
|
package/dist/runtime/dom.d.ts
CHANGED
|
@@ -41,6 +41,15 @@ export declare function block(ctx: Ctx, index: number, which: () => number, bran
|
|
|
41
41
|
html: () => string;
|
|
42
42
|
wire: () => void;
|
|
43
43
|
}[]): void;
|
|
44
|
+
/**
|
|
45
|
+
* An @await's promise in an island (#430): `k()` is 0 while it's pending, 1 once it resolved, 2 once it rejected
|
|
46
|
+
* (tracked, so a block follows it); `v()` is the value or error. When the expression's signals change, a new
|
|
47
|
+
* promise starts (back to pending) and only the newest one's answer counts. @internal
|
|
48
|
+
*/
|
|
49
|
+
export declare function awaited(fn: () => unknown): {
|
|
50
|
+
k(): number;
|
|
51
|
+
v(): unknown;
|
|
52
|
+
};
|
|
44
53
|
/** @internal Compiled components call this; apps don't. */
|
|
45
54
|
export declare function region(ctx: Ctx, index: number, html: () => string, wire: () => void): void;
|
|
46
55
|
/**
|
package/dist/runtime/dom.js
CHANGED
|
@@ -139,6 +139,30 @@ const onlyIsland = (nodes) => {
|
|
|
139
139
|
const kept = nodes.filter((n) => n.nodeType !== 3 || n.textContent.trim());
|
|
140
140
|
return kept.length === 1 && kept[0].localName === 'cl-island' ? kept[0] : null;
|
|
141
141
|
};
|
|
142
|
+
/**
|
|
143
|
+
* An @await's promise in an island (#430): `k()` is 0 while it's pending, 1 once it resolved, 2 once it rejected
|
|
144
|
+
* (tracked, so a block follows it); `v()` is the value or error. When the expression's signals change, a new
|
|
145
|
+
* promise starts (back to pending) and only the newest one's answer counts. @internal
|
|
146
|
+
*/
|
|
147
|
+
export function awaited(fn) {
|
|
148
|
+
const k = state(0);
|
|
149
|
+
let v;
|
|
150
|
+
let run = 0;
|
|
151
|
+
onDispose(() => { run++; }); // an answer after the island is gone changes nothing
|
|
152
|
+
effect(() => {
|
|
153
|
+
const p = fn();
|
|
154
|
+
const id = ++run;
|
|
155
|
+
untrack(() => k.set(0));
|
|
156
|
+
Promise.resolve(p).then((x) => { if (id === run) {
|
|
157
|
+
v = x;
|
|
158
|
+
k.set(1);
|
|
159
|
+
} }, (e) => { if (id === run) {
|
|
160
|
+
v = e;
|
|
161
|
+
k.set(2);
|
|
162
|
+
} });
|
|
163
|
+
});
|
|
164
|
+
return { k: () => k.get(), v: () => v };
|
|
165
|
+
}
|
|
142
166
|
/** @internal Compiled components call this; apps don't. */
|
|
143
167
|
export function region(ctx, index, html, wire) {
|
|
144
168
|
const r = scan(ctx).regions[index];
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { state, derived, shared, effect, scope, onDispose, untrack, batch, type Signal, type ReadSignal } from './signals.ts';
|
|
2
|
-
export { holes, blocks, text, on, attr, spread, block, forBlock, region, model, modelInput, type Hole, type Block, type Ctx } from './dom.ts';
|
|
2
|
+
export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, type Hole, type Block, type Ctx } from './dom.ts';
|
|
3
3
|
export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
|
|
4
4
|
export { parse as parseIslandData } from './serialize.ts';
|
|
5
5
|
export { classValue, styleValue } from './attrs.ts';
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Browser runtime used by compiled attach() functions.
|
|
2
2
|
export { state, derived, shared, effect, scope, onDispose, untrack, batch } from './signals.js';
|
|
3
|
-
export { holes, blocks, text, on, attr, spread, block, forBlock, region, model, modelInput } from './dom.js';
|
|
3
|
+
export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput } from './dom.js';
|
|
4
4
|
export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
|
|
5
5
|
export { parse as parseIslandData } from './serialize.js';
|
|
6
6
|
export { classValue, styleValue } from './attrs.js';
|
package/dist/runtime/server.d.ts
CHANGED
|
@@ -7,6 +7,18 @@ export { classValue, styleValue } from './attrs.ts';
|
|
|
7
7
|
* @internal Compiled components call this; apps don't.
|
|
8
8
|
*/
|
|
9
9
|
export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string, paths?: Record<string, unknown>): string;
|
|
10
|
+
/**
|
|
11
|
+
* The parts of a template level that calls components or places slots (#430): joined into a string, or into a
|
|
12
|
+
* promise of one when a part is a promise (a component that awaits in its <script server>). @internal
|
|
13
|
+
*/
|
|
14
|
+
export declare function join(parts: unknown[]): string | Promise<string>;
|
|
15
|
+
/**
|
|
16
|
+
* An @await outside islands (#430): the server waits for the promise and renders @then with the value or @catch
|
|
17
|
+
* with the error; without @catch, a rejection fails the render. @internal
|
|
18
|
+
*/
|
|
19
|
+
export declare function awaitHtml(promise: unknown, then: ((v: unknown) => string | Promise<string>) | null, caught: ((e: unknown) => string | Promise<string>) | null): Promise<string>;
|
|
20
|
+
/** A child component's HTML inside an island: a promise (it awaits) is an error naming both. @internal */
|
|
21
|
+
export declare function sync(html: string | Promise<string>, child: string, island: string): string;
|
|
10
22
|
/** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
|
|
11
23
|
export declare const attr: typeof attrHtml;
|
|
12
24
|
/**
|
package/dist/runtime/server.js
CHANGED
|
@@ -15,6 +15,36 @@ export function island(name, src, props, html, state, attach, paths) {
|
|
|
15
15
|
const d = Object.entries(paths ?? {}).map(([model, path]) => ` data-cl-path-${escape(model)}="${escape(String(path))}"`).join('');
|
|
16
16
|
return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(toBrowser(props))}"${s}${a}${d}>${html}</cl-island>`;
|
|
17
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* The parts of a template level that calls components or places slots (#430): joined into a string, or into a
|
|
20
|
+
* promise of one when a part is a promise (a component that awaits in its <script server>). @internal
|
|
21
|
+
*/
|
|
22
|
+
export function join(parts) {
|
|
23
|
+
return parts.some((p) => p instanceof Promise) ? Promise.all(parts).then((all) => all.join('')) : parts.join('');
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* An @await outside islands (#430): the server waits for the promise and renders @then with the value or @catch
|
|
27
|
+
* with the error; without @catch, a rejection fails the render. @internal
|
|
28
|
+
*/
|
|
29
|
+
export async function awaitHtml(promise, then, caught) {
|
|
30
|
+
let value;
|
|
31
|
+
try {
|
|
32
|
+
value = await promise;
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
if (!caught)
|
|
36
|
+
throw err;
|
|
37
|
+
return caught(err);
|
|
38
|
+
}
|
|
39
|
+
return then ? then(value) : '';
|
|
40
|
+
}
|
|
41
|
+
/** A child component's HTML inside an island: a promise (it awaits) is an error naming both. @internal */
|
|
42
|
+
export function sync(html, child, island) {
|
|
43
|
+
if (typeof html === 'string')
|
|
44
|
+
return html;
|
|
45
|
+
html.catch(() => { }); // its own rejection isn't the error to report
|
|
46
|
+
throw new Error(`[clarusjs] <${child}> awaits in its <script server>, so it can't be inside the island <${island}>: an island re-renders its children in the browser, where it can't wait. Render <${child}> outside the island, or load its data in a parent and pass it in as props`);
|
|
47
|
+
}
|
|
18
48
|
/** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
|
|
19
49
|
export const attr = attrHtml;
|
|
20
50
|
/**
|
|
@@ -37,7 +67,10 @@ export function toBrowser(value, path = '', seen = new Set()) {
|
|
|
37
67
|
* compiled components that have a loader. @internal
|
|
38
68
|
*/
|
|
39
69
|
export function loaded(key) {
|
|
40
|
-
|
|
70
|
+
// The server handler keeps each render's data in an AsyncLocalStorage (#430: a render may pause at an await);
|
|
71
|
+
// this module stays free of Node APIs (it also runs in the docs playground), so it only reads it.
|
|
72
|
+
const scope = globalThis;
|
|
73
|
+
return (scope.__clLoadedStore?.getStore() ?? scope.__clLoaded)?.get(key) ?? {};
|
|
41
74
|
}
|
|
42
75
|
/**
|
|
43
76
|
* Render with component loaders' results available to `loaded()`. Rendering is synchronous, so one render's data never
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type ModeTable } from './modes.ts';
|
|
2
2
|
import { type HeadOptions, type SiteOptions } from './head.ts';
|
|
3
3
|
type PageModule = {
|
|
4
|
-
render(props?: object): string
|
|
4
|
+
render(props?: object): string | Promise<string>;
|
|
5
5
|
};
|
|
6
6
|
type Params = Record<string, string>;
|
|
7
7
|
/**
|