Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott committed Mar 6, 2020
1 parent 9b6704b commit 2f7c72b
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 27 deletions.
42 changes: 31 additions & 11 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import path from 'path';
import {cosmiconfigSync} from 'cosmiconfig';
import {Plugin} from 'rollup';
import {validate} from 'jsonschema';
import merge from 'deepmerge';
import {all as merge} from 'deepmerge';

const CONFIG_NAME = 'snowpack';

Expand All @@ -17,7 +17,8 @@ type DeepPartial<T> = {
// interface this library uses internally
export interface SnowpackConfig {
source: 'local' | 'pika';
webDependencies?: string[];
webDependencies?: {[packageName: string]: string};
entrypoints?: string[];
dedupe?: string[];
namedExports?: {[filepath: string]: string[]};
installOptions: {
Expand Down Expand Up @@ -51,8 +52,7 @@ export interface CLIFlags extends Partial<SnowpackConfig['installOptions']> {
}

// default settings
const DEFAULT_CONFIG: SnowpackConfig = {
source: 'local',
const DEFAULT_CONFIG: Partial<SnowpackConfig> = {
dedupe: [],
installOptions: {
clean: false,
Expand All @@ -73,7 +73,12 @@ const configSchema = {
type: 'object',
properties: {
source: {type: 'string'},
webDependencies: {type: 'array', items: {type: 'string'}},
entrypoints: {type: 'array', items: {type: 'string'}},
webDependencies: {
type: ['array', 'object'],
additionalProperties: {type: 'string'},
items: {type: 'string'},
},
dedupe: {
type: 'array',
items: {type: 'string'},
Expand Down Expand Up @@ -126,13 +131,21 @@ function expandCliFlags(flags: CLIFlags): DeepPartial<SnowpackConfig> {
return result;
}

/** resolve --dest relative to cwd */
function normalizeDest(config: SnowpackConfig) {
/** resolve --dest relative to cwd, and set the default "source" */
function normalizeConfig(config: SnowpackConfig): SnowpackConfig {
config.installOptions.dest = path.resolve(process.cwd(), config.installOptions.dest);
if (Array.isArray(config.webDependencies)) {
config.entrypoints = config.webDependencies;
delete config.webDependencies;
}
if (!config.source) {
const isDetailedObject = config.webDependencies && typeof config.webDependencies === 'object';
config.source = isDetailedObject ? 'pika' : 'local';
}
return config;
}

export default function loadConfig(flags: CLIFlags) {
export default function loadConfig(flags: CLIFlags, pkgManifest: any) {
const cliConfig = expandCliFlags(flags);

const explorerSync = cosmiconfigSync(CONFIG_NAME, {
Expand Down Expand Up @@ -160,7 +173,9 @@ export default function loadConfig(flags: CLIFlags) {
if (!result || !result.config || result.isEmpty) {
// if CLI flags present, apply those as overrides
return {
config: normalizeDest(merge<any>(DEFAULT_CONFIG, cliConfig)),
config: normalizeConfig(
merge<SnowpackConfig>([DEFAULT_CONFIG, cliConfig as any]),
),
errors,
};
}
Expand All @@ -174,11 +189,16 @@ export default function loadConfig(flags: CLIFlags) {
});

// if valid, apply config over defaults
const mergedConfig = merge(DEFAULT_CONFIG, config);
const mergedConfig = merge<SnowpackConfig>([
DEFAULT_CONFIG,
{webDependencies: pkgManifest.webDependencies},
config,
cliConfig as any,
]);

// if CLI flags present, apply those as overrides
return {
config: normalizeDest(merge<any>(mergedConfig, cliConfig)),
config: normalizeConfig(mergedConfig),
errors: validation.errors.map(msg => `${path.basename(result.filepath)}: ${msg.toString()}`),
};
}
29 changes: 15 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ export async function install(
if (Object.keys(installEntrypoints).length > 0) {
try {
const packageBundle = await rollup(inputOptions);
logUpdate('');
logUpdate(formatInstallResults(skipFailures));
await packageBundle.write(outputOptions);
} catch (err) {
const {loc} = err as RollupError;
Expand Down Expand Up @@ -486,8 +486,17 @@ export async function cli(args: string[]) {
await clearCache();
}

// Load the current package manifest
let pkgManifest: any;
try {
pkgManifest = require(path.join(cwd, 'package.json'));
} catch (err) {
console.log(chalk.red('[ERROR] package.json required but no file was found.'));
process.exit(0);
}

// load config
const {config, errors} = loadConfig(cliFlags);
const {config, errors} = loadConfig(cliFlags, pkgManifest);

// handle config errors (if any)
if (Array.isArray(errors) && errors.length) {
Expand All @@ -510,18 +519,10 @@ export async function cli(args: string[]) {

const {
installOptions: {clean, dest, exclude, include},
webDependencies,
entrypoints: configInstallTargets,
source,
} = config;

let pkgManifest: any;
try {
pkgManifest = require(path.join(cwd, 'package.json'));
} catch (err) {
console.log(chalk.red('[ERROR] package.json required but no file was found.'));
process.exit(0);
}

const implicitDependencies = [
...Object.keys(pkgManifest.peerDependencies || {}),
...Object.keys(pkgManifest.dependencies || {}),
Expand All @@ -535,15 +536,15 @@ export async function cli(args: string[]) {
let isExplicit = false;
const installTargets: InstallTarget[] = [];

if (webDependencies) {
if (configInstallTargets) {
isExplicit = true;
installTargets.push(...scanDepList(webDependencies, cwd));
installTargets.push(...scanDepList(configInstallTargets, cwd));
}
if (include) {
isExplicit = true;
installTargets.push(...(await scanImports({include, exclude})));
}
if (!webDependencies && !include) {
if (!isExplicit) {
installTargets.push(...scanDepList(implicitDependencies, cwd));
}
if (installTargets.length === 0) {
Expand Down
2 changes: 2 additions & 0 deletions src/resolve-remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ export async function resolveTargetsFromRemoteCDN(
const allInstallSpecifiers = new Set(installTargets.map(dep => dep.specifier));
for (const installSpecifier of allInstallSpecifiers) {
const installSemver: string =
(config.webDependencies || {})[installSpecifier] ||
(pkgManifest.webDependencies || {})[installSpecifier] ||
(pkgManifest.dependencies || {})[installSpecifier] ||
(pkgManifest.devDependencies || {})[installSpecifier] ||
(pkgManifest.peerDependencies || {})[installSpecifier] ||
Expand Down
3 changes: 2 additions & 1 deletion src/rollup-plugin-remote-cdn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function rollupPluginDependencyCache({log}: {log: (url: string) => void})
// If the source path is a CDN path including a hash, it's assumed the
// file will never change and it is safe to pull from our local cache
// without a network request.
log(source);
log(cacheKey);
if (HAS_CDN_HASH_REGEX.test(source)) {
const cachedResult = await cacache.get
.info(RESOURCE_CACHE, cacheKey)
Expand Down Expand Up @@ -61,6 +61,7 @@ export function rollupPluginDependencyCache({log}: {log: (url: string) => void})
return null;
}
const cacheKey = id.substring(CACHED_FILE_ID_PREFIX.length);
log(cacheKey);
const cachedResult = await cacache.get(RESOURCE_CACHE, cacheKey);
return cachedResult.data.toString('utf8');
},
Expand Down
2 changes: 1 addition & 1 deletion test/integration/config-invalid/expected-output.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
⠼ snowpack installing...
✖ package.json: snowpack.webDependencies is not of a type(s) array
✖ package.json: snowpack.webDependencies is not of a type(s) array,object

0 comments on commit 2f7c72b

Please sign in to comment.