Skip to content

Commit

Permalink
[ci] yarn format
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott authored and actions-user committed Mar 31, 2021
1 parent d3859c8 commit 16f58b9
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 62 deletions.
54 changes: 42 additions & 12 deletions snowpack/src/build/build-import-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import postCss from 'postcss';
import postCssModules from 'postcss-modules';
import {logger} from '../logger';
import {SnowpackConfig} from '../types';
import {appendHtmlToHead, hasExtension, spliceString, HMR_CLIENT_CODE, HMR_OVERLAY_CODE} from '../util';
import {
appendHtmlToHead,
hasExtension,
spliceString,
HMR_CLIENT_CODE,
HMR_OVERLAY_CODE,
} from '../util';
import {generateSRI} from './import-sri';
import {scanImportGlob} from '../scan-import-glob';

Expand Down Expand Up @@ -164,35 +170,59 @@ if (typeof document !== 'undefined') {${
return wrapImportMeta({code: cssImportProxyCode, hmr, env: false, config});
}

function createImportGlobValue(importGlob, i: number): { value: string, imports: string } {
function createImportGlobValue(importGlob, i: number): {value: string; imports: string} {
let value: string;
let imports: string;

if (importGlob.isEager) {
value = `{\n${importGlob.resolvedImports.map((spec: string, j: number, { length: len }) => `\t"${spec}": __glob__${i}_${j}${j === len - 1 ? '' : ','}`).join('\n')}\n}`;
imports = importGlob.resolvedImports.map((spec: string, j: number) => `import * as __glob__${i}_${j} from '${spec}';`).join('\n');
value = `{\n${importGlob.resolvedImports
.map(
(spec: string, j: number, {length: len}) =>
`\t"${spec}": __glob__${i}_${j}${j === len - 1 ? '' : ','}`,
)
.join('\n')}\n}`;
imports = importGlob.resolvedImports
.map((spec: string, j: number) => `import * as __glob__${i}_${j} from '${spec}';`)
.join('\n');
} else {
value = `{\n${importGlob.resolvedImports.map((spec: string, j: number, { length: len }) => `\t"${spec}": () => import("${spec}")${j === len - 1 ? '' : ','}`).join('\n')}\n}`;
value = `{\n${importGlob.resolvedImports
.map(
(spec: string, j: number, {length: len}) =>
`\t"${spec}": () => import("${spec}")${j === len - 1 ? '' : ','}`,
)
.join('\n')}\n}`;
imports = '';
}

return { value, imports };
return {value, imports};
}

export async function transformGlobImports({ contents: _code, resolveImportGlobSpecifier = async (i) => [i] }: { contents: string, resolveImportGlobSpecifier: any }) {
export async function transformGlobImports({
contents: _code,
resolveImportGlobSpecifier = async (i) => [i],
}: {
contents: string;
resolveImportGlobSpecifier: any;
}) {
const importGlobs = scanImportGlob(_code);
let rewrittenCode = _code;
const resolvedImportGlobs = await Promise.all(importGlobs.reverse().map(({ glob, ...importGlob }) => {
return resolveImportGlobSpecifier(glob).then(resolvedImports => ({ ...importGlob, glob, resolvedImports }))
}))
const resolvedImportGlobs = await Promise.all(
importGlobs.reverse().map(({glob, ...importGlob}) => {
return resolveImportGlobSpecifier(glob).then((resolvedImports) => ({
...importGlob,
glob,
resolvedImports,
}));
}),
);

resolvedImportGlobs.forEach((importGlob, i) => {
const { value, imports } = createImportGlobValue(importGlob, i);
const {value, imports} = createImportGlobValue(importGlob, i);
rewrittenCode = spliceString(rewrittenCode, value, importGlob.start, importGlob.end);
if (imports) {
rewrittenCode = `${imports}\n${rewrittenCode}`;
}
})
});

return rewrittenCode;
}
Expand Down
6 changes: 3 additions & 3 deletions snowpack/src/build/file-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export class FileBuilder {
}
// Finalize the response
contents = this.finalizeResult(type, contents);
//
//
const resolveImportGlobSpecifier = createImportGlobResolver({
fileLoc: this.loc,
config: this.config,
Expand Down Expand Up @@ -179,8 +179,8 @@ export class FileBuilder {
],
this.config,
);
contents = await transformGlobImports({ contents, resolveImportGlobSpecifier })
contents = await transformFileImports({type, contents }, async (spec) => {
contents = await transformGlobImports({contents, resolveImportGlobSpecifier});
contents = await transformFileImports({type, contents}, async (spec) => {
let resolvedImportUrl = await resolveImport(spec);

// Handle normal "./" & "../" import specifiers
Expand Down
32 changes: 16 additions & 16 deletions snowpack/src/build/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,24 +167,24 @@ export function createImportGlobResolver({
searchSpec = path.relative(path.dirname(fileLoc), searchSpec);
}



const resolved = await new Promise<string[]>((resolve, reject) =>
glob(searchSpec, { cwd: path.dirname(fileLoc), nodir: true }, (err, matches) => {
const resolved = await new Promise<string[]>((resolve, reject) =>
glob(searchSpec, {cwd: path.dirname(fileLoc), nodir: true}, (err, matches) => {
if (err) {
return reject(err)
return reject(err);
}
return resolve(matches)
})
return resolve(matches);
}),
);
return resolved.map((fileLoc) => {
const normalized = slash(fileLoc);
if (normalized.startsWith('.') || normalized.startsWith('/')) return normalized;
return `./${normalized}`;
}).filter(_fileLoc => {
// If final import *might* be the same as the source file, double check to avoid importing self
const finalImportAbsolute = slash(path.resolve(path.dirname(fileLoc), toPath(_fileLoc)));
return slash(finalImportAbsolute) !== slash(fileLoc);
});
return resolved
.map((fileLoc) => {
const normalized = slash(fileLoc);
if (normalized.startsWith('.') || normalized.startsWith('/')) return normalized;
return `./${normalized}`;
})
.filter((_fileLoc) => {
// If final import *might* be the same as the source file, double check to avoid importing self
const finalImportAbsolute = slash(path.resolve(path.dirname(fileLoc), toPath(_fileLoc)));
return slash(finalImportAbsolute) !== slash(fileLoc);
});
};
}
41 changes: 24 additions & 17 deletions snowpack/src/lexer-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,31 @@ export function checkIdent(code: string, pos: number, text: string): boolean {
}

export function isEOL(code: string, pos: number): boolean {
return (code.charAt(pos) === '\n') || (code.charAt(pos) === '\r' && code.charAt(pos + 1) === '\n');
return code.charAt(pos) === '\n' || (code.charAt(pos) === '\r' && code.charAt(pos + 1) === '\n');
}

/*
* Adopted from https://github.com/guybedford/es-module-lexer
* Licensed under the
*
/*
* Adopted from https://github.com/guybedford/es-module-lexer
* Licensed under the
*
* MIT License
* -----------
*
*
* Copyright (C) 2018-2019 Guy Bedford
*
* Permission is hereby granted, free of charge, to any person obtaining
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Expand All @@ -36,18 +36,25 @@ export function isEOL(code: string, pos: number): boolean {

export function isBrOrWsOrPunctuatorNotDot(ch: string): boolean {
const c = ch.charCodeAt(0);
return c > 8 && c < 14 || c == 32 || c == 160 || isPunctuator(ch) && ch != '.';
return (c > 8 && c < 14) || c == 32 || c == 160 || (isPunctuator(ch) && ch != '.');
}

export function isPunctuator(ch: string): boolean {
const c = ch.charCodeAt(0);
// 23 possible punctuator endings: !%&()*+,-./:;<=>?[]^{}|~
return ch == '!' || ch == '%' || ch == '&' ||
c > 39 && c < 48 || c > 57 && c < 64 ||
ch == '[' || ch == ']' || ch == '^' ||
c > 122 && c < 127;
return (
ch == '!' ||
ch == '%' ||
ch == '&' ||
(c > 39 && c < 48) ||
(c > 57 && c < 64) ||
ch == '[' ||
ch == ']' ||
ch == '^' ||
(c > 122 && c < 127)
);
}

export function keywordStart (source: string, pos: number) {
export function keywordStart(source: string, pos: number) {
return pos === 0 || isBrOrWsOrPunctuatorNotDot(source.charAt(pos - 1));
}
2 changes: 1 addition & 1 deletion snowpack/src/rewrite-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export async function transformFileImports(
replaceImport: (specifier: string) => string | Promise<string>,
) {
if (type === '.js') {
return transformEsmImports(contents, replaceImport)
return transformEsmImports(contents, replaceImport);
}
if (type === '.html') {
return transformHtmlImports(contents, replaceImport);
Expand Down
22 changes: 13 additions & 9 deletions snowpack/src/scan-import-glob.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { keywordStart, checkIdent, isEOL } from './lexer-util';
import {keywordStart, checkIdent, isEOL} from './lexer-util';

export interface ImportGlobStatement {
start: number;
Expand Down Expand Up @@ -33,12 +33,12 @@ export function scanImportGlob(code: string) {
let state = ScannerState.idle;

let importGlobs: ImportGlobStatement[] = [];
let importGlob: ImportGlobStatement|null = null;
let importGlob: ImportGlobStatement | null = null;
let glob: string = '';

while (pos++ < code.length) {
const ch = code.charAt(pos);

if (isInQuote(state)) {
switch (ch) {
case '"':
Expand All @@ -56,7 +56,7 @@ export function scanImportGlob(code: string) {

if (isInComment(state)) {
if (state === ScannerState.inSingleLineComment && isEOL(code, pos)) {
state = ScannerState.idle;
state = ScannerState.idle;
} else if (state === ScannerState.inMutliLineComment && checkIdent(code, pos, '*/')) {
state = ScannerState.idle;
} else {
Expand Down Expand Up @@ -98,7 +98,7 @@ export function scanImportGlob(code: string) {
if (state === ScannerState.onImportMeta && checkIdent(code, pos, 'glob')) {
state = ScannerState.onImportMetaGlob;
const isEager = checkIdent(code, pos, 'globEager');
importGlob = { start, isEager } as any;
importGlob = {start, isEager} as any;
}
break;
}
Expand All @@ -112,7 +112,7 @@ export function scanImportGlob(code: string) {
glob = '';
break;
}
case "`": {
case '`': {
state = ScannerState.inTemplateLiteral;
glob = '';
break;
Expand All @@ -125,7 +125,7 @@ export function scanImportGlob(code: string) {
state = ScannerState.idle;
end = pos + 1;
if (importGlob) {
Object.assign(importGlob, { glob, end });
Object.assign(importGlob, {glob, end});
importGlobs.push(importGlob);
importGlob = null;
start = 0;
Expand All @@ -140,9 +140,13 @@ export function scanImportGlob(code: string) {
}

function isInQuote(state: ScannerState): boolean {
return state === ScannerState.inDoubleQuote || state === ScannerState.inSingleQuote || state === ScannerState.inTemplateLiteral
return (
state === ScannerState.inDoubleQuote ||
state === ScannerState.inSingleQuote ||
state === ScannerState.inTemplateLiteral
);
}

function isInComment(state: ScannerState): boolean {
return state === ScannerState.inSingleLineComment || state === ScannerState.inMutliLineComment
return state === ScannerState.inSingleLineComment || state === ScannerState.inMutliLineComment;
}
2 changes: 1 addition & 1 deletion test/build/import-glob/src/globCommented.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* import.meta.glob('./pages/*.js'); */
// import.meta.glob('./pages/*.js');
// import.meta.glob('./pages/*.js');

const modules = null; // import.meta.glob('./pages/*.js');

Expand Down
2 changes: 1 addition & 1 deletion test/build/import-glob/src/pages/a.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export default 'a'
export default 'a';
2 changes: 1 addition & 1 deletion test/build/import-glob/src/pages/b.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export default 'b'
export default 'b';
2 changes: 1 addition & 1 deletion test/build/import-glob/src/pages/c.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export default 'c'
export default 'c';

1 comment on commit 16f58b9

@vercel
Copy link

@vercel vercel bot commented on 16f58b9 Mar 31, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.