-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
201 lines (155 loc) · 5.42 KB
/
Copy pathindex.js
File metadata and controls
201 lines (155 loc) · 5.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import fs from 'fs';
import path from 'path';
import adapterStatic from '@sveltejs/adapter-static';
import { applyFirefoxSupport } from './firefox.js';
function toPosix(filePath) {
return filePath.replaceAll('\\', '/');
}
function findHtmlFiles(dir) {
if (!fs.existsSync(dir)) return [];
const results = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...findHtmlFiles(fullPath));
} else if (entry.isFile() && entry.name.endsWith('.html')) {
results.push(fullPath);
}
}
return results;
}
function applyRenames(html, renames) {
for (const { old, new: newPath } of renames) {
html = html.replaceAll(old, newPath);
}
return html;
}
function transformInlineScript(source) {
let script = source;
script = script.replace(/(?<!globalThis\.)(__sveltekit_\w+)\s*=/g, 'globalThis.$1 =');
script = script.replaceAll(
'document.currentScript.parentElement',
'document.body.querySelector(\'div[style*="display: contents"]\')'
);
script = script.replace(
/import\(["'][^"']*scripts\/immutable\/bundle[^"']*\.js["']\)/g,
'import("./immutable/bundle.js")'
);
return script;
}
function collectInlineScripts(html) {
const tagRe = /<script(\b[^>]*)>([\s\S]*?)<\/script>/gi;
const matches = [];
let match;
while ((match = tagRe.exec(html)) !== null) {
const attrs = match[1] || '';
if (/\bsrc\s*=/i.test(attrs)) continue;
if (!match[2].trim()) continue;
matches.push({
full: match[0],
body: match[2],
index: match.index
});
}
return matches;
}
function scriptFileName(relativeHtml, scriptIndex, scriptCount) {
const posixHtml = toPosix(relativeHtml);
const isRootIndex = posixHtml === 'index.html';
const stem = path.basename(posixHtml, '.html');
if (isRootIndex) {
return scriptIndex === 0 ? 'init.js' : `init-${scriptIndex}.js`;
}
const suffix = scriptCount > 1 ? `-${scriptIndex + 1}` : '';
return `start-${stem}${suffix}.js`;
}
function scriptSrc(extensionDir, htmlFile, scriptName) {
const htmlDir = path.dirname(path.resolve(htmlFile));
const target = path.resolve(extensionDir, 'scripts', scriptName);
let relativeSrc = toPosix(path.relative(htmlDir, target));
if (!relativeSrc.startsWith('.')) {
relativeSrc = `./${relativeSrc}`;
}
if (htmlDir === path.resolve(extensionDir)) {
return `./${relativeSrc}`;
}
return relativeSrc;
}
export async function runPostBuildScript(outputDir) {
const extensionDir = outputDir;
const immutableDir = path.join(extensionDir, 'scripts', 'immutable');
const assetsDir = path.join(immutableDir, 'assets');
const scriptsDir = path.join(extensionDir, 'scripts');
function findAndRenameFiles() {
const renames = [];
if (fs.existsSync(immutableDir)) {
const files = fs.readdirSync(immutableDir);
const jsFile = files.find((f) => f.startsWith('bundle') && f.endsWith('.js'));
if (jsFile && jsFile !== 'bundle.js') {
fs.renameSync(path.join(immutableDir, jsFile), path.join(immutableDir, 'bundle.js'));
renames.push({ old: `scripts/immutable/${jsFile}`, new: 'scripts/immutable/bundle.js' });
}
}
if (fs.existsSync(assetsDir)) {
const files = fs.readdirSync(assetsDir);
const cssFile = files.find((f) => f.startsWith('bundle') && f.endsWith('.css'));
if (cssFile && cssFile !== 'style.css') {
fs.renameSync(path.join(assetsDir, cssFile), path.join(assetsDir, 'style.css'));
renames.push({
old: `scripts/immutable/assets/${cssFile}`,
new: 'scripts/immutable/assets/style.css'
});
}
}
return renames;
}
function updateGeneratedHtml(renames) {
const htmlFiles = findHtmlFiles(extensionDir);
if (htmlFiles.length === 0) return;
fs.mkdirSync(scriptsDir, { recursive: true });
for (const htmlFile of htmlFiles) {
let html = applyRenames(fs.readFileSync(htmlFile, 'utf-8'), renames);
const inlineScripts = collectInlineScripts(html);
const relativeHtml = path.relative(extensionDir, htmlFile);
if (inlineScripts.length > 0) {
let nextHtml = html;
for (let i = inlineScripts.length - 1; i >= 0; i--) {
const inlineScript = inlineScripts[i];
const name = scriptFileName(relativeHtml, i, inlineScripts.length);
const transformed = transformInlineScript(inlineScript.body);
const src = scriptSrc(extensionDir, htmlFile, name);
fs.writeFileSync(path.join(scriptsDir, name), transformed, 'utf-8');
const start = inlineScript.index;
const end = start + inlineScript.full.length;
nextHtml =
nextHtml.slice(0, start) +
`<script src="${src}" type="module"></script>` +
nextHtml.slice(end);
}
html = nextHtml;
}
fs.writeFileSync(htmlFile, html, 'utf-8');
}
}
const renames = findAndRenameFiles();
updateGeneratedHtml(renames);
}
export default function adapterStaticExtension(options = {}) {
const { firefox = false, firefoxBuildScript = 'build-firefox', ...staticOptions } = options;
const adapter = adapterStatic(staticOptions);
const originalAdapt = adapter.adapt;
adapter.name = '@cattn/adapter-extension';
adapter.adapt = async (builder) => {
await originalAdapt(builder);
const outputDir = path.resolve(staticOptions.pages || 'build');
await runPostBuildScript(outputDir);
if (
firefox &&
(process.env.npm_lifecycle_event === firefoxBuildScript ||
process.env.ADAPTER_EXTENSION_FIREFOX === '1')
) {
await applyFirefoxSupport(outputDir, firefox === true ? {} : firefox);
}
};
return adapter;
}