-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathindex.js
More file actions
162 lines (143 loc) · 4.65 KB
/
Copy pathindex.js
File metadata and controls
162 lines (143 loc) · 4.65 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
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { rolldown } from 'rolldown';
const files = fileURLToPath(new URL('./files', import.meta.url).href);
/** @param {string} str */
function escape_regex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/** @type {import('./index.js').default} */
export default function (opts = {}) {
const { out = 'build', precompress = true, envPrefix = '' } = opts;
return {
name: '@sveltejs/adapter-node',
async adapt(builder) {
const tmp = builder.getBuildDirectory('adapter-node');
builder.rimraf(out);
builder.rimraf(tmp);
builder.mkdirp(tmp);
builder.log.minor('Copying assets');
builder.writeClient(`${out}/client${builder.config.kit.paths.base}`);
builder.writePrerendered(`${out}/prerendered${builder.config.kit.paths.base}`);
if (precompress) {
builder.log.minor('Compressing assets');
await Promise.all([
builder.compress(`${out}/client`),
builder.compress(`${out}/prerendered`)
]);
}
builder.log.minor('Building server');
const pkg = JSON.parse(readFileSync('package.json', 'utf8'));
const server = builder.getServerDirectory();
// Copy the prebuilt entrypoints into the build directory so that the
// adapter's own bundled dependencies resolve correctly, then bundle them
// together with the app's server code. Bundling everything in a single
// pass means shared modules (e.g. `SvelteKitError` from `@sveltejs/kit`)
// aren't duplicated. See https://github.com/sveltejs/kit/issues/15755
const entries = posixify(`${tmp}/entries`);
builder.copy(files, entries);
const dir_id = `${entries}/dir.js`;
writeFileSync(
`${server}/manifest.js`,
[
`export const manifest = ${builder.generateManifest({ relativePath: './' })};`,
`export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});`,
`export const base = ${JSON.stringify(builder.config.kit.paths.base)};`
].join('\n\n')
);
/** @type {Record<string, string>} */
const input = {
index: `${entries}/index.js`,
env: `${entries}/env.js`,
handler: `${entries}/handler.js`
};
if (builder.hasServerInstrumentationFile()) {
input['instrumentation.server'] = `${server}/instrumentation.server.js`;
}
// we bundle the Vite output so that deployments only need
// their production dependencies. Anything in devDependencies
// will get included in the bundled code
const bundle = await rolldown({
input,
external: [
// dependencies could have deep exports, so we need a regex
...Object.keys(pkg.dependencies || {}).map((d) => new RegExp(`^${d}(\\/.*)?$`))
],
platform: 'node',
resolve: {
conditionNames: ['node']
},
experimental: {
nativeMagicString: true
},
plugins: [
{
// resolve the app's server and manifest, generated above
name: 'adapter-node-resolve-app',
resolveId(id) {
if (id === 'SERVER') return `${server}/index.js`;
if (id === 'MANIFEST') return `${server}/manifest.js`;
}
},
{
// replace build-time constants in the adapter's own entrypoints
// only, so that identifiers in the app or its dependencies aren't
// accidentally replaced
name: 'adapter-node-replace-constants',
transform: {
filter: { id: new RegExp(escape_regex(entries)) },
handler(_code, _id, { magicString }) {
if (!magicString) throw new Error('experimental.nativeMagicString is not enabled');
magicString
.replace(/\bENV_PREFIX\b/g, JSON.stringify(envPrefix))
.replace(/\bPRECOMPRESS\b/g, JSON.stringify(precompress))
.replace(
/\bORIGIN\b/g,
JSON.stringify(builder.config.kit.paths.origin) || 'undefined'
);
return {
code: magicString,
map: magicString.generateMap().toString()
};
}
}
}
]
});
await bundle.write({
dir: out,
format: 'esm',
sourcemap: true,
codeSplitting: {
groups: [
{
name: 'dir',
test: dir_id
}
]
},
chunkFileNames(chunk) {
if (chunk.name === 'dir') return '[name].js';
return 'server/chunks/[name]-[hash].js';
}
});
if (builder.hasServerInstrumentationFile()) {
builder.instrument({
entrypoint: `${out}/index.js`,
instrumentation: `${out}/instrumentation.server.js`,
module: {
exports: ['path', 'host', 'port', 'server']
}
});
}
},
supports: {
read: () => true,
instrumentation: () => true
}
};
}
/** @param {string} str */
function posixify(str) {
return str.replace(/\\/g, '/');
}