-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathconfig.ts
More file actions
207 lines (179 loc) · 6.53 KB
/
config.ts
File metadata and controls
207 lines (179 loc) · 6.53 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
202
203
204
205
206
207
import type { Plugin } from '@web/dev-server-core';
import type { DevServerConfig } from '@web/dev-server';
import type { Middleware, Context, Next } from 'koa';
import { readdir, stat } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import rollupReplace from '@rollup/plugin-replace';
import { litCss, type LitCSSOptions } from 'web-dev-server-plugin-lit-css';
import { fromRollup } from '@web/dev-server-rollup';
import { esbuildPlugin } from '@web/dev-server-esbuild';
import { getPfeConfig, type PfeConfig } from '../config.js';
import {
importMapGeneratorPlugin,
type Options as ImportMapOptions,
} from './plugins/import-map-generator.js';
import { pfeDevServerPlugin } from './plugins/pfe-dev-server.js';
import { join } from 'node:path';
const replace = fromRollup(rollupReplace);
type BaseConfig = DevServerConfig & PfeConfig;
export interface PfeDevServerConfigOptions extends BaseConfig {
hostname?: string;
litcssOptions?: LitCSSOptions;
tsconfig?: string;
/** Extra dev server plugins */
loadDemo?: boolean;
plugins?: Plugin[];
watchFiles?: string;
importMapOptions?: ImportMapOptions;
}
function normalizeOptions(options?: PfeDevServerConfigOptions) {
const config: PfeDevServerConfigOptions = {
...getPfeConfig(),
...options ?? {},
};
/**
* Plain case: this file is running from `/node_modules/@patternfly/pfe-tools`.
* two dirs up from here is `node_modules`, so we just shear it clean off the path string
* Other case: this file is running in the `patternfly/patternfly-elements` monorepo
* two dirs up from here is the project root. There is no `/node_modules$` to replace,
* so we get the correct path
* Edge/Corner cases: all other cases must set the `rootDir` option themselves so as to avoid 404s
*/
config.rootDir = options?.rootDir ?? fileURLToPath(new URL('../../..', import.meta.url))
.replace(/node_modules\/$/, '/')
.replace(/\/node_modules$/, '/')
.replace('//', '/');
config.importMapOptions ??= {} as PfeDevServerConfigOptions['importMapOptions'];
config.importMapOptions!.providers ??= {};
config.site = { ...config.site, ...options?.site ?? {} };
config.loadDemo ??= true;
config.watchFiles ??= '{elements,core}/**/*.{css,html}';
config.litcssOptions ??= {
include: /\.css$/,
exclude: /(?:@patternfly\/pfe-tools\/dev-server\/(?:fonts|demo).css)|-lightdom(?:-shim)?\.css$/,
};
return config as Required<PfeDevServerConfigOptions> & { site: Required<PfeConfig['site']> };
}
/**
* CORS middleware
* @param ctx koa context
* @param next middleware
*/
function cors(ctx: Context, next: Next) {
ctx.set('Access-Control-Allow-Origin', '*');
return next();
}
async function cacheBusterMiddleware(ctx: Context, next: Next) {
await next();
if (ctx.path.match(/(elements|pfe-core)\/.*\.js$/)) {
const stats = await stat(join(process.cwd(), ctx.path));
const mtime = stats.mtime.getTime();
const etag = `modified-${mtime}`;
ctx.response.set('Cache-Control', 'no-store, no-cache, must-revalidate');
ctx.response.set('Pragma', 'no-cache');
ctx.response.set('Last-Modified', mtime.toString());
ctx.response.etag = etag;
}
}
function liveReloadTsChangesMiddleware(
config: ReturnType<typeof normalizeOptions>,
): Middleware {
/**
* capture group 1:
* Either config.elementsDir or `pfe-core`
* `/`
* **ANY** (_>= 0x_)
* `.js`
*/
const TYPESCRIPT_SOURCES_RE = new RegExp(`(${config.elementsDir}|pfe-core)/.*\\.js`);
return function(ctx, next) {
if (!ctx.path.includes('node_modules') && ctx.path
.match(TYPESCRIPT_SOURCES_RE)) {
ctx.redirect(ctx.path.replace('.js', '.ts'));
} else {
return next();
}
};
}
/**
* Creates a default config for PFE's dev server.
* @param options dev server config
*/
export function pfeDevServerConfig(options?: PfeDevServerConfigOptions): DevServerConfig {
const config = normalizeOptions(options);
const tsconfig = config?.tsconfig;
return {
...options ?? {},
rootDir: config.rootDir,
middleware: [
cors,
cacheBusterMiddleware,
liveReloadTsChangesMiddleware(config),
...config?.middleware ?? [],
],
plugins: [
// Dev server app which loads component demo files
pfeDevServerPlugin(config),
// serve typescript sources as javascript
esbuildPlugin({
ts: true,
tsconfig,
}),
replace({
'preventAssignment': true,
'process.env.NODE_ENV': '"production"',
}),
// load .css files as lit CSSResult modules
litCss(config.litcssOptions),
importMapGeneratorPlugin({
...config.importMapOptions,
providers: {
'construct-style-sheets-polyfill': 'nodemodules',
'element-internals-polyfill': 'nodemodules',
'lit-html': 'nodemodules',
'lit': 'nodemodules',
'zero-md': 'nodemodules',
'codemirror': 'nodemodules',
'@codemirror/lang-html': 'nodemodules',
'@codemirror/language': 'nodemodules',
'@codemirror/autocomplete': 'nodemodules',
'@codemirror/view': 'nodemodules',
'@lit/reactive-element': 'nodemodules',
'@lit/context': 'nodemodules',
...config.importMapOptions?.providers,
},
resolveHtmlUrl(fileUrl, rootUrl) {
const override = config.importMapOptions.resolveHtmlUrl?.(fileUrl, rootUrl);
if (override) {
return override;
} else {
return fileUrl.replace('/components/', '/elements/pf-');
}
},
}),
...config?.plugins ?? [],
],
};
}
/**
* Returns an import map `imports` section containing the entire
* `@patternfly/icons` collection, pointing to node_modules
* @param rootUrl repository root
*/
export async function getPatternflyIconNodemodulesImports(
rootUrl: string,
): Promise<Record<string, string>> {
const files = await readdir(new URL('./node_modules/@patternfly/icons', rootUrl));
const dirs = [];
for (const dir of files) {
if (!dir.startsWith('.') && (await stat(new URL(`./node_modules/@patternfly/icons/${dir}`, rootUrl))).isDirectory()) {
dirs.push(dir);
}
}
const specs = await Promise.all(dirs.flatMap(dir =>
readdir(new URL(`./node_modules/@patternfly/icons/${dir}`, rootUrl))
.then(files => files.filter(x => x.endsWith('.js')))
.then(icons => icons.flatMap(icon => `@patternfly/icons/${dir}/${icon}`))
));
return Object.fromEntries(specs.flat().map(spec => [spec, `./node_modules/${spec}`]));
}