@embroider/vite 0.0.1-unstable.2c0e2bd

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/.eslintignore ADDED
@@ -0,0 +1,11 @@
1
+ # compiled output
2
+ /src/**/*.js
3
+ /src/**/*.d.ts
4
+
5
+ # shims
6
+ /index.d.ts
7
+ /index.mjs
8
+
9
+ # dependencies
10
+ /node_modules/
11
+
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './src/resolver.js';
2
+ export * from './src/hbs.js';
3
+ export * from './src/scripts.js';
4
+ export * from './src/template-tag.js';
5
+ export * from './src/addons.js';
package/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ export * from './src/resolver.js';
2
+ export * from './src/hbs.js';
3
+ export * from './src/scripts.js';
4
+ export * from './src/template-tag.js';
5
+ export * from './src/addons.js';
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@embroider/vite",
3
+ "version": "0.0.1-unstable.2c0e2bd",
4
+ "main": "index.mjs",
5
+ "peerDependencies": {
6
+ "@embroider/core": "3.1.4-unstable.2c0e2bd",
7
+ "vite": "^4.3.9"
8
+ },
9
+ "dependencies": {
10
+ "@rollup/pluginutils": "^4.1.1",
11
+ "assert-never": "^1.2.1",
12
+ "content-tag": "^1.0.0",
13
+ "debug": "^4.3.2",
14
+ "fs-extra": "^10.0.0",
15
+ "jsdom": "^16.6.0",
16
+ "source-map-url": "^0.4.1",
17
+ "terser": "^5.7.0"
18
+ },
19
+ "devDependencies": {
20
+ "@embroider/core": "3.1.4-unstable.2c0e2bd",
21
+ "@types/debug": "^4.1.5",
22
+ "@types/jsdom": "^16.2.11",
23
+ "@types/fs-extra": "^9.0.12",
24
+ "rollup": "^3.23.0",
25
+ "vite": "^4.3.9"
26
+ }
27
+ }
package/src/addons.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { ResolverLoader, packageName } from '@embroider/core';
2
+
3
+ export function addons(root: string): string[] {
4
+ let rloader = new ResolverLoader(root);
5
+ let { options } = rloader.resolver;
6
+ let names = new Set<string>();
7
+ for (let from of Object.keys(options.renameModules)) {
8
+ let pName = packageName(from);
9
+ if (pName) {
10
+ names.add(pName);
11
+ }
12
+ }
13
+ for (let from of Object.keys(options.renamePackages)) {
14
+ names.add(from);
15
+ }
16
+ for (let name of Object.keys(options.activeAddons)) {
17
+ names.add(name);
18
+ }
19
+ return [...names];
20
+ }
package/src/hbs.ts ADDED
@@ -0,0 +1,129 @@
1
+ // TODO: I copied this from @embroider/addon-dev, it needs to be its own package
2
+ // (or be in shared-internals or core)
3
+ import { createFilter } from '@rollup/pluginutils';
4
+ import type { PluginContext, ResolvedId } from 'rollup';
5
+ import type { Plugin } from 'vite';
6
+ import { readFileSync } from 'fs';
7
+ import { hbsToJS } from '@embroider/core';
8
+ import assertNever from 'assert-never';
9
+ import { parse as pathParse } from 'path';
10
+ import makeDebug from 'debug';
11
+
12
+ const debug = makeDebug('embroider:hbs-plugin');
13
+
14
+ export function hbs(): Plugin {
15
+ return {
16
+ name: 'rollup-hbs-plugin',
17
+ enforce: 'pre',
18
+ async resolveId(source: string, importer: string | undefined) {
19
+ let resolution = await this.resolve(source, importer, {
20
+ skipSelf: true,
21
+ });
22
+
23
+ if (!resolution) {
24
+ return maybeSynthesizeComponentJS(this, source, importer);
25
+ } else {
26
+ return maybeRewriteHBS(resolution);
27
+ }
28
+ },
29
+
30
+ load(id: string) {
31
+ const meta = getMeta(this, id);
32
+ if (!meta) {
33
+ return;
34
+ }
35
+
36
+ switch (meta.type) {
37
+ case 'template':
38
+ let input = readFileSync(id, 'utf8');
39
+ let code = hbsToJS(input);
40
+ return {
41
+ code,
42
+ };
43
+ case 'template-only-component-js':
44
+ return {
45
+ code: templateOnlyComponent,
46
+ };
47
+ default:
48
+ assertNever(meta);
49
+ }
50
+ },
51
+ };
52
+ }
53
+
54
+ const templateOnlyComponent =
55
+ `import templateOnly from '@ember/component/template-only';\n` + `export default templateOnly();\n`;
56
+
57
+ type Meta =
58
+ | {
59
+ type: 'template';
60
+ }
61
+ | {
62
+ type: 'template-only-component-js';
63
+ };
64
+
65
+ function getMeta(context: PluginContext, id: string): Meta | null {
66
+ const meta = context.getModuleInfo(id)?.meta?.['rollup-hbs-plugin'];
67
+ if (meta) {
68
+ return meta as Meta;
69
+ } else {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ function correspondingTemplate(filename: string): string {
75
+ let { ext } = pathParse(filename);
76
+ return filename.slice(0, filename.length - ext.length) + '.hbs';
77
+ }
78
+
79
+ async function maybeSynthesizeComponentJS(context: PluginContext, source: string, importer: string | undefined) {
80
+ debug(`checking for template-only component: %s`, source);
81
+ let templateResolution = await context.resolve(correspondingTemplate(source), importer, {
82
+ skipSelf: true,
83
+ custom: {
84
+ embroider: {
85
+ // we don't want to recurse into the whole embroider compatbility
86
+ // resolver here. It has presumably already steered our request to the
87
+ // correct place. All we want to do is slightly modify the request we
88
+ // were given (changing the extension) and check if that would resolve
89
+ // instead.
90
+ //
91
+ // Currently this guard is only actually exercised in rollup, not in
92
+ // vite, due to https://github.com/vitejs/vite/issues/13852
93
+ enableCustomResolver: false,
94
+ },
95
+ },
96
+ });
97
+ if (!templateResolution) {
98
+ return null;
99
+ }
100
+ debug(`emitting template only component: %s`, templateResolution.id);
101
+
102
+ // we're trying to resolve a JS module but only the corresponding HBS
103
+ // file exists. Synthesize the template-only component JS.
104
+ return {
105
+ id: templateResolution.id.replace(/\.hbs$/, '.js'),
106
+ meta: {
107
+ 'rollup-hbs-plugin': {
108
+ type: 'template-only-component-js',
109
+ },
110
+ },
111
+ };
112
+ }
113
+
114
+ const hbsFilter = createFilter('**/*.hbs');
115
+
116
+ function maybeRewriteHBS(resolution: ResolvedId) {
117
+ if (!hbsFilter(resolution.id)) {
118
+ return null;
119
+ }
120
+ debug('emitting hbs rewrite: %s', resolution.id);
121
+ return {
122
+ ...resolution,
123
+ meta: {
124
+ 'rollup-hbs-plugin': {
125
+ type: 'template',
126
+ },
127
+ },
128
+ };
129
+ }
package/src/request.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { ModuleRequest, cleanUrl } from '@embroider/core';
2
+
3
+ export const virtualPrefix = 'embroider_virtual:';
4
+
5
+ export class RollupModuleRequest implements ModuleRequest {
6
+ static from(
7
+ source: string,
8
+ importer: string | undefined,
9
+ custom: Record<string, any> | undefined
10
+ ): RollupModuleRequest | undefined {
11
+ if (!(custom?.embroider?.enableCustomResolver ?? true)) {
12
+ return;
13
+ }
14
+
15
+ if (source && importer && source[0] !== '\0') {
16
+ let nonVirtual: string;
17
+ if (importer.startsWith(virtualPrefix)) {
18
+ nonVirtual = importer.slice(virtualPrefix.length);
19
+ } else {
20
+ nonVirtual = importer;
21
+ }
22
+
23
+ // strip query params off the importer
24
+ let fromFile = cleanUrl(nonVirtual);
25
+ return new RollupModuleRequest(source, fromFile, custom?.embroider?.meta);
26
+ }
27
+ }
28
+
29
+ private constructor(
30
+ readonly specifier: string,
31
+ readonly fromFile: string,
32
+ readonly meta: Record<string, any> | undefined
33
+ ) {}
34
+
35
+ get isVirtual(): boolean {
36
+ return this.specifier.startsWith(virtualPrefix);
37
+ }
38
+
39
+ alias(newSpecifier: string) {
40
+ return new RollupModuleRequest(newSpecifier, this.fromFile, this.meta) as this;
41
+ }
42
+ rehome(newFromFile: string) {
43
+ if (this.fromFile === newFromFile) {
44
+ return this;
45
+ } else {
46
+ return new RollupModuleRequest(this.specifier, newFromFile, this.meta) as this;
47
+ }
48
+ }
49
+ virtualize(filename: string) {
50
+ return new RollupModuleRequest(virtualPrefix + filename, this.fromFile, this.meta) as this;
51
+ }
52
+ withMeta(meta: Record<string, any> | undefined): this {
53
+ return new RollupModuleRequest(this.specifier, this.fromFile, meta) as this;
54
+ }
55
+ }
@@ -0,0 +1,69 @@
1
+ import type { PluginContext, ResolveIdResult } from 'rollup';
2
+ import { Plugin } from 'vite';
3
+ import { join } from 'path';
4
+ import {
5
+ Resolution,
6
+ Resolver,
7
+ ResolverFunction,
8
+ ResolverOptions,
9
+ locateEmbroiderWorkingDir,
10
+ virtualContent,
11
+ } from '@embroider/core';
12
+ import { readJSONSync } from 'fs-extra';
13
+ import { RollupModuleRequest, virtualPrefix } from './request';
14
+ import assertNever from 'assert-never';
15
+
16
+ export function resolver(): Plugin {
17
+ let resolverOptions: ResolverOptions = readJSONSync(join(locateEmbroiderWorkingDir(process.cwd()), 'resolver.json'));
18
+ let resolver = new Resolver(resolverOptions);
19
+
20
+ return {
21
+ name: 'embroider-resolver',
22
+ enforce: 'pre',
23
+ async resolveId(source, importer, options) {
24
+ let request = RollupModuleRequest.from(source, importer, options.custom);
25
+ if (!request) {
26
+ // fallthrough to other rollup plugins
27
+ return null;
28
+ }
29
+ let resolution = await resolver.resolve(request, defaultResolve(this));
30
+ switch (resolution.type) {
31
+ case 'found':
32
+ return resolution.result;
33
+ case 'not_found':
34
+ return null;
35
+ default:
36
+ throw assertNever(resolution);
37
+ }
38
+ },
39
+ load(id) {
40
+ if (id.startsWith(virtualPrefix)) {
41
+ return virtualContent(id.slice(virtualPrefix.length), resolver);
42
+ }
43
+ },
44
+ };
45
+ }
46
+
47
+ function defaultResolve(context: PluginContext): ResolverFunction<RollupModuleRequest, Resolution<ResolveIdResult>> {
48
+ return async (request: RollupModuleRequest) => {
49
+ if (request.isVirtual) {
50
+ return {
51
+ type: 'found',
52
+ result: { id: request.specifier, resolvedBy: request.fromFile },
53
+ };
54
+ }
55
+ let result = await context.resolve(request.specifier, request.fromFile, {
56
+ skipSelf: true,
57
+ custom: {
58
+ embroider: {
59
+ meta: request.meta,
60
+ },
61
+ },
62
+ });
63
+ if (result) {
64
+ return { type: 'found', result };
65
+ } else {
66
+ return { type: 'not_found', err: undefined };
67
+ }
68
+ };
69
+ }
package/src/scripts.ts ADDED
@@ -0,0 +1,136 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { EmittedFile } from 'rollup';
3
+ import { JSDOM } from 'jsdom';
4
+ import { readFileSync, readJSONSync } from 'fs-extra';
5
+ import { dirname, posix, resolve } from 'path';
6
+
7
+ // This is a type-only import, so it gets compiled away. At runtime, we load
8
+ // terser lazily so it's only loaded for production builds that use it. Don't
9
+ // add any non-type-only imports here.
10
+ import type { MinifyOptions } from 'terser';
11
+
12
+ const defaults = ['/assets/vendor.js', '/assets/test-support.js'];
13
+
14
+ export function scripts(params?: { include?: string[]; exclude?: string[] }): Plugin {
15
+ let optimizer: ScriptOptimizer;
16
+
17
+ // configured names are always interpreted as origin-absolute URLs.
18
+ let names = (params?.include ?? defaults)
19
+ .filter(name => !params?.exclude?.includes(name))
20
+ .map(name => {
21
+ if (name.startsWith('/')) {
22
+ return name;
23
+ } else {
24
+ return '/' + name;
25
+ }
26
+ });
27
+
28
+ return {
29
+ name: 'embroider-scripts',
30
+ enforce: 'pre',
31
+
32
+ configResolved(resolvedConfig) {
33
+ optimizer = new ScriptOptimizer(resolvedConfig.root);
34
+ },
35
+
36
+ async generateBundle() {
37
+ // this hook only runs in `vite build`
38
+ for (let name of names) {
39
+ for (let file of await optimizer.optimizedScript(name)) {
40
+ this.emitFile(file);
41
+ }
42
+ }
43
+ },
44
+
45
+ transformIndexHtml(htmlIn, context) {
46
+ // we don't do anything in `vite dev`, we only need to work in `vite
47
+ // build`
48
+ if (!context.server) {
49
+ return optimizer.transformHTML(htmlIn);
50
+ }
51
+ },
52
+ };
53
+ }
54
+
55
+ class ScriptOptimizer {
56
+ private emitted = new Map<string, string>();
57
+ private transformState:
58
+ | {
59
+ htmlIn: string;
60
+ htmlOut: string;
61
+ parsed: JSDOM;
62
+ }
63
+ | undefined;
64
+
65
+ constructor(private rootDir: string) {}
66
+
67
+ async optimizedScript(script: string): Promise<EmittedFile[]> {
68
+ // loading these lazily here so they never load in non-production builds.
69
+ // The node cache will ensures we only load them once.
70
+ const [Terser, srcURL] = await Promise.all([import('terser'), import('source-map-url')]);
71
+
72
+ let inCode = readFileSync(resolve(this.rootDir, script.slice(1)), 'utf8');
73
+ let terserOpts: MinifyOptions = {};
74
+ let fileRelativeSourceMapURL;
75
+ let appRelativeSourceMapURL;
76
+ if (srcURL.default.existsIn(inCode)) {
77
+ fileRelativeSourceMapURL = srcURL.default.getFrom(inCode)!;
78
+ appRelativeSourceMapURL = posix.join(dirname(script.slice(1)), fileRelativeSourceMapURL);
79
+ let content;
80
+ try {
81
+ content = readJSONSync(resolve(this.rootDir, appRelativeSourceMapURL));
82
+ } catch (err) {
83
+ // the script refers to a sourcemap that doesn't exist, so we just leave
84
+ // the map out.
85
+ }
86
+ if (content) {
87
+ terserOpts.sourceMap = { content, url: fileRelativeSourceMapURL };
88
+ }
89
+ }
90
+ let { code: outCode, map: outMap } = await Terser.default.minify(inCode, terserOpts);
91
+ let finalFilename = await this.getFingerprintedFilename(script, outCode!);
92
+ let emit: EmittedFile[] = [];
93
+ emit.push({
94
+ type: 'asset',
95
+ fileName: finalFilename.slice(1),
96
+ source: outCode!,
97
+ });
98
+ this.emitted.set(script, finalFilename);
99
+ if (appRelativeSourceMapURL && outMap) {
100
+ emit.push({
101
+ type: 'asset',
102
+ fileName: appRelativeSourceMapURL,
103
+ source: JSON.stringify(outMap, null, 2),
104
+ });
105
+ }
106
+ return emit;
107
+ }
108
+
109
+ async getFingerprintedFilename(filename: string, content: string): Promise<string> {
110
+ let crypto = await import('crypto');
111
+ let md5 = crypto.createHash('md5');
112
+ md5.update(content);
113
+ let hash = md5.digest('hex');
114
+ let fileParts = filename.split('.');
115
+ fileParts.splice(fileParts.length - 1, 0, hash);
116
+ return fileParts.join('.');
117
+ }
118
+
119
+ transformHTML(htmlIn: string) {
120
+ if (this.transformState?.htmlIn !== htmlIn) {
121
+ let parsed = new JSDOM(htmlIn);
122
+ let scriptTags = [...parsed.window.document.querySelectorAll('script')] as HTMLScriptElement[];
123
+ for (let scriptTag of scriptTags) {
124
+ if (scriptTag.type !== 'module') {
125
+ let fingerprinted = this.emitted.get(scriptTag.src);
126
+ if (fingerprinted) {
127
+ scriptTag.src = fingerprinted;
128
+ }
129
+ }
130
+ }
131
+ let htmlOut = parsed.serialize();
132
+ this.transformState = { htmlIn, parsed, htmlOut };
133
+ }
134
+ return this.transformState.htmlOut;
135
+ }
136
+ }
@@ -0,0 +1,50 @@
1
+ import { createFilter } from '@rollup/pluginutils';
2
+ import type { Plugin } from 'vite';
3
+ import { readFileSync } from 'fs';
4
+ import { Preprocessor } from 'content-tag';
5
+
6
+ const gjsFilter = createFilter('**/*.gjs');
7
+
8
+ export function templateTag(): Plugin {
9
+ let preprocessor = new Preprocessor();
10
+
11
+ function candidates(id: string) {
12
+ return [id + '.gjs'];
13
+ }
14
+
15
+ return {
16
+ name: 'embroider-template-tag',
17
+ enforce: 'pre',
18
+
19
+ async resolveId(id: string, importer: string | undefined) {
20
+ let resolution = await this.resolve(id, importer, {
21
+ skipSelf: true,
22
+ });
23
+ if (resolution) {
24
+ return resolution;
25
+ }
26
+ for (let candidate of candidates(id)) {
27
+ resolution = await this.resolve(candidate, importer, {
28
+ skipSelf: true,
29
+ custom: {
30
+ embroider: {
31
+ enableCustomResolver: false,
32
+ },
33
+ },
34
+ });
35
+ if (resolution) {
36
+ return {
37
+ id: resolution.id,
38
+ };
39
+ }
40
+ }
41
+ },
42
+
43
+ load(id: string) {
44
+ if (!gjsFilter(id)) {
45
+ return null;
46
+ }
47
+ return preprocessor.process(readFileSync(id, 'utf8'), id);
48
+ },
49
+ };
50
+ }