How to use upath - 10 common examples

To help you get started, we’ve selected a few upath examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aurelia / webpack-plugin / src / resolve-template.js View on Github external
async function getDependency(fromPath, relativeParent, srcPath, nodeModulesList, fromWithinModule, requestedBy, isLazy, bundleName, rootAlias, triedToCorrectPath, doNotAdd) {
  const dependencies = {};
  const requestedByRelativeToSrc = path.relative(srcPath, requestedBy);
  
  let split = requestedByRelativeToSrc.split(pathSep);
  if (split[0] == 'node_modules') {
    // handle edge case when adding htmlCounterpart
    nodeModulesList = nodeModulesList.concat([path.join(srcPath, 'node_modules')]);
    srcPath = path.join(srcPath, split[0], split[1]);
    fromWithinModule = split[1];
  }
  
  async function addDependency(webpackRequireString, webpackPath, htmlCounterpart, rootAlias, moduleName, modulePath) {
    if (/*filesProcessed.indexOf(webpackRequireString) == -1 && */webpackRequireString.indexOf('..') == -1) {
      dependencies[webpackRequireString] = webpackPath;
      console.log((fromWithinModule ? '<' + fromWithinModule + '> ' + '[' + path.basename(requestedBy) : '[' + requestedByRelativeToSrc) + '] required "' + webpackRequireString + '" from "' + webpackPath.replace(optionsGlobal.root + pathSep, '') + '".')
      filesProcessed.push(webpackRequireString);
    }
github GoogleChrome / workbox / gulp-tasks / transpile-typescript.js View on Github external
const transpilePackage = async (packageName) => {
  try {
    // Compile TypeScript for the given project.
    // Reference the local `node_modules` version of `tsc` since on Windows
    // it will call the version in `Microsoft SDKs/TypeScript`.
    await exec(`npm run local-tsc -- -b packages/${packageName}`);

    // Mirror all `.ts` files with `.mjs` files.
    const tsFiles = await globby(`**/*.ts`, {
      cwd: path.join('packages', packageName, 'src'),
    });

    for (const tsFile of tsFiles) {
      const assetBasename = path.basename(tsFile, '.ts');
      const mjsFile = path.join('packages',
          packageName, path.dirname(tsFile), assetBasename + '.mjs');

      if (!(await fs.pathExists(mjsFile))) {
        const mjsSource = `export * from './${assetBasename}.js';`;

        // console.log({mjsFile, tsFile, assetBasename})
        fs.outputFileSync(mjsFile, mjsSource);
      }
    }
  } catch (error) {
    logHelper.error(error.stdout);
    throw error;
  }
};
github ryanelian / instapack / src / CopyBuildTool.ts View on Github external
// file or folder does not exist, is probably a glob...
                if (FastGlob.isDynamicPattern(relativeFilePath)) {
                    globs.push(relativeFilePath);
                }
            }
        }

        const assets = await FastGlob(globs, {
            cwd: libraryPath
        }); // folder/something.svg

        const commonPath = this.findCommonParentFolderPath(assets); // folder
        // console.log('COMMON PATH:', commonPath);

        for (const asset of assets) {
            const absoluteFilePath = upath.join(libraryPath, asset); // /project/node_modules/library/folder/something.svg
            const relativeFilePath = upath.relative(commonPath, asset); // something.svg
            const targetFilePath = upath.join(targetPath, relativeFilePath); // /project/wwwroot/target/something.svg
            // console.log(relativeFilePath);
            // console.log(absoluteFilePath);
            // console.log(targetFilePath);
            const task = this.tryCopyFile(absoluteFilePath, targetFilePath, overwrite);
            tasks.push(task)
        }

        const success = await Promise.all(tasks);
        return success.filter(Q => Q).length;
    }
github ryanelian / instapack / src / index.ts View on Github external
async scaffold(template: string): Promise {
        const templateFolder = upath.join(__dirname, '../templates', template);

        const exist = await fse.pathExists(templateFolder);
        if (!exist) {
            Shout.error('Unable to find new project template for:', chalk.cyan(template));
            return;
        }

        let mergedPackageJson: unknown;
        const projectPackageJsonPath = upath.join(this.projectFolder, 'package.json');
        const templatePackageJsonPath = upath.join(templateFolder, 'package.json');
        if (await fse.pathExists(projectPackageJsonPath) && await fse.pathExists(templatePackageJsonPath)) {
            // would override, should merge fields instead: instapack, dependencies, and devDependencies
            const projectPackageJson = await fse.readJson(projectPackageJsonPath);
            const templatePackageJson = await fse.readJson(templatePackageJsonPath);

            mergedPackageJson = mergePackageJson(projectPackageJson, templatePackageJson);
        }

        console.log('Initializing new project using template:', chalk.cyan(template));
        console.log('Scaffolding project into your web app...');
        await fse.copy(templateFolder, this.projectFolder);

        if (mergedPackageJson) {
            console.log(`Merging ${chalk.blue('package.json')}...`);
            await fse.writeJson(projectPackageJsonPath, mergedPackageJson, {
                spaces: 2
github pingyhq / pingy-cli / packages / export / lib / index.js View on Github external
compiled.result
                          }\n/*# ${sourcemapStr}*/`;
                        } else if (compiled.extension === '.js') {
                          // # sourceMappingURL=script.js.map
                          // eslint-disable-next-line no-param-reassign
                          compiled.result = `${
                            compiled.result
                          }\n//# ${sourcemapStr}`;
                        }
                      }

                      writeFiles.push(
                        fsp.writeFile(compiledOutputFullPath, compiled.result)
                      );
                      fileNames.push(
                        path.relative(outputDir, compiledOutputFullPath)
                      );

                      shas.push({
                        type: compiled.transformId,
                        inputSha: compiled.inputSha.map(x => ({
                          file: path.relative(inputDir, x.file),
                          sha: x.sha,
                        })),
                        outputSha: createHash(compiled.result),
                        input: relativePath,
                        output: fileNames,
                      });
                      eventEmitter.emit('compile-done', file);
                      return Promise.all(writeFiles).then(() => {
                        fileNames.forEach(addFileToWhitelist);
                      });
github ryanelian / instapack / src / SassBuildTool.ts View on Github external
inline: false,
                prev: false
            };
        }

        const postcssResult = await postcss([
            autoprefixer()
        ]).process(sassResult.css, postcssOptions);

        const result: CssBuildResult = {
            css: postcssResult.css
        };

        if (this.variables.sourceMap && sassResult.map && postcssResult.map) {
            const sm2 = postcssResult.map.toJSON();
            const abs = upath.resolve(upath.dirname(virtualPostcssOutputPath), sm2.sources[0]);
            // console.log(abs);

            sm2.sources[0] = '/' + upath.relative(this.variables.root, abs);
            // console.log(sm2.sources);
            // console.log(sm2.file);

            result.map = mergeSourceMap(sassResult.map, sm2);
            /*
            => Found "merge-source-map@1.1.0"
            info Reasons this module exists
            - Hoisted from "vue-loader#@vue#component-compiler-utils#merge-source-map"
            */
        }

        return result;
    }
github pixelnest / presskit.html / lib / core / generator.js View on Github external
async function copyMandatoryFiles () {
  const buildDir = createAndGetBuildFolder()

  for (const f of assetsToCopy) {
    const filepath = path.resolve(f)

    // Get filename and dirname from the provided path.
    const filename = path.basename(filepath)
    const dirname = path.basename(path.dirname(filepath))

    // Create the directory for this file if needed.
    // ie. css/master.css needs a `css` directory.
    const targetDir = path.join(buildDir, dirname)
    sfs.createDir(targetDir)

    // And copy the file.
    const targetPath = path.join(targetDir, filename)

    console.log('- ' + targetPath)
    try {
      await writeFilePromised(targetPath, await readFilePromised(filepath))
    } catch (e) {
      const msg = chalk.dim(`(${e.message})`)
      console.error(`There was an error while copying ${chalk.bold(filename)}. ${msg}`)
    }
github ryanelian / instapack / src / SassBuildTool.ts View on Github external
css: cleanResult.styles
        };

        if (this.variables.sourceMap && postcssResult.map && cleanResult.sourceMap) {
            const sm3: RawSourceMap = cleanResult.sourceMap.toJSON();
            sm3.sources[0] = '/(intermediate)/(postcss-output).css';
            sm3.file = upath.basename(cssOutputPath);

            // console.log(sm3.sources);
            // console.log(sm3.file);

            result.map = mergeSourceMap(postcssResult.map, sm3);
            // console.log(result.map.sources);
            // console.log(result.map.file);

            const sourceMapFileName = upath.basename(cssOutputPath) + '.map';
            result.css += `\n/*# sourceMappingURL=${sourceMapFileName} */`;
        }

        return result;
    }
github ryanelian / instapack / src / SassBuildTool.ts View on Github external
const cleanResult = new CleanCSS(cleanCssOptions).minify(postcssResult.css);
        const errors: Error[] = cleanResult.errors;
        if (errors.length) {
            const errorMessage = "Error when minifying CSS:\n" + errors.map(Q => '- ' + Q.toString()).join("\n");
            throw new Error(errorMessage);
        }

        const result: CssBuildResult = {
            css: cleanResult.styles
        };

        if (this.variables.sourceMap && postcssResult.map && cleanResult.sourceMap) {
            const sm3: RawSourceMap = cleanResult.sourceMap.toJSON();
            sm3.sources[0] = '/(intermediate)/(postcss-output).css';
            sm3.file = upath.basename(cssOutputPath);

            // console.log(sm3.sources);
            // console.log(sm3.file);

            result.map = mergeSourceMap(postcssResult.map, sm3);
            // console.log(result.map.sources);
            // console.log(result.map.file);

            const sourceMapFileName = upath.basename(cssOutputPath) + '.map';
            result.css += `\n/*# sourceMappingURL=${sourceMapFileName} */`;
        }

        return result;
    }
github ryanelian / instapack / src / TypeScriptSourceStore.ts View on Github external
private parseThenStoreSource(filePath: string, raw: string): boolean {
        filePath = upath.toUnix(filePath);
        let sourcePath = filePath;

        if (filePath.endsWith('.vue')) {
            sourcePath = upath.addExt(filePath, '.ts');
            raw = parseTypeScriptInVueFile(raw);
        }

        const version = this.calculateFileVersion(raw);

        const previousSource = this.sources.get(sourcePath);
        if (previousSource && previousSource.version === version) {
            return false;
        }

        // console.log(sourcePath);
        // https://github.com/Microsoft/TypeScript/blob/master/src/compiler/program.ts
        this.sources.set(sourcePath, {
            filePath: filePath,
            source: TypeScript.createSourceFile(sourcePath, raw, this.target),
            version: version

upath

A proxy to `path`, replacing `\` with `/` for all results (supports UNC paths) & new methods to normalize & join keeping leading `./` and add, change, default, trim file extensions.

MIT
Latest version published 4 years ago

Package Health Score

67 / 100
Full package analysis