clarusjs 0.12.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.
Files changed (45) hide show
  1. package/README.md +2 -0
  2. package/dist/check/generate.js +54 -11
  3. package/dist/cli/check.js +15 -4
  4. package/dist/compiler/class-style.d.ts +2 -0
  5. package/dist/compiler/class-style.js +53 -0
  6. package/dist/compiler/emit-client.js +24 -4
  7. package/dist/compiler/emit-server.js +15 -5
  8. package/dist/compiler/html-expr.d.ts +10 -2
  9. package/dist/compiler/html-expr.js +31 -17
  10. package/dist/compiler/icon.d.ts +24 -0
  11. package/dist/compiler/icon.js +83 -0
  12. package/dist/compiler/index.d.ts +4 -0
  13. package/dist/compiler/index.js +53 -9
  14. package/dist/compiler/ir.d.ts +23 -0
  15. package/dist/compiler/ir.js +69 -2
  16. package/dist/compiler/lint.js +12 -1
  17. package/dist/compiler/parse.d.ts +24 -0
  18. package/dist/compiler/parse.js +66 -0
  19. package/dist/compiler/script.d.ts +10 -1
  20. package/dist/compiler/script.js +17 -3
  21. package/dist/fetch/index.d.ts +157 -3
  22. package/dist/fetch/index.js +135 -14
  23. package/dist/icons.d.ts +59 -0
  24. package/dist/icons.js +112 -0
  25. package/dist/runtime/attrs.d.ts +27 -0
  26. package/dist/runtime/attrs.js +66 -0
  27. package/dist/runtime/dom.d.ts +15 -0
  28. package/dist/runtime/dom.js +50 -1
  29. package/dist/runtime/html.d.ts +6 -0
  30. package/dist/runtime/html.js +19 -1
  31. package/dist/runtime/index.d.ts +3 -2
  32. package/dist/runtime/index.js +3 -2
  33. package/dist/runtime/server.d.ts +14 -1
  34. package/dist/runtime/server.js +36 -2
  35. package/dist/server/handler.d.ts +1 -1
  36. package/dist/server/handler.js +5 -2
  37. package/dist/server/views.d.ts +1 -1
  38. package/dist/server/views.js +1 -1
  39. package/dist/vite/node.d.ts +2 -0
  40. package/dist/vite/node.js +13 -0
  41. package/dist/vite/plugin.d.ts +6 -1
  42. package/dist/vite/plugin.js +114 -17
  43. package/dist/vite/sitemap.d.ts +20 -1
  44. package/dist/vite/sitemap.js +27 -3
  45. package/package.json +5 -1
@@ -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
- * `fetch(url, init)`, then the response's JSON. A response that isn't 2xx throws an Error naming the URL and status
140
- * (its `status` property holds the code), so a resource's `retry` and `error` see it.
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 function json<T = any>(url: string | URL, init?: RequestInit): Promise<T>;
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 {};
@@ -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 rc = new AbortController();
78
- const first = fetcher({ signal: rc.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 = request(e, retrying(first, () => fetcher({ signal: rc.signal }), rc.signal));
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: c.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: c.signal }), c.signal)).then((v) => { if (latest()) {
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
- } }, (err) => { if (latest()) {
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 request = (e, answer) => {
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 ?? request(e, (async () => fetcher({ signal: new AbortController().signal }))());
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
- export async function json(url, init) {
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 res.text().catch(() => { });
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.json();
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' });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * An icon as the compiler draws it: its SVG body and its box (`viewBox="left top width height"`).
3
+ * @see https://clarusjs.com/guide/icons
4
+ */
5
+ export type IconData = {
6
+ body: string;
7
+ width: number;
8
+ height: number;
9
+ left: number;
10
+ top: number;
11
+ };
12
+ /**
13
+ * What a lookup found: the icon, or what's missing (the set, or the icon in it, with the closest names).
14
+ * @see https://clarusjs.com/guide/icons
15
+ */
16
+ export type IconLookup = {
17
+ data: IconData;
18
+ } | {
19
+ missing: 'set';
20
+ set: string;
21
+ } | {
22
+ missing: 'icon';
23
+ set: string;
24
+ suggestions: string[];
25
+ };
26
+ /**
27
+ * The icon `set:name` (Iconify naming), from the sets installed for the package `fromFile` is in. Throws for an alias
28
+ * that flips or rotates its icon (not supported yet).
29
+ * @example
30
+ * resolveIcon('lucide:rocket', '/app/src/pages/index.tscl') // { data: { body: '<path …/>', width: 24, … } }
31
+ * @see https://clarusjs.com/guide/icons
32
+ */
33
+ export declare function resolveIcon(name: string, fromFile: string): IconLookup;
34
+ /**
35
+ * The icon sets installed for the package `fromFile` is in (its `@iconify-json/*` dependencies, and those in its
36
+ * node_modules), for the editor's completion.
37
+ * @example
38
+ * iconSets('/app/src/pages/index.tscl') // [{ prefix: 'lucide', name: 'Lucide', total: 1600 }]
39
+ * @see https://clarusjs.com/guide/icons
40
+ */
41
+ export declare function iconSets(fromFile: string): {
42
+ prefix: string;
43
+ name: string;
44
+ total: number;
45
+ }[];
46
+ /**
47
+ * The names in an installed set (icons and aliases, sorted); none when it isn't installed.
48
+ * @example
49
+ * iconNames('lucide', '/app/src/pages/index.tscl') // ['a-arrow-down', …, 'rocket', …]
50
+ * @see https://clarusjs.com/guide/icons
51
+ */
52
+ export declare function iconNames(set: string, fromFile: string): string[];
53
+ /**
54
+ * A standalone `<svg>` for an icon, with extra attributes (`'width="48"'`); the editor's hover preview uses it.
55
+ * @example
56
+ * iconSvg(data, 'width="48" height="48"') // '<svg xmlns="…" viewBox="0 0 24 24" width="48" height="48">…</svg>'
57
+ * @see https://clarusjs.com/guide/icons
58
+ */
59
+ export declare function iconSvg(data: IconData, attrs?: string): string;
package/dist/icons.js ADDED
@@ -0,0 +1,112 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join } from 'node:path';
4
+ const sets = new Map();
5
+ function packageDir(file) {
6
+ for (let dir = dirname(file);; dir = dirname(dir)) {
7
+ if (existsSync(join(dir, 'package.json')))
8
+ return dir;
9
+ if (dirname(dir) === dir)
10
+ return dirname(file);
11
+ }
12
+ }
13
+ function loadSet(set, fromFile) {
14
+ const dir = packageDir(fromFile);
15
+ let path;
16
+ try {
17
+ path = createRequire(join(dir, 'package.json')).resolve(`@iconify-json/${set}/icons.json`);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ const mtime = statSync(path).mtimeMs;
23
+ const cached = sets.get(path);
24
+ if (cached?.mtime === mtime)
25
+ return cached.data;
26
+ const data = JSON.parse(readFileSync(path, 'utf8'));
27
+ sets.set(path, { mtime, data });
28
+ return data;
29
+ }
30
+ function distance(a, b) {
31
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
32
+ for (let i = 1; i <= a.length; i++) {
33
+ const next = [i];
34
+ for (let j = 1; j <= b.length; j++)
35
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
36
+ row = next;
37
+ }
38
+ return row[b.length];
39
+ }
40
+ export function resolveIcon(name, fromFile) {
41
+ const colon = name.indexOf(':');
42
+ const set = colon === -1 ? name : name.slice(0, colon);
43
+ const icon = colon === -1 ? '' : name.slice(colon + 1);
44
+ const data = loadSet(set, fromFile);
45
+ if (!data)
46
+ return { missing: 'set', set };
47
+ const all = Object.assign(Object.create(null), data.aliases, data.icons);
48
+ const own = (n) => (Object.hasOwn(all, n) ? all[n] : undefined);
49
+ const first = own(icon);
50
+ if (!first) {
51
+ const suggestions = Object.keys(all)
52
+ .map((n) => [n, distance(icon, n)])
53
+ .filter(([n, d]) => d <= Math.max(2, Math.floor(n.length / 3)))
54
+ .sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]))
55
+ .slice(0, 3)
56
+ .map(([n]) => n);
57
+ return { missing: 'icon', set, suggestions };
58
+ }
59
+ let found = first;
60
+ let merged = { ...found };
61
+ for (let depth = 0; found.parent && depth < 10; depth++) {
62
+ const parent = own(found.parent);
63
+ if (!parent)
64
+ break;
65
+ merged = { ...parent, ...merged, parent: parent.parent };
66
+ found = parent;
67
+ }
68
+ for (const key of ['hFlip', 'vFlip', 'rotate']) {
69
+ if (merged[key])
70
+ throw new Error(`the icon ${name} uses ${key}, which <icon> doesn't support yet`);
71
+ }
72
+ return {
73
+ data: {
74
+ body: merged.body ?? '',
75
+ width: merged.width ?? data.width ?? 16,
76
+ height: merged.height ?? data.height ?? 16,
77
+ left: merged.left ?? data.left ?? 0,
78
+ top: merged.top ?? data.top ?? 0,
79
+ },
80
+ };
81
+ }
82
+ export function iconSets(fromFile) {
83
+ const dir = packageDir(fromFile);
84
+ const names = new Set();
85
+ try {
86
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
87
+ for (const deps of [pkg.dependencies, pkg.devDependencies])
88
+ for (const d of Object.keys(deps ?? {}))
89
+ if (d.startsWith('@iconify-json/'))
90
+ names.add(d.slice(14));
91
+ }
92
+ catch { }
93
+ try {
94
+ for (const d of readdirSync(join(dir, 'node_modules/@iconify-json')))
95
+ names.add(d);
96
+ }
97
+ catch { }
98
+ const out = [];
99
+ for (const prefix of [...names].sort()) {
100
+ const data = loadSet(prefix, fromFile);
101
+ if (data)
102
+ out.push({ prefix, name: data.info?.name ?? prefix, total: data.info?.total ?? Object.keys(data.icons).length });
103
+ }
104
+ return out;
105
+ }
106
+ export function iconNames(set, fromFile) {
107
+ const data = loadSet(set, fromFile);
108
+ return data ? Object.keys({ ...data.icons, ...data.aliases }).sort() : [];
109
+ }
110
+ export function iconSvg(data, attrs = '') {
111
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${data.left} ${data.top} ${data.width} ${data.height}"${attrs ? ' ' + attrs : ''}>${data.body}</svg>`;
112
+ }
@@ -1,5 +1,32 @@
1
1
  export declare const UNSAFE_URL = "about:invalid#unsafe";
2
+ /**
3
+ * A class from a string (as written), an object (its truthy keys) or an array (flattened, falsy entries dropped), like
4
+ * clsx. Templates use it for `[class]` values and `[class.name]` toggles.
5
+ * @example
6
+ * classValue(['a', on && 'b', { c: true, d: false }]) // 'a b c' when on
7
+ * @see https://clarusjs.com/guide/attributes
8
+ */
9
+ export declare function classValue(value: unknown): string;
10
+ /**
11
+ * A style from a string (as written), an object (camelCase keys to kebab-case, custom properties as they are; null,
12
+ * undefined, false and '' left out; no units added) or an array of those. Templates use it for `[style]` values and
13
+ * `[style.prop]` bindings.
14
+ * @example
15
+ * styleValue({ fontSize: '2em', '--accent': c, color: null }) // 'font-size: 2em; --accent: …;'
16
+ * @see https://clarusjs.com/guide/attributes
17
+ */
18
+ export declare function styleValue(value: unknown): string;
2
19
  /**
3
20
  * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
4
21
  */
5
22
  export declare function attrValue(name: string, value: unknown, tag?: string): string | true | null;
23
+ /**
24
+ * A spread's attributes (#405): each key with its value as attrValue gives it, except the names written on the element
25
+ * (`skip`, lowercase), class and style (merged with the element's own), and what a spread may never set, listed in
26
+ * `dropped` with why: event handlers, srcdoc, invalid names, JSX names and objects or functions.
27
+ * @internal the runtimes call this; apps write [...]="attrs".
28
+ */
29
+ export declare function spreadAttrs(obj: unknown, skip: readonly string[], tag?: string): {
30
+ set: [string, string | true | null][];
31
+ dropped: [string, string][];
32
+ };