@symbiotejs/symbiote 3.8.3 → 3.10.1

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 (137) hide show
  1. package/README.md +52 -2
  2. package/core/AppRouter.js +97 -58
  3. package/core/PubSub.js +42 -11
  4. package/core/Symbiote.js +90 -59
  5. package/core/itemizeProcessor-keyed.js +88 -188
  6. package/core/itemizeProcessor.js +1 -12
  7. package/core/itemizeSetup.js +26 -3
  8. package/core/ownElements.js +1 -4
  9. package/core/resolveTemplate.js +12 -0
  10. package/core/tpl-processors.js +3 -3
  11. package/docs/README.md +5 -4
  12. package/docs/html-app-vs-htmx.md +55 -0
  13. package/docs/lifecycle.md +2 -0
  14. package/docs/list-rendering.md +10 -2
  15. package/docs/properties.md +28 -1
  16. package/docs/pubsub.md +3 -0
  17. package/docs/routing.md +15 -4
  18. package/docs/security.md +41 -12
  19. package/docs/templates.md +29 -0
  20. package/html-app/BaseClass.js +203 -0
  21. package/html-app/README.md +369 -0
  22. package/html-app/action-data.js +168 -0
  23. package/html-app/actions.js +366 -0
  24. package/html-app/collection-actions.js +104 -0
  25. package/html-app/collection-data.js +234 -0
  26. package/html-app/collection-items.js +45 -0
  27. package/html-app/conditions.js +42 -0
  28. package/html-app/context-data.js +185 -0
  29. package/html-app/context-requests.js +374 -0
  30. package/html-app/context-storage.js +376 -0
  31. package/html-app/declarations.js +55 -0
  32. package/html-app/examples/assets/actions.html +56 -0
  33. package/html-app/examples/assets/collections.html +72 -0
  34. package/html-app/examples/assets/components.html +25 -0
  35. package/html-app/examples/assets/conditional.html +29 -0
  36. package/html-app/examples/assets/data.html +31 -0
  37. package/html-app/examples/assets/guide.html +4 -0
  38. package/html-app/examples/assets/imports.html +11 -0
  39. package/html-app/examples/assets/not-found.html +4 -0
  40. package/html-app/examples/assets/routes.json +58 -0
  41. package/html-app/examples/assets/routing.html +27 -0
  42. package/html-app/examples/assets/state.html +32 -0
  43. package/html-app/examples/assets/storage.html +28 -0
  44. package/html-app/examples/assets/tasks.json +25 -0
  45. package/html-app/examples/full-app.html +147 -0
  46. package/html-app/examples/todo-ref.html +37 -0
  47. package/html-app/fetch-source.js +147 -0
  48. package/html-app/fragment-content.js +29 -0
  49. package/html-app/fragment-source.js +169 -0
  50. package/html-app/index.js +34 -0
  51. package/html-app/initial-data.js +88 -0
  52. package/html-app/pub-map.js +93 -0
  53. package/html-app/router-data.js +50 -0
  54. package/html-app/router-navigation.js +70 -0
  55. package/html-app/storage-revisions.js +130 -0
  56. package/html-app/sym-collection.js +142 -0
  57. package/html-app/sym-component.js +20 -0
  58. package/html-app/sym-conditional.js +141 -0
  59. package/html-app/sym-context.js +176 -0
  60. package/html-app/sym-import.js +218 -0
  61. package/html-app/sym-router.js +107 -0
  62. package/package.json +18 -8
  63. package/scripts/check-html-app-package.js +117 -0
  64. package/scripts/check-html-app-size.js +91 -0
  65. package/scripts/update-exports.js +4 -0
  66. package/skills/symbiote/SKILL.md +197 -0
  67. package/skills/symbiote/agents/openai.yaml +3 -0
  68. package/types/core/AppRouter.d.ts +13 -4
  69. package/types/core/AppRouter.d.ts.map +1 -1
  70. package/types/core/PubSub.d.ts +1 -1
  71. package/types/core/PubSub.d.ts.map +1 -1
  72. package/types/core/Symbiote.d.ts +6 -2
  73. package/types/core/Symbiote.d.ts.map +1 -1
  74. package/types/core/itemizeProcessor-keyed.d.ts.map +1 -1
  75. package/types/core/itemizeProcessor.d.ts.map +1 -1
  76. package/types/core/itemizeSetup.d.ts +1 -0
  77. package/types/core/itemizeSetup.d.ts.map +1 -1
  78. package/types/core/ownElements.d.ts +1 -1
  79. package/types/core/ownElements.d.ts.map +1 -1
  80. package/types/core/resolveTemplate.d.ts +2 -0
  81. package/types/core/resolveTemplate.d.ts.map +1 -0
  82. package/types/html-app/BaseClass.d.ts +24 -0
  83. package/types/html-app/BaseClass.d.ts.map +1 -0
  84. package/types/html-app/action-data.d.ts +15 -0
  85. package/types/html-app/action-data.d.ts.map +1 -0
  86. package/types/html-app/actions.d.ts +104 -0
  87. package/types/html-app/actions.d.ts.map +1 -0
  88. package/types/html-app/collection-actions.d.ts +12 -0
  89. package/types/html-app/collection-actions.d.ts.map +1 -0
  90. package/types/html-app/collection-data.d.ts +13 -0
  91. package/types/html-app/collection-data.d.ts.map +1 -0
  92. package/types/html-app/collection-items.d.ts +7 -0
  93. package/types/html-app/collection-items.d.ts.map +1 -0
  94. package/types/html-app/conditions.d.ts +5 -0
  95. package/types/html-app/conditions.d.ts.map +1 -0
  96. package/types/html-app/context-data.d.ts +31 -0
  97. package/types/html-app/context-data.d.ts.map +1 -0
  98. package/types/html-app/context-requests.d.ts +97 -0
  99. package/types/html-app/context-requests.d.ts.map +1 -0
  100. package/types/html-app/context-storage.d.ts +102 -0
  101. package/types/html-app/context-storage.d.ts.map +1 -0
  102. package/types/html-app/declarations.d.ts +3 -0
  103. package/types/html-app/declarations.d.ts.map +1 -0
  104. package/types/html-app/fetch-source.d.ts +23 -0
  105. package/types/html-app/fetch-source.d.ts.map +1 -0
  106. package/types/html-app/fragment-content.d.ts +6 -0
  107. package/types/html-app/fragment-content.d.ts.map +1 -0
  108. package/types/html-app/fragment-source.d.ts +14 -0
  109. package/types/html-app/fragment-source.d.ts.map +1 -0
  110. package/types/html-app/index.d.ts +9 -0
  111. package/types/html-app/index.d.ts.map +1 -0
  112. package/types/html-app/initial-data.d.ts +8 -0
  113. package/types/html-app/initial-data.d.ts.map +1 -0
  114. package/types/html-app/pub-map.d.ts +19 -0
  115. package/types/html-app/pub-map.d.ts.map +1 -0
  116. package/types/html-app/router-data.d.ts +4 -0
  117. package/types/html-app/router-data.d.ts.map +1 -0
  118. package/types/html-app/router-navigation.d.ts +3 -0
  119. package/types/html-app/router-navigation.d.ts.map +1 -0
  120. package/types/html-app/storage-revisions.d.ts +11 -0
  121. package/types/html-app/storage-revisions.d.ts.map +1 -0
  122. package/types/html-app/sym-collection.d.ts +16 -0
  123. package/types/html-app/sym-collection.d.ts.map +1 -0
  124. package/types/html-app/sym-component.d.ts +5 -0
  125. package/types/html-app/sym-component.d.ts.map +1 -0
  126. package/types/html-app/sym-conditional.d.ts +10 -0
  127. package/types/html-app/sym-conditional.d.ts.map +1 -0
  128. package/types/html-app/sym-context.d.ts +16 -0
  129. package/types/html-app/sym-context.d.ts.map +1 -0
  130. package/types/html-app/sym-import.d.ts +19 -0
  131. package/types/html-app/sym-import.d.ts.map +1 -0
  132. package/types/html-app/sym-router.d.ts +12 -0
  133. package/types/html-app/sym-router.d.ts.map +1 -0
  134. package/docs/llms-index.md +0 -49
  135. package/llms-full.txt +0 -5432
  136. package/llms.txt +0 -49
  137. package/scripts/build-llms.js +0 -56
@@ -0,0 +1,169 @@
1
+ import { sourceURL, SourceError } from './fetch-source.js';
2
+ import { parseInitialData } from './initial-data.js';
3
+
4
+ /** @type {WeakMap<Node, { url: string, chain: string[] }>} */
5
+ export let fragmentSources = new WeakMap();
6
+
7
+ /** @param {Node} owner */
8
+ export function fragmentSource(owner) {
9
+ let node = owner;
10
+ while (node) {
11
+ let source = fragmentSources.get(node);
12
+ if (source) {
13
+ return source;
14
+ }
15
+ node = node.parentNode || (node instanceof ShadowRoot ? node.host : null);
16
+ }
17
+ return {
18
+ url: owner.baseURI,
19
+ chain: [],
20
+ };
21
+ }
22
+
23
+ let urlAttributes = new Set([
24
+ 'href',
25
+ 'xlink:href',
26
+ 'src',
27
+ 'action',
28
+ 'formaction',
29
+ 'poster',
30
+ 'cite',
31
+ 'background',
32
+ 'longdesc',
33
+ 'sync',
34
+ ]);
35
+ let blockedElements = new Set([
36
+ 'base',
37
+ 'iframe',
38
+ 'frame',
39
+ 'frameset',
40
+ 'object',
41
+ 'embed',
42
+ 'meta',
43
+ 'foreignobject',
44
+ 'animate',
45
+ 'animatemotion',
46
+ 'animatetransform',
47
+ 'set',
48
+ ]);
49
+
50
+ /**
51
+ * Resolve authored URL attributes without making executable schemes available.
52
+ * @param {string} value
53
+ * @param {string} base
54
+ * @param {string} name
55
+ */
56
+ function fragmentURL(value, base, name) {
57
+ let url = new URL(value, base);
58
+ let allowed = [
59
+ 'http:',
60
+ 'https:',
61
+ ];
62
+ if (name === 'href') {
63
+ allowed.push('mailto:', 'tel:');
64
+ }
65
+ if (!allowed.includes(url.protocol) || url.username || url.password) {
66
+ throw new SourceError('UNSAFE_TEMPLATE', 'Fragment URL attributes require non-executable URLs without credentials.');
67
+ }
68
+ // Fragment links, including SVG references, target the composed document.
69
+ return value.trim().startsWith('#') ? value : url.href;
70
+ }
71
+
72
+ /**
73
+ * Source sets use HTTP(S) candidates; descriptors are left to the browser.
74
+ * URL tokens may contain commas, which are separators only after descriptors
75
+ * or at the end of the URL token (the native source-set tokenization rule).
76
+ * @param {string} value
77
+ * @param {string} base
78
+ */
79
+ function sourceSet(value, base) {
80
+ let candidates = [];
81
+ let rest = value;
82
+ while (rest.trim()) {
83
+ rest = rest.replace(/^[\s,]+/, '');
84
+ let token = /^\S+/.exec(rest)?.[0];
85
+ if (!token) {
86
+ break;
87
+ }
88
+ rest = rest.slice(token.length);
89
+ let descriptor = '';
90
+ if (!token.endsWith(',')) {
91
+ let end = rest.indexOf(',');
92
+ descriptor = (end < 0 ? rest : rest.slice(0, end)).trim();
93
+ rest = end < 0 ? '' : rest.slice(end + 1);
94
+ }
95
+ candidates.push(fragmentURL(token.replace(/,+$/, ''), base, 'src') + (descriptor ? ' ' + descriptor : ''));
96
+ }
97
+ return candidates.join(', ');
98
+ }
99
+
100
+ /**
101
+ * Validate authored application templates, including otherwise inert templates.
102
+ * This rejects common executable markup; it is not an untrusted-HTML sanitizer.
103
+ * @param {DocumentFragment} root
104
+ * @param {string} base
105
+ */
106
+ function prepareElements(root, base) {
107
+ for (let element of root.querySelectorAll('*')) {
108
+ let name = element.localName.toLowerCase();
109
+ if (blockedElements.has(name)) {
110
+ throw new SourceError('UNSAFE_TEMPLATE', 'Fragments cannot embed browsing contexts, plugins or document metadata.');
111
+ }
112
+ if (name === 'script') {
113
+ if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml'
114
+ || element.getAttribute('type') !== 'application/json' || element.hasAttribute('src')) {
115
+ throw new SourceError('UNSAFE_TEMPLATE', 'Fragments accept inert JSON scripts only.');
116
+ }
117
+ parseInitialData(element.textContent || '');
118
+ }
119
+ for (let attribute of element.getAttributeNames()) {
120
+ let lower = attribute.toLowerCase();
121
+ if (lower.startsWith('on') || lower === 'srcdoc') {
122
+ throw new SourceError('UNSAFE_TEMPLATE', 'Use declarative bindings instead of executable HTML attributes.');
123
+ }
124
+ let value = element.getAttribute(attribute);
125
+ if (urlAttributes.has(lower) && value.trim()) {
126
+ element.setAttribute(attribute, fragmentURL(value, base, lower));
127
+ } else if (lower === 'srcset' || lower === 'imagesrcset') {
128
+ element.setAttribute(attribute, sourceSet(value, base));
129
+ } else if (lower === 'ping' && value.trim()) {
130
+ element.setAttribute(attribute, value.trim().split(/\s+/).map((url) => fragmentURL(url, base, lower)).join(' '));
131
+ }
132
+ }
133
+ if (element instanceof HTMLTemplateElement) {
134
+ prepareElements(element.content, base);
135
+ }
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Parse inertly before constructing custom elements in the destination registry.
141
+ * @param {Document} document
142
+ * @param {string} text
143
+ * @param {string} base
144
+ */
145
+ export function fragmentTemplate(document, text, base) {
146
+ let template = document.createElement('template');
147
+ template.innerHTML = text;
148
+ prepareElements(template.content, base);
149
+ return template.content;
150
+ }
151
+
152
+ /**
153
+ * @param {Element} owner
154
+ * @param {string} source
155
+ */
156
+ export function importSource(owner, source) {
157
+ let parent = fragmentSource(owner);
158
+ let url = sourceURL(source, parent.url);
159
+ if (parent.chain.includes(url) || parent.chain.length >= 16) {
160
+ throw new SourceError('IMPORT_CYCLE', 'HTML imports cannot cycle or exceed 16 nested fragments.');
161
+ }
162
+ return {
163
+ url,
164
+ chain: [
165
+ ...parent.chain,
166
+ url,
167
+ ],
168
+ };
169
+ }
@@ -0,0 +1,34 @@
1
+ import { BaseClass } from './BaseClass.js';
2
+ import { SymComponent } from './sym-component.js';
3
+ import { SymContext } from './sym-context.js';
4
+ import { SymCollection } from './sym-collection.js';
5
+ import { SymConditional } from './sym-conditional.js';
6
+ import { SymImport } from './sym-import.js';
7
+ import { SymRouter } from './sym-router.js';
8
+
9
+ if (typeof document !== 'undefined' && !globalThis.__SYMBIOTE_SSR) {
10
+ // Capture the loader before awaiting; module/CDN wrappers use the marked script.
11
+ let script = document.currentScript ??
12
+ document.querySelector('script[type="module"][src][webmcp-mode="true"]');
13
+ if (script?.getAttribute('webmcp-mode') === 'true') {
14
+ await import('../core/webmcp.js');
15
+ BaseClass.mcpToolMode = true;
16
+ }
17
+ }
18
+
19
+ SymComponent.reg('sym-component');
20
+ SymContext.reg('sym-context');
21
+ SymCollection.reg('sym-collection');
22
+ SymConditional.reg('sym-conditional');
23
+ SymImport.reg('sym-import');
24
+ SymRouter.reg('sym-router');
25
+
26
+ export {
27
+ BaseClass,
28
+ SymComponent,
29
+ SymContext,
30
+ SymCollection,
31
+ SymConditional,
32
+ SymImport,
33
+ SymRouter,
34
+ };
@@ -0,0 +1,88 @@
1
+ import { DICT } from '../core/dictionary.js';
2
+ import { resolveTemplate } from '../core/resolveTemplate.js';
3
+
4
+ /** @type {WeakMap<import('../core/PubSub.js').PubSub, Record<string, unknown>>} */
5
+ export let initialDefaults = new WeakMap();
6
+
7
+ /**
8
+ * Remember authored defaults separately from mutable application state.
9
+ * @param {import('../core/PubSub.js').PubSub} context
10
+ * @param {Record<string, unknown>} data
11
+ */
12
+ export function rememberDefaults(context, data) {
13
+ let defaults = initialDefaults.get(context) || {};
14
+ for (let key of Object.keys(data)) {
15
+ if (!Object.hasOwn(defaults, key)) {
16
+ defaults[key] = structuredClone(data[key]);
17
+ }
18
+ }
19
+ initialDefaults.set(context, defaults);
20
+ }
21
+
22
+ /** @param {string} key */
23
+ export function isDataKey(key) {
24
+ return !!key && !key.startsWith('__htmlApp') && key !== 'prototype' && !Object.hasOwn(Object.prototype, key) && !/^[@*^+]/.test(key) && !key.startsWith('--') && !key.includes('/');
25
+ }
26
+
27
+ /** @param {string} text */
28
+ export function parseInitialData(text) {
29
+ let data = JSON.parse(text, (key, value) => {
30
+ if (key === 'prototype' || Object.hasOwn(Object.prototype, key)) {
31
+ throw new TypeError('HTML-app data contains an unsafe key.');
32
+ }
33
+ return value;
34
+ });
35
+ if (!data || typeof data !== 'object' || Array.isArray(data)
36
+ || Object.keys(data).some((key) => !isDataKey(key))) {
37
+ throw new TypeError('HTML-app data must be an object with local data keys.');
38
+ }
39
+ return data;
40
+ }
41
+
42
+ /** @param {Element | DocumentFragment} root */
43
+ export function readInitialData(root) {
44
+ let scripts = [...root.children].filter((element) => element.matches('script[type="application/json"]'));
45
+ if (scripts.length > 1) {
46
+ throw new TypeError('HTML-app accepts one direct JSON data script per component.');
47
+ }
48
+ let script = scripts[0];
49
+ if (!script) { return {}; }
50
+ let data = parseInitialData(script.textContent || '');
51
+ script.setAttribute(DICT.TEXT_NODE_SKIP_ATTR, '');
52
+ return data;
53
+ }
54
+
55
+ /**
56
+ * Read the selected native template before incoming object bindings initialize.
57
+ * @param {import('./BaseClass.js').BaseClass} owner
58
+ */
59
+ export function readTemplateData(owner) {
60
+ let selector = owner.allowCustomTemplate && owner.getAttribute('use-template');
61
+ let source = selector ? resolveTemplate(owner, selector) : null;
62
+ if (source) {
63
+ return readInitialData(/** @type {DocumentFragment} */ (source.content.cloneNode(true)));
64
+ }
65
+ let markup = Reflect.get(owner.constructor, 'template');
66
+ if (!markup) {
67
+ return {};
68
+ }
69
+ let template = owner.ownerDocument.createElement('template');
70
+ template.innerHTML = markup;
71
+ return readInitialData(template.content);
72
+ }
73
+
74
+ /**
75
+ * Initialize template-owned defaults before native binding and Itemize processors.
76
+ * @param {Element | DocumentFragment} root
77
+ * @param {import('./BaseClass.js').BaseClass} owner
78
+ */
79
+ export function initialDataProcessor(root, owner) {
80
+ let data = readInitialData(root);
81
+ rememberDefaults(owner.localCtx, data);
82
+ for (let [
83
+ key,
84
+ value,
85
+ ] of Object.entries(data)) {
86
+ owner.localCtx.add(key, value);
87
+ }
88
+ }
@@ -0,0 +1,93 @@
1
+ import { isDataKey } from './initial-data.js';
2
+ import { resolveData } from './action-data.js';
3
+ export class PubMap {
4
+ connected = false;
5
+ queued = false;
6
+ version = 0;
7
+ /** @type {{ target: string, source: string }[]} */
8
+ bindings = [];
9
+ /** @type {{ remove(): void }[]} */
10
+ subscriptions = [];
11
+ /** @param {import('./BaseClass.js').BaseClass} owner */
12
+ constructor(owner) {
13
+ this.owner = owner;
14
+ }
15
+ connect() {
16
+ if (this.connected || !this.owner.isConnected) {
17
+ return;
18
+ }
19
+ this.connected = true;
20
+ this.refresh();
21
+ }
22
+ disconnect() {
23
+ this.connected = false;
24
+ this.version += 1;
25
+ this.queued = false;
26
+ for (let subscription of this.subscriptions) {
27
+ subscription.remove();
28
+ }
29
+ this.subscriptions = [];
30
+ this.bindings = [];
31
+ }
32
+ refresh() {
33
+ if (!this.connected) {
34
+ return;
35
+ }
36
+ this.disconnect();
37
+ this.connected = true;
38
+ let targets = new Set();
39
+ this.bindings = (this.owner.getAttribute('pub-map') || '').split(';').filter((part) => part.trim()).map((part) => {
40
+ let pieces = part.split(':').map((value) => value.trim());
41
+ let [
42
+ target,
43
+ source,
44
+ ] = pieces;
45
+ if (pieces.length !== 2 || !target || !source || targets.has(target)
46
+ || !isDataKey(source.startsWith('+') ? source.slice(1) : source)
47
+ || !this.owner.localCtx.has(source)) {
48
+ throw new TypeError('pub-map requires unique target: localProperty pairs.');
49
+ }
50
+ resolveData(this.owner, target);
51
+ targets.add(target);
52
+ return {
53
+ target,
54
+ source,
55
+ };
56
+ });
57
+ for (let source of new Set(this.bindings.map((binding) => binding.source))) {
58
+ let subscription = this.owner.localCtx.sub(source, () => this.schedule(), false);
59
+ if (subscription) {
60
+ this.subscriptions.push(subscription);
61
+ }
62
+ }
63
+ this.schedule();
64
+ }
65
+ schedule() {
66
+ if (this.queued || !this.connected || !this.bindings.length) {
67
+ return;
68
+ }
69
+ this.queued = true;
70
+ let version = this.version;
71
+ queueMicrotask(() => {
72
+ if (version !== this.version) {
73
+ return;
74
+ }
75
+ this.queued = false;
76
+ if (!this.connected || !this.owner.isConnected) {
77
+ return;
78
+ }
79
+ let values = Object.create(null);
80
+ for (let {
81
+ target,
82
+ source,
83
+ } of this.bindings) {
84
+ let destination = resolveData(this.owner, target);
85
+ let value = this.owner.$[source];
86
+ if (value !== undefined && !Object.is(destination.ctx.read(destination.name), value)) {
87
+ values[target] = value;
88
+ }
89
+ }
90
+ this.owner.$ = values;
91
+ });
92
+ }
93
+ }
@@ -0,0 +1,50 @@
1
+ import { cloneData, recordData } from './collection-data.js';
2
+
3
+ /**
4
+ * JSON configuration uses native descriptors, without executable loaders.
5
+ * @param {unknown} value
6
+ * @returns {typeof import('../core/AppRouter.js').AppRouter.appMap & Record<string, { src?: string }>}
7
+ */
8
+ export function routingMap(value) {
9
+ let routes = cloneData(recordData(value));
10
+ let entries = Object.values(routes);
11
+ if (!entries.length) {
12
+ throw new TypeError('sym-router requires a nonempty routes object.');
13
+ }
14
+ let patterns = 0;
15
+ for (let value of entries) {
16
+ let route = recordData(value);
17
+ if (Object.hasOwn(route, 'load') || Object.hasOwn(route, '__loaded')) {
18
+ throw new TypeError('HTML routes cannot define executable loaders. Use sym-import for fragments.');
19
+ }
20
+ if (Object.hasOwn(route, 'title') && typeof route.title !== 'string') {
21
+ throw new TypeError('HTML route titles must be strings.');
22
+ }
23
+ if (Object.hasOwn(route, 'src') && typeof route.src !== 'string') {
24
+ throw new TypeError('HTML route sources must be strings.');
25
+ }
26
+ for (let flag of [
27
+ 'default',
28
+ 'error',
29
+ ]) {
30
+ if (Object.hasOwn(route, flag) && typeof route[flag] !== 'boolean') {
31
+ throw new TypeError('Route default and error flags must be booleans.');
32
+ }
33
+ }
34
+ if (route.default && route.error) {
35
+ throw new TypeError('The default and error routes must be distinct.');
36
+ }
37
+ if (Object.hasOwn(route, 'pattern')) {
38
+ if (typeof route.pattern !== 'string' || !route.pattern.startsWith('/')) {
39
+ throw new TypeError('Route patterns must be absolute URL paths.');
40
+ }
41
+ patterns++;
42
+ }
43
+ }
44
+ if ((patterns && patterns !== entries.length)
45
+ || entries.filter((route) => route.default).length > 1
46
+ || entries.filter((route) => route.error).length > 1) {
47
+ throw new TypeError('Use one route mode, at most one default and at most one error route.');
48
+ }
49
+ return routes;
50
+ }
@@ -0,0 +1,70 @@
1
+ import { AppRouter } from '../core/AppRouter.js';
2
+ import { PubSub } from '../core/PubSub.js';
3
+ import { controlValue, resolveData } from './action-data.js';
4
+ import { cloneData, recordData } from './collection-data.js';
5
+
6
+ /**
7
+ * The fixed framework handler delegates to the connected router owner.
8
+ * @param {import('./BaseClass.js').BaseClass} owner
9
+ * @param {string} reference
10
+ * @param {Element} element
11
+ * @param {Element} operand
12
+ * @param {import('./actions.js').ActionEvent} event
13
+ * @returns {ReturnType<typeof AppRouter.navigate> | undefined}
14
+ */
15
+ export function navigateAction(owner, reference, element, operand, event) {
16
+ let anchor = element instanceof HTMLAnchorElement ? element : null;
17
+ if (anchor && (event.button && event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey
18
+ || anchor.hasAttribute('download') || anchor.target && anchor.target !== '_self'
19
+ || anchor.getAttribute('href')?.trim().startsWith('#'))) {
20
+ return;
21
+ }
22
+ let route;
23
+ let options = {};
24
+ if (anchor) {
25
+ if (!anchor.hasAttribute('href')) {
26
+ return;
27
+ }
28
+ let url = new URL(anchor.href);
29
+ if (url.hash || url.origin !== owner.ownerDocument.defaultView.location.origin) {
30
+ return;
31
+ }
32
+ let match = AppRouter.readAddressBar(url);
33
+ if (!match.route || !Object.hasOwn(AppRouter.appMap, match.route)) {
34
+ return;
35
+ }
36
+ if (!AppRouter.appMap[match.route].pattern && url.pathname !== owner.ownerDocument.defaultView.location.pathname) {
37
+ return;
38
+ }
39
+ route = match.route;
40
+ options = match.options;
41
+ } else {
42
+ let value = controlValue(operand, '');
43
+ if (value.skip) {
44
+ return;
45
+ }
46
+ route = value.value;
47
+ }
48
+ let data = operand.getAttribute('action-data') ?? element.getAttribute('action-data');
49
+ if (data !== null) {
50
+ let source = resolveData(owner, data, true);
51
+ options = {
52
+ ...options,
53
+ ...recordData(source.ctx.read(source.name)),
54
+ };
55
+ }
56
+ options = cloneData(recordData(options));
57
+ if (Object.values(options).some((value) => value !== null && typeof value === 'object')) {
58
+ throw new TypeError('Route URL options must be JSON scalar values.');
59
+ }
60
+ let context = PubSub.getCtx(reference, false);
61
+ let navigate = context?.read('__htmlAppNavigate');
62
+ if (typeof navigate !== 'function') {
63
+ throw new TypeError('navigate requires a connected sym-router: ' + reference);
64
+ }
65
+ if (typeof route !== 'string' || !Object.hasOwn(AppRouter.appMap, route)) {
66
+ throw new TypeError('navigate requires a configured route name.');
67
+ }
68
+ anchor && event.preventDefault?.();
69
+ return navigate(route, options);
70
+ }
@@ -0,0 +1,130 @@
1
+ import { SourceError } from './fetch-source.js';
2
+
3
+ const databaseName = 'symbiote:html-app:storage';
4
+ const storeName = 'revisions';
5
+
6
+ /**
7
+ * @param {Window} win
8
+ * @param {AbortSignal} signal
9
+ * @returns {Promise<IDBDatabase>}
10
+ */
11
+ function openRevisions(win, signal) {
12
+ signal.throwIfAborted();
13
+ if (!win.indexedDB) {
14
+ throw new SourceError('STORAGE_UNAVAILABLE', 'Browser persistence requires IndexedDB for revision coordination.');
15
+ }
16
+ return new Promise((resolve, reject) => {
17
+ let request = win.indexedDB.open(databaseName, 1);
18
+ let blocked = false;
19
+ request.onupgradeneeded = () => request.result.createObjectStore(storeName);
20
+ request.onblocked = () => {
21
+ blocked = true;
22
+ reject(new SourceError('STORAGE_UNAVAILABLE', 'Browser storage revision coordination is blocked.'));
23
+ };
24
+ request.onerror = () => reject(request.error);
25
+ request.onsuccess = () => {
26
+ let db = request.result;
27
+ db.onversionchange = () => db.close();
28
+ if (blocked || signal.aborted) {
29
+ db.close();
30
+ reject(signal.reason);
31
+ } else {
32
+ resolve(db);
33
+ }
34
+ };
35
+ });
36
+ }
37
+
38
+ /**
39
+ * @typedef {Object} RevisionChange
40
+ * @property {string} key
41
+ * @property {string | null | undefined} expected
42
+ * @property {string | undefined} next
43
+ * @property {boolean} overwrite
44
+ * @property {AbortSignal} [signal]
45
+ */
46
+
47
+ /**
48
+ * Atomically reserve a revision, independently of per-document localStorage caches.
49
+ * @param {IDBDatabase} db
50
+ * @param {RevisionChange} change
51
+ * @returns {Promise<string | undefined>}
52
+ */
53
+ function exchangeRevision(db, change) {
54
+ change.signal?.throwIfAborted();
55
+ return new Promise((resolve, reject) => {
56
+ let transaction = db.transaction(storeName, 'readwrite');
57
+ let store = transaction.objectStore(storeName);
58
+ let request = store.get(change.key);
59
+ /** @type {string | undefined} */
60
+ let previous;
61
+ /** @type {unknown} */
62
+ let failure;
63
+ let abort = () => {
64
+ failure = change.signal.reason;
65
+ // A committing transaction cannot abort; the caller also checks before writing.
66
+ try { transaction.abort(); } catch {}
67
+ };
68
+ let cleanup = () => change.signal?.removeEventListener('abort', abort);
69
+ change.signal?.addEventListener('abort', abort, {
70
+ once: true,
71
+ });
72
+ request.onsuccess = () => {
73
+ try {
74
+ previous = request.result;
75
+ if (previous !== undefined && typeof previous !== 'string') {
76
+ throw new SourceError('STORAGE_UNAVAILABLE', 'Browser storage revision metadata is invalid.');
77
+ }
78
+ if (!change.overwrite && previous !== undefined && previous !== change.expected) {
79
+ throw new SourceError('STORAGE_CONFLICT', 'Stored data changed; restore it or explicitly overwrite it with this draft.');
80
+ }
81
+ if (change.next === undefined) {
82
+ store.delete(change.key);
83
+ } else {
84
+ store.put(change.next, change.key);
85
+ }
86
+ } catch (error) {
87
+ failure = error;
88
+ transaction.abort();
89
+ }
90
+ };
91
+ transaction.onabort = () => {
92
+ cleanup();
93
+ reject(failure ?? transaction.error);
94
+ };
95
+ transaction.oncomplete = () => {
96
+ cleanup();
97
+ resolve(previous);
98
+ };
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Keep the enclosing Web Lock held through reservation, the write, and rollback.
104
+ * A failed/interrupted reservation never acknowledges a browser save.
105
+ * @template T
106
+ * @param {Window} win
107
+ * @param {RevisionChange & { signal: AbortSignal }} change
108
+ * @param {() => T} commit
109
+ * @returns {Promise<T>}
110
+ */
111
+ export async function commitStorageRevision(win, change, commit) {
112
+ let db = await openRevisions(win, change.signal);
113
+ try {
114
+ let previous = await exchangeRevision(db, change);
115
+ try {
116
+ change.signal.throwIfAborted();
117
+ return commit();
118
+ } catch (failure) {
119
+ await exchangeRevision(db, {
120
+ key: change.key,
121
+ expected: change.next,
122
+ next: previous,
123
+ overwrite: false,
124
+ });
125
+ throw failure;
126
+ }
127
+ } finally {
128
+ db.close();
129
+ }
130
+ }