@hamur/adapter-svelte 0.0.0-stage → 0.0.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.
- package/LICENSE +22 -0
- package/README.md +31 -2
- package/dist/chunks/browser-index-324qgh1c.js +190 -0
- package/dist/chunks/browser-index-evqp5a71.js +64 -0
- package/dist/chunks/browser-index-xc6081e3.js +9 -0
- package/dist/src/adapter.js +480 -0
- package/dist/src/index.js +1161 -0
- package/dist/src/runtime/client.js +65 -0
- package/dist/src/runtime/island.js +72 -0
- package/dist/src/runtime/server.js +142 -0
- package/dist/types/src/activation.d.ts +15 -0
- package/dist/types/src/adapter.d.ts +2 -0
- package/dist/types/src/async-data.d.ts +21 -0
- package/dist/types/src/boundary-error.d.ts +9 -0
- package/dist/types/src/client-only.d.ts +6 -0
- package/dist/types/src/context.d.ts +87 -0
- package/dist/types/src/deferred.svelte.d.ts +6 -0
- package/dist/types/src/effect.svelte.d.ts +2 -0
- package/dist/types/src/hydrating.d.ts +4 -0
- package/dist/types/src/index.d.ts +270 -0
- package/dist/types/src/island-html.d.ts +13 -0
- package/dist/types/src/keepalive.d.ts +11 -0
- package/dist/types/src/lazy-hydration.d.ts +25 -0
- package/dist/types/src/markdown-page.d.ts +9 -0
- package/dist/types/src/plugin.d.ts +52 -0
- package/dist/types/src/runtime/client.d.ts +12 -0
- package/dist/types/src/runtime/hmr.d.ts +28 -0
- package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
- package/dist/types/src/runtime/hydration.d.ts +8 -0
- package/dist/types/src/runtime/island.d.ts +8 -0
- package/dist/types/src/runtime/server.d.ts +12 -0
- package/dist/types/src/server-component.d.ts +3 -0
- package/dist/types/src/store.d.ts +7 -0
- package/dist/types/src/svg.d.ts +10 -0
- package/package.json +43 -4
- package/src/Announcer.svelte +26 -0
- package/src/Await.svelte +43 -0
- package/src/AwaitAsync.svelte +42 -0
- package/src/BodyAttrs.svelte +7 -0
- package/src/Caught.svelte +41 -0
- package/src/ClientComponent.svelte +35 -0
- package/src/ClientFallback.svelte +46 -0
- package/src/ClientOnly.svelte +22 -0
- package/src/DefaultErrorPage.svelte +15 -0
- package/src/DevOnly.svelte +12 -0
- package/src/ErrorBoundary.svelte +14 -0
- package/src/FallbackEffect.svelte +9 -0
- package/src/Form.svelte +96 -0
- package/src/HeadLink.svelte +7 -0
- package/src/HeadMeta.svelte +7 -0
- package/src/HeadScript.svelte +7 -0
- package/src/HeadStyle.svelte +7 -0
- package/src/HeadTitle.svelte +6 -0
- package/src/HtmlAttrs.svelte +7 -0
- package/src/HttpHeader.svelte +7 -0
- package/src/HttpStatusCode.svelte +7 -0
- package/src/Island.svelte +59 -0
- package/src/IslandChildren.svelte +7 -0
- package/src/KeptOutlet.svelte +46 -0
- package/src/KeptPage.svelte +55 -0
- package/src/LazyHydration.svelte +54 -0
- package/src/Link.svelte +209 -0
- package/src/LoadingIndicator.svelte +18 -0
- package/src/MarkdownNodes.svelte +36 -0
- package/src/MarkdownRenderer.svelte +20 -0
- package/src/MarkdownSlots.svelte +33 -0
- package/src/Navigate.svelte +10 -0
- package/src/Nest.svelte +83 -0
- package/src/Outlet.svelte +31 -0
- package/src/Rethrow.svelte +7 -0
- package/src/Root.svelte +29 -0
- package/src/RouteAnnouncer.svelte +47 -0
- package/src/Scoped.svelte +11 -0
- package/src/ServerComponent.svelte +19 -0
- package/src/ServerComponentClient.svelte +64 -0
- package/src/ServerIsland.svelte +26 -0
- package/src/Slotted.svelte +11 -0
- package/src/Thrown.svelte +9 -0
- package/src/Time.svelte +23 -0
- package/src/activation.ts +51 -0
- package/src/adapter.ts +24 -0
- package/src/async-data.ts +105 -0
- package/src/boundary-error.ts +77 -0
- package/src/client-only.ts +8 -0
- package/src/context.ts +227 -0
- package/src/deferred.svelte.ts +33 -0
- package/src/effect.svelte.ts +7 -0
- package/src/env.d.ts +3 -0
- package/src/hydrating.ts +18 -0
- package/src/index.ts +1337 -0
- package/src/island-html.ts +58 -0
- package/src/keepalive.ts +12 -0
- package/src/lazy-hydration.ts +89 -0
- package/src/markdown-page.ts +17 -0
- package/src/plugin.ts +558 -0
- package/src/runtime/client.ts +61 -0
- package/src/runtime/hmr.ts +177 -0
- package/src/runtime/hydration-dev.ts +22 -0
- package/src/runtime/hydration.ts +7 -0
- package/src/runtime/island.ts +94 -0
- package/src/runtime/server.ts +87 -0
- package/src/server-component.ts +13 -0
- package/src/store.ts +31 -0
- package/src/svelte.d.ts +5 -0
- package/src/svg.ts +30 -0
- package/src/webmcp.d.ts +18 -0
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
import type { BunPlugin } from "bun"
|
|
2
|
+
import { realpathSync } from "node:fs"
|
|
3
|
+
import { join, relative } from "node:path"
|
|
4
|
+
import type { AdapterBuildContext, AdapterTransform } from "hamur/adapter"
|
|
5
|
+
import { DiagnosticError } from "hamur/kit"
|
|
6
|
+
import { compile, compileModule, parse, preprocess } from "svelte/compiler"
|
|
7
|
+
|
|
8
|
+
const STYLE_NS = "hamur-svelte-style"
|
|
9
|
+
const HMR_RUNTIME = join(import.meta.dir, "runtime/hmr.ts")
|
|
10
|
+
const CLIENT_RUNTIME = join(import.meta.dir, "runtime/client.ts")
|
|
11
|
+
const HYDRATION_DEV = join(import.meta.dir, "runtime/hydration-dev.ts")
|
|
12
|
+
const AWAIT = join(import.meta.dir, "Await.svelte")
|
|
13
|
+
const AWAIT_ASYNC = join(import.meta.dir, "AwaitAsync.svelte")
|
|
14
|
+
const PREPROCESSED: Record<string, string> = {
|
|
15
|
+
scss: "sass",
|
|
16
|
+
sass: "sass",
|
|
17
|
+
less: "less",
|
|
18
|
+
styl: "stylus",
|
|
19
|
+
stylus: "stylus",
|
|
20
|
+
}
|
|
21
|
+
const STYLE_TAG = /<style\b([^>]*)>/g
|
|
22
|
+
const LANG_ATTRIBUTE = /\blang\s*=\s*["']?(\w+)/
|
|
23
|
+
const STYLE_BLOCK = /(<style\b[^>]*>)([\s\S]*?)(<\/style>)/g
|
|
24
|
+
const DEFAULT_EXPORT = /^export default (\w+);$/gm
|
|
25
|
+
/** Imports whose namespace says nothing about code: Svelte itself, Hamur's virtual modules, styles, assets and data. */
|
|
26
|
+
const NOT_A_MODULE =
|
|
27
|
+
/^svelte(?:\/|$)|^#hamur\/|\.(?:css|scss|sass|less|styl|svg|png|jpe?g|gif|webp|avif|ico|json|txt|md|wasm|html)(?:\?.*)?$|\?/i
|
|
28
|
+
|
|
29
|
+
interface MarkupNode {
|
|
30
|
+
type?: string
|
|
31
|
+
name?: string
|
|
32
|
+
data?: string
|
|
33
|
+
start: number
|
|
34
|
+
end: number
|
|
35
|
+
expression?: { name?: string }
|
|
36
|
+
fragment?: { nodes: MarkupNode[] }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The local names under which a script imports `DevOnly` from this adapter. */
|
|
40
|
+
function devOnlyNames(source: string): Set<string> {
|
|
41
|
+
const names = new Set<string>()
|
|
42
|
+
for (const found of source.matchAll(/import\s*\{([^}]*)\}\s*from\s*["']@hamur\/adapter-svelte["']/g)) {
|
|
43
|
+
for (const part of found[1]!.split(",")) {
|
|
44
|
+
const [imported, local = imported] = part
|
|
45
|
+
.trim()
|
|
46
|
+
.split(/\s+as\s+/)
|
|
47
|
+
.map((name) => name.trim())
|
|
48
|
+
if (imported === "DevOnly" && local) names.add(local)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return names
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Production: empties every `<DevOnly>` of the markup except its `fallback` snippet; the removed text leaves its line breaks. */
|
|
55
|
+
export function dropDevOnlyMarkup(source: string): string {
|
|
56
|
+
const names = devOnlyNames(source)
|
|
57
|
+
if (!names.size) return source
|
|
58
|
+
let root: { fragment: unknown }
|
|
59
|
+
try {
|
|
60
|
+
root = parse(source, { modern: true }) as unknown as typeof root
|
|
61
|
+
} catch {
|
|
62
|
+
return source
|
|
63
|
+
}
|
|
64
|
+
const cuts: Array<[number, number]> = []
|
|
65
|
+
const seen = new Set<object>()
|
|
66
|
+
const visit = (node: unknown): void => {
|
|
67
|
+
if (typeof node !== "object" || node === null || seen.has(node)) return
|
|
68
|
+
seen.add(node)
|
|
69
|
+
if (Array.isArray(node)) return node.forEach(visit)
|
|
70
|
+
const element = node as MarkupNode
|
|
71
|
+
if (element.type === "Component" && element.name !== undefined && names.has(element.name) && element.fragment) {
|
|
72
|
+
for (const child of element.fragment.nodes) {
|
|
73
|
+
if (child.type === "SnippetBlock" && child.expression?.name === "fallback") visit(child)
|
|
74
|
+
else cuts.push([child.start, child.end])
|
|
75
|
+
}
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
for (const [key, value] of Object.entries(node)) if (key !== "metadata" && key !== "parent") visit(value)
|
|
79
|
+
}
|
|
80
|
+
visit(root.fragment)
|
|
81
|
+
let out = source
|
|
82
|
+
for (const [start, end] of cuts.sort((a, b) => b[0] - a[0]))
|
|
83
|
+
out = `${out.slice(0, start)}${out.slice(start, end).replace(/[^\n]/g, "")}${out.slice(end)}`
|
|
84
|
+
return out
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The source locator, dev only: gives the markup's single root element, when it is a plain HTML element, `data-hamur-src="<file>:<line>:<column>"`.
|
|
89
|
+
* The insertion stays on its line, so no line moves; a source that does not parse is returned as it is.
|
|
90
|
+
*/
|
|
91
|
+
export function locateRootElement(source: string, file: string): string {
|
|
92
|
+
let root: { fragment: { nodes: MarkupNode[] } }
|
|
93
|
+
try {
|
|
94
|
+
const scriptsOnly = source.replace(
|
|
95
|
+
STYLE_BLOCK,
|
|
96
|
+
(_, open: string, body: string, close: string) => `${open}${body.replace(/[^\n]/g, " ")}${close}`,
|
|
97
|
+
)
|
|
98
|
+
root = parse(scriptsOnly, { filename: file, modern: true }) as unknown as typeof root
|
|
99
|
+
} catch {
|
|
100
|
+
return source
|
|
101
|
+
}
|
|
102
|
+
const significant = root.fragment.nodes.filter((node) =>
|
|
103
|
+
node.type === "Text" ? (node.data ?? "").trim() !== "" : node.type !== "Comment" && node.type !== "SnippetBlock",
|
|
104
|
+
)
|
|
105
|
+
const [node] = significant
|
|
106
|
+
if (significant.length !== 1 || node!.type !== "RegularElement") return source
|
|
107
|
+
const before = source.slice(0, node!.start)
|
|
108
|
+
const line = before.split("\n").length
|
|
109
|
+
const column = node!.start - (before.lastIndexOf("\n") + 1) + 1
|
|
110
|
+
const at = node!.start + 1 + node!.name!.length
|
|
111
|
+
return `${source.slice(0, at)} data-hamur-src="${file}:${line}:${column}"${source.slice(at)}`
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const ESM_ENV_IMPORT = /import\s*\{([^}]*)\}\s*from\s*(["'])esm-env\2\s*;?/g
|
|
115
|
+
const ESM_ENV_VALUES: Record<string, string> = { DEV: "false", BROWSER: "true", NODE: "false" }
|
|
116
|
+
|
|
117
|
+
/** A production client reads svelte's `DEV`, `BROWSER` and `NODE` as constants, so the minifier drops the dev branches. */
|
|
118
|
+
export function foldEsmEnv(source: string): string {
|
|
119
|
+
return source.replace(ESM_ENV_IMPORT, (whole, list: string) => {
|
|
120
|
+
const declarations: string[] = []
|
|
121
|
+
for (const part of list.split(",")) {
|
|
122
|
+
if (part.trim() === "") continue
|
|
123
|
+
const match = /^\s*(\w+)(?:\s+as\s+(\w+))?\s*$/.exec(part)
|
|
124
|
+
const value = match && ESM_ENV_VALUES[match[1]!]
|
|
125
|
+
if (!match || value === undefined) return whole
|
|
126
|
+
declarations.push(`${match[2] ?? match[1]} = ${value}`)
|
|
127
|
+
}
|
|
128
|
+
return declarations.length === 0 ? whole : `const ${declarations.join(", ")};`
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
interface SvelteDiagnostic {
|
|
133
|
+
message: string
|
|
134
|
+
code?: string
|
|
135
|
+
start?: { line: number; column: number }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Bun places a plugin's thrown error at `0:0`, so the place goes in the message. */
|
|
139
|
+
function located(
|
|
140
|
+
error: unknown,
|
|
141
|
+
path: string,
|
|
142
|
+
source: string,
|
|
143
|
+
rootDir: string | undefined,
|
|
144
|
+
lineOf: (line: number) => number = (line) => line,
|
|
145
|
+
): unknown {
|
|
146
|
+
const { message, code, start: compiled } = (error ?? {}) as Partial<SvelteDiagnostic>
|
|
147
|
+
if (typeof message !== "string" || typeof compiled?.line !== "number" || typeof compiled.column !== "number")
|
|
148
|
+
return error
|
|
149
|
+
const start = { line: lineOf(compiled.line), column: compiled.column }
|
|
150
|
+
const shown = rootDir === undefined ? path : relative(rootDir, path)
|
|
151
|
+
const file = shown === "" || shown.startsWith("..") ? path : shown.split("\\").join("/")
|
|
152
|
+
// Svelte's line is 1-based and its column 0-based.
|
|
153
|
+
const column = start.column + 1
|
|
154
|
+
const [first, ...rest] = message.split("\n")
|
|
155
|
+
const lineText = source.split(/\r?\n/)[start.line - 1]
|
|
156
|
+
const lines = [`${file}:${start.line}:${column}: ${first}`]
|
|
157
|
+
if (lineText !== undefined) {
|
|
158
|
+
const gutter = String(start.line)
|
|
159
|
+
const pad = [...lineText.slice(0, start.column)].map((char) => (char === "\t" ? "\t" : " ")).join("")
|
|
160
|
+
lines.push(` ${gutter} | ${lineText}`, ` ${" ".repeat(gutter.length)} | ${pad}^`)
|
|
161
|
+
}
|
|
162
|
+
return Object.assign(new Error([...lines, ...rest].join("\n"), { cause: error }), code === undefined ? {} : { code })
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
interface RawMap {
|
|
166
|
+
version: number
|
|
167
|
+
sources: string[]
|
|
168
|
+
sourcesContent?: string[]
|
|
169
|
+
mappings: string
|
|
170
|
+
names: string[]
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** `code` ends with its map, pointing at `written` (the file as authored) under its path relative to `rootDir`; `shift` empty lines were put above the compiled code. */
|
|
174
|
+
export function withInlineMap(
|
|
175
|
+
code: string,
|
|
176
|
+
map: RawMap | null,
|
|
177
|
+
path: string,
|
|
178
|
+
written: string,
|
|
179
|
+
rootDir: string,
|
|
180
|
+
shift = 0,
|
|
181
|
+
): string {
|
|
182
|
+
if (!map) return code
|
|
183
|
+
const file = relative(rootDir, path).split("\\").join("/")
|
|
184
|
+
const inline = { ...map, sources: [file], sourcesContent: [written], mappings: ";".repeat(shift) + map.mappings }
|
|
185
|
+
return `${code}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(inline)).toString("base64")}`
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const ASYNC_HINT = "Svelte async SSR is experimental: set experimental.svelteAsync: true"
|
|
189
|
+
|
|
190
|
+
/** Svelte's own `experimental_async` error, followed by the line naming the key. */
|
|
191
|
+
function hinted(error: unknown): unknown {
|
|
192
|
+
if ((error as Partial<SvelteDiagnostic> | null)?.code !== "experimental_async") return error
|
|
193
|
+
;(error as Error).message += `\n${ASYNC_HINT}`
|
|
194
|
+
return error
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** A component whose style blocks went through `preprocessStyle`: `code` is what `compile` reads, `original` what it was made from, `lineOf` takes a line of `code` back to `original`. */
|
|
198
|
+
export interface Preprocessed {
|
|
199
|
+
code: string
|
|
200
|
+
original: string
|
|
201
|
+
map: string | object | undefined
|
|
202
|
+
lineOf(line: number): number
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** `<style lang="scss" | "sass" | "less" | "styl" | "stylus">` blocks go through the build's style preprocessor, `undefined` when no block needs one. */
|
|
206
|
+
export async function preprocessStyles(
|
|
207
|
+
source: string,
|
|
208
|
+
path: string,
|
|
209
|
+
preprocessStyle: AdapterBuildContext["preprocessStyle"],
|
|
210
|
+
): Promise<Preprocessed | undefined> {
|
|
211
|
+
const langs = [...source.matchAll(STYLE_TAG)]
|
|
212
|
+
.map((tag) => LANG_ATTRIBUTE.exec(tag[1]!)?.[1])
|
|
213
|
+
.filter((lang): lang is string => lang !== undefined && lang in PREPROCESSED)
|
|
214
|
+
if (langs.length === 0) return undefined
|
|
215
|
+
const lines = (text: string) => text.split("\n").length - 1
|
|
216
|
+
const blocks: Array<{ line: number; before: number; after: number }> = []
|
|
217
|
+
let cursor = 0
|
|
218
|
+
const processed = await preprocess(
|
|
219
|
+
source,
|
|
220
|
+
{
|
|
221
|
+
name: "hamur-style",
|
|
222
|
+
async style({ content, attributes }) {
|
|
223
|
+
const at = source.indexOf(content, cursor)
|
|
224
|
+
cursor = at + content.length
|
|
225
|
+
const lang = String(attributes.lang ?? "")
|
|
226
|
+
if (!(lang in PREPROCESSED)) return undefined
|
|
227
|
+
if (!preprocessStyle)
|
|
228
|
+
throw new DiagnosticError(
|
|
229
|
+
"HAMUR_E4201",
|
|
230
|
+
`<style lang="${lang}"> needs the @hamur/css module: install @hamur/css and ${PREPROCESSED[lang]} and add "@hamur/css" to modules`,
|
|
231
|
+
)
|
|
232
|
+
const line = lines(source.slice(0, at)) + 1
|
|
233
|
+
const css = await preprocessStyle({ lang, code: content, file: path })
|
|
234
|
+
blocks.push({ line, before: lines(content), after: lines(css.code) })
|
|
235
|
+
return { code: css.code, dependencies: css.dependencies }
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
{ filename: path },
|
|
239
|
+
)
|
|
240
|
+
const lineOf = (line: number) => {
|
|
241
|
+
let shift = 0
|
|
242
|
+
for (const block of blocks.sort((a, b) => a.line - b.line)) {
|
|
243
|
+
const from = block.line + shift
|
|
244
|
+
if (line < from) break
|
|
245
|
+
if (line < from + block.after) return block.line
|
|
246
|
+
shift += block.after - block.before
|
|
247
|
+
}
|
|
248
|
+
return line - shift
|
|
249
|
+
}
|
|
250
|
+
return { code: processed.code, original: source, map: processed.map, lineOf }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function compileSvelte(
|
|
254
|
+
path: string,
|
|
255
|
+
source: string,
|
|
256
|
+
target: "client" | "server",
|
|
257
|
+
hmr = false,
|
|
258
|
+
rootDir?: string,
|
|
259
|
+
svelteAsync = false,
|
|
260
|
+
preprocessed?: Preprocessed,
|
|
261
|
+
dev = false,
|
|
262
|
+
) {
|
|
263
|
+
try {
|
|
264
|
+
const result = compile(source, {
|
|
265
|
+
filename: path,
|
|
266
|
+
generate: target,
|
|
267
|
+
css: "external",
|
|
268
|
+
dev,
|
|
269
|
+
hmr,
|
|
270
|
+
...(preprocessed?.map ? { sourcemap: preprocessed.map } : {}),
|
|
271
|
+
...(svelteAsync ? { experimental: { async: true } } : {}),
|
|
272
|
+
})
|
|
273
|
+
return { code: result.js.code, css: result.css?.code, map: result.js.map as unknown as RawMap | null }
|
|
274
|
+
} catch (error) {
|
|
275
|
+
throw located(
|
|
276
|
+
svelteAsync ? error : hinted(error),
|
|
277
|
+
path,
|
|
278
|
+
preprocessed?.original ?? source,
|
|
279
|
+
rootDir,
|
|
280
|
+
preprocessed?.lineOf,
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function compileSvelteModule(
|
|
286
|
+
path: string,
|
|
287
|
+
source: string,
|
|
288
|
+
target: "client" | "server",
|
|
289
|
+
rootDir?: string,
|
|
290
|
+
svelteAsync = false,
|
|
291
|
+
dev = false,
|
|
292
|
+
): string {
|
|
293
|
+
const js = path.endsWith(".ts") ? new Bun.Transpiler({ loader: "ts" }).transformSync(source) : source
|
|
294
|
+
try {
|
|
295
|
+
return compileModule(js, {
|
|
296
|
+
filename: path,
|
|
297
|
+
generate: target,
|
|
298
|
+
dev,
|
|
299
|
+
...(svelteAsync ? { experimental: { async: true } } : {}),
|
|
300
|
+
}).js.code
|
|
301
|
+
} catch (error) {
|
|
302
|
+
throw located(svelteAsync ? error : hinted(error), path, js, rootDir)
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The module's path relative to `rootDir` when it is an app source (not under `node_modules` or the build dir). */
|
|
307
|
+
export function appModuleId(rootDir: string, buildDir: string): (path: string) => string | undefined {
|
|
308
|
+
let real = rootDir
|
|
309
|
+
try {
|
|
310
|
+
real = realpathSync(rootDir)
|
|
311
|
+
} catch {}
|
|
312
|
+
const roots = [...new Set([rootDir, real])]
|
|
313
|
+
const build = relative(rootDir, buildDir)
|
|
314
|
+
const inBuild = (id: string) =>
|
|
315
|
+
build !== "" && !build.startsWith("..") && (id === build || id.startsWith(`${build}/`))
|
|
316
|
+
return (path) => {
|
|
317
|
+
if (path.includes("/node_modules/")) return undefined
|
|
318
|
+
for (const root of roots) {
|
|
319
|
+
const id = relative(root, path)
|
|
320
|
+
if (!id.startsWith("..") && !id.startsWith("/")) return inBuild(id) ? undefined : id
|
|
321
|
+
}
|
|
322
|
+
return undefined
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
interface Node {
|
|
327
|
+
type: string
|
|
328
|
+
start: number
|
|
329
|
+
end: number
|
|
330
|
+
[key: string]: any
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** `$state(…)` or `$state.raw(…)`: the rune a recorded state is created by. */
|
|
334
|
+
function stateRune(init: Node | null): string | undefined {
|
|
335
|
+
if (init?.type !== "CallExpression") return undefined
|
|
336
|
+
const { callee } = init
|
|
337
|
+
if (callee.type === "Identifier" && callee.name === "$state") return "$state"
|
|
338
|
+
if (
|
|
339
|
+
callee.type === "MemberExpression" &&
|
|
340
|
+
!callee.computed &&
|
|
341
|
+
callee.object.type === "Identifier" &&
|
|
342
|
+
callee.object.name === "$state" &&
|
|
343
|
+
callee.property.name === "raw"
|
|
344
|
+
)
|
|
345
|
+
return "$state.raw"
|
|
346
|
+
return undefined
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Numbers the recorded states of a component (top-level `$state`/`$state.raw` declarators with an
|
|
351
|
+
* identifier), routes their initial values through the hot runtime and starts the module script with the module's
|
|
352
|
+
* `hotModule` call. Every insertion stays on its line, so line numbers do not move. Returns `source` when it does not parse.
|
|
353
|
+
*/
|
|
354
|
+
export function hotTransform(source: string, file: string, rootDir: string, runtime = HMR_RUNTIME): string {
|
|
355
|
+
let ast: { instance: Node | null; module: Node | null }
|
|
356
|
+
try {
|
|
357
|
+
// Svelte parses a <style> block as CSS and throws on Sass or Less text; blanking it keeps every script offset.
|
|
358
|
+
const scriptsOnly = source.replace(
|
|
359
|
+
STYLE_BLOCK,
|
|
360
|
+
(_, open: string, body: string, close: string) => `${open}${body.replace(/[^\n]/g, " ")}${close}`,
|
|
361
|
+
)
|
|
362
|
+
ast = parse(scriptsOnly, { filename: file, modern: true }) as unknown as typeof ast
|
|
363
|
+
} catch {
|
|
364
|
+
return source
|
|
365
|
+
}
|
|
366
|
+
const { instance, module } = ast
|
|
367
|
+
const edits: Array<{ at: number; end?: number; text: string }> = []
|
|
368
|
+
const names: string[] = []
|
|
369
|
+
const signature: string[] = []
|
|
370
|
+
for (const statement of (instance?.content.body ?? []) as Node[]) {
|
|
371
|
+
if (statement.type !== "VariableDeclaration") continue
|
|
372
|
+
for (const declarator of statement.declarations as Node[]) {
|
|
373
|
+
const rune = stateRune(declarator.init)
|
|
374
|
+
if (declarator.id.type !== "Identifier" || !rune) continue
|
|
375
|
+
const args = declarator.init!.arguments as Node[]
|
|
376
|
+
const i = names.length
|
|
377
|
+
names.push(declarator.id.name)
|
|
378
|
+
signature.push(
|
|
379
|
+
`${declarator.id.name}=${rune}(${args.length ? source.slice(args[0]!.start, args.at(-1)!.end) : ""})`,
|
|
380
|
+
)
|
|
381
|
+
if (args.length)
|
|
382
|
+
edits.push({
|
|
383
|
+
at: args[0]!.start,
|
|
384
|
+
end: args[0]!.end,
|
|
385
|
+
text: `__hamurHotI.take(${i}, (${source.slice(args[0]!.start, args[0]!.end)}))`,
|
|
386
|
+
})
|
|
387
|
+
else edits.push({ at: declarator.init!.end - 1, text: `__hamurHotI.take(${i}, undefined)` })
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (instance) {
|
|
391
|
+
edits.push({ at: instance.content.start, text: "const __hamurHotI = __hamurHotM.enter();" })
|
|
392
|
+
if (names.length)
|
|
393
|
+
edits.push({
|
|
394
|
+
at: (instance.content.body as Node[]).at(-1)!.end,
|
|
395
|
+
text: `;__hamurHotI.read(() => [${names.join(", ")}]);`,
|
|
396
|
+
})
|
|
397
|
+
}
|
|
398
|
+
const dependencies = new Set<string>()
|
|
399
|
+
for (const script of [module, instance])
|
|
400
|
+
for (const statement of (script?.content.body ?? []) as Node[])
|
|
401
|
+
if (
|
|
402
|
+
statement.type === "ImportDeclaration" &&
|
|
403
|
+
statement.importKind !== "type" &&
|
|
404
|
+
!NOT_A_MODULE.test(statement.source.value)
|
|
405
|
+
)
|
|
406
|
+
dependencies.add(statement.source.value)
|
|
407
|
+
const deps = [...dependencies]
|
|
408
|
+
const head = [
|
|
409
|
+
`import { hotModule as __hamurHot } from ${JSON.stringify(runtime)};`,
|
|
410
|
+
...deps.map((path, index) => `import * as __hamurHotDep${index} from ${JSON.stringify(path)};`),
|
|
411
|
+
`const __hamurHotM = __hamurHot(import.meta.hot ? import.meta.hot.data.hamur : undefined, ${JSON.stringify(relative(rootDir, file))}, ${JSON.stringify(signature.join(";"))}, ${JSON.stringify(String(Bun.hash(source)))}, [${deps.map((_, index) => `__hamurHotDep${index}`).join(", ")}]);`,
|
|
412
|
+
`if (import.meta.hot) import.meta.hot.data.hamur = __hamurHotM;`,
|
|
413
|
+
].join(" ")
|
|
414
|
+
if (module) edits.push({ at: module.content.start, text: head })
|
|
415
|
+
else {
|
|
416
|
+
const lang =
|
|
417
|
+
instance && /\slang\s*=\s*["']ts["']/.test(source.slice(instance.start, instance.content.start))
|
|
418
|
+
? ` lang="ts"`
|
|
419
|
+
: ""
|
|
420
|
+
edits.push({ at: instance?.start ?? 0, text: `<script module${lang}>${head}</script>` })
|
|
421
|
+
}
|
|
422
|
+
let out = source
|
|
423
|
+
for (const { at, end = at, text } of edits.sort((a, b) => b.at - a.at))
|
|
424
|
+
out = `${out.slice(0, at)}${text}${out.slice(end)}`
|
|
425
|
+
return out
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Records the compiled component in the hot runtime, so `Nest.svelte` keeps rendering its first version. */
|
|
429
|
+
export function hotTail(code: string): string {
|
|
430
|
+
const names = [...code.matchAll(DEFAULT_EXPORT)]
|
|
431
|
+
return names.length === 1 ? `${code}\n__hamurHotM.component(${names[0]![1]});` : code
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Bun 1.4.4 does not link a CSS import a self-accepting module gains or loses in an update, so the document loads again then; one line keeps the map shift at 1. */
|
|
435
|
+
export function styleGuard(styled: boolean): string {
|
|
436
|
+
return `if (import.meta.hot) { const was = import.meta.hot.data.hamurStyled; import.meta.hot.data.hamurStyled = ${styled}; if (was !== undefined && was !== ${styled}) location.reload(); }`
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function sameFile(a: string, b: string): boolean {
|
|
440
|
+
try {
|
|
441
|
+
return realpathSync(a) === realpathSync(b)
|
|
442
|
+
} catch {
|
|
443
|
+
return false
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function svelteEsmEnv(): AdapterTransform {
|
|
448
|
+
return {
|
|
449
|
+
name: "hamur-svelte-esm-env",
|
|
450
|
+
filter: { id: /[\\/]node_modules[\\/]svelte[\\/]src[\\/].*\.js$/ },
|
|
451
|
+
transform(code) {
|
|
452
|
+
const folded = foldEsmEnv(code)
|
|
453
|
+
return folded === code ? undefined : folded
|
|
454
|
+
},
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export function sveltePlugin(ctx: AdapterBuildContext): BunPlugin {
|
|
459
|
+
const { target, dev, hmr, svelteAsync = false } = ctx
|
|
460
|
+
const isAwait = (path: string) => path === AWAIT || (svelteAsync && sameFile(path, AWAIT))
|
|
461
|
+
const styles = new Map<string, string>()
|
|
462
|
+
const appModule = hmr && target === "client" ? appModuleId(ctx.rootDir, ctx.buildDir) : () => undefined
|
|
463
|
+
const locatable = dev ? appModuleId(ctx.rootDir, ctx.buildDir) : () => undefined
|
|
464
|
+
return {
|
|
465
|
+
name: `hamur-svelte-${target}`,
|
|
466
|
+
setup(build) {
|
|
467
|
+
build.onLoad({ filter: /\.svelte$/, namespace: "file" }, async ({ path }) => {
|
|
468
|
+
const written = await Bun.file(isAwait(path) && svelteAsync ? AWAIT_ASYNC : path).text()
|
|
469
|
+
const file = locatable(path)
|
|
470
|
+
const marked = dev
|
|
471
|
+
? file === undefined
|
|
472
|
+
? written
|
|
473
|
+
: locateRootElement(written, file)
|
|
474
|
+
: dropDevOnlyMarkup(written)
|
|
475
|
+
const id = appModule(path)
|
|
476
|
+
const hot = id === undefined ? marked : hotTransform(marked, join(ctx.rootDir, id), ctx.rootDir)
|
|
477
|
+
const preprocessed = await preprocessStyles(hot, path, ctx.preprocessStyle)
|
|
478
|
+
let compiled: ReturnType<typeof compileSvelte>
|
|
479
|
+
try {
|
|
480
|
+
compiled = compileSvelte(
|
|
481
|
+
path,
|
|
482
|
+
preprocessed?.code ?? hot,
|
|
483
|
+
target,
|
|
484
|
+
hmr,
|
|
485
|
+
ctx.rootDir,
|
|
486
|
+
svelteAsync,
|
|
487
|
+
preprocessed,
|
|
488
|
+
dev,
|
|
489
|
+
)
|
|
490
|
+
} catch (error) {
|
|
491
|
+
// the inserted imports and hot calls move columns, so the place is taken from the file as written
|
|
492
|
+
if (hot !== written) {
|
|
493
|
+
const plain = await preprocessStyles(written, path, ctx.preprocessStyle)
|
|
494
|
+
compileSvelte(path, plain?.code ?? written, target, hmr, ctx.rootDir, svelteAsync, plain, dev)
|
|
495
|
+
}
|
|
496
|
+
throw error
|
|
497
|
+
}
|
|
498
|
+
const code = hot === marked ? compiled.code : hotTail(compiled.code)
|
|
499
|
+
const css = target === "client" ? compiled.css : undefined
|
|
500
|
+
if (css) styles.set(`${path}.css`, css)
|
|
501
|
+
const head = [
|
|
502
|
+
css ? `import ${JSON.stringify(`${STYLE_NS}:${path}.css`)};` : "",
|
|
503
|
+
hot === marked ? "" : styleGuard(!!css),
|
|
504
|
+
].join("")
|
|
505
|
+
if (head === "")
|
|
506
|
+
return { contents: withInlineMap(code, compiled.map, path, written, ctx.rootDir), loader: "js" }
|
|
507
|
+
return {
|
|
508
|
+
contents: `${head}\n${withInlineMap(code, compiled.map, path, written, ctx.rootDir, 1)}`,
|
|
509
|
+
loader: "js",
|
|
510
|
+
}
|
|
511
|
+
})
|
|
512
|
+
|
|
513
|
+
build.onLoad({ filter: /\.svelte\.(ts|js)$/, namespace: "file" }, async ({ path }) => ({
|
|
514
|
+
contents: compileSvelteModule(path, await Bun.file(path).text(), target, ctx.rootDir, svelteAsync, dev),
|
|
515
|
+
loader: "js",
|
|
516
|
+
}))
|
|
517
|
+
|
|
518
|
+
build.onResolve({ filter: new RegExp(`^${STYLE_NS}:`) }, ({ path }) => ({
|
|
519
|
+
path: path.slice(STYLE_NS.length + 1),
|
|
520
|
+
namespace: STYLE_NS,
|
|
521
|
+
}))
|
|
522
|
+
build.onLoad({ filter: /.*/, namespace: STYLE_NS }, async ({ path }) => {
|
|
523
|
+
const first = styles.get(path)
|
|
524
|
+
if (first !== undefined && !hmr) {
|
|
525
|
+
styles.delete(path)
|
|
526
|
+
return { contents: first, loader: "css" }
|
|
527
|
+
}
|
|
528
|
+
// in dev every load may be the stamp's after a Sass partial changed, so the block is compiled again
|
|
529
|
+
const file = path.slice(0, -".css".length)
|
|
530
|
+
const written = await Bun.file(file).text()
|
|
531
|
+
const preprocessed = await preprocessStyles(written, file, ctx.preprocessStyle)
|
|
532
|
+
return {
|
|
533
|
+
contents:
|
|
534
|
+
compileSvelte(
|
|
535
|
+
file,
|
|
536
|
+
preprocessed?.code ?? written,
|
|
537
|
+
"client",
|
|
538
|
+
hmr,
|
|
539
|
+
ctx.rootDir,
|
|
540
|
+
svelteAsync,
|
|
541
|
+
preprocessed,
|
|
542
|
+
dev,
|
|
543
|
+
).css ?? "",
|
|
544
|
+
loader: "css",
|
|
545
|
+
}
|
|
546
|
+
})
|
|
547
|
+
},
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** In `hamur dev` the client runtime imports `runtime/hydration-dev.ts` first, which feeds the hydration mismatch report; a build adds nothing. */
|
|
552
|
+
export function svelteHydrationPlugin(): AdapterTransform {
|
|
553
|
+
return {
|
|
554
|
+
name: "hamur-svelte-hydration",
|
|
555
|
+
filter: { id: new RegExp(`^${CLIENT_RUNTIME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) },
|
|
556
|
+
transform: (code) => `import ${JSON.stringify(HYDRATION_DEV)}; ${code}`,
|
|
557
|
+
}
|
|
558
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { flushSync, hydrate as hydrateRoot, mount as mountRoot, settled } from "svelte"
|
|
2
|
+
import { setAdapterInstance } from "hamur/adapter"
|
|
3
|
+
import type { ClientContext } from "hamur/adapter"
|
|
4
|
+
import { appSource, appState } from "../context.ts"
|
|
5
|
+
import type { AppState } from "../context.ts"
|
|
6
|
+
import type { Source } from "../store.ts"
|
|
7
|
+
import Root from "../Root.svelte"
|
|
8
|
+
import { whileHydratingPage } from "../hydrating.ts"
|
|
9
|
+
import { devHydration } from "./hydration.ts"
|
|
10
|
+
import ServerComponent from "../ServerComponentClient.svelte"
|
|
11
|
+
import { withServer } from "../server-component.ts"
|
|
12
|
+
import ClientComponent from "../ClientComponent.svelte"
|
|
13
|
+
import type { Component } from "svelte"
|
|
14
|
+
|
|
15
|
+
export { installKeepAlive } from "../context.ts"
|
|
16
|
+
|
|
17
|
+
let source: Source<AppState> | undefined
|
|
18
|
+
|
|
19
|
+
function watchError(ctx: ClientContext, current: Source<AppState>): void {
|
|
20
|
+
;(ctx.app as AppState["app"]).error?.subscribe?.(() => current.set({ ...current.get() }))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function hydrate(ctx: ClientContext): Promise<void> {
|
|
24
|
+
await setAdapterInstance(ctx.app, null)
|
|
25
|
+
source = appSource(ctx)
|
|
26
|
+
watchError(ctx, source)
|
|
27
|
+
const watch = devHydration.watch?.(ctx.root)
|
|
28
|
+
try {
|
|
29
|
+
whileHydratingPage(() => hydrateRoot(Root, { target: ctx.root, props: { source } }))
|
|
30
|
+
} finally {
|
|
31
|
+
watch?.done()
|
|
32
|
+
}
|
|
33
|
+
await settled()
|
|
34
|
+
flushSync()
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function mount(ctx: ClientContext): Promise<void> {
|
|
38
|
+
await setAdapterInstance(ctx.app, null)
|
|
39
|
+
source = appSource(ctx)
|
|
40
|
+
watchError(ctx, source)
|
|
41
|
+
mountRoot(Root, { target: ctx.root, props: { source } })
|
|
42
|
+
flushSync()
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function update(ctx: ClientContext): void {
|
|
46
|
+
if (!source) throw new Error("update() called before hydrate() or mount()")
|
|
47
|
+
source.set(appState(ctx))
|
|
48
|
+
flushSync()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The client side of a client-only component: nothing in the hydration render, the file's chunk once mounted. */
|
|
52
|
+
export function clientComponent(
|
|
53
|
+
load: () => Promise<{ default: Component<Record<string, unknown>> }>,
|
|
54
|
+
): Component<Record<string, unknown>> {
|
|
55
|
+
return withServer(ClientComponent, { load })
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The client side of a server-only component: the server HTML, never hydrated; a new props text fetches it anew. */
|
|
59
|
+
export function serverComponent(name: string): Component<Record<string, unknown>> {
|
|
60
|
+
return withServer(ServerComponent, { name })
|
|
61
|
+
}
|