@nifrajs/web 3.1.0 → 3.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.
- package/dist/build-plan.d.ts +228 -0
- package/dist/build-plan.d.ts.map +1 -0
- package/dist/build-plan.js +514 -0
- package/dist/build-plan.js.map +1 -0
- package/dist/build-vite.d.ts +2 -1
- package/dist/build-vite.d.ts.map +1 -1
- package/dist/build-vite.js.map +1 -1
- package/dist/build.d.ts +2 -197
- package/dist/build.d.ts.map +1 -1
- package/dist/build.js +61 -502
- package/dist/build.js.map +1 -1
- package/dist/chunk-names.d.ts.map +1 -1
- package/dist/chunk-names.js +3 -2
- package/dist/chunk-names.js.map +1 -1
- package/dist/dev-ssr-graph.d.ts.map +1 -1
- package/dist/dev-ssr-graph.js +63 -28
- package/dist/dev-ssr-graph.js.map +1 -1
- package/dist/diagnostic.d.ts.map +1 -1
- package/dist/diagnostic.js +9 -2
- package/dist/diagnostic.js.map +1 -1
- package/dist/fonts-google.d.ts.map +1 -1
- package/dist/fonts-google.js +3 -1
- package/dist/fonts-google.js.map +1 -1
- package/dist/fs.d.ts.map +1 -1
- package/dist/fs.js +2 -1
- package/dist/fs.js.map +1 -1
- package/dist/index.d.ts +15 -609
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +22 -1935
- package/dist/index.js.map +1 -1
- package/dist/internal/codegen.d.ts +68 -0
- package/dist/internal/codegen.d.ts.map +1 -0
- package/dist/internal/codegen.js +317 -0
- package/dist/internal/codegen.js.map +1 -0
- package/dist/internal/head-merge.d.ts +2 -0
- package/dist/internal/head-merge.d.ts.map +1 -1
- package/dist/internal/head-merge.js +17 -1
- package/dist/internal/head-merge.js.map +1 -1
- package/dist/internal/parity.d.ts +7 -0
- package/dist/internal/parity.d.ts.map +1 -1
- package/dist/internal/parity.js +212 -30
- package/dist/internal/parity.js.map +1 -1
- package/dist/internal/render-document.d.ts +372 -0
- package/dist/internal/render-document.d.ts.map +1 -0
- package/dist/internal/render-document.js +744 -0
- package/dist/internal/render-document.js.map +1 -0
- package/dist/internal/runtime-contract.d.ts +48 -0
- package/dist/internal/runtime-contract.d.ts.map +1 -0
- package/dist/internal/runtime-contract.js +27 -0
- package/dist/internal/runtime-contract.js.map +1 -0
- package/dist/internal/web-app.d.ts +171 -0
- package/dist/internal/web-app.d.ts.map +1 -0
- package/dist/internal/web-app.js +844 -0
- package/dist/internal/web-app.js.map +1 -0
- package/dist/islands.d.ts +48 -0
- package/dist/islands.d.ts.map +1 -1
- package/dist/islands.js +79 -0
- package/dist/islands.js.map +1 -1
- package/dist/module-graph.d.ts.map +1 -1
- package/dist/module-graph.js +22 -9
- package/dist/module-graph.js.map +1 -1
- package/dist/nano.d.ts +125 -0
- package/dist/nano.d.ts.map +1 -0
- package/dist/nano.js +190 -0
- package/dist/nano.js.map +1 -0
- package/dist/plugins/css-modules.js +2 -2
- package/dist/plugins/css-modules.js.map +1 -1
- package/dist/plugins/kit.d.ts +12 -0
- package/dist/plugins/kit.d.ts.map +1 -1
- package/dist/plugins/kit.js +62 -12
- package/dist/plugins/kit.js.map +1 -1
- package/dist/plugins/postcss.js +2 -2
- package/dist/plugins/postcss.js.map +1 -1
- package/dist/plugins/scss.js +2 -2
- package/dist/plugins/scss.js.map +1 -1
- package/dist/plugins/stylex.d.ts +70 -0
- package/dist/plugins/stylex.d.ts.map +1 -0
- package/dist/plugins/stylex.js +166 -0
- package/dist/plugins/stylex.js.map +1 -0
- package/dist/plugins/svg.js +2 -2
- package/dist/plugins/svg.js.map +1 -1
- package/dist/router.d.ts +1 -1
- package/dist/router.js +23 -23
- package/dist/router.js.map +1 -1
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +26 -10
- package/dist/vite.js.map +1 -1
- package/package.json +39 -3
- package/src/build-plan.ts +741 -0
- package/src/build-vite.ts +1 -4
- package/src/build.ts +84 -716
- package/src/chunk-names.ts +3 -2
- package/src/dev-ssr-graph.ts +63 -28
- package/src/diagnostic.ts +14 -2
- package/src/fonts-google.ts +3 -1
- package/src/fs.ts +2 -1
- package/src/index.ts +73 -2705
- package/src/internal/codegen.ts +400 -0
- package/src/internal/head-merge.ts +19 -1
- package/src/internal/parity.ts +215 -35
- package/src/internal/render-document.ts +1116 -0
- package/src/internal/runtime-contract.ts +54 -0
- package/src/internal/web-app.ts +1114 -0
- package/src/islands.ts +85 -0
- package/src/module-graph.ts +23 -9
- package/src/nano.ts +246 -0
- package/src/plugins/css-modules.ts +2 -2
- package/src/plugins/kit.ts +65 -12
- package/src/plugins/postcss.ts +2 -2
- package/src/plugins/scss.ts +2 -2
- package/src/plugins/stylex.ts +298 -0
- package/src/plugins/svg.ts +2 -2
- package/src/router.ts +24 -24
- package/src/vite.ts +33 -9
package/src/islands.ts
CHANGED
|
@@ -34,6 +34,28 @@ export type IslandCleanup = () => void
|
|
|
34
34
|
// biome-ignore lint/suspicious/noConfusingVoidType: `void` = "no cleanup returned", like React's EffectCallback - cleanup is optional.
|
|
35
35
|
export type IslandEnhancer<P = unknown> = (el: HTMLElement, props: P) => IslandCleanup | void
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Author a typed enhancer. Pure identity at runtime (zero cost, tree-shaken away) - its only job is
|
|
39
|
+
* to pin the `data-props` shape so `el` and `props` are typed inside the body and the enhancer is
|
|
40
|
+
* assignable to `mountIslands`. Prefer this over an inline arrow whenever an island reads props:
|
|
41
|
+
*
|
|
42
|
+
* const counter = defineIsland<{ start: number }>((el, props) => {
|
|
43
|
+
* let n = props.start // props typed, no cast
|
|
44
|
+
* const out = el.querySelector("output")!
|
|
45
|
+
* const onClick = () => { out.textContent = String(++n) }
|
|
46
|
+
* el.querySelector("button")?.addEventListener("click", onClick)
|
|
47
|
+
* return () => el.querySelector("button")?.removeEventListener("click", onClick)
|
|
48
|
+
* })
|
|
49
|
+
* mountIslands({ counter })
|
|
50
|
+
*
|
|
51
|
+
* The props type is a contract, not a validator - `data-props` is JSON authored by your own SSR, so
|
|
52
|
+
* it is trusted framing, not user input. Keep the enhancer body imperative: read the DOM, wire
|
|
53
|
+
* listeners, return cleanup. No hidden reactivity to get wrong.
|
|
54
|
+
*/
|
|
55
|
+
export function defineIsland<P = unknown>(enhancer: IslandEnhancer<P>): IslandEnhancer<P> {
|
|
56
|
+
return enhancer
|
|
57
|
+
}
|
|
58
|
+
|
|
37
59
|
/** Parse an island's inline `data-props` JSON; malformed/absent → `undefined` (never throws). */
|
|
38
60
|
function readProps(el: HTMLElement): unknown {
|
|
39
61
|
const raw = el.dataset.props
|
|
@@ -100,3 +122,66 @@ export function mountIslands(
|
|
|
100
122
|
}
|
|
101
123
|
}
|
|
102
124
|
}
|
|
125
|
+
|
|
126
|
+
/** Unsubscribe one bus handler; calling twice is a no-op. Also returned so an enhancer can hand it
|
|
127
|
+
* straight back as its `IslandCleanup`. */
|
|
128
|
+
export type IslandBusUnsubscribe = () => void
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* A typed publish/subscribe channel for coordinating islands that must talk to each other without a
|
|
132
|
+
* shared reactive store - a cart badge reacting to an "add to cart" island, a filter island driving
|
|
133
|
+
* a results island. Create ONE bus in your mount entry and close over it in each enhancer; there is
|
|
134
|
+
* no implicit global, so concurrent renders and tests never cross-talk.
|
|
135
|
+
*
|
|
136
|
+
* type Events = { "cart:add": { sku: string }; "cart:count": number }
|
|
137
|
+
* const bus = createIslandBus<Events>()
|
|
138
|
+
* mountIslands({
|
|
139
|
+
* addBtn: defineIsland((el) => {
|
|
140
|
+
* const onClick = () => bus.emit("cart:add", { sku: el.dataset.sku! })
|
|
141
|
+
* el.addEventListener("click", onClick)
|
|
142
|
+
* return () => el.removeEventListener("click", onClick)
|
|
143
|
+
* }),
|
|
144
|
+
* badge: defineIsland((el) => bus.on("cart:count", (n) => { el.textContent = String(n) })),
|
|
145
|
+
* })
|
|
146
|
+
*
|
|
147
|
+
* `on` returns its own unsubscribe, so an enhancer whose only job is to listen can `return bus.on(...)`
|
|
148
|
+
* directly as its cleanup. A handler that throws is isolated - it never blocks the other subscribers
|
|
149
|
+
* or the `emit` caller. Synchronous, in-memory, no DOM dependency (safe to construct under SSR); it
|
|
150
|
+
* carries no history, so a subscriber only sees events emitted after it subscribed.
|
|
151
|
+
*/
|
|
152
|
+
export function createIslandBus<
|
|
153
|
+
Events extends Record<string, unknown> = Record<string, unknown>,
|
|
154
|
+
>(): {
|
|
155
|
+
emit<K extends keyof Events>(type: K, detail: Events[K]): void
|
|
156
|
+
on<K extends keyof Events>(type: K, handler: (detail: Events[K]) => void): IslandBusUnsubscribe
|
|
157
|
+
} {
|
|
158
|
+
const channels = new Map<keyof Events, Set<(detail: never) => void>>()
|
|
159
|
+
return {
|
|
160
|
+
emit(type, detail) {
|
|
161
|
+
const handlers = channels.get(type)
|
|
162
|
+
if (handlers === undefined) return
|
|
163
|
+
// Snapshot so a handler that (un)subscribes mid-dispatch cannot corrupt this iteration.
|
|
164
|
+
for (const handler of [...handlers]) {
|
|
165
|
+
try {
|
|
166
|
+
;(handler as (d: Events[typeof type]) => void)(detail)
|
|
167
|
+
} catch (err) {
|
|
168
|
+
console.error(`[nifra/islands] bus handler for "${String(type)}" failed:`, err)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
on(type, handler) {
|
|
173
|
+
let handlers = channels.get(type)
|
|
174
|
+
if (handlers === undefined) {
|
|
175
|
+
handlers = new Set()
|
|
176
|
+
channels.set(type, handlers)
|
|
177
|
+
}
|
|
178
|
+
handlers.add(handler as (detail: never) => void)
|
|
179
|
+
return () => {
|
|
180
|
+
const set = channels.get(type)
|
|
181
|
+
if (set === undefined) return
|
|
182
|
+
set.delete(handler as (detail: never) => void)
|
|
183
|
+
if (set.size === 0) channels.delete(type)
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
}
|
|
187
|
+
}
|
package/src/module-graph.ts
CHANGED
|
@@ -44,6 +44,11 @@ export interface ClientModuleGraph {
|
|
|
44
44
|
readonly chunks: Readonly<Record<string, GraphChunk>>
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
/** Module ids are graph identifiers, not filesystem paths exposed to an OS API. Bun uses `\\` on
|
|
48
|
+
* Windows, while Rollup and the guards use `/` for suffix matching and stable diagnostics. Normalize at
|
|
49
|
+
* each adapter boundary so every consumer sees one graph shape. */
|
|
50
|
+
const normalizeModuleId = (id: string): string => id.replaceAll("\\", "/")
|
|
51
|
+
|
|
47
52
|
/** The slice of Bun's metafile this seam consumes. Not yet in `@types/bun`; shape per the docs. */
|
|
48
53
|
export interface BunMetafileLike {
|
|
49
54
|
readonly inputs?: Readonly<
|
|
@@ -66,14 +71,23 @@ export interface BunMetafileLike {
|
|
|
66
71
|
*/
|
|
67
72
|
export function fromBunMetafile(meta: BunMetafileLike | undefined): ClientModuleGraph {
|
|
68
73
|
const modules: Record<string, GraphModule> = {}
|
|
69
|
-
for (const [
|
|
70
|
-
|
|
74
|
+
for (const [rawId, input] of Object.entries(meta?.inputs ?? {})) {
|
|
75
|
+
const id = normalizeModuleId(rawId)
|
|
76
|
+
modules[id] = {
|
|
77
|
+
imports: (input.imports ?? []).map((im) => ({
|
|
78
|
+
...(im.path === undefined ? {} : { path: normalizeModuleId(im.path) }),
|
|
79
|
+
...(im.original === undefined ? {} : { original: im.original }),
|
|
80
|
+
})),
|
|
81
|
+
}
|
|
71
82
|
}
|
|
72
83
|
const chunks: Record<string, GraphChunk> = {}
|
|
73
|
-
for (const [
|
|
84
|
+
for (const [rawPath, output] of Object.entries(meta?.outputs ?? {})) {
|
|
85
|
+
const path = normalizeModuleId(rawPath)
|
|
74
86
|
chunks[path] = {
|
|
75
|
-
...(output.entryPoint !== undefined
|
|
76
|
-
|
|
87
|
+
...(output.entryPoint !== undefined
|
|
88
|
+
? { entryPoint: normalizeModuleId(output.entryPoint) }
|
|
89
|
+
: {}),
|
|
90
|
+
modules: Object.keys(output.inputs ?? {}).map(normalizeModuleId),
|
|
77
91
|
}
|
|
78
92
|
}
|
|
79
93
|
return { modules, chunks }
|
|
@@ -117,11 +131,11 @@ export function fromRollupBundle(
|
|
|
117
131
|
// Assets (CSS, copied files) have no module graph; `type` is absent only on hand-built test inputs,
|
|
118
132
|
// which are always chunks, so treat "not explicitly an asset" as a chunk.
|
|
119
133
|
if (output.type === "asset") continue
|
|
120
|
-
const moduleIds = output.moduleIds ?? []
|
|
134
|
+
const moduleIds = (output.moduleIds ?? []).map(normalizeModuleId)
|
|
121
135
|
// Start from the real modules; `node:` builtins get appended below.
|
|
122
136
|
const chunkModules: string[] = [...moduleIds]
|
|
123
137
|
for (const id of moduleIds) {
|
|
124
|
-
const imports = importsOf(id).map((path) => ({ path }))
|
|
138
|
+
const imports = importsOf(id).map((path) => ({ path: normalizeModuleId(path) }))
|
|
125
139
|
if (modules[id] === undefined) modules[id] = { imports }
|
|
126
140
|
// The guards locate a leak by finding the builtin IN a chunk's module list - Bun BUNDLES the `node:`
|
|
127
141
|
// polyfill, so the builtin appears there as an input. Rollup EXTERNALIZES `node:`, so it never lands
|
|
@@ -135,10 +149,10 @@ export function fromRollupBundle(
|
|
|
135
149
|
if (modules[im.path] === undefined) modules[im.path] = { imports: [] }
|
|
136
150
|
}
|
|
137
151
|
}
|
|
138
|
-
chunks[fileName] = {
|
|
152
|
+
chunks[normalizeModuleId(fileName)] = {
|
|
139
153
|
// `facadeModuleId` is null for a shared/common chunk (no single entry) - omit it then, matching
|
|
140
154
|
// how a non-entry Bun output omits `entryPoint`, so the guards' entry set stays the real entries.
|
|
141
|
-
...(output.facadeModuleId ? { entryPoint: output.facadeModuleId } : {}),
|
|
155
|
+
...(output.facadeModuleId ? { entryPoint: normalizeModuleId(output.facadeModuleId) } : {}),
|
|
142
156
|
modules: chunkModules,
|
|
143
157
|
}
|
|
144
158
|
}
|
package/src/nano.ts
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@nifrajs/web/nano` - the smallest state layer that still lets an island drive a keyed list.
|
|
3
|
+
*
|
|
4
|
+
* The islands lane (`@nifrajs/web/islands`) is imperative and correct-by-construction, but it has no
|
|
5
|
+
* state primitive: every DOM update is hand-written, and a list means rebuilding the whole container.
|
|
6
|
+
* nano adds a small, closed set of primitives and stops:
|
|
7
|
+
*
|
|
8
|
+
* - `signal(v)` - a current-value cell you read with `.get()` and write with `.set()`.
|
|
9
|
+
* - `computed(fn, [deps])` - a derived cell. Its dependencies are DECLARED, never auto-tracked.
|
|
10
|
+
* - `resource(fetcher, [deps])` - an async cell with an explicit pending/error/ready value. This is
|
|
11
|
+
* nano's answer to "suspense": no thrown promise, no magic boundary, just a value you can bind.
|
|
12
|
+
* - `bind` / `bindList` / `bindResource` - explicit, one-directional DOM bindings that each return
|
|
13
|
+
* their teardown.
|
|
14
|
+
*
|
|
15
|
+
* The design rule is the whole point: every reactive edge is a call you can see - a `bind(...)` or a
|
|
16
|
+
* `computed(fn, [deps])`. There is no re-render scope, no VDOM, no template compiler, and no effect
|
|
17
|
+
* that silently subscribes to whatever it happened to read. That is what removes the three failure
|
|
18
|
+
* modes an AI (or a human) hits in a framework - stale closures, wrong effect deps, hydration
|
|
19
|
+
* mismatch - and, just as importantly, it is what makes every remaining mistake STATICALLY
|
|
20
|
+
* detectable: a missing dep is `[deps]` that doesn't list a signal the body reads; a leak is a `bind`
|
|
21
|
+
* whose cleanup isn't returned. A framework's reactivity can't be linted like that; nano's can.
|
|
22
|
+
*
|
|
23
|
+
* Where nano stops: no client router and no nested/composable view state (a component tree that mounts
|
|
24
|
+
* and unmounts its own children). When an app needs those, it has outgrown a vanilla page - reach for
|
|
25
|
+
* a framework adapter (`@nifrajs/web-preact`), not more nano.
|
|
26
|
+
*
|
|
27
|
+
* Browser code: it touches the DOM and is meant to run in an island enhancer, never under SSR.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** A value you can read now and be told about later. Both `signal` and `computed` are `Readable`, so
|
|
31
|
+
* `bind`/`bindList` accept either. */
|
|
32
|
+
export interface Readable<T> {
|
|
33
|
+
get(): T
|
|
34
|
+
subscribe(listener: (value: T) => void): () => void
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A writable cell. `set` notifies subscribers only when the value actually changes (`Object.is`), so
|
|
38
|
+
* a redundant write costs nothing. */
|
|
39
|
+
export interface Signal<T> extends Readable<T> {
|
|
40
|
+
set(value: T): void
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Notify a snapshot of the current listeners, so a listener that (un)subscribes mid-dispatch does not
|
|
44
|
+
* corrupt the walk. A throwing listener is isolated - it never blocks the others. */
|
|
45
|
+
function notify<T>(listeners: Set<(value: T) => void>, value: T): void {
|
|
46
|
+
for (const listener of [...listeners]) {
|
|
47
|
+
try {
|
|
48
|
+
listener(value)
|
|
49
|
+
} catch (error) {
|
|
50
|
+
console.error("[nifra/nano] a subscriber threw:", error)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A current-value cell. `signal(0)` -> `.get()` reads, `.set(1)` writes and notifies. */
|
|
56
|
+
export function signal<T>(initial: T): Signal<T> {
|
|
57
|
+
let value = initial
|
|
58
|
+
const listeners = new Set<(value: T) => void>()
|
|
59
|
+
return {
|
|
60
|
+
get: () => value,
|
|
61
|
+
set(next: T) {
|
|
62
|
+
if (Object.is(next, value)) return
|
|
63
|
+
value = next
|
|
64
|
+
notify(listeners, value)
|
|
65
|
+
},
|
|
66
|
+
subscribe(listener) {
|
|
67
|
+
listeners.add(listener)
|
|
68
|
+
return () => {
|
|
69
|
+
listeners.delete(listener)
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A derived cell. `computed(() => a.get() + b.get(), [a, b])` recomputes whenever a declared
|
|
77
|
+
* dependency changes and notifies its own subscribers when the derived value changes.
|
|
78
|
+
*
|
|
79
|
+
* The `deps` array is mandatory and explicit ON PURPOSE - it is the contract a linter checks against
|
|
80
|
+
* the signals the body reads (`NF-C023`). Auto-tracking would remove the array but reintroduce the
|
|
81
|
+
* exact "why didn't this update" bug that makes framework reactivity hard to get right.
|
|
82
|
+
*/
|
|
83
|
+
export function computed<T>(compute: () => T, deps: readonly Readable<unknown>[]): Readable<T> {
|
|
84
|
+
let value = compute()
|
|
85
|
+
const listeners = new Set<(value: T) => void>()
|
|
86
|
+
const recompute = (): void => {
|
|
87
|
+
const next = compute()
|
|
88
|
+
if (Object.is(next, value)) return
|
|
89
|
+
value = next
|
|
90
|
+
notify(listeners, value)
|
|
91
|
+
}
|
|
92
|
+
// A computed with a live subscriber must itself be subscribed to its deps; to keep the prototype
|
|
93
|
+
// simple it subscribes eagerly for its whole life (fine for the island-scoped, few-signal case).
|
|
94
|
+
for (const dep of deps) dep.subscribe(recompute)
|
|
95
|
+
return {
|
|
96
|
+
get: () => value,
|
|
97
|
+
subscribe(listener) {
|
|
98
|
+
listeners.add(listener)
|
|
99
|
+
return () => {
|
|
100
|
+
listeners.delete(listener)
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The three states of an async cell. A discriminated union on `status` so a consumer must handle
|
|
107
|
+
* every branch - there is no "value that might secretly be loading", the failure mode of ad-hoc
|
|
108
|
+
* `isLoading` booleans. `value`/`error` are narrowed by `status`. */
|
|
109
|
+
export type ResourceState<T> =
|
|
110
|
+
| { readonly status: "pending"; readonly value: undefined; readonly error: undefined }
|
|
111
|
+
| { readonly status: "ready"; readonly value: T; readonly error: undefined }
|
|
112
|
+
| { readonly status: "error"; readonly value: undefined; readonly error: unknown }
|
|
113
|
+
|
|
114
|
+
/** An async cell: a `Readable` of `ResourceState<T>` plus `refetch()`. This is nano's answer to
|
|
115
|
+
* "suspense" - an explicit pending/error/ready value, never a thrown promise or a magic boundary. */
|
|
116
|
+
export interface Resource<T> extends Readable<ResourceState<T>> {
|
|
117
|
+
refetch(): void
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* An async derived cell. `resource(fetcher, [deps])` runs `fetcher` immediately and again whenever a
|
|
122
|
+
* declared dependency changes, exposing the result as an explicit `{ status, value, error }`.
|
|
123
|
+
*
|
|
124
|
+
* Two footguns are handled here so they cannot be got wrong by hand:
|
|
125
|
+
* - Races: each run holds a generation; a stale run's resolution is dropped, and its `AbortSignal` is
|
|
126
|
+
* aborted, so an earlier-started-later-finishing fetch never overwrites a newer one.
|
|
127
|
+
* - Deps: like `computed`, dependencies are DECLARED (`NF-C023` checks the fetcher's `.get()` reads
|
|
128
|
+
* against the array). A `resource` that reads a signal its deps omit won't refetch when it changes.
|
|
129
|
+
*/
|
|
130
|
+
export function resource<T>(
|
|
131
|
+
fetcher: (signal: AbortSignal) => Promise<T>,
|
|
132
|
+
deps: readonly Readable<unknown>[] = [],
|
|
133
|
+
): Resource<T> {
|
|
134
|
+
const state = signal<ResourceState<T>>({ status: "pending", value: undefined, error: undefined })
|
|
135
|
+
let generation = 0
|
|
136
|
+
let controller: AbortController | undefined
|
|
137
|
+
const run = (): void => {
|
|
138
|
+
const mine = ++generation
|
|
139
|
+
controller?.abort()
|
|
140
|
+
controller = new AbortController()
|
|
141
|
+
const active = controller
|
|
142
|
+
state.set({ status: "pending", value: undefined, error: undefined })
|
|
143
|
+
fetcher(active.signal).then(
|
|
144
|
+
(value) => {
|
|
145
|
+
if (mine === generation) state.set({ status: "ready", value, error: undefined })
|
|
146
|
+
},
|
|
147
|
+
(error) => {
|
|
148
|
+
// A stale run (superseded) or one we aborted must not surface as an error state.
|
|
149
|
+
if (mine === generation && !active.signal.aborted)
|
|
150
|
+
state.set({ status: "error", value: undefined, error })
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
for (const dep of deps) dep.subscribe(run)
|
|
155
|
+
run()
|
|
156
|
+
return {
|
|
157
|
+
get: () => state.get(),
|
|
158
|
+
subscribe: (listener) => state.subscribe(listener),
|
|
159
|
+
refetch: run,
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Bind one element to a source: `apply(el, value)` runs once immediately and again on every change.
|
|
165
|
+
* Returns the unsubscribe - hand it back as the island's cleanup (or collect several).
|
|
166
|
+
*
|
|
167
|
+
* bind(count, remaining, (el, n) => { el.textContent = String(n) })
|
|
168
|
+
*/
|
|
169
|
+
export function bind<T>(
|
|
170
|
+
el: HTMLElement,
|
|
171
|
+
source: Readable<T>,
|
|
172
|
+
apply: (el: HTMLElement, value: T) => void,
|
|
173
|
+
): () => void {
|
|
174
|
+
apply(el, source.get())
|
|
175
|
+
return source.subscribe((value) => apply(el, value))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** How a `bindList` turns items into keyed DOM. `key` MUST be stable and unique per item (never the
|
|
179
|
+
* array index) - it is what lets add/remove/reorder touch only the changed rows. */
|
|
180
|
+
export interface BindListOptions<T> {
|
|
181
|
+
key(item: T): string | number
|
|
182
|
+
create(item: T): HTMLElement
|
|
183
|
+
update?(el: HTMLElement, item: T): void
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Bind a list signal to a container with keyed reconciliation: new items are `create`d, surviving
|
|
188
|
+
* items are `update`d in place (keeping focus, scroll, and selection), removed items are detached,
|
|
189
|
+
* and the children are ordered to match the array. Returns the unsubscribe.
|
|
190
|
+
*
|
|
191
|
+
* This is the one imperative task too error-prone to hand-write each time - it is why nano exists on
|
|
192
|
+
* top of islands rather than leaving you to rebuild the container on every change.
|
|
193
|
+
*/
|
|
194
|
+
export function bindList<T>(
|
|
195
|
+
source: Readable<readonly T[]>,
|
|
196
|
+
container: HTMLElement,
|
|
197
|
+
options: BindListOptions<T>,
|
|
198
|
+
): () => void {
|
|
199
|
+
let nodes = new Map<string | number, HTMLElement>()
|
|
200
|
+
const render = (items: readonly T[]): void => {
|
|
201
|
+
const next = new Map<string | number, HTMLElement>()
|
|
202
|
+
for (const item of items) {
|
|
203
|
+
const key = options.key(item)
|
|
204
|
+
const el = nodes.get(key) ?? options.create(item)
|
|
205
|
+
options.update?.(el, item)
|
|
206
|
+
next.set(key, el)
|
|
207
|
+
}
|
|
208
|
+
for (const [key, el] of nodes) if (!next.has(key)) el.remove()
|
|
209
|
+
// Append in item order; appending an already-attached node MOVES it, so the final order matches.
|
|
210
|
+
for (const item of items) container.appendChild(next.get(options.key(item)) as HTMLElement)
|
|
211
|
+
nodes = next
|
|
212
|
+
}
|
|
213
|
+
render(source.get())
|
|
214
|
+
return source.subscribe(render)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** How a `bindResource` maps each async state to the DOM. `ready` is required (there is always a
|
|
218
|
+
* success shape to render); `pending`/`error` are optional. Every branch is explicit - no hidden
|
|
219
|
+
* "still loading" state can slip through as a rendered `undefined`. */
|
|
220
|
+
export interface BindResourceHandlers<T> {
|
|
221
|
+
ready(el: HTMLElement, value: T): void
|
|
222
|
+
pending?(el: HTMLElement): void
|
|
223
|
+
error?(el: HTMLElement, error: unknown): void
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Bind an element to a `resource`, dispatching on `status`. Like `bind`, it applies immediately and
|
|
228
|
+
* on every change and returns the unsubscribe - collect it (a discarded disposer is `NF-C021`).
|
|
229
|
+
*
|
|
230
|
+
* bindResource(el, user, {
|
|
231
|
+
* pending: (n) => { n.textContent = "Loading…" },
|
|
232
|
+
* ready: (n, u) => { n.textContent = u.name },
|
|
233
|
+
* error: (n) => { n.textContent = "Failed to load" },
|
|
234
|
+
* })
|
|
235
|
+
*/
|
|
236
|
+
export function bindResource<T>(
|
|
237
|
+
el: HTMLElement,
|
|
238
|
+
source: Readable<ResourceState<T>>,
|
|
239
|
+
handlers: BindResourceHandlers<T>,
|
|
240
|
+
): () => void {
|
|
241
|
+
return bind(el, source, (node, state) => {
|
|
242
|
+
if (state.status === "pending") handlers.pending?.(node)
|
|
243
|
+
else if (state.status === "error") handlers.error?.(node, state.error)
|
|
244
|
+
else handlers.ready(node, state.value)
|
|
245
|
+
})
|
|
246
|
+
}
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* Not handled: the bare `:global`/`:local` *switch* form and `composes:` - out of scope by design.
|
|
21
21
|
*/
|
|
22
22
|
import type { BunPlugin } from "bun"
|
|
23
|
-
import { createStylesheetEmitter, hash8, reproduciblePath } from "./kit.ts"
|
|
23
|
+
import { createStylesheetEmitter, hash8, normalizeFilePath, reproduciblePath } from "./kit.ts"
|
|
24
24
|
|
|
25
25
|
const STYLE_NS = "nifra-css-module"
|
|
26
26
|
|
|
@@ -425,7 +425,7 @@ export function cssModulesBunPlugin(generate: "dom" | "ssr"): BunPlugin {
|
|
|
425
425
|
setup(build) {
|
|
426
426
|
const stylesheet = createStylesheetEmitter(build, STYLE_NS)
|
|
427
427
|
build.onLoad({ filter: /\.module\.css(\?|$)/ }, async (args) => {
|
|
428
|
-
const path = args.path
|
|
428
|
+
const path = normalizeFilePath(args.path)
|
|
429
429
|
const source = await Bun.file(path).text()
|
|
430
430
|
// Hash scoped names off the cwd-relative path so they're reproducible across machines/CI.
|
|
431
431
|
const { exports, css } = transformCssModule(source, reproduciblePath(path))
|
package/src/plugins/kit.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* `@nifrajs/web` (imported by the sibling plugin modules); not a public subpath.
|
|
6
6
|
*/
|
|
7
7
|
import { existsSync } from "node:fs"
|
|
8
|
-
import { dirname, relative } from "node:path"
|
|
8
|
+
import { dirname, join, relative } from "node:path"
|
|
9
|
+
import { fileURLToPath, pathToFileURL } from "node:url"
|
|
9
10
|
import type { BunPlugin } from "bun"
|
|
10
11
|
|
|
11
12
|
/** The argument Bun passes to a plugin's `setup` - Bun doesn't export the type, so derive it. */
|
|
@@ -23,6 +24,38 @@ export { rewriteSsrImports } from "../dev-ssr-graph.ts"
|
|
|
23
24
|
|
|
24
25
|
const packageRootCache = new Map<string, string>()
|
|
25
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Convert a plugin/runtime path into a path the host filesystem can open.
|
|
29
|
+
*
|
|
30
|
+
* Bun and URL-based test/build APIs can hand a Windows path to a plugin as `/D:/…` (the
|
|
31
|
+
* `pathname` form of a file URL). Node's filesystem APIs correctly treat the native form as
|
|
32
|
+
* `D:\…`, but do not reinterpret that URL pathname. Keep this conversion at the boundary so
|
|
33
|
+
* generated module specifiers can remain slash-normalized without making filesystem reads
|
|
34
|
+
* platform-dependent.
|
|
35
|
+
*/
|
|
36
|
+
export function normalizeFilePath(path: string): string {
|
|
37
|
+
let value = path.split("?", 1)[0] ?? path
|
|
38
|
+
if (value.startsWith("file://")) {
|
|
39
|
+
try {
|
|
40
|
+
value = fileURLToPath(value)
|
|
41
|
+
} catch {
|
|
42
|
+
// Preserve malformed URL-shaped input. Converting it with Windows slash rules would turn
|
|
43
|
+
// `file://%` into a plausible-looking local path (`file:\\%`) and hide the actual bad specifier.
|
|
44
|
+
return value
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (process.platform === "win32") {
|
|
48
|
+
if (/^\/[A-Za-z]:[\\/]/.test(value)) value = value.slice(1)
|
|
49
|
+
return value.replaceAll("/", "\\")
|
|
50
|
+
}
|
|
51
|
+
return value
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A stable slash-separated path for generated imports, virtual module IDs, and diagnostics. */
|
|
55
|
+
export function portablePath(path: string): string {
|
|
56
|
+
return normalizeFilePath(path).replaceAll("\\", "/")
|
|
57
|
+
}
|
|
58
|
+
|
|
26
59
|
/** The nearest ancestor directory of `startDir` that holds a `package.json` (the file's package root),
|
|
27
60
|
* cached. Falls back to `startDir` if none is found, so it never throws. */
|
|
28
61
|
function packageRootOf(startDir: string): string {
|
|
@@ -30,7 +63,7 @@ function packageRootOf(startDir: string): string {
|
|
|
30
63
|
if (cached !== undefined) return cached
|
|
31
64
|
let dir = startDir
|
|
32
65
|
for (;;) {
|
|
33
|
-
if (existsSync(
|
|
66
|
+
if (existsSync(join(dir, "package.json"))) break
|
|
34
67
|
const parent = dirname(dir)
|
|
35
68
|
if (parent === dir) {
|
|
36
69
|
dir = startDir // reached the filesystem root with no package.json - anchor on the file's own dir
|
|
@@ -52,8 +85,9 @@ function packageRootOf(startDir: string): string {
|
|
|
52
85
|
* cwd-relative path would silently desync if the SSR server started from a non-project-root cwd.)
|
|
53
86
|
*/
|
|
54
87
|
export function reproduciblePath(absolutePath: string): string {
|
|
55
|
-
const
|
|
56
|
-
|
|
88
|
+
const filePath = normalizeFilePath(absolutePath)
|
|
89
|
+
const root = packageRootOf(dirname(filePath))
|
|
90
|
+
return relative(root, filePath).replaceAll("\\", "/")
|
|
57
91
|
}
|
|
58
92
|
|
|
59
93
|
/**
|
|
@@ -100,7 +134,14 @@ export const DEV_ROUTES_ENV = "NIFRA_DEV_ROUTES"
|
|
|
100
134
|
const under = (path: string, dir: string | undefined): boolean =>
|
|
101
135
|
dir !== undefined &&
|
|
102
136
|
dir !== "" &&
|
|
103
|
-
(
|
|
137
|
+
(() => {
|
|
138
|
+
const normalizedPath = portablePath(path)
|
|
139
|
+
const normalizedDir = portablePath(dir)
|
|
140
|
+
return (
|
|
141
|
+
normalizedPath === normalizedDir ||
|
|
142
|
+
normalizedPath.startsWith(normalizedDir.endsWith("/") ? normalizedDir : `${normalizedDir}/`)
|
|
143
|
+
)
|
|
144
|
+
})()
|
|
104
145
|
|
|
105
146
|
/**
|
|
106
147
|
* Whether a dev compile of `path` may wrap the module in component-level hot-patching - i.e. whether it
|
|
@@ -124,7 +165,7 @@ const under = (path: string, dir: string | undefined): boolean =>
|
|
|
124
165
|
export function devHotComponent(path: string): boolean {
|
|
125
166
|
const root = process.env[DEV_ROOT_ENV]
|
|
126
167
|
if (!under(path, root)) return false
|
|
127
|
-
if (path.includes("/node_modules/")) return false
|
|
168
|
+
if (portablePath(path).includes("/node_modules/")) return false
|
|
128
169
|
return !under(path, process.env[DEV_ROUTES_ENV])
|
|
129
170
|
}
|
|
130
171
|
|
|
@@ -151,17 +192,20 @@ export function createStylesheetEmitter(
|
|
|
151
192
|
const cssByPath = new Map<string, string>()
|
|
152
193
|
// `\?${namespace}$`: namespaces are plain identifiers, so no regex metachars to escape.
|
|
153
194
|
build.onResolve({ filter: new RegExp(`\\?${namespace}$`) }, (args) => ({
|
|
154
|
-
path
|
|
195
|
+
// Bun may hand this hook a native Windows path while the emitter stores portable module IDs.
|
|
196
|
+
// Normalize the path portion but preserve the virtual namespace suffix.
|
|
197
|
+
path: `${portablePath(args.path.slice(0, -suffix.length))}${suffix}`,
|
|
155
198
|
namespace,
|
|
156
199
|
}))
|
|
157
200
|
build.onLoad({ filter: /.*/, namespace }, (args) => ({
|
|
158
|
-
contents: cssByPath.get(args.path.slice(0, -suffix.length)) ?? "",
|
|
201
|
+
contents: cssByPath.get(portablePath(args.path.slice(0, -suffix.length))) ?? "",
|
|
159
202
|
loader: "css",
|
|
160
203
|
}))
|
|
161
204
|
return {
|
|
162
205
|
emit(path, css) {
|
|
163
|
-
|
|
164
|
-
|
|
206
|
+
const filePath = portablePath(path)
|
|
207
|
+
cssByPath.set(filePath, css)
|
|
208
|
+
return `import ${JSON.stringify(filePath + suffix)}\n`
|
|
165
209
|
},
|
|
166
210
|
}
|
|
167
211
|
}
|
|
@@ -175,13 +219,22 @@ export async function requirePeer<T>(
|
|
|
175
219
|
specifier: string,
|
|
176
220
|
hint: { readonly feature: string; readonly install: string },
|
|
177
221
|
): Promise<T> {
|
|
222
|
+
const isPathSpecifier =
|
|
223
|
+
specifier.startsWith("file://") ||
|
|
224
|
+
/^\/[A-Za-z]:[\\/]/.test(specifier) ||
|
|
225
|
+
/^[A-Za-z]:[\\/]/.test(specifier)
|
|
178
226
|
try {
|
|
179
|
-
|
|
227
|
+
// Dynamic import treats a Windows URL pathname (`/D:/…`) as a POSIX root. Convert local path
|
|
228
|
+
// seams to a file URL so the runtime, regardless of platform, receives an unambiguous module ID.
|
|
229
|
+
const importPath = isPathSpecifier
|
|
230
|
+
? pathToFileURL(normalizeFilePath(specifier)).href
|
|
231
|
+
: specifier
|
|
232
|
+
return (await import(importPath)) as T
|
|
180
233
|
} catch (err) {
|
|
181
234
|
// Only a genuine resolution failure means "not installed" - surface anything else (a corrupt
|
|
182
235
|
// install, a native-binding error, a throw at module top-level) as the real error rather than
|
|
183
236
|
// masking it behind a misleading "please install it" hint.
|
|
184
|
-
if ((err as { code?: unknown }).code === "ERR_MODULE_NOT_FOUND") {
|
|
237
|
+
if (!isPathSpecifier && (err as { code?: unknown }).code === "ERR_MODULE_NOT_FOUND") {
|
|
185
238
|
throw new Error(
|
|
186
239
|
`[nifra/web] ${hint.feature} requires the optional peer "${specifier}". Install it: ${hint.install}`,
|
|
187
240
|
)
|
package/src/plugins/postcss.ts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import type { BunPlugin } from "bun"
|
|
20
20
|
import { transformCssModule } from "./css-modules.ts"
|
|
21
|
-
import { createStylesheetEmitter, reproduciblePath, requirePeer } from "./kit.ts"
|
|
21
|
+
import { createStylesheetEmitter, normalizeFilePath, reproduciblePath, requirePeer } from "./kit.ts"
|
|
22
22
|
|
|
23
23
|
const STYLE_NS = "nifra-postcss"
|
|
24
24
|
|
|
@@ -93,7 +93,7 @@ export function postcssBunPlugin(
|
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
build.onLoad({ filter: CSS_FILTER }, async (args) => {
|
|
96
|
-
const path = args.path
|
|
96
|
+
const path = normalizeFilePath(args.path)
|
|
97
97
|
const source = await Bun.file(path).text()
|
|
98
98
|
const postcss = await getProcessor()
|
|
99
99
|
const plugins = await getPlugins()
|
package/src/plugins/scss.ts
CHANGED
|
@@ -17,7 +17,7 @@ import { dirname } from "node:path"
|
|
|
17
17
|
import { pathToFileURL } from "node:url"
|
|
18
18
|
import type { BunPlugin } from "bun"
|
|
19
19
|
import { transformCssModule } from "./css-modules.ts"
|
|
20
|
-
import { createStylesheetEmitter, reproduciblePath, requirePeer } from "./kit.ts"
|
|
20
|
+
import { createStylesheetEmitter, normalizeFilePath, reproduciblePath, requirePeer } from "./kit.ts"
|
|
21
21
|
|
|
22
22
|
const STYLE_NS = "nifra-scss"
|
|
23
23
|
|
|
@@ -65,7 +65,7 @@ export function scssBunPlugin(generate: "dom" | "ssr", options: ScssPluginOption
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
build.onLoad({ filter: /\.s[ac]ss(\?|$)/ }, async (args) => {
|
|
68
|
-
const path = args.path
|
|
68
|
+
const path = normalizeFilePath(args.path)
|
|
69
69
|
const source = await Bun.file(path).text()
|
|
70
70
|
const sass = await getCompiler()
|
|
71
71
|
let css: string
|