@tensile-tools/auth-client 0.0.0-stage → 0.3.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 (44) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +62 -2
  3. package/dist/client.d.ts +569 -0
  4. package/dist/client.js +637 -0
  5. package/dist/devtools.d.ts +12 -0
  6. package/dist/devtools.js +44 -0
  7. package/dist/elements/account.d.ts +63 -0
  8. package/dist/elements/account.js +331 -0
  9. package/dist/elements/approvals.d.ts +61 -0
  10. package/dist/elements/approvals.js +252 -0
  11. package/dist/elements/auth.d.ts +48 -0
  12. package/dist/elements/auth.js +238 -0
  13. package/dist/elements/base.d.ts +176 -0
  14. package/dist/elements/base.js +540 -0
  15. package/dist/elements/config.d.ts +70 -0
  16. package/dist/elements/config.js +119 -0
  17. package/dist/elements/format.d.ts +32 -0
  18. package/dist/elements/format.js +67 -0
  19. package/dist/elements/index.d.ts +21 -0
  20. package/dist/elements/index.js +31 -0
  21. package/dist/elements/qr.d.ts +9 -0
  22. package/dist/elements/qr.js +302 -0
  23. package/dist/elements/returnto.d.ts +17 -0
  24. package/dist/elements/returnto.js +63 -0
  25. package/dist/elements/setup.d.ts +70 -0
  26. package/dist/elements/setup.js +316 -0
  27. package/dist/elements/styles.d.ts +3 -0
  28. package/dist/elements/styles.js +194 -0
  29. package/dist/elements/text.d.ts +21 -0
  30. package/dist/elements/text.js +302 -0
  31. package/dist/fonts/OFL-geist-mono.txt +93 -0
  32. package/dist/fonts/OFL-geist.txt +93 -0
  33. package/dist/fonts/OFL-inter.txt +93 -0
  34. package/dist/fonts/README.md +18 -0
  35. package/dist/fonts/geist-mono.woff2 +0 -0
  36. package/dist/fonts/geist.woff2 +0 -0
  37. package/dist/fonts/inter.woff2 +0 -0
  38. package/dist/index.d.ts +4 -0
  39. package/dist/index.js +5 -0
  40. package/dist/problem.d.ts +54 -0
  41. package/dist/problem.js +40 -0
  42. package/dist/webauthn.d.ts +46 -0
  43. package/dist/webauthn.js +102 -0
  44. package/package.json +51 -4
@@ -0,0 +1,540 @@
1
+ // The base of every element: options from attributes, properties, and
2
+ // configure(); the shadow root and its styles; text; events; focus; and
3
+ // the live region.
4
+ import { createAuthClient } from "../client.js";
5
+ import { attrName, fromAttr, onAccent, optionNames, resolve } from "./config.js";
6
+ import { css, fontFaces } from "./styles.js";
7
+ import { withReturnTo } from "./returnto.js";
8
+ import { english, fill, plain, runs } from "./text.js";
9
+ /** HTML that is already safe to insert. */
10
+ export class Html {
11
+ s;
12
+ constructor(s) {
13
+ this.s = s;
14
+ }
15
+ toString() {
16
+ return this.s;
17
+ }
18
+ }
19
+ /** Escapes text for HTML. */
20
+ export const esc = (s) => s.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;' })[c]);
21
+ const toHTML = (v) => {
22
+ if (v === undefined || v === null || v === false)
23
+ return '';
24
+ if (v instanceof Html)
25
+ return v.s;
26
+ if (Array.isArray(v))
27
+ return v.map(toHTML).join('');
28
+ return esc(String(v));
29
+ };
30
+ /** A template tag that escapes every value that isn't Html. */
31
+ export function html(strings, ...vals) {
32
+ let out = strings[0];
33
+ vals.forEach((v, i) => { out += toHTML(v) + strings[i + 1]; });
34
+ return new Html(out);
35
+ }
36
+ /** Fills {name} values in a run's text, escaping text values. */
37
+ function fillHtml(text, vars) {
38
+ return text.split(/(\{\w+\})/).map(part => {
39
+ const m = /^\{(\w+)\}$/.exec(part);
40
+ return m ? toHTML(vars[m[1]] ?? '') : esc(part);
41
+ }).join('');
42
+ }
43
+ /** Renders a text template: [join] grey, *ok* green, !warn! orange, and values. */
44
+ export function rich(template, vars) {
45
+ return new Html(runs(template).map(r => {
46
+ switch (r.kind) {
47
+ case 'value': return toHTML(vars[r.name ?? ''] ?? '');
48
+ case 'join': return `<span class="j">${fillHtml(r.text, vars)}</span>`;
49
+ case 'ok': return `<span class="ok">${fillHtml(r.text, vars)}</span>`;
50
+ case 'warn': return `<span class="warn">${fillHtml(r.text, vars)}</span>`;
51
+ default: return fillHtml(r.text, vars);
52
+ }
53
+ }).join(''));
54
+ }
55
+ let global = {};
56
+ let sharedClient;
57
+ const live = new Set();
58
+ /**
59
+ * Sets options for every element on the page, and the client they share.
60
+ * An element's own `config`, properties, and attributes win over these.
61
+ * Calling it again merges, and every element renders again.
62
+ */
63
+ export function configure(c) {
64
+ const { client, ...opts } = c;
65
+ global = { ...global, ...opts, text: { ...global.text, ...opts.text } };
66
+ for (const el of live)
67
+ el.update();
68
+ if (client && client !== sharedClient) {
69
+ sharedClient = client;
70
+ for (const el of live)
71
+ el.reload();
72
+ }
73
+ }
74
+ /**
75
+ * The element that shows the signed-out prompt for its client. Every
76
+ * element that follows the session and shares a client lost the session
77
+ * at the same moment, so one prompt is enough: the first of them in
78
+ * document order shows it, and the others collapse until the next
79
+ * sign-in.
80
+ */
81
+ function promptOwner(c) {
82
+ let first;
83
+ for (const el of live) {
84
+ if (!el.isConnected || !el.wantsPrompt() || el.client !== c)
85
+ continue;
86
+ if (!first || before(el, first))
87
+ first = el;
88
+ }
89
+ return first;
90
+ }
91
+ /** Reports whether a comes before b in the document. */
92
+ function before(a, b) {
93
+ if (typeof a.compareDocumentPosition !== 'function')
94
+ return false;
95
+ return (a.compareDocumentPosition(b) & 4) !== 0; // Node.DOCUMENT_POSITION_FOLLOWING
96
+ }
97
+ /** Renders every other element that shares c, so the prompt moves to the right one. */
98
+ function settlePrompt(c, except) {
99
+ for (const el of live)
100
+ if (el !== except && el.client === c && el.wantsPrompt())
101
+ el.update();
102
+ }
103
+ let sheet;
104
+ let fontsAdded = false;
105
+ /** Adds the bundled fonts to the document once. @font-face doesn't work inside a shadow root. */
106
+ function addFonts() {
107
+ if (fontsAdded || typeof document === 'undefined' || !('adoptedStyleSheets' in document))
108
+ return;
109
+ fontsAdded = true;
110
+ const s = new CSSStyleSheet();
111
+ s.replaceSync(fontFaces(new URL('../fonts/', import.meta.url).href));
112
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, s];
113
+ }
114
+ /** The base class of the elements. */
115
+ export class TensileElement extends HTMLElement {
116
+ /** Attributes this element reads besides the options. */
117
+ static attrs = [];
118
+ static get observedAttributes() {
119
+ return [...optionNames.map(attrName), ...this.attrs];
120
+ }
121
+ /** The state the element shows, such as `start` or `done`. */
122
+ state = 'start';
123
+ /** An error to show, or empty. */
124
+ error = '';
125
+ /** A message that isn't an error, such as "a link is on its way", or empty. */
126
+ notice = '';
127
+ /** What the person typed, by input name. */
128
+ values = {};
129
+ /** True while a request runs; actions wait. */
130
+ busy = false;
131
+ root;
132
+ view;
133
+ liveRegion;
134
+ dyn;
135
+ focusNext = false;
136
+ /** True after the session ended, until the next sign-in. */
137
+ lost = false;
138
+ /** The load generation: every session change bumps it, so a load that started before drops its result. */
139
+ gen = 0;
140
+ started = false;
141
+ /** Options set as properties. */
142
+ _props = {};
143
+ ownConfig;
144
+ ownClient;
145
+ constructor() {
146
+ super();
147
+ this.root = this.attachShadow({ mode: 'open' });
148
+ if (!sheet) {
149
+ sheet = new CSSStyleSheet();
150
+ sheet.replaceSync(css);
151
+ }
152
+ this.dyn = new CSSStyleSheet();
153
+ this.root.adoptedStyleSheets = [sheet, this.dyn];
154
+ this.view = document.createElement('div');
155
+ this.view.setAttribute('part', 'root');
156
+ this.liveRegion = document.createElement('p');
157
+ this.liveRegion.className = 'vh';
158
+ this.liveRegion.setAttribute('role', 'status');
159
+ this.liveRegion.setAttribute('aria-live', 'polite');
160
+ this.root.append(this.view, this.liveRegion);
161
+ this.root.addEventListener('click', e => {
162
+ const t = e.target.closest('[data-do]');
163
+ if (!t || t.tagName === 'FORM' || t.getAttribute('aria-disabled') === 'true')
164
+ return;
165
+ e.preventDefault();
166
+ void this.run(t.dataset.do, t);
167
+ });
168
+ this.root.addEventListener('submit', e => {
169
+ e.preventDefault();
170
+ const f = e.target;
171
+ void this.run(f.dataset.do ?? '', f);
172
+ });
173
+ this.root.addEventListener('input', e => {
174
+ const t = e.target;
175
+ if (t.name)
176
+ this.values[t.name] = t.value;
177
+ });
178
+ }
179
+ /** Options for this element only, as one object. */
180
+ get config() {
181
+ return this.ownConfig;
182
+ }
183
+ set config(c) {
184
+ this.ownConfig = c;
185
+ this.update();
186
+ }
187
+ /** The auth client this element uses. Default: the one `configure` set, or `createAuthClient()`. */
188
+ get client() {
189
+ return this.ownClient ?? (sharedClient ??= createAuthClient());
190
+ }
191
+ set client(c) {
192
+ this.ownClient = c;
193
+ }
194
+ /** The options in force: defaults, then configure(), then `config`, then properties, then attributes. */
195
+ get options() {
196
+ const attrs = {};
197
+ for (const k of optionNames)
198
+ attrs[k] = fromAttr(k, this.getAttribute(attrName(k)));
199
+ return resolve(global, this.ownConfig, this._props, attrs);
200
+ }
201
+ connectedCallback() {
202
+ // A property set before the element was defined hides the accessor.
203
+ for (const k of optionNames) {
204
+ if (Object.prototype.hasOwnProperty.call(this, k)) {
205
+ const v = this[k];
206
+ delete this[k];
207
+ this[k] = v;
208
+ }
209
+ }
210
+ addFonts();
211
+ live.add(this);
212
+ if (this.followsSession && !this.offSession) {
213
+ this.offSession = this.client.onSessionChange(e => this.sessionChanged(e.type));
214
+ }
215
+ this.update();
216
+ // Load after the current task, so configure() in a module script
217
+ // sets the client first.
218
+ setTimeout(() => {
219
+ this.started = true;
220
+ if (this.isConnected && this.on(this.options))
221
+ void this.load();
222
+ });
223
+ }
224
+ disconnectedCallback() {
225
+ live.delete(this);
226
+ this.offSession?.();
227
+ this.offSession = undefined;
228
+ if (this.lost)
229
+ settlePrompt(this.client, this);
230
+ }
231
+ attributeChangedCallback(name, old, next) {
232
+ if (old === next || !this.isConnected)
233
+ return;
234
+ this.update();
235
+ if (this.started && this.constructor.attrs.includes(name) && this.on(this.options))
236
+ void this.load();
237
+ }
238
+ /** Whether the element shows at all under o; a section turned off hides it. */
239
+ on(_o) {
240
+ return true;
241
+ }
242
+ /** Loads again, for example after the client changes. It does nothing while signed out. */
243
+ reload() {
244
+ if (this.isConnected && !this.lost && this.on(this.options))
245
+ void this.load();
246
+ }
247
+ /**
248
+ * Follows the session. When it ends, by sign-out, expiry, or a
249
+ * revocation in any tab, the element forgets what it loaded at once and
250
+ * shows the signed-out state. It never fetches then: a fetch would get
251
+ * 401 and report the lost session again. It loads once more only after
252
+ * the next sign-in, which clears the flag.
253
+ */
254
+ sessionChanged(type) {
255
+ if (!this.followsSession || type === 'stepped-up')
256
+ return;
257
+ if (type === 'signed-in') {
258
+ // Someone signed in, perhaps another person: drop the earlier data
259
+ // and show the loading state before loading theirs.
260
+ this.gen++;
261
+ this.lost = false;
262
+ this.forget();
263
+ this.values = {};
264
+ this.error = '';
265
+ this.notice = '';
266
+ this.state = 'start';
267
+ this.update();
268
+ this.reload();
269
+ return;
270
+ }
271
+ if (type !== 'signed-out' && type !== 'session-lost')
272
+ return;
273
+ this.gen++;
274
+ if (this.lost)
275
+ return;
276
+ this.lost = true;
277
+ this.forget();
278
+ this.values = {};
279
+ this.error = '';
280
+ this.notice = '';
281
+ this.state = 'start';
282
+ this.update();
283
+ settlePrompt(this.client, this);
284
+ }
285
+ /** True while this element would show the signed-out prompt, if it owned it. */
286
+ wantsPrompt() {
287
+ return this.lost && this.isConnected && this.on(this.options);
288
+ }
289
+ /** True while the session that the element showed has ended. */
290
+ get signedOut() {
291
+ return this.lost;
292
+ }
293
+ /** The load generation now. A load reads it before it awaits, and passes it to `stale` after. */
294
+ get generation() {
295
+ return this.gen;
296
+ }
297
+ /** Whether a load that started at generation g must drop its result: the session changed since, or ended. */
298
+ stale(g) {
299
+ return g !== this.gen || this.lost;
300
+ }
301
+ /** Drops every piece of the person's data that the element loaded. */
302
+ forget() { }
303
+ /** The signed-out state: what ended, and a way to sign in. */
304
+ signedOutBody(o) {
305
+ return html `${this.heading(o, this.r('signedOut.headline'), this.t('signedOut.title'))}${this.signInActions(o)}`;
306
+ }
307
+ /**
308
+ * The ways to sign in from a signed-out state: a passkey, unless the
309
+ * app turned passkeys off, and a link to `sign-in-href` when it is set.
310
+ */
311
+ signInActions(o, fine) {
312
+ const href = sameOrigin(this.getAttribute('sign-in-href'));
313
+ const other = href ? withReturnTo(href, location.pathname + location.search) : '';
314
+ const pk = o.methods !== 'password';
315
+ const link = other ? html `<a class="${pk ? 'lnk' : 'btn fill'}" part="${pk ? 'link' : 'button button-primary'}" href="${other}"${pk ? '' : html ` data-autofocus`}>${this.t(pk ? 'signedOut.other' : 'signIn.submit')}</a>` : '';
316
+ const fallback = !pk && !other ? html `<p class="fine">${this.t('signedOut.reload')}</p>` : '';
317
+ return html `<div class="body">${fine ? html `<p class="fine">${fine}</p>` : ''}${fallback}
318
+ ${this.err()}
319
+ <div class="acts">${pk ? html `<button class="btn fill" type="button" part="button button-primary" data-do="session-sign-in" data-key="session-sign-in" data-autofocus>${this.t('signIn.passkey')}</button>` : ''}${link}</div></div>`;
320
+ }
321
+ /** The state before the first load: the element's title, and a quiet line that says it is loading. */
322
+ loadingBody(o, title) {
323
+ const failed = this.error !== '';
324
+ return html `${this.heading(o, html `${title}`, title)}<div class="body">${failed
325
+ ? html `${this.err()}<div class="acts"><button class="btn plain" type="button" part="button" data-do="retry" data-key="retry" data-autofocus>${this.t('tryAgain')}</button></div>`
326
+ : html `<p class="cap" role="status">${this.t('loading')}</p>`}</div>`;
327
+ }
328
+ /** Signs in again with a passkey from the signed-out state. */
329
+ async signInAgain() {
330
+ const g = this.gen;
331
+ const r = await this.client.enter();
332
+ if (r.outcome !== 'ok')
333
+ return this.failWith(r);
334
+ // The client announces the sign-in, which reloads the element once.
335
+ // Without that announcement, the generation is unchanged: do it here.
336
+ if (g === this.gen)
337
+ this.sessionChanged('signed-in');
338
+ }
339
+ /** Loads what the element shows. */
340
+ async load() { }
341
+ /** True for elements that turn into a page section when wide. */
342
+ wide = false;
343
+ /** True for elements that load the signed-in person's data again when the session changes, in any tab. */
344
+ followsSession = false;
345
+ offSession;
346
+ async run(name, from) {
347
+ if (this.busy)
348
+ return;
349
+ this.busy = true;
350
+ this.setAttribute('aria-busy', 'true');
351
+ try {
352
+ if (name === 'session-sign-in')
353
+ await this.signInAgain();
354
+ else if (name === 'retry') {
355
+ this.error = '';
356
+ this.update();
357
+ await this.load();
358
+ this.focusNext = true;
359
+ this.update();
360
+ }
361
+ else
362
+ await this.act(name, from);
363
+ }
364
+ finally {
365
+ this.busy = false;
366
+ this.removeAttribute('aria-busy');
367
+ }
368
+ }
369
+ /** Renders again with the options in force. */
370
+ update() {
371
+ if (!this.isConnected)
372
+ return;
373
+ const o = this.options;
374
+ for (const k of ['theme', 'density', 'radius', 'font', 'headline'])
375
+ this.setAttribute('data-' + k, o[k]);
376
+ const accent = o.accent === 'ink' ? '' : `--_accent:${o.accent};--_on-accent:${onAccent(o.accent)};`;
377
+ this.dyn.replaceSync(`:host{${accent}}`);
378
+ if (!this.on(o)) {
379
+ this.setAttribute('data-off', '');
380
+ this.view.replaceChildren();
381
+ return;
382
+ }
383
+ this.removeAttribute('data-off');
384
+ const key = this.root.activeElement?.dataset?.key;
385
+ // Only one element per client shows the signed-out prompt; the others collapse.
386
+ if (this.lost && promptOwner(this.client) !== this) {
387
+ this.setAttribute('data-off', '');
388
+ this.view.replaceChildren();
389
+ return;
390
+ }
391
+ this.view.className = this.wide ? 'wide' : '';
392
+ this.view.innerHTML = this.frame(o, this.lost ? this.signedOutBody(o) : this.body(o)).s;
393
+ this.rendered();
394
+ const again = key ? this.view.querySelector(`[data-key="${CSS.escape(key)}"]`) : null;
395
+ if (this.focusNext) {
396
+ this.focusNext = false;
397
+ const target = this.view.querySelector('[data-autofocus]') ?? this.view.querySelector('#h');
398
+ target?.focus();
399
+ }
400
+ else if (again && !again.hasAttribute('disabled')) {
401
+ again.focus();
402
+ }
403
+ }
404
+ /** Runs after each render, for measuring. */
405
+ rendered() { }
406
+ /** Moves to state s, clears the error, renders, and moves focus to the new content. */
407
+ go(s) {
408
+ this.state = s;
409
+ this.error = '';
410
+ this.notice = '';
411
+ this.focusNext = true;
412
+ this.update();
413
+ }
414
+ /** Shows an error, announced by its role="alert". */
415
+ fail(msg) {
416
+ this.error = msg;
417
+ this.notice = '';
418
+ this.update();
419
+ this.view.querySelector('[aria-invalid="true"]')?.focus();
420
+ }
421
+ /** Announces msg to screen readers without moving focus. */
422
+ announce(msg) {
423
+ this.liveRegion.textContent = '';
424
+ requestAnimationFrame(() => { this.liveRegion.textContent = msg; });
425
+ }
426
+ /**
427
+ * Dispatches a DOM event that bubbles out of the shadow root. It
428
+ * returns false when a listener called preventDefault on a cancelable
429
+ * event.
430
+ */
431
+ emit(name, detail = {}, cancelable = false) {
432
+ return this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true, cancelable }));
433
+ }
434
+ /** The template for key, from the `text` option or English. */
435
+ tpl(key) {
436
+ return this.options.text[key] ?? english[key] ?? key;
437
+ }
438
+ /** The plain text for key, with {appName} and vars filled. */
439
+ t(key, vars = {}) {
440
+ return plain(this.tpl(key), { appName: this.app(), ...vars });
441
+ }
442
+ /** The rendered text for key. */
443
+ r(key, vars = {}) {
444
+ return rich(this.tpl(key), { appName: this.app(), ...vars });
445
+ }
446
+ /** Renders a template that isn't a key, such as one chosen at run time. */
447
+ rt(template, vars = {}) {
448
+ return rich(template, { appName: this.app(), ...vars });
449
+ }
450
+ app() {
451
+ return this.options.appName.trim() || 'Acme';
452
+ }
453
+ /** What to show for an outcome that isn't ok. */
454
+ explain(r) {
455
+ switch (r.outcome) {
456
+ case 'problem': return [r.problem.title, r.problem.fix].filter(Boolean).join('. ').replace(/\.\./g, '.');
457
+ case 'throttled': return this.t('throttled', { seconds: r.retryAfter });
458
+ case 'unsupported': return this.t('passkey.unsupported');
459
+ case 'no_passkey_or_cancelled': return this.t('passkey.none');
460
+ case 'already_registered': return this.t('passkey.exists');
461
+ default: return this.t('failed');
462
+ }
463
+ }
464
+ /** Shows a failed outcome and dispatches `problem`. */
465
+ failWith(r) {
466
+ this.emit('problem', r);
467
+ this.fail(this.explain(r));
468
+ }
469
+ /** The frame: the app header, then the body. */
470
+ frame(o, inner) {
471
+ let mark = '';
472
+ if (o.logo === 'letter')
473
+ mark = html `<span class="lm" aria-hidden="true">${this.app()[0].toUpperCase()}</span>`;
474
+ if (o.logo === 'image' && o.logoSrc)
475
+ mark = html `<img class="li" src="${o.logoSrc}" alt="">`;
476
+ return html `<div class="scr" part="frame" role="group" aria-labelledby="h"><div class="app" part="header">${mark}<span>${this.app()}</span></div>${inner}</div>`;
477
+ }
478
+ /** The headline: the large sentence, or a quiet title with an optional lead. */
479
+ heading(o, sentence, title, lead) {
480
+ if (o.headline === 'title') {
481
+ return html `<div class="ttl"><h2 id="h" tabindex="-1" part="headline">${title}</h2>${lead ? html `<p class="lead">${lead}</p>` : ''}</div>`;
482
+ }
483
+ return html `<h2 id="h" class="say" tabindex="-1" part="headline">${sentence}</h2>`;
484
+ }
485
+ /** The error paragraph, or a notice that isn't an error, when there is one. */
486
+ err() {
487
+ if (this.error)
488
+ return html `<p class="err" id="err" role="alert" part="error">${this.error}</p>`;
489
+ return this.notice ? html `<p class="note" role="status">${this.notice}</p>` : '';
490
+ }
491
+ /** A finished state: a chip, a sentence, and an optional link. */
492
+ done(chip, tone, text, back) {
493
+ return html `<div class="done"><span class="chip ${tone}" part="chip">${chip}</span><p>${text}</p>${back ? html `<button class="lnk" type="button" part="link" data-do="${back.action}" data-autofocus>${back.label}</button>` : ''}</div>`;
494
+ }
495
+ /** A labelled input. */
496
+ field(name, label, attrs, opts = {}) {
497
+ const id = 'f-' + name;
498
+ const hint = opts.hint ? html `<p class="hint" id="${id}-hint">${opts.hint}</p>` : '';
499
+ const described = [opts.hint ? id + '-hint' : '', opts.invalid && this.error ? 'err' : ''].filter(Boolean).join(' ');
500
+ return html `<div class="f" part="field"><label for="${id}">${label}</label><div class="fi"><input id="${id}" name="${name}" part="input" value="${this.values[name] ?? ''}" ${attrs}${opts.invalid && this.error ? html ` aria-invalid="true"` : ''}${described ? html ` aria-describedby="${described}"` : ''}>${opts.after ?? ''}</div>${hint}</div>`;
501
+ }
502
+ }
503
+ // Each option is also a property: el.appName = 'Acme'.
504
+ for (const k of optionNames) {
505
+ Object.defineProperty(TensileElement.prototype, k, {
506
+ configurable: true,
507
+ get() {
508
+ return this.options[k];
509
+ },
510
+ set(v) {
511
+ this._props[k] = v;
512
+ this.update();
513
+ },
514
+ });
515
+ }
516
+ /** A same-origin URL to go to, or undefined for anything else. */
517
+ export function sameOrigin(url) {
518
+ if (!url)
519
+ return undefined;
520
+ try {
521
+ const u = new URL(url, location.href);
522
+ return u.origin === location.origin ? u.href : undefined;
523
+ }
524
+ catch {
525
+ return undefined;
526
+ }
527
+ }
528
+ /** Glyphs, drawn in currentColor. */
529
+ export const glyph = {
530
+ key: new Html('<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="8" cy="12" r="4" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 12h9M18 12v3M21 12v2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>'),
531
+ // An agent is a program that acts for the person: a prompt on a tile,
532
+ // in the same shape as the person's tile, in the agents' violet.
533
+ agent: new Html('<svg class="gl agent" viewBox="0 0 24 24" aria-hidden="true"><rect width="24" height="24" rx="7" fill="var(--violet-t)"/><path d="M7.5 9l3 3-3 3M12.5 15.5h4" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>'),
534
+ laptop: new Html('<svg class="gl" viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="5" width="16" height="11" rx="1.5" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M2 19h20" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>'),
535
+ phone: new Html('<svg class="gl" viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="2.5" width="10" height="19" rx="2.2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M11 18.5h2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>'),
536
+ token: new Html('<svg class="gl" viewBox="0 0 24 24" aria-hidden="true"><circle cx="8" cy="12" r="4" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M12 12h9M18 12v3" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>'),
537
+ app: new Html('<svg class="gl" viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="4" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M9 12h6M12 9v6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>'),
538
+ you: new Html('<svg class="gl" viewBox="0 0 24 24" aria-hidden="true"><rect width="24" height="24" rx="7" fill="var(--chip)"/><circle cx="12" cy="10" r="3.6" fill="var(--soft)"/><path d="M5.5 20.5c1.2-3.4 3.6-5 6.5-5s5.3 1.6 6.5 5" fill="var(--soft)"/></svg>'),
539
+ };
540
+ export { fill };
@@ -0,0 +1,70 @@
1
+ /** Every option of the elements. An empty config renders them as designed. */
2
+ export interface Options {
3
+ /** How people sign in, sign up, and confirm: `passkey`, `password`, or `both`. */
4
+ methods: 'passkey' | 'password' | 'both';
5
+ /** With `methods: "both"`, which method comes first and gets the filled button. */
6
+ first: 'passkey' | 'password';
7
+ /** Offers saved passkeys in the email field's autofill. */
8
+ autofill: boolean;
9
+ /** The app's name, in the header and the headlines. */
10
+ appName: string;
11
+ /** A mark before the app name: `none`, `letter`, or `image` (`logoSrc`). */
12
+ logo: 'none' | 'letter' | 'image';
13
+ /** The image for `logo: "image"`, 24 px high and up to 96 px wide. */
14
+ logoSrc: string;
15
+ /** `ink`, which follows the theme, or a hex colour such as `#7c4dff`. */
16
+ accent: string;
17
+ /** Corner radii: `sharp`, `soft`, or `round`. */
18
+ radius: 'sharp' | 'soft' | 'round';
19
+ /** The type pairing: `geist`, `tight`, `serif`, or `system`. */
20
+ font: 'geist' | 'tight' | 'serif' | 'system';
21
+ /** `light`, `dark`, or `auto`, which follows `prefers-color-scheme`. */
22
+ theme: 'light' | 'dark' | 'auto';
23
+ /** Spacing and control size: `comfortable` or `compact`. */
24
+ density: 'comfortable' | 'compact';
25
+ /** `sentence`, the large sentence, or `title`, a quiet 22 px title. */
26
+ headline: 'sentence' | 'title';
27
+ /** Shows the sessions element. */
28
+ sessions: boolean;
29
+ /** Shows connected agents and the approval elements. */
30
+ agents: boolean;
31
+ /** Shows the activity element. */
32
+ activity: boolean;
33
+ /** Shows the authenticator setup. */
34
+ twoStep: boolean;
35
+ /** Adds the recovery-code step to setup, and shows "That wasn't me" and the recovery codes element. */
36
+ recoveryCodes: boolean;
37
+ /** Replaces the sign-in headline. */
38
+ headlineText: string;
39
+ /** Replaces the passkey button label on the sign-in screen. */
40
+ passkeyLabel: string;
41
+ /** Replaces the email button label on the sign-in screen. */
42
+ passwordLabel: string;
43
+ /** Replaces the main sign-up button label. */
44
+ signUpLabel: string;
45
+ /** Replaces any text by its key, for example `{"signIn.or": "or else"}`. */
46
+ text: Record<string, string>;
47
+ }
48
+ export declare const defaults: Readonly<Options>;
49
+ /** The option names. */
50
+ export declare const optionNames: Array<keyof Options>;
51
+ /** `appName` → `app-name`. */
52
+ export declare const attrName: (k: string) => string;
53
+ /** `app-name` → `appName`. */
54
+ export declare const propName: (a: string) => string;
55
+ /**
56
+ * Reads one option from an attribute value. A boolean attribute is true
57
+ * when present, unless its value is `false`, `0`, or `off`. `text` takes
58
+ * JSON. A value that isn't one of the choices is ignored.
59
+ */
60
+ export declare function fromAttr(k: keyof Options, v: string | null): unknown;
61
+ /**
62
+ * Merges layers of options, lowest first, and checks each value: a value
63
+ * of the wrong type, an unknown choice, or an accent that isn't a hex
64
+ * colour falls back to the layer below. `text` merges key by key.
65
+ */
66
+ export declare function resolve(...layers: Array<Partial<Record<string, unknown>> | undefined>): Options;
67
+ /** Reports whether s is a hex colour of 3 or 6 digits. */
68
+ export declare const isHex: (s: string) => boolean;
69
+ /** The text colour on an accent: white or near-black, whichever has the better contrast. */
70
+ export declare function onAccent(hex: string): string;