@christianirack/brainllm-runtime 0.3.1 → 0.4.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.
@@ -0,0 +1,211 @@
1
+ web-features 3.44.0
2
+ Source: https://github.com/web-platform-dx/web-features
3
+ Official npm archive: https://registry.npmjs.org/web-features/-/web-features-3.44.0.tgz
4
+ Published: 2026-10-22T16:30:26.001Z
5
+ Data SHA-256: 72577e8df9c8abe8a8af86a03bc161ac06be21488d76857f157c7f83f017f706
6
+ The license below is reproduced from package/LICENSE.txt in the integrity-verified official npm archive.
7
+ Only the trailing blank line is omitted.
8
+
9
+ Apache License
10
+ Version 2.0, January 2004
11
+ http://www.apache.org/licenses/
12
+
13
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
14
+
15
+ 1. Definitions.
16
+
17
+ "License" shall mean the terms and conditions for use, reproduction,
18
+ and distribution as defined by Sections 1 through 9 of this document.
19
+
20
+ "Licensor" shall mean the copyright owner or entity authorized by
21
+ the copyright owner that is granting the License.
22
+
23
+ "Legal Entity" shall mean the union of the acting entity and all
24
+ other entities that control, are controlled by, or are under common
25
+ control with that entity. For the purposes of this definition,
26
+ "control" means (i) the power, direct or indirect, to cause the
27
+ direction or management of such entity, whether by contract or
28
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
29
+ outstanding shares, or (iii) beneficial ownership of such entity.
30
+
31
+ "You" (or "Your") shall mean an individual or Legal Entity
32
+ exercising permissions granted by this License.
33
+
34
+ "Source" form shall mean the preferred form for making modifications,
35
+ including but not limited to software source code, documentation
36
+ source, and configuration files.
37
+
38
+ "Object" form shall mean any form resulting from mechanical
39
+ transformation or translation of a Source form, including but
40
+ not limited to compiled object code, generated documentation,
41
+ and conversions to other media types.
42
+
43
+ "Work" shall mean the work of authorship, whether in Source or
44
+ Object form, made available under the License, as indicated by a
45
+ copyright notice that is included in or attached to the work
46
+ (an example is provided in the Appendix below).
47
+
48
+ "Derivative Works" shall mean any work, whether in Source or Object
49
+ form, that is based on (or derived from) the Work and for which the
50
+ editorial revisions, annotations, elaborations, or other modifications
51
+ represent, as a whole, an original work of authorship. For the purposes
52
+ of this License, Derivative Works shall not include works that remain
53
+ separable from, or merely link (or bind by name) to the interfaces of,
54
+ the Work and Derivative Works thereof.
55
+
56
+ "Contribution" shall mean any work of authorship, including
57
+ the original version of the Work and any modifications or additions
58
+ to that Work or Derivative Works thereof, that is intentionally
59
+ submitted to Licensor for inclusion in the Work by the copyright owner
60
+ or by an individual or Legal Entity authorized to submit on behalf of
61
+ the copyright owner. For the purposes of this definition, "submitted"
62
+ means any form of electronic, verbal, or written communication sent
63
+ to the Licensor or its representatives, including but not limited to
64
+ communication on electronic mailing lists, source code control systems,
65
+ and issue tracking systems that are managed by, or on behalf of, the
66
+ Licensor for the purpose of discussing and improving the Work, but
67
+ excluding communication that is conspicuously marked or otherwise
68
+ designated in writing by the copyright owner as "Not a Contribution."
69
+
70
+ "Contributor" shall mean Licensor and any individual or Legal Entity
71
+ on behalf of whom a Contribution has been received by Licensor and
72
+ subsequently incorporated within the Work.
73
+
74
+ 2. Grant of Copyright License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ copyright license to reproduce, prepare Derivative Works of,
78
+ publicly display, publicly perform, sublicense, and distribute the
79
+ Work and such Derivative Works in Source or Object form.
80
+
81
+ 3. Grant of Patent License. Subject to the terms and conditions of
82
+ this License, each Contributor hereby grants to You a perpetual,
83
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
84
+ (except as stated in this section) patent license to make, have made,
85
+ use, offer to sell, sell, import, and otherwise transfer the Work,
86
+ where such license applies only to those patent claims licensable
87
+ by such Contributor that are necessarily infringed by their
88
+ Contribution(s) alone or by combination of their Contribution(s)
89
+ with the Work to which such Contribution(s) was submitted. If You
90
+ institute patent litigation against any entity (including a
91
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
92
+ or a Contribution incorporated within the Work constitutes direct
93
+ or contributory patent infringement, then any patent licenses
94
+ granted to You under this License for that Work shall terminate
95
+ as of the date such litigation is filed.
96
+
97
+ 4. Redistribution. You may reproduce and distribute copies of the
98
+ Work or Derivative Works thereof in any medium, with or without
99
+ modifications, and in Source or Object form, provided that You
100
+ meet the following conditions:
101
+
102
+ (a) You must give any other recipients of the Work or
103
+ Derivative Works a copy of this License; and
104
+
105
+ (b) You must cause any modified files to carry prominent notices
106
+ stating that You changed the files; and
107
+
108
+ (c) You must retain, in the Source form of any Derivative Works
109
+ that You distribute, all copyright, patent, trademark, and
110
+ attribution notices from the Source form of the Work,
111
+ excluding those notices that do not pertain to any part of
112
+ the Derivative Works; and
113
+
114
+ (d) If the Work includes a "NOTICE" text file as part of its
115
+ distribution, then any Derivative Works that You distribute must
116
+ include a readable copy of the attribution notices contained
117
+ within such NOTICE file, excluding those notices that do not
118
+ pertain to any part of the Derivative Works, in at least one
119
+ of the following places: within a NOTICE text file distributed
120
+ as part of the Derivative Works; within the Source form or
121
+ documentation, if provided along with the Derivative Works; or,
122
+ within a display generated by the Derivative Works, if and
123
+ wherever such third-party notices normally appear. The contents
124
+ of the NOTICE file are for informational purposes only and
125
+ do not modify the License. You may add Your own attribution
126
+ notices within Derivative Works that You distribute, alongside
127
+ or as an addendum to the NOTICE text from the Work, provided
128
+ that such additional attribution notices cannot be construed
129
+ as modifying the License.
130
+
131
+ You may add Your own copyright statement to Your modifications and
132
+ may provide additional or different license terms and conditions
133
+ for use, reproduction, or distribution of Your modifications, or
134
+ for any such Derivative Works as a whole, provided Your use,
135
+ reproduction, and distribution of the Work otherwise complies with
136
+ the conditions stated in this License.
137
+
138
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
139
+ any Contribution intentionally submitted for inclusion in the Work
140
+ by You to the Licensor shall be under the terms and conditions of
141
+ this License, without any additional terms or conditions.
142
+ Notwithstanding the above, nothing herein shall supersede or modify
143
+ the terms of any separate license agreement you may have executed
144
+ with Licensor regarding such Contributions.
145
+
146
+ 6. Trademarks. This License does not grant permission to use the trade
147
+ names, trademarks, service marks, or product names of the Licensor,
148
+ except as required for reasonable and customary use in describing the
149
+ origin of the Work and reproducing the content of the NOTICE file.
150
+
151
+ 7. Disclaimer of Warranty. Unless required by applicable law or
152
+ agreed to in writing, Licensor provides the Work (and each
153
+ Contributor provides its Contributions) on an "AS IS" BASIS,
154
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
155
+ implied, including, without limitation, any warranties or conditions
156
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
157
+ PARTICULAR PURPOSE. You are solely responsible for determining the
158
+ appropriateness of using or redistributing the Work and assume any
159
+ risks associated with Your exercise of permissions under this License.
160
+
161
+ 8. Limitation of Liability. In no event and under no legal theory,
162
+ whether in tort (including negligence), contract, or otherwise,
163
+ unless required by applicable law (such as deliberate and grossly
164
+ negligent acts) or agreed to in writing, shall any Contributor be
165
+ liable to You for damages, including any direct, indirect, special,
166
+ incidental, or consequential damages of any character arising as a
167
+ result of this License or out of the use or inability to use the
168
+ Work (including but not limited to damages for loss of goodwill,
169
+ work stoppage, computer failure or malfunction, or any and all
170
+ other commercial damages or losses), even if such Contributor
171
+ has been advised of the possibility of such damages.
172
+
173
+ 9. Accepting Warranty or Additional Liability. While redistributing
174
+ the Work or Derivative Works thereof, You may choose to offer,
175
+ and charge a fee for, acceptance of support, warranty, indemnity,
176
+ or other liability obligations and/or rights consistent with this
177
+ License. However, in accepting such obligations, You may act only
178
+ on Your own behalf and on Your sole responsibility, not on behalf
179
+ of any other Contributor, and only if You agree to indemnify,
180
+ defend, and hold each Contributor harmless for any liability
181
+ incurred by, or claims asserted against, such Contributor by reason
182
+ of your accepting any such warranty or additional liability.
183
+
184
+ END OF TERMS AND CONDITIONS
185
+
186
+ APPENDIX: How to apply the Apache License to your work.
187
+
188
+ To apply the Apache License to your work, attach the following
189
+ boilerplate notice, with the fields enclosed by brackets "[]"
190
+ replaced with your own identifying information. (Don't include
191
+ the brackets!) The text should be enclosed in the appropriate
192
+ comment syntax for the file format. We also recommend that a
193
+ file or class name and description of purpose be included on the
194
+ same "printed page" as the copyright notice for easier
195
+ identification within third-party archives.
196
+
197
+ Copyright [yyyy] [name of copyright owner]
198
+
199
+ Licensed under the Apache License, Version 2.0 (the "License");
200
+ you may not use this file except in compliance with the License.
201
+ You may obtain a copy of the License at
202
+
203
+ http://www.apache.org/licenses/LICENSE-2.0
204
+
205
+ Unless required by applicable law or agreed to in writing, software
206
+ distributed under the License is distributed on an "AS IS" BASIS,
207
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
208
+ See the License for the specific language governing permissions and
209
+ limitations under the License.
210
+
211
+ Native compiler dependency licenses accompany each platform package in THIRD_PARTY_NOTICES.txt, CARGO_NOTICES.txt, CARGO_DEPENDENCIES.json RUST_STD_COPYRIGHT.html and RUST_TOOLCHAIN_COPYRIGHT.html. Launcher/initializer/runtime-only packages do not embed a Rust compiler binary.
@@ -0,0 +1,142 @@
1
+ // Preventive checkpoints for compiler-owned code. Native/foreign calls cannot be preempted here.
2
+ import { _rt, fx } from './brain.js'
3
+ const I = _rt(), owners = new WeakMap(), active = []
4
+ const LIMITS = Object.freeze({ steps: 1000000, depth: 128, ms: 200, rows: 100000, signals: 100000, resources: 1024, pending: 32, workerMs: 30000 })
5
+ const now = () => globalThis.performance ? performance.now() : Date.now()
6
+ const metaOf = m => ({ file: typeof m?.file === 'string' ? m.file.slice(0, 256) : null, component: typeof m?.component === 'string' ? m.component.slice(0, 80) : null, line: Number.isSafeInteger(m?.line) && m.line > 0 ? m.line : null, column: Number.isSafeInteger(m?.column) && m.column > 0 ? m.column : null })
7
+ const limitsOf = options => Object.fromEntries(Object.entries(LIMITS).map(([k, max]) => [k, Number.isFinite(options?.[k]) && options[k] >= 1 ? Math.min(max, options[k]) : max]))
8
+ const failure = (code, kind, limit, meta) => Object.assign(new Error(`${code}: ${kind} budget exceeded`), { code, kind: 'budget', budget: kind, limit, ...metaOf(meta), fix: kind === 'ms' || kind === 'steps' || kind === 'depth' ? 'Bound the work or move it to an owned worker.' : 'Bound the collection and dispose resources with their owner.' })
9
+ function charge(root) {
10
+ if (root.running) { const t = now(); root.work += Math.max(0, t - root.started); root.started = t }
11
+ }
12
+ function enforce(frame, kind, value) {
13
+ const r = frame.root
14
+ if (r.error) throw r.error
15
+ if (value > r.limits[kind]) throw (r.error = failure('B0910', kind, r.limits[kind], frame.meta))
16
+ }
17
+ export function budgetOwner() { return I.owner() }
18
+ export function budgetEnter(meta, owner = I.owner(), options) {
19
+ const parent = active[active.length - 1]
20
+ const root = parent?.root || { limits: limitsOf(options), steps: 0, work: 0, depth: 0, running: false, started: 0, error: null }
21
+ const f = { root, meta: metaOf(meta), owner, state: 'active' }
22
+ charge(root)
23
+ enforce(f, 'depth', root.depth + 1)
24
+ root.depth++
25
+ if (!root.running) { root.running = true; root.started = now() }
26
+ active.push(f)
27
+ return f
28
+ }
29
+ export function budgetStep(frame, site) {
30
+ if (!frame || frame.state !== 'active') throw failure('B0910', 'inactive-frame', 0, site)
31
+ if (site) frame.meta = metaOf(site)
32
+ const r = frame.root
33
+ charge(r)
34
+ enforce(frame, 'steps', ++r.steps)
35
+ enforce(frame, 'ms', r.work)
36
+ }
37
+ function detach(f) {
38
+ if (f.state !== 'active') return
39
+ const index = active.lastIndexOf(f)
40
+ if (index >= 0) active.splice(index, 1)
41
+ const r = f.root
42
+ charge(r)
43
+ r.depth--
44
+ if (!active.some(x => x.root === r)) r.running = false
45
+ }
46
+ export function budgetLeave(frame) {
47
+ if (!frame || frame.state === 'closed') return
48
+ detach(frame)
49
+ frame.state = 'closed'
50
+ }
51
+ // The outcome always resolves: the generated resume runs even on a rejected await, preserving catch/finally.
52
+ export function budgetSuspend(frame, promise) {
53
+ detach(frame)
54
+ frame.state = 'suspended'
55
+ return Promise.resolve(promise).then(value => ({ ok: true, value }), error => ({ ok: false, error }))
56
+ }
57
+ export function budgetResume(frame, outcome) {
58
+ if (frame.state !== 'suspended') throw failure('B0910', 'inactive-frame', 0, frame.meta)
59
+ const r = frame.root
60
+ if (!r.running) { r.running = true; r.started = now() }
61
+ r.depth++
62
+ frame.state = 'active'
63
+ active.push(frame)
64
+ // Preserve the original rejection; a later checkpoint still sees a poisoned root.
65
+ if (!outcome.ok) throw outcome.error
66
+ budgetStep(frame)
67
+ return outcome.value
68
+ }
69
+ function ledger(owner, meta, options) {
70
+ if (!owner || typeof owner !== 'object') throw failure('B0911', 'missing-owner', 0, meta)
71
+ if (owner.s === 3) throw failure('B0911', 'disposed-owner', 0, meta)
72
+ let l = owners.get(owner)
73
+ if (!l) {
74
+ l = { limits: limitsOf(options), counts: Object.create(null), releases: new Set(), disposed: false }
75
+ owners.set(owner, l)
76
+ I.root(() => fx(() => () => {
77
+ l.disposed = true
78
+ owners.delete(owner)
79
+ for (const release of [...l.releases]) release()
80
+ }), owner)
81
+ }
82
+ if (l.disposed) throw failure('B0911', 'disposed-owner', 0, meta)
83
+ return l
84
+ }
85
+ // Core hook before owned sig construction / list materialization. Arrays may already exist at this point.
86
+ export function budgetAllocation(kind, owner, units) {
87
+ if (!owner) return // Module-level shared state has no disposable component owner.
88
+ if (!['rows', 'signals'].includes(kind) || !Number.isSafeInteger(units) || units < 0) throw failure('B0911', 'invalid-allocation', 0, null)
89
+ const frame = active[active.length - 1]
90
+ const meta = frame?.meta
91
+ const l = ledger(owner, meta)
92
+ const next = kind === 'signals' ? (l.counts.signals || 0) + units : units
93
+ if (next > l.limits[kind]) throw failure('B0911', kind, l.limits[kind], meta)
94
+ l.counts[kind] = next
95
+ }
96
+ export function budgetClaim(owner, kind, units = 1, dispose, meta, options) {
97
+ const l = ledger(owner, meta, options)
98
+ if (!['rows', 'signals', 'resources', 'pending'].includes(kind) || !Number.isSafeInteger(units) || units < 0) throw failure('B0911', 'invalid-claim', 0, meta)
99
+ const count = l.counts[kind] || 0
100
+ if (count + units > l.limits[kind]) throw failure('B0911', kind, l.limits[kind], meta)
101
+ // Bound disposal bookkeeping independently of units (including zero-unit claims).
102
+ if (l.releases.size >= LIMITS.resources) throw failure('B0911', 'resources', LIMITS.resources, meta)
103
+ l.counts[kind] = count + units
104
+ let live = true
105
+ const release = () => {
106
+ if (!live) return
107
+ live = false
108
+ l.releases.delete(release)
109
+ l.counts[kind] -= units
110
+ if (dispose) {
111
+ try { dispose() } catch { I.oops(failure('B0911', 'cleanup', 0, meta), owner, 'budget') }
112
+ }
113
+ }
114
+ l.releases.add(release)
115
+ return release
116
+ }
117
+ // Caller must supply a Worker it created exclusively, never an unrelated shared worker.
118
+ export function budgetWatchWorker(ownedWorker, rejectAll, meta, options) {
119
+ const limits = limitsOf(options), tasks = new Map()
120
+ let closed = false
121
+ const stop = (error = failure('B0911', 'worker-disposed', 0, meta)) => {
122
+ if (closed) return
123
+ closed = true
124
+ for (const timer of tasks.values()) clearTimeout(timer)
125
+ tasks.clear()
126
+ ownedWorker.terminate()
127
+ rejectAll(error)
128
+ }
129
+ return {
130
+ track(id) {
131
+ if (closed) throw failure('B0911', 'worker-disposed', 0, meta)
132
+ if (tasks.has(id)) throw failure('B0911', 'duplicate-worker-task', 0, meta)
133
+ if (tasks.size >= limits.pending) throw failure('B0911', 'pending', limits.pending, meta)
134
+ tasks.set(id, setTimeout(() => stop(failure('B0910', 'workerMs', limits.workerMs, meta)), limits.workerMs))
135
+ let live = true
136
+ return () => { if (live) { live = false; clearTimeout(tasks.get(id)); tasks.delete(id) } }
137
+ },
138
+ dispose: stop,
139
+ }
140
+ }
141
+ // Optional small core hook; old runtimes remain loadable while the compiler/runtime version gate handles upgrades.
142
+ I.budget?.(budgetAllocation)
package/brain-data.js CHANGED
@@ -327,9 +327,16 @@ function slot(origin, pri, sg) {
327
327
  // paths in api() are the app's own (`/users`): `<meta http base>` then the app's base path (<meta name="brain-base">)
328
328
  const appBase = () => {
329
329
  const m = G.document && document.querySelector('meta[name=brain-base]')
330
- return m ? m.getAttribute('content').replace(/\/$/, '') : ''
330
+ const base = m && m.getAttribute('content') || ''
331
+ if (base && (!base.startsWith('/') || base.startsWith('//') || /[\\?#\x00-\x20]/.test(base))) throw Error('Invalid application base')
332
+ return base.replace(/\/$/, '')
333
+ }
334
+ const full = u => {
335
+ if (!u.startsWith('/') || u.startsWith('//')) return u
336
+ // Native account/media endpoints never inherit a foreign API base or send account credentials off origin.
337
+ if (u === '/_brain' || u.startsWith('/_brain/')) return appBase() + u
338
+ return (/^(?:https?:)?\/\//i.test(P.base) ? '' : appBase()) + P.base + u
331
339
  }
332
- const full = u => (u.startsWith('/') && !u.startsWith('//') ? appBase() + P.base + u : u)
333
340
 
334
341
  async function once(u, M, body, sg, pri, up) {
335
342
  const url = full(u), origin = new URL(url, G.location ? location.href : 'http://localhost').origin
@@ -368,7 +375,10 @@ async function once(u, M, body, sg, pri, up) {
368
375
  if (st >= 200 && st < 300) return { value: j, cacheable: !/no-store|private/i.test(h('cache-control') || '') }
369
376
  const ra = h('retry-after'), retryAfter = ra == null ? undefined : isNaN(ra) ? Math.max(0, (Date.parse(ra) - Date.now()) / 1e3) : +ra
370
377
  if (st === 401 && P.login && G.location && !location.pathname.endsWith(P.login)) location.assign(appBase() + P.login + '?next=' + encodeURIComponent(location.pathname + location.search))
371
- throw new ApiError('http', (j && j.error) || `${M} ${u}: ${st}`, { status: st, errors: j && j.errors, retryAfter, id: h('x-request-id') || undefined })
378
+ const native = j && j.schemaVersion === 1 && j.error && typeof j.error === 'object' && typeof j.error.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(j.error.code)
379
+ const generic = st === 401 ? 'Authentication failed. Sign in again.' : st === 403 ? 'You do not have permission to continue.' : st === 422 ? 'Check the highlighted fields.' : st === 429 ? 'Too many requests. Wait before trying again.' : `Request failed (${st}).`
380
+ const message = !native && st < 500 && typeof j?.error === 'string' && j.error.length <= 512 && !/[\r\n]|(?:TypeError|ReferenceError|SyntaxError|Error):/.test(j.error) ? j.error : generic
381
+ throw new ApiError('http', message, { status: st, errors: native && st === 422 ? j.error.fields : j && j.errors, retryAfter, id: h('x-request-id') || undefined, ...(native ? { backendCode: j.error.code, fix: typeof j.error.fix === 'string' ? j.error.fix.slice(0,1024) : undefined } : {}) })
372
382
  }
373
383
 
374
384
  // multipart upload with progress (fetch has no upload progress)
package/brain-dev.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // BRAINLLM dev (SPEC §6.2): HMR that keeps sig state by name. Development only.
2
2
  // Served next to the core under /@brain/ and imports ./brain.js relatively: a single instance of the signal graph.
3
3
  // The dev codegen wraps each component: `export default dev(Counter)` and emits `sig(v, 'name')`.
4
- // v0 limit: if after an hmr a parent removes that row or branch, it removes the old nodes; then do a full reload.
4
+ // Static proof retains node identity; incompatible nested updates rebuild a proven owner boundary before parent ranges can become stale.
5
5
  // Registry for brain-inspect (§9): `live` (hash → instances), `inst` (root node N → instance) and the event `bus`.
6
- import { _dev, fx } from './brain.js'
6
+ import { _dev, fx, tpl } from './brain.js'
7
7
 
8
8
  let cur = null // instance under construction: { m: Map name→sig, r: Map name→value to restore | null }
9
9
  let quiet = 0 // >0 during hmr: the bus emits `hmr` instead of mount/dispose
10
+ const definitions = new Map() // bounded current implementations for future mounts through an older import
10
11
  export const live = new Map()
11
12
  export const inst = new WeakMap()
12
13
  export const bus = new Set() // fn(kind, data): 'mount' | 'dispose' | 'hmr' | 'hydrate'
@@ -30,18 +31,22 @@ export { owner }
30
31
 
31
32
  function build(i, restore) {
32
33
  const pc = cur
33
- cur = { m: new Map(), r: restore, f: i.C.f || i.h || null }
34
+ cur = { m: new Map(), r: restore, f: i.C.f || i.h || null, i }
34
35
  try {
35
36
  return root(d => {
36
37
  i.r = owner() // register before C(): fx from the first run already have an owner (inspector)
37
38
  inst.set(i.r, i)
38
39
  const t = performance.now()
39
- const out = i.C(i.$p)
40
+ i.fragments = new Set()
41
+ i.fragmentRefs = 0
42
+ i.fragmentOverflow = false
43
+ let out = i.C(i.$p)
40
44
  i.$mt = performance.now() - t
41
45
  mounts.unshift({ comp: i.C.f || i.h || null, ms: Math.round(i.$mt * 100) / 100, at: Date.now(), hmr: quiet > 0 })
42
46
  if (mounts.length > 50) mounts.length = 50
43
47
  // a component may return a node, a fragment or an array (guard() returns its nodes plus an anchor)
44
- i.n = Array.isArray(out) ? out.flat(Infinity) : out.nodeType === 11 ? [...out.childNodes] : [out]
48
+ i.n = out == null ? [] : Array.isArray(out) ? out.flat(Infinity) : out.nodeType === 11 ? [...out.childNodes] : [out]
49
+ if (!i.n.length) { out = document.createComment(''); i.n = [out] }
45
50
  for (const x of i.n) if (x.nodeType === 1) x.$i = i
46
51
  i.d = d
47
52
  i.m = cur.m
@@ -51,7 +56,9 @@ function build(i, restore) {
51
56
  // (last hovered or focused element, accessibility tree) and must not keep the whole instance with it
52
57
  fx(() => () => {
53
58
  set.delete(i)
59
+ if (!set.size) live.delete(i.h)
54
60
  for (const x of i.n || []) if (x.nodeType === 1 && x.$i === i) x.$i = null
61
+ if (!quiet) for (const node of i.n || []) node.remove()
55
62
  quiet || emit('dispose', i)
56
63
  })
57
64
  if (!quiet) emit('mount', i)
@@ -63,38 +70,194 @@ function build(i, restore) {
63
70
  }
64
71
 
65
72
  export function dev(C) {
66
- const W = $p => build({ C, $p, h: C.h, p: owner(), n: null, d: null, m: null, r: null }, null)
73
+ const registered = typeof C.h === 'string' && (definitions.has(C.h) || definitions.size < 1024)
74
+ if (registered) definitions.set(C.h, C)
75
+ const W = $p => build({ C: definitions.get(C.h) || C, $p, h: C.h, p: owner(), n: null, d: null, m: null, r: null }, null)
67
76
  Object.assign(W, C) // h, p, form, seo, head… whatever the compiler (or guard) put on it
68
77
  W.C = C
78
+ if (typeof C.h === 'string' && !registered) W.$hmrUnsupportedReason = 'definition-registry-budget'
69
79
  return W
70
80
  }
71
81
 
72
- // Remounts in place every live instance of `hash` with the new component from `mod`.
82
+ // Compiler-only fragment factories record pristine references before dynamic holes insert/move siblings.
83
+ // Per-owner cleanup prevents inactive branches/rows from retaining detached nodes.
84
+ export function fragment(create, hash, index) {
85
+ let cached = null, factory = create
86
+ return () => {
87
+ let i = cur?.i?.h === hash ? cur.i : null
88
+ for (let o = owner(); !i && o; o = o.p) { const found = inst.get(o); if (found?.h === hash) i = found }
89
+ const html = i?.C?.$hmr?.templates?.[index]
90
+ if (typeof html === 'string' && html !== cached) { cached = html; factory = tpl(html) }
91
+ const out = factory()
92
+ if (!i || i.fragmentOverflow) return out
93
+ const nodes = [], roots = out.nodeType === 11 ? [...out.childNodes] : [out]
94
+ const rootSet = new Set(roots)
95
+ const visit = (node, depth) => {
96
+ if (depth > 64 || nodes.length >= 4096) return false
97
+ nodes.push({ node, parent: node.parentNode, root: rootSet.has(node) })
98
+ for (const child of node.childNodes || []) if (!visit(child, depth + 1)) return false
99
+ return true
100
+ }
101
+ if (!roots.every(node => visit(node, 0)) || i.fragmentRefs + nodes.length > 8192 || i.fragments.size >= 2048) { i.fragmentOverflow = true; return out }
102
+ const record = { index, nodes, owner: owner() }
103
+ i.fragments.add(record)
104
+ i.fragmentRefs += nodes.length
105
+ fx(() => () => { if (i.fragments.delete(record)) i.fragmentRefs -= nodes.length })
106
+ return out
107
+ }
108
+ }
109
+
110
+ export let lastUpdate = { mode: 'none', patched: 0, remounted: 0, reason: 'not-run' }
111
+ const safeAttribute = name => ['class', 'title', 'alt', 'placeholder', 'style'].includes(name) || name.startsWith('aria-') || name.startsWith('data-') && !['data-b', 'data-cv-ref'].includes(name)
112
+ const attributes = node => new Map([...node.attributes].map(attribute => [attribute.name, attribute.value]))
113
+ function metadata(value) {
114
+ return value?.version === 1 && typeof value.wiring === 'string' && value.wiring.length <= 65536 && Array.isArray(value.templates) && value.templates.length <= 64 && value.templates.every(html => typeof html === 'string') && value.templates.reduce((n, html) => n + html.length, 0) <= 65536
115
+ }
116
+ function templateChanges(before, after) {
117
+ const changes = [], shapes = []
118
+ let visits = 0
119
+ for (let index = 0; index < before.length; index++) {
120
+ const old = tpl(before[index])(), next = tpl(after[index])(), flat = []
121
+ const walk = (a, b, depth) => {
122
+ if (++visits > 8192 || depth > 64) throw Error('template-budget')
123
+ if (!a || !b || a.nodeType !== b.nodeType || a.nodeName !== b.nodeName || a.namespaceURI !== b.namespaceURI) throw Error('template-topology')
124
+ const position = flat.length
125
+ flat.push(a)
126
+ if (a.nodeType === 3 && a.data !== b.data) changes.push({ index, position, kind: 'text', before: a.data, after: b.data })
127
+ else if (a.nodeType === 8 && a.data !== b.data) throw Error('anchor-topology')
128
+ if (a.nodeType === 1) {
129
+ const previous = attributes(a), current = attributes(b)
130
+ for (const name of new Set([...previous.keys(), ...current.keys()])) if (previous.get(name) !== current.get(name)) {
131
+ if (!safeAttribute(name)) throw Error('stateful-or-unsupported-attribute')
132
+ changes.push({ index, position, kind: 'attribute', name, before: previous.get(name) ?? null, after: current.get(name) ?? null })
133
+ }
134
+ }
135
+ if (a.childNodes.length !== b.childNodes.length) throw Error('template-topology')
136
+ for (let n = 0; n < a.childNodes.length; n++) walk(a.childNodes[n], b.childNodes[n], depth + 1)
137
+ }
138
+ const a = old.nodeType === 11 ? [...old.childNodes] : [old], b = next.nodeType === 11 ? [...next.childNodes] : [next]
139
+ if (a.length !== b.length) throw Error('template-topology')
140
+ for (let n = 0; n < a.length; n++) walk(a[n], b[n], 0)
141
+ shapes.push(flat)
142
+ }
143
+ return { changes, shapes }
144
+ }
145
+ function staticPlan(i, C) {
146
+ const before = i.C.$hmr, after = C.$hmr
147
+ if (!metadata(before) || !metadata(after)) return 'metadata-unavailable-or-budget'
148
+ if (before.wiring !== after.wiring) return 'compiled-wiring-changed'
149
+ if (before.templates.length !== after.templates.length) return 'template-topology'
150
+ if (i.fragmentOverflow) return 'instance-reference-budget'
151
+ let analysis
152
+ try { analysis = templateChanges(before.templates, after.templates) } catch (error) { return ['template-budget', 'template-topology', 'anchor-topology', 'stateful-or-unsupported-attribute'].includes(error.message) ? error.message : 'template-proof-failed' }
153
+ const operations = []
154
+ for (const record of i.fragments || []) {
155
+ const shape = analysis.shapes[record.index]
156
+ if (!shape || shape.length !== record.nodes.length) return 'instance-shape-conflict'
157
+ for (const change of analysis.changes) if (change.index === record.index) {
158
+ const entry = record.nodes[change.position], node = entry?.node
159
+ if (!node || node.nodeType !== shape[change.position].nodeType || !entry.root && node.parentNode !== entry.parent) return 'instance-node-conflict'
160
+ if (change.kind === 'text' ? node.data !== change.before : node.getAttribute(change.name) !== change.before) return 'runtime-owned-content-conflict'
161
+ operations.push({ node, ...change })
162
+ if (operations.length > 8192) return 'instance-operation-budget'
163
+ }
164
+ }
165
+ return { i, C, operations }
166
+ }
167
+ function applyStaticPlan({ i, C, operations }) {
168
+ // Plan first; preserve live handlers/effects/owners and target the original nodes only.
169
+ const selection = document.getSelection?.()
170
+ const saved = selection?.rangeCount ? { anchor: selection.anchorNode, anchorOffset: selection.anchorOffset, focus: selection.focusNode, focusOffset: selection.focusOffset } : null
171
+ try {
172
+ for (const operation of operations) {
173
+ if (operation.kind === 'text') operation.node.data = operation.after
174
+ else if (operation.after === null) operation.node.removeAttribute(operation.name)
175
+ else operation.node.setAttribute(operation.name, operation.after)
176
+ }
177
+ } catch { return 'native-dom-patch-failed' }
178
+ if (saved && selection.setBaseAndExtent) {
179
+ const length = node => node?.nodeType === 3 ? node.data.length : node?.childNodes.length || 0
180
+ try { selection.setBaseAndExtent(saved.anchor, Math.min(saved.anchorOffset, length(saved.anchor)), saved.focus, Math.min(saved.focusOffset, length(saved.focus))) } catch {}
181
+ }
182
+ i.C = C
183
+ return null
184
+ }
185
+
186
+ // A parent list/branch keeps its own node range. Replacing a child range directly would leave those
187
+ // captured roots stale, so incompatible nested updates rebuild the outermost owned component once.
188
+ function boundary(i) {
189
+ let target = i, count = 0
190
+ for (let owner = i.p; owner; owner = owner.p) {
191
+ if (++count > 256) return null
192
+ const ancestor = inst.get(owner)
193
+ if (ancestor) target = ancestor
194
+ }
195
+ return !target.p || !target.p.f && !target.p.p ? target : null
196
+ }
197
+ function under(i, ancestor) {
198
+ if (i === ancestor) return true
199
+ let count = 0
200
+ for (let owner = i.p; owner && ++count <= 256; owner = owner.p) if (owner === ancestor.r) return true
201
+ return false
202
+ }
203
+ function remount(i, C) {
204
+ const old = i.n, parent = old[0]?.parentNode
205
+ const anchor = document.createComment('')
206
+ if (parent) parent.insertBefore(anchor, old[0])
207
+ const values = new Map([...i.m].map(([name, node]) => [name, node._]))
208
+ i.d()
209
+ emit('dispose', { h: i.h, C: i.C, n: old, r: null, hmr: 1 })
210
+ i.C = C
211
+ build(i, values)
212
+ if (parent) for (const node of i.n) parent.insertBefore(node, anchor)
213
+ for (const node of old) node.remove()
214
+ anchor.remove()
215
+ }
216
+ // Safe static fragments retain node identity. Other updates rebuild a proven owner boundary.
73
217
  export function hmr(hash, mod) {
74
- const W = Object.values(mod).find(c => c && c.h === hash)
218
+ const W = Object.values(mod).find(component => component && component.h === hash)
75
219
  if (!W) return 0
76
220
  const C = W.C || W
77
- let k = 0
221
+ if (W.$hmrUnsupportedReason) { lastUpdate = { mode: 'reload-required', patched: 0, remounted: 0, reason: W.$hmrUnsupportedReason }; return 0 }
222
+ const instances = [...(live.get(hash) || [])].filter(i => i.r?.s !== 3)
223
+ const plans = [], rebuild = new Map(), reasons = new Set(), patched = new Set()
224
+ for (const i of instances) {
225
+ let plan
226
+ try { plan = staticPlan(i, C) } catch { plan = 'native-proof-operation-failed' }
227
+ if (typeof plan !== 'string') { plans.push(plan); continue }
228
+ const target = boundary(i)
229
+ if (!target) { lastUpdate = { mode: 'reload-required', patched: 0, remounted: 0, reason: 'parent-range-owner-unavailable' }; return 0 }
230
+ reasons.add(plan)
231
+ if (target !== i) reasons.add('ancestor-remount-for-parent-owned-range')
232
+ rebuild.set(target, definitions.get(target.h) || target.C)
233
+ }
234
+ let affected = 0, remounted = 0, ancestors = 0
78
235
  quiet++
79
236
  try {
80
- for (const i of [...(live.get(hash) || [])]) {
81
- const old = i.n, pa = old[0].parentNode
82
- // an anchor that survives the dispose (guard() removes its own nodes when its owner is disposed)
83
- const first = document.createComment('')
84
- if (pa) pa.insertBefore(first, old[0])
85
- const vals = new Map([...i.m].map(([name, n]) => [name, n._]))
86
- i.d()
87
- emit('dispose', { h: i.h, C: i.C, n: old, r: null, hmr: 1 })
88
- i.C = C
89
- build(i, vals)
90
- if (pa) for (const x of i.n) pa.insertBefore(x, first)
91
- for (const x of old) x.remove()
92
- first.remove()
93
- k++
237
+ for (const plan of plans) {
238
+ if ([...rebuild.keys()].some(target => under(plan.i, target))) continue
239
+ const failure = applyStaticPlan(plan)
240
+ if (!failure) patched.add(plan.i)
241
+ else {
242
+ const target = boundary(plan.i)
243
+ if (!target) { lastUpdate = { mode: 'reload-required', patched: patched.size, remounted, reason: 'native-patch-failed-without-owned-range' }; return 0 }
244
+ rebuild.set(target, definitions.get(target.h) || target.C)
245
+ reasons.add(failure)
246
+ if (target !== plan.i) reasons.add('ancestor-remount-for-parent-owned-range')
247
+ }
94
248
  }
95
- } finally {
96
- quiet--
97
- }
98
- emit('hmr', { h: hash, n: k })
99
- return k
249
+ for (const [target, implementation] of rebuild) {
250
+ if (target.r?.s === 3) continue
251
+ const covered = instances.filter(i => under(i, target)).length
252
+ for (const i of patched) if (under(i, target)) patched.delete(i)
253
+ if (target.h !== hash) ancestors++
254
+ remount(target, implementation)
255
+ affected += covered
256
+ remounted++
257
+ }
258
+ } finally { quiet-- }
259
+ const count = patched.size + affected
260
+ lastUpdate = { mode: !count ? 'future-mount-updated' : remounted ? patched.size ? 'mixed' : ancestors ? 'ancestor-remount' : 'component-remount' : 'static-fragment', patched: patched.size, remounted, ancestorRemounted: ancestors, reason: [...reasons].join(',') || (!count ? 'no-live-instance; current-definition-retained' : 'exact-compiled-wiring-and-template-shape'), stateRestoration: ancestors ? 'ancestor-named-state; descendant-instances-recreated' : 'named-state-or-static-identity' }
261
+ emit('hmr', { h: hash, n: count, ...lastUpdate })
262
+ return count
100
263
  }