@hyperspan/plugin-preact 1.0.4 → 2.0.0-alpha.2
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/package.json +19 -8
- package/src/index.test.ts +22 -6
- package/src/index.ts +177 -207
package/package.json
CHANGED
|
@@ -1,35 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyperspan/plugin-preact",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0-alpha.2",
|
|
4
4
|
"description": "Hyperspan Plugin for Preact",
|
|
5
|
+
"type": "module",
|
|
5
6
|
"main": "src/index.ts",
|
|
6
7
|
"types": "src/index.ts",
|
|
7
8
|
"public": true,
|
|
8
9
|
"publishConfig": {
|
|
9
|
-
"access": "public"
|
|
10
|
+
"access": "public",
|
|
11
|
+
"tag": "alpha"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./src/index.ts",
|
|
16
|
+
"default": "./src/index.ts"
|
|
17
|
+
}
|
|
10
18
|
},
|
|
11
19
|
"author": "Vance Lucas <vance@vancelucas.com>",
|
|
12
20
|
"license": "BSD-3-Clause",
|
|
13
|
-
"keywords": [],
|
|
14
21
|
"homepage": "https://www.hyperspan.dev/docs/clientjs/islands",
|
|
15
22
|
"bugs": {
|
|
16
23
|
"url": "https://github.com/vlucas/hyperspan/issues"
|
|
17
24
|
},
|
|
18
25
|
"scripts": {
|
|
19
|
-
"test": "
|
|
26
|
+
"test": "vitest run"
|
|
20
27
|
},
|
|
21
28
|
"repository": {
|
|
22
29
|
"type": "git",
|
|
23
30
|
"url": "git+https://github.com/vlucas/hyperspan.git"
|
|
24
31
|
},
|
|
25
32
|
"devDependencies": {
|
|
26
|
-
"@
|
|
33
|
+
"@hyperspan/vite-plugin": "^2.0.0-alpha.2",
|
|
27
34
|
"prettier": "^3.8.1",
|
|
28
|
-
"typescript": "^5.9.3"
|
|
35
|
+
"typescript": "^5.9.3",
|
|
36
|
+
"vite": "^6.3.5",
|
|
37
|
+
"vitest": "^3.2.4"
|
|
29
38
|
},
|
|
30
39
|
"peerDependencies": {
|
|
31
|
-
"@hyperspan/html": "^
|
|
32
|
-
"@hyperspan/framework": "^
|
|
40
|
+
"@hyperspan/html": "^2.0.0-alpha.2",
|
|
41
|
+
"@hyperspan/framework": "^2.0.0-alpha.2",
|
|
42
|
+
"@hyperspan/vite-plugin": "^2.0.0-alpha.2",
|
|
43
|
+
"vite": "^6.0.0 || ^7.0.0"
|
|
33
44
|
},
|
|
34
45
|
"dependencies": {
|
|
35
46
|
"debug": "^4.4.3",
|
package/src/index.test.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { test, describe, expect } from '
|
|
1
|
+
import { test, describe, expect } from 'vitest';
|
|
2
2
|
import { h } from 'preact';
|
|
3
3
|
import { buildIslandHtml, renderPreactSSR, renderPreactIsland } from './index';
|
|
4
4
|
|
|
@@ -49,6 +49,14 @@ describe('buildIslandHtml', () => {
|
|
|
49
49
|
expect(result).not.toContain('data-loading="lazy"');
|
|
50
50
|
expect(result).not.toContain('<template>');
|
|
51
51
|
});
|
|
52
|
+
|
|
53
|
+
test('named export uses brace import syntax', () => {
|
|
54
|
+
const result = buildIslandHtml(jsId, componentName, esmName, '', '<p>SSR</p>', {
|
|
55
|
+
exportKind: 'named',
|
|
56
|
+
});
|
|
57
|
+
expect(result).toContain(`import { ${componentName} } from "${esmName}"`);
|
|
58
|
+
expect(result).not.toContain(`import ${componentName} from "${esmName}"`);
|
|
59
|
+
});
|
|
52
60
|
});
|
|
53
61
|
|
|
54
62
|
// ---------------------------------------------------------------------------
|
|
@@ -91,9 +99,7 @@ describe('renderPreactSSR', () => {
|
|
|
91
99
|
|
|
92
100
|
describe('renderPreactIsland', () => {
|
|
93
101
|
test('throws when component has no __HS_ISLAND property', () => {
|
|
94
|
-
expect(() => renderPreactIsland(Hello, {})).toThrow(
|
|
95
|
-
'was not loaded with an island plugin'
|
|
96
|
-
);
|
|
102
|
+
expect(() => renderPreactIsland(Hello, {})).toThrow(/not a Hyperspan island/i);
|
|
97
103
|
});
|
|
98
104
|
|
|
99
105
|
test('returns an html_safe object', () => {
|
|
@@ -179,10 +185,20 @@ describe('renderPreactIsland', () => {
|
|
|
179
185
|
(Hello as any).__HS_ISLAND = {
|
|
180
186
|
id: jsId,
|
|
181
187
|
render: (props: any, options: any = {}) =>
|
|
182
|
-
buildIslandHtml(
|
|
188
|
+
buildIslandHtml(
|
|
189
|
+
jsId,
|
|
190
|
+
'Hello',
|
|
191
|
+
'hello',
|
|
192
|
+
'console.log(1)',
|
|
193
|
+
renderPreactSSR(Hello, props),
|
|
194
|
+
options
|
|
195
|
+
),
|
|
183
196
|
};
|
|
184
197
|
|
|
185
|
-
const result = renderPreactIsland(Hello, { name: 'World' }, {
|
|
198
|
+
const result = renderPreactIsland(Hello, { name: 'World' }, {
|
|
199
|
+
ssr: true,
|
|
200
|
+
loading: 'lazy',
|
|
201
|
+
} as any);
|
|
186
202
|
expect(result.content).toContain('data-loading="lazy"');
|
|
187
203
|
expect(result.content).toContain('<template>');
|
|
188
204
|
expect(result.content).toContain('Hello World!');
|
package/src/index.ts
CHANGED
|
@@ -1,261 +1,231 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
import { resolve, dirname } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
2
4
|
import { assetHash } from '@hyperspan/framework/utils';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
+
import { registerImport, JS_ISLAND_PUBLIC_PATH } from '@hyperspan/framework/client/js';
|
|
6
|
+
import { renderIsland } from '@hyperspan/framework';
|
|
5
7
|
import type { Hyperspan as HS } from '@hyperspan/framework';
|
|
6
8
|
import { html } from '@hyperspan/html';
|
|
7
9
|
import { h } from 'preact';
|
|
8
10
|
import { render as preactRenderToString } from 'preact-render-to-string';
|
|
11
|
+
import {
|
|
12
|
+
registerIslandPlugin,
|
|
13
|
+
isIslandModule,
|
|
14
|
+
islandPluginResolveId,
|
|
15
|
+
splitIslandId,
|
|
16
|
+
} from '@hyperspan/vite-plugin/islands';
|
|
9
17
|
import debug from 'debug';
|
|
10
18
|
|
|
11
19
|
const log = debug('hyperspan:plugin-preact');
|
|
12
20
|
|
|
13
|
-
|
|
21
|
+
export type IslandExportKind = 'default' | 'named';
|
|
14
22
|
|
|
15
|
-
/** Dev: stable `[name].js` via Bun default. Prod: hashed filenames for caching. */
|
|
16
|
-
const ISLAND_JS_NAMING = IS_PROD ? '[dir]/[name]-[hash].[ext]' : undefined;
|
|
17
|
-
|
|
18
|
-
function islandBundleBaseName(outputPath: string): string {
|
|
19
|
-
return String(outputPath.split('/').reverse()[0]!.replace(/\.js$/i, ''));
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function pickEntryPointJsOutput(
|
|
23
|
-
outputs: ReadonlyArray<{ path: string; kind?: string }>,
|
|
24
|
-
entrySourcePath: string
|
|
25
|
-
): { path: string } {
|
|
26
|
-
const js = outputs.filter((o) => o.path.endsWith('.js'));
|
|
27
|
-
const entry = js.find((o) => o.kind === 'entry-point');
|
|
28
|
-
if (entry) return entry;
|
|
29
|
-
const sourceBase = entrySourcePath.split('/').pop()!.replace(/\.(tsx|ts|jsx|js)$/i, '');
|
|
30
|
-
const byName = js.find((o) => {
|
|
31
|
-
const b = islandBundleBaseName(o.path);
|
|
32
|
-
return b === sourceBase || b.startsWith(`${sourceBase}-`);
|
|
33
|
-
});
|
|
34
|
-
if (byName) return byName;
|
|
35
|
-
if (js[0]) return js[0];
|
|
36
|
-
throw new Error('[Hyperspan] Preact island build produced no JS output');
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Build the island wrapper HTML: a div for SSR content + a module script tag for client hydration.
|
|
41
|
-
* Exported so it can be imported by generated island module code and used directly in tests.
|
|
42
|
-
*/
|
|
43
23
|
export function buildIslandHtml(
|
|
44
24
|
jsId: string,
|
|
45
25
|
componentName: string,
|
|
46
26
|
esmName: string,
|
|
47
27
|
jsContent: string,
|
|
48
28
|
ssrContent: string,
|
|
49
|
-
options: { loading?: string } = {}
|
|
29
|
+
options: { loading?: string; exportKind?: IslandExportKind } = {}
|
|
50
30
|
): string {
|
|
51
|
-
const
|
|
31
|
+
const importStmt =
|
|
32
|
+
options.exportKind === 'named'
|
|
33
|
+
? `import { ${componentName} } from "${esmName}";`
|
|
34
|
+
: `import ${componentName} from "${esmName}";`;
|
|
35
|
+
const scriptTag = `<script type="module" id="${jsId}_script" data-source-id="${jsId}">${importStmt}${jsContent}</script>`;
|
|
52
36
|
if (options.loading === 'lazy') {
|
|
53
37
|
return `<div id="${jsId}">${ssrContent}</div><div data-loading="lazy" style="height:1px;width:1px;overflow:hidden;"><template>\n${scriptTag}</template></div>`;
|
|
54
38
|
}
|
|
55
39
|
return `<div id="${jsId}">${ssrContent}</div>\n${scriptTag}`;
|
|
56
40
|
}
|
|
57
41
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
* Exported for direct use in tests and external tooling.
|
|
61
|
-
*/
|
|
62
|
-
export function renderPreactSSR(Component: any, props: any = {}): string {
|
|
63
|
-
return preactRenderToString(h(Component, props));
|
|
42
|
+
export function renderPreactSSR(Component: unknown, props: Record<string, unknown> = {}): string {
|
|
43
|
+
return preactRenderToString(h(Component as Parameters<typeof h>[0], props));
|
|
64
44
|
}
|
|
65
45
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
// Preact client JS is always production mode
|
|
80
|
-
process.env.NODE_ENV = 'production';
|
|
81
|
-
const result = await Bun.build({
|
|
82
|
-
entrypoints: [sourceFile],
|
|
83
|
-
outdir,
|
|
84
|
-
naming: ISLAND_JS_NAMING,
|
|
85
|
-
minify: true,
|
|
86
|
-
format: 'esm',
|
|
87
|
-
target: 'browser',
|
|
88
|
-
});
|
|
89
|
-
process.env.NODE_ENV = currentNodeEnv;
|
|
90
|
-
|
|
91
|
-
const preactEntry = pickEntryPointJsOutput(result.outputs, sourceFile);
|
|
92
|
-
const builtFileName = islandBundleBaseName(preactEntry.path);
|
|
93
|
-
const builtFilePath = `${JS_ISLAND_PUBLIC_PATH}/${builtFileName}.js`;
|
|
94
|
-
|
|
95
|
-
JS_IMPORT_MAP.set('preact', builtFilePath);
|
|
96
|
-
JS_IMPORT_MAP.set('preact/compat', builtFilePath);
|
|
97
|
-
JS_IMPORT_MAP.set('preact/hooks', builtFilePath);
|
|
98
|
-
JS_IMPORT_MAP.set('preact/jsx-runtime', builtFilePath);
|
|
99
|
-
JS_IMPORT_MAP.set('preact/jsx-dev-runtime', builtFilePath);
|
|
100
|
-
|
|
101
|
-
if (!JS_IMPORT_MAP.has('react')) {
|
|
102
|
-
JS_IMPORT_MAP.set('react', builtFilePath);
|
|
103
|
-
JS_IMPORT_MAP.set('react-dom', builtFilePath);
|
|
46
|
+
type DiscoveredExport = { name: string; kind: IslandExportKind };
|
|
47
|
+
|
|
48
|
+
function extractDefaultExportName(code: string): string | null {
|
|
49
|
+
const patterns = [
|
|
50
|
+
/export\{([^\s]+) as default\}/,
|
|
51
|
+
/export default function\s+([^\s(]+)/,
|
|
52
|
+
/export default function\s*\(/,
|
|
53
|
+
/export default const\s+([^\s=]+)/,
|
|
54
|
+
/export default class\s+([^\s{]+)/,
|
|
55
|
+
];
|
|
56
|
+
for (const re of patterns) {
|
|
57
|
+
const m = code.match(re);
|
|
58
|
+
if (m?.[1]) return m[1];
|
|
104
59
|
}
|
|
60
|
+
if (/export default function/.test(code)) return 'DefaultComponent';
|
|
61
|
+
const anyMatch = code.match(/export default\s+([A-Za-z_$][\w$]*)/);
|
|
62
|
+
return anyMatch?.[1] ?? null;
|
|
105
63
|
}
|
|
106
64
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
export function preactPlugin(): HS.Plugin {
|
|
111
|
-
return async (config: HS.Config) => {
|
|
112
|
-
try {
|
|
113
|
-
log('plugin loaded');
|
|
114
|
-
// Ensure Preact can be loaded on the client
|
|
115
|
-
if (!JS_IMPORT_MAP.has('preact')) {
|
|
116
|
-
await copyPreactToPublicFolder(config);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// Define a Bun plugin to handle .tsx files
|
|
120
|
-
await Bun.plugin({
|
|
121
|
-
name: 'Hyperspan Preact Loader',
|
|
122
|
-
async setup(build) {
|
|
123
|
-
// when a .tsx file is imported...
|
|
124
|
-
build.onLoad({ filter: /\.tsx$/ }, async (args) => {
|
|
125
|
-
log('tsx file loaded', args.path);
|
|
126
|
-
const jsId = assetHash(args.path);
|
|
127
|
-
|
|
128
|
-
if (!JS_IMPORT_MAP.has('preact')) {
|
|
129
|
-
await copyPreactToPublicFolder(config);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// Cache: Avoid re-processing the same file
|
|
133
|
-
if (PREACT_ISLAND_CACHE.has(jsId)) {
|
|
134
|
-
const hit = PREACT_ISLAND_CACHE.get(jsId)!;
|
|
135
|
-
JS_IMPORT_MAP.set(hit.esmName, `${JS_ISLAND_PUBLIC_PATH}/${hit.esmName}.js`);
|
|
136
|
-
log('tsx file cached', args.path);
|
|
137
|
-
return {
|
|
138
|
-
contents: hit.contents,
|
|
139
|
-
loader: 'js',
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
log('tsx file not cached, building...', args.path);
|
|
144
|
-
// We need to build the file to ensure we can ship it to the client with dependencies
|
|
145
|
-
// Ironic, right? Calling Bun.build() inside of a plugin that runs on Bun.build()?
|
|
146
|
-
const islandOutdir = resolve(CWD, config.publicDir, JS_ISLAND_PUBLIC_PATH.replace(/^\//, ''));
|
|
147
|
-
const result = await Bun.build({
|
|
148
|
-
entrypoints: [args.path],
|
|
149
|
-
outdir: islandOutdir,
|
|
150
|
-
naming: ISLAND_JS_NAMING,
|
|
151
|
-
external: Array.from(JS_IMPORT_MAP.keys()),
|
|
152
|
-
minify: true,
|
|
153
|
-
format: 'esm',
|
|
154
|
-
target: 'browser',
|
|
155
|
-
env: 'APP_PUBLIC_*',
|
|
156
|
-
});
|
|
65
|
+
function discoverPreactExports(code: string): DiscoveredExport[] {
|
|
66
|
+
const exports: DiscoveredExport[] = [];
|
|
67
|
+
const seen = new Set<string>();
|
|
157
68
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
log('added to import map', esmName, `${JS_ISLAND_PUBLIC_PATH}/${esmName}.js`);
|
|
164
|
-
|
|
165
|
-
let contents = await Bun.file(entryOut.path).text();
|
|
166
|
-
|
|
167
|
-
// Look for the default export
|
|
168
|
-
const RE_EXPORT_DEFAULT = /export\{([^\s]+) as default\}/;
|
|
169
|
-
const RE_EXPORT_DEFAULT_FN = /export default function\s+([^\s]+)/;
|
|
170
|
-
const RE_EXPORT_DEFAULT_CONST = /export default const\s+([^\s]+)/;
|
|
171
|
-
const RE_EXPORT_DEFAULT_ANY = /export default\s+([^\s]+)/;
|
|
172
|
-
|
|
173
|
-
const exportedDefault = contents.match(RE_EXPORT_DEFAULT);
|
|
174
|
-
const exportedDefaultFn = contents.match(RE_EXPORT_DEFAULT_FN);
|
|
175
|
-
const exportedDefaultConst = contents.match(RE_EXPORT_DEFAULT_CONST);
|
|
176
|
-
const exportedDefaultAny = contents.match(RE_EXPORT_DEFAULT_ANY);
|
|
177
|
-
|
|
178
|
-
const componentName =
|
|
179
|
-
exportedDefault?.[1] ||
|
|
180
|
-
exportedDefaultFn?.[1] ||
|
|
181
|
-
exportedDefaultConst?.[1] ||
|
|
182
|
-
exportedDefaultAny?.[1];
|
|
69
|
+
const defaultName = extractDefaultExportName(code);
|
|
70
|
+
if (defaultName) {
|
|
71
|
+
exports.push({ name: defaultName, kind: 'default' });
|
|
72
|
+
seen.add(defaultName);
|
|
73
|
+
}
|
|
183
74
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
75
|
+
for (const re of [
|
|
76
|
+
/export\s+function\s+([A-Za-z_$][\w$]*)/g,
|
|
77
|
+
/export\s+const\s+([A-Za-z_$][\w$]*)/g,
|
|
78
|
+
/export\s+class\s+([A-Za-z_$][\w$]*)/g,
|
|
79
|
+
]) {
|
|
80
|
+
let match: RegExpExecArray | null;
|
|
81
|
+
while ((match = re.exec(code)) !== null) {
|
|
82
|
+
if (!seen.has(match[1])) {
|
|
83
|
+
exports.push({ name: match[1], kind: 'named' });
|
|
84
|
+
seen.add(match[1]);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
190
88
|
|
|
191
|
-
|
|
192
|
-
|
|
89
|
+
const exportBlock = /export\s*\{([^}]+)\}/g;
|
|
90
|
+
let block: RegExpExecArray | null;
|
|
91
|
+
while ((block = exportBlock.exec(code)) !== null) {
|
|
92
|
+
for (const part of block[1].split(',')) {
|
|
93
|
+
const trimmed = part.trim();
|
|
94
|
+
if (!trimmed || trimmed.startsWith('type ')) continue;
|
|
95
|
+
const asMatch = trimmed.match(/^(?:([\w$]+)\s+as\s+)?([\w$]+)$/);
|
|
96
|
+
const name = asMatch?.[2] ?? trimmed;
|
|
97
|
+
if (name && name !== 'default' && !seen.has(name)) {
|
|
98
|
+
exports.push({ name, kind: 'named' });
|
|
99
|
+
seen.add(name);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
193
103
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
// A lot of this work actaully has to be done now, ahead of time, to ensure we use the same Preact instance to hydrate and render the component so there are no errors.
|
|
197
|
-
// So... we have to import the preact-render-to-string library to render the component to a string here, with simple functions to do that work and return HTML.
|
|
198
|
-
// All imports needed for this work are prefixed with __hs_ to avoid clashing with other imports in the module, as some of them may be duplicates.
|
|
199
|
-
// Finally, we need to export all of the functions that do this work in a special way so we don't change the default export or other functions in the module, so that only the Hyperspan renderIsland() function can use them.
|
|
200
|
-
const moduleCode = `// hyperspan:processed
|
|
201
|
-
import { render as __hs_renderToString } from 'preact-render-to-string';
|
|
202
|
-
import { buildIslandHtml as __hs_buildIslandHtml } from '@hyperspan/plugin-preact';
|
|
104
|
+
return exports;
|
|
105
|
+
}
|
|
203
106
|
|
|
204
|
-
|
|
205
|
-
|
|
107
|
+
function buildIslandAttachment(
|
|
108
|
+
exportInfo: DiscoveredExport,
|
|
109
|
+
cleanId: string,
|
|
110
|
+
esmName: string
|
|
111
|
+
): string {
|
|
112
|
+
const { name: componentName, kind } = exportInfo;
|
|
113
|
+
const jsId = assetHash(`${cleanId}:${componentName}`);
|
|
114
|
+
const exportKind = kind;
|
|
206
115
|
|
|
207
|
-
|
|
208
|
-
function __hs_renderIsland(jsContent = '', ssrContent = '', options = {}) {
|
|
209
|
-
return __hs_buildIslandHtml("${jsId}", "${componentName}", "${esmName}", jsContent, ssrContent, options);
|
|
210
|
-
}
|
|
116
|
+
return `
|
|
211
117
|
${componentName}.__HS_ISLAND = {
|
|
212
118
|
id: "${jsId}",
|
|
213
119
|
render: (props, options = {}) => {
|
|
120
|
+
const __hs_exportKind = ${JSON.stringify(exportKind)};
|
|
214
121
|
if (options.ssr === false) {
|
|
215
122
|
const jsContent = \`import { h as __hs_h, render as __hs_render } from 'preact';__hs_render(__hs_h(${componentName}, \${JSON.stringify(props)}), document.getElementById("${jsId}"));\`;
|
|
216
|
-
return
|
|
123
|
+
return __hs_renderIsland_${componentName}(jsContent, '', options);
|
|
217
124
|
}
|
|
218
|
-
|
|
219
125
|
const ssrContent = __hs_renderToString(__hs_h(${componentName}, props));
|
|
220
126
|
const jsContent = \`import { h as __hs_h, hydrate as __hs_hydrate } from 'preact';__hs_hydrate(__hs_h(${componentName}, \${JSON.stringify(props)}), document.getElementById("${jsId}"));\`;
|
|
221
|
-
return
|
|
222
|
-
|
|
127
|
+
return __hs_renderIsland_${componentName}(jsContent, ssrContent, options);
|
|
223
128
|
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
function __hs_renderIsland_${componentName}(jsContent = '', ssrContent = '', options = {}) {
|
|
132
|
+
return __hs_buildIslandHtml("${jsId}", "${componentName}", "${esmName}", jsContent, ssrContent, { ...options, exportKind: ${JSON.stringify(exportKind)} });
|
|
224
133
|
}
|
|
225
134
|
`;
|
|
135
|
+
}
|
|
226
136
|
|
|
227
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Vite plugin for Preact islands.
|
|
139
|
+
*/
|
|
140
|
+
export function preactIslandPlugin(): Plugin {
|
|
141
|
+
const preactClientPath = resolve(dirname(fileURLToPath(import.meta.url)), './preact-client.ts');
|
|
228
142
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
143
|
+
return {
|
|
144
|
+
name: 'hyperspan-preact',
|
|
145
|
+
enforce: 'pre',
|
|
146
|
+
|
|
147
|
+
config() {
|
|
148
|
+
return {
|
|
149
|
+
optimizeDeps: {
|
|
150
|
+
include: ['preact', 'preact/hooks', 'preact/jsx-runtime'],
|
|
234
151
|
},
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
|
|
155
|
+
resolveId: islandPluginResolveId('preact', '.tsx'),
|
|
156
|
+
|
|
157
|
+
configureServer() {
|
|
158
|
+
const clientUrl = '/islands/preact-client.js';
|
|
159
|
+
registerImport('preact', clientUrl);
|
|
160
|
+
registerImport('preact/hooks', clientUrl);
|
|
161
|
+
registerImport('preact/jsx-runtime', clientUrl);
|
|
162
|
+
registerImport('preact/jsx-dev-runtime', clientUrl);
|
|
163
|
+
registerImport('preact/compat', clientUrl);
|
|
164
|
+
registerImport('react', clientUrl);
|
|
165
|
+
registerImport('react-dom', clientUrl);
|
|
166
|
+
},
|
|
167
|
+
|
|
168
|
+
async transform(code, id) {
|
|
169
|
+
if (!isIslandModule(id, 'preact', '.tsx')) return;
|
|
170
|
+
|
|
171
|
+
log('transform island', id);
|
|
172
|
+
const cleanId = splitIslandId(id).path;
|
|
173
|
+
const esmName = `island-${assetHash(cleanId)}`;
|
|
174
|
+
const exports = discoverPreactExports(code);
|
|
175
|
+
|
|
176
|
+
if (exports.length === 0) {
|
|
177
|
+
throw new Error(
|
|
178
|
+
`No component exports found in ${cleanId}. Export a default or named Preact component and import with \`with { island: 'preact' }\`.`
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
registerImport(esmName, `${JS_ISLAND_PUBLIC_PATH}/${esmName}.js`);
|
|
183
|
+
|
|
184
|
+
const attachments = exports
|
|
185
|
+
.map((exp) => buildIslandAttachment(exp, cleanId, esmName))
|
|
186
|
+
.join('\n');
|
|
187
|
+
|
|
188
|
+
const moduleCode = `// hyperspan:processed
|
|
189
|
+
import { h as __hs_h, render as __hs_render, hydrate as __hs_hydrate } from 'preact';
|
|
190
|
+
import { render as __hs_renderToString } from 'preact-render-to-string';
|
|
191
|
+
import { buildIslandHtml as __hs_buildIslandHtml } from '@hyperspan/plugin-preact';
|
|
192
|
+
|
|
193
|
+
${code}
|
|
194
|
+
${attachments}
|
|
195
|
+
`;
|
|
196
|
+
|
|
197
|
+
return { code: moduleCode, map: null };
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
buildStart() {
|
|
201
|
+
if (this.meta.watchMode) return;
|
|
202
|
+
try {
|
|
203
|
+
this.emitFile({
|
|
204
|
+
type: 'chunk',
|
|
205
|
+
id: preactClientPath,
|
|
206
|
+
fileName: 'islands/preact-client.js',
|
|
207
|
+
});
|
|
208
|
+
} catch {
|
|
209
|
+
// Serve mode — client is resolved via import map / Vite deps instead.
|
|
210
|
+
}
|
|
211
|
+
},
|
|
242
212
|
};
|
|
243
213
|
}
|
|
244
214
|
|
|
245
|
-
|
|
246
215
|
/**
|
|
247
|
-
*
|
|
216
|
+
* Hyperspan config plugin — register in hyperspan.config.ts plugins array.
|
|
248
217
|
*/
|
|
249
|
-
export function
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
return html.raw(Component.__HS_ISLAND.render(props, options));
|
|
256
|
-
}
|
|
218
|
+
export function preactPlugin(): HS.Plugin {
|
|
219
|
+
registerIslandPlugin('preact', { vitePlugin: preactIslandPlugin });
|
|
220
|
+
return () => {
|
|
221
|
+
log('preactPlugin loaded');
|
|
222
|
+
};
|
|
223
|
+
}
|
|
257
224
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
}
|
|
225
|
+
export function renderPreactIsland(
|
|
226
|
+
Component: Parameters<typeof renderIsland>[0],
|
|
227
|
+
props: Record<string, unknown> = {},
|
|
228
|
+
options: Parameters<typeof renderIsland>[2] = { ssr: true }
|
|
229
|
+
) {
|
|
230
|
+
return renderIsland(Component, props, options);
|
|
231
|
+
}
|