@angular-devkit/core#normalize TypeScript Examples

The following examples show how to use @angular-devkit/core#normalize. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: find-module.ts    From router with MIT License 6 votes vote down vote up
/**
 * Find the module referred by a set of options passed to the schematics.
 */
export function findModuleFromOptions(
  host: Tree,
  options: ModuleOptions
): Path | undefined {
  if (options.hasOwnProperty('skipImport') && options.skipImport) {
    return undefined;
  }

  if (!options.module) {
    const pathToCheck =
      (options.path || '') +
      (options.flat ? '' : '/' + strings.dasherize(options.name as string));

    return normalize(findModule(host, pathToCheck));
  } else {
    const modulePath = normalize('/' + options.path + '/' + options.module);
    const moduleBaseName = normalize(modulePath).split('/').pop();

    if (host.exists(modulePath)) {
      return normalize(modulePath);
    } else if (host.exists(modulePath + '.ts')) {
      return normalize(modulePath + '.ts');
    } else if (host.exists(modulePath + '.module.ts')) {
      return normalize(modulePath + '.module.ts');
    } else if (host.exists(modulePath + '/' + moduleBaseName + '.module.ts')) {
      return normalize(modulePath + '/' + moduleBaseName + '.module.ts');
    } else {
      throw new Error(`Specified module path ${modulePath} does not exist`);
    }
  }
}
Example #2
Source File: merge-using-component-path.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export function getUseComponents(
  libraryPath: UseComponent[],
  localPath: UseComponent[],
  moduleId: string
) {
  const list = [...libraryPath];
  list.push(
    ...localPath.map((item) => {
      item.path = getComponentOutputPath(moduleId, item.className);
      return item;
    })
  );
  return list.reduce((pre, cur) => {
    pre[cur.selector] = resolve(
      normalize('/'),
      join(normalize(LIBRARY_OUTPUT_ROOTDIR), cur.path)
    );
    return pre;
  }, {} as Record<string, string>);
}
Example #3
Source File: output-template-metadata.service.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
private getSelfTemplate() {
    const selfMetaCollection = this.dataGroup.otherMetaCollectionGroup['$self'];
    if (!selfMetaCollection) {
      return '';
    }
    this.selfMetaCollection = selfMetaCollection;
    const templateStr = selfMetaCollection.templateList
      .map((item) => item.content)
      .join('');

    const extraTemplateData: ExtraTemplateData = {
      template: templateStr,
      outputPath: resolve(
        normalize('/'),
        join(normalize(LIBRARY_OUTPUT_ROOTDIR), this.entryPoint, 'self')
      ),
    };

    delete this.dataGroup.otherMetaCollectionGroup['$self'];

    return `let $self_${GLOBAL_TEMPLATE_SUFFIX}=${JSON.stringify(
      extraTemplateData
    )}`;
  }
Example #4
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async importPathRename(list: string[]) {
    for (let i = 0; i < list.length; i++) {
      const element = list[i];
      const content = await this.read(normalize(element)).toPromise();
      let contentString = fileBufferToString(content);

      contentString = contentString
        .replace(/\/__components\//g, '/components/')
        .replace(/\/__pages\//g, '/pages/');

      await this.write(
        normalize(element),
        stringToFileBuffer(contentString)
      ).toPromise();
    }
  }
Example #5
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async moveDir(list: string[], from: string, to: string) {
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      await this.rename(
        normalize(join(this.root(), 'src', from, item)),
        normalize(join(this.root(), 'src', to, item))
      ).toPromise();
    }
  }
Example #6
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async addPageEntry(list: string[]) {
    const configPath = join(normalize(this.root()), 'src', 'app.json');
    const file = await this.read(configPath).toPromise();
    const json = JSON.parse(fileBufferToString(file));
    const entryList = list.map((item) => `pages/${item}/${item}-entry`);
    json.pages = entryList;
    await this.write(
      configPath,
      stringToFileBuffer(JSON.stringify(json))
    ).toPromise();
  }
Example #7
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async addSpecEntry(list: string[]) {
    const configPath = join(normalize(this.root()), 'src', 'app.json');
    const file = await this.read(configPath).toPromise();
    const json = JSON.parse(fileBufferToString(file));
    const entryList = list.map((item) => `spec/${item}/${item}-entry`);
    json.pages = entryList;
    await this.write(
      configPath,
      stringToFileBuffer(JSON.stringify(json))
    ).toPromise();
  }
Example #8
Source File: builder.prod.spec.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
describeBuilder(runBuilder, BROWSER_BUILDER_INFO, (harness) => {
  describe('builder-prod', () => {
    it('运行', async () => {
      const root = harness.host.root();
      const list = await harness.host.getFileList(
        normalize(join(root, 'src', '__pages'))
      );
      list.push(
        ...(await harness.host.getFileList(
          normalize(join(root, 'src', '__components'))
        ))
      );
      await harness.host.importPathRename(list);
      await harness.host.moveDir(ALL_PAGE_NAME_LIST, '__pages', 'pages');
      await harness.host.moveDir(
        ALL_COMPONENT_NAME_LIST,
        '__components',
        'components'
      );
      await harness.host.addPageEntry(ALL_PAGE_NAME_LIST);
      harness.useTarget('build', angularConfig);
      const result = await harness.executeOnce();
      expect(result).toBeTruthy();
      expect(result.error).toBeFalsy();
      expect(result.logs[0].level !== 'error').toBeTruthy();
      expect(result.result?.success).toBeTruthy();
    });
  });
});
Example #9
Source File: webpack-configuration-change.service.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
init() {
    this.injector = Injector.create({
      parent: this.injector,
      providers: [
        { provide: ExportMiniProgramAssetsPlugin },
        { provide: LibraryTemplateScopeService },
        {
          provide: TS_CONFIG_TOKEN,
          useValue: path.resolve(
            this.context.workspaceRoot,
            this.options.tsConfig
          ),
        },
        {
          provide: DynamicWatchEntryPlugin,
          deps: [BuildPlatform],
          useFactory: (buildPlatform: BuildPlatform) => {
            return new DynamicWatchEntryPlugin(
              {
                pages: this.options.pages,
                components: this.options.components,
                workspaceRoot: normalize(this.context.workspaceRoot),
                context: this.context,
                config: this.config,
              },
              buildPlatform
            );
          },
        },
        { provide: DynamicLibraryComponentEntryPlugin },
      ],
    });
    this.buildPlatform = this.injector.get(BuildPlatform);
    this.buildPlatform.fileExtname.config =
      this.buildPlatform.fileExtname.config || '.json';
    this.config.output!.globalObject = this.buildPlatform.globalObject;
  }
Example #10
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async writeFile(path: string, content: string | Buffer): Promise<void> {
    this.host
      .scopedSync()
      .write(
        normalize(path),
        typeof content === 'string' ? Buffer.from(content) : content
      );

    this.watcherNotifier?.notify([
      { path: getSystemPath(join(this.host.root(), path)), type: 'modified' },
    ]);
  }
Example #11
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async writeFiles(files: Record<string, string | Buffer>): Promise<void> {
    const watchEvents = this.watcherNotifier
      ? ([] as { path: string; type: 'modified' | 'deleted' }[])
      : undefined;

    for (const [path, content] of Object.entries(files)) {
      this.host
        .scopedSync()
        .write(
          normalize(path),
          typeof content === 'string' ? Buffer.from(content) : content
        );

      watchEvents?.push({
        path: getSystemPath(join(this.host.root(), path)),
        type: 'modified',
      });
    }

    if (watchEvents) {
      this.watcherNotifier?.notify(watchEvents);
    }
  }
Example #12
Source File: mini-program-application-analysis.service.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
private saveModuleDependency(
    filePath: string,
    moduleName: string,
    module: ts.ResolvedModule
  ) {
    if (!module) {
      throw new Error(`模块未被解析,文件名${filePath},模块名${moduleName}`);
    }
    const useList =
      this.dependencyUseModule.get(path.normalize(module.resolvedFileName)) ||
      [];
    useList.push(filePath);
    this.dependencyUseModule.set(
      path.normalize(module.resolvedFileName),
      useList
    );
  }
Example #13
Source File: mini-program-application-analysis.service.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
private getComponentPagePattern(fileName: string) {
    const findList = [fileName];
    let maybeEntryPath: PagePattern | undefined;

    while (findList.length) {
      const module = findList.shift();
      const moduleList = this.dependencyUseModule.get(path.normalize(module!));
      if (moduleList && moduleList.length) {
        findList.push(...moduleList);
      } else {
        maybeEntryPath = this.pagePatternList.find(
          (item) => path.normalize(item.src) === path.normalize(module!)
        );
        if (maybeEntryPath) {
          break;
        }
      }
    }
    if (!maybeEntryPath) {
      throw new Error(`没有找到组件[${fileName}]对应的入口点`);
    }
    return maybeEntryPath;
  }
Example #14
Source File: get-angular-sub-dir.rule.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export function getAngularSubDirRuleFactory(options: HookOptions): Rule {
  return async (tree: Tree, context: SchematicContext) => {
    const dirs = tree.getDir(
      join(normalize(options.sourceInSchematicsPath), options.subDir)
    );
    if (dirs.subdirs.length && dirs.subfiles.length) {
      return;
    }
    await cloneSpecifiedDir(options);
  };
}
Example #15
Source File: const.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
SCHEMATICS_FORMS_LIBRARY_HOOK_FILE_LIST = [
  join(
    normalize(SCHEMATICS_FORMS_LIBRARY_PATH),
    'src/directives/default_value_accessor.ts'
  ),
  join(
    normalize(SCHEMATICS_FORMS_LIBRARY_PATH),
    'src/directives/checkbox_value_accessor.ts'
  ),
  join(
    normalize(SCHEMATICS_FORMS_LIBRARY_PATH),
    'src/directives/number_value_accessor.ts'
  ),
  join(
    normalize(SCHEMATICS_FORMS_LIBRARY_PATH),
    'src/directives/radio_control_value_accessor.ts'
  ),
  join(
    normalize(SCHEMATICS_FORMS_LIBRARY_PATH),
    'src/directives/range_value_accessor.ts'
  ),
  join(
    normalize(SCHEMATICS_FORMS_LIBRARY_PATH),
    'src/directives/select_control_value_accessor.ts'
  ),
  join(
    normalize(SCHEMATICS_FORMS_LIBRARY_PATH),
    'src/directives/select_multiple_control_value_accessor.ts'
  ),
  join(normalize(SCHEMATICS_FORMS_LIBRARY_PATH), 'src/directives.ts'),
  join(normalize(SCHEMATICS_FORMS_LIBRARY_PATH), 'src/forms.ts'),
]
Example #16
Source File: find-module.ts    From edit-in-place with MIT License 6 votes vote down vote up
/**
 * Find the module referred by a set of options passed to the schematics.
 */
export function findRootModule(host: Tree, module: string, rootPath = '', skipImport = false): string | undefined {
  if (skipImport || !module) {
    return undefined;
  }

  const modulePath = normalize(`${rootPath}/${module}`);
  if (host.exists(modulePath)) {
    return modulePath;
  } else if (host.exists(modulePath + '.ts')) {
    return normalize(modulePath + '.ts');
  } else if (host.exists(modulePath + MODULE_EXT)) {
    return normalize(modulePath + MODULE_EXT);
  } else if (host.exists(`${modulePath}/${module}${MODULE_EXT}`)) {
    return normalize(`${modulePath}/${module}${MODULE_EXT}`);
  } else if (host.exists(`${modulePath}/${module}.ts`)) {
    return normalize(`${modulePath}/${module}.ts`);
  } else {
    throw new Error(`Specified module path ${modulePath} does not exist`);
  }
}
Example #17
Source File: parsers.ts    From form-schematic with MIT License 6 votes vote down vote up
parseName = (
	path: string,
	name: string
): { name: string; path: Path } => {
	const nameWithoutPath = basename(name as Path);
	const namePath = dirname((path + '/' + name) as Path);

	return {
		name: dasherize(nameWithoutPath),
		path: normalize('/' + namePath)
	};
}
Example #18
Source File: tsconfig.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function updateTsConfig(_options: CoveoSchema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const tsconfigBuffer = tree.read(normalize('./tsconfig.json'));
    if (tsconfigBuffer === null) {
      return;
    }
    try {
      const originalTsConfig = tsconfigBuffer.toString();
      const tsConfigComment =
        originalTsConfig.match(commentRegExp)?.[0]?.trim() ?? '';
      const tsConfig = JSON.parse(
        originalTsConfig.replace(commentRegExp, '').trim()
      );

      tsConfig.compilerOptions.skipLibCheck = true;
      tree.overwrite(
        normalize('./tsconfig.json'),
        `${tsConfigComment}
${JSON.stringify(tsConfig, null, 4)}`
      );
    } catch (error) {
      console.error(
        `Unable to update the Angular tsconfig.json file by adding the "allowSyntheticDefaultImports" flag.
Make sure to add this flag to your tsconfig.json. Otherwise, you might experience errors when running the app`,
        error
      );
    }
  };
}
Example #19
Source File: start.ts    From cli with Apache License 2.0 6 votes vote down vote up
/**
 * Create a npm script in the project root to start both the Angular app and the search token server
 */
export function configureStartCommand(_options: CoveoSchema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const packageJsonBuffer = tree.read(normalize('./package.json'));
    if (packageJsonBuffer === null) {
      return;
    }

    try {
      const packageJson = JSON.parse(packageJsonBuffer.toString());

      packageJson.scripts['allocate-port'] =
        'node ./scripts/port-allocator.mjs';
      packageJson.scripts['start'] =
        'npm run allocate-port && concurrently --raw "npm run start-server" "ng serve"';
      packageJson.scripts['start-server'] = 'node ./scripts/start-server.js';

      tree.overwrite(
        normalize('./package.json'),
        JSON.stringify(packageJson, null, 4)
      );
    } catch (error) {
      console.error(
        'Something wrong happened while reading the package.json',
        error
      );
    }
  };
}
Example #20
Source File: templates.ts    From cli with Apache License 2.0 6 votes vote down vote up
/**
 * Schematic rule that copies files into the Angular project.
 *
 * @export
 * @param {CoveoSchema} _options
 * @param {string} [workspaceRootPath='./']      The root path from which the applyTemplates function will start pasting files.
 *                                               The default value is "./" because the file structure is already defined within the ./files directories
 * @param {string} [templateFilePath='./files']  Path containing the files to copy into the Angular project
 * @returns {Rule}
 */
export function createFiles(
  _options: CoveoSchema,
  workspaceRootPath = './',
  templateFilePath = './files',
  customFilter = isNotNodeModuleFile
): Rule {
  return (tree: Tree, context: SchematicContext) => {
    const templateSource = apply(url(templateFilePath), [
      filter(customFilter),
      applyTemplates({
        ..._options,
      }),
      move(normalize(workspaceRootPath)),
      overwriteIfExists(tree),
    ]);

    const rule = mergeWith(templateSource);
    return rule(tree, context);
  };
}
Example #21
Source File: dependencies.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function allowCommonJsDependencies(options: CoveoSchema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const workspaceBuffer = tree.read(normalize('./angular.json'));
    if (workspaceBuffer === null || !options.project) {
      return;
    }
    try {
      const workspaceConfig = JSON.parse(workspaceBuffer.toString());

      const allowedCommonJsDependencies =
        workspaceConfig.projects[options.project].architect.build.options[
          'allowedCommonJsDependencies'
        ] || [];

      allowedCommonJsDependencies.push('@coveo/headless');

      workspaceConfig.projects[options.project].architect.build.options[
        'allowedCommonJsDependencies'
      ] = allowedCommonJsDependencies;

      tree.overwrite(
        normalize('./angular.json'),
        JSON.stringify(workspaceConfig, null, 4)
      );
    } catch (error) {
      console.error(
        `Unable to update the Angular workspace configuration by adding @coveo/headless as a "allowedCommonJsDependencies".
Make sure your angular.json file is valid and contains a "build" target (see https://angular.io/guide/glossary#target).`,
        error
      );
    }
  };
}
Example #22
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
async removeFile(path: string): Promise<void> {
    this.host.scopedSync().delete(normalize(path));

    this.watcherNotifier?.notify([
      { path: getSystemPath(join(this.host.root(), path)), type: 'deleted' },
    ]);
  }
Example #23
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
hasFile(path: string): boolean {
    return this.host.scopedSync().exists(normalize(path));
  }
Example #24
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
hasFileMatch(directory: string, pattern: RegExp): boolean {
    return this.host
      .scopedSync()
      .list(normalize(directory))
      .some((name) => pattern.test(name));
  }
Example #25
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
readFile(path: string): string {
    const content = this.host.scopedSync().read(normalize(path));

    return Buffer.from(content).toString('utf8');
  }
Example #26
Source File: setup-component-data.service.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
run(
    data: string,
    originFileName: string,
    customStyleSheetProcessor: CustomStyleSheetProcessor
  ) {
    const changedData = changeComponent(data);
    if (!changedData) {
      return data;
    }
    const useComponentPath =
      this.dataGroup.useComponentPath.get(originFileName)!;
    const componentClassName = changedData.componentName;
    const componentDirName = strings.dasherize(
      strings.camelize(componentClassName)
    );
    const libraryPath = getComponentOutputPath(
      this.entryPoint,
      componentClassName
    );
    const styleUrlList = this.dataGroup.style.get(originFileName);
    const styleContentList: string[] = [];
    styleUrlList?.forEach((item) => {
      styleContentList.push(customStyleSheetProcessor.styleMap.get(item)!);
    });
    const selfTemplateImportStr = this.dataGroup.otherMetaCollectionGroup[
      '$self'
    ]
      ? `<import src="${resolve(
          normalize('/'),
          join(
            normalize(LIBRARY_OUTPUT_ROOTDIR),
            this.entryPoint,
            'self' + this.buildPlatform.fileExtname.contentTemplate
          )
        )}"/>`
      : '';

    const insertComponentData: ExportLibraryComponentMeta = {
      id:
        strings.classify(this.entryPoint) +
        strings.classify(strings.camelize(componentDirName)),
      className: componentClassName,
      content:
        selfTemplateImportStr +
        this.dataGroup.outputContent.get(originFileName)!,
      libraryPath: libraryPath,
      useComponents: {
        ...getUseComponents(
          useComponentPath.libraryPath,
          useComponentPath.localPath,
          this.entryPoint
        ),
        ...this.addGlobalTemplateService.getSelfUseComponents(),
      },
      moduleId: this.entryPoint,
    };
    if (styleContentList.length) {
      insertComponentData.style = styleContentList.join('\n');
    }

    return `${
      changedData.content
    }\nlet ${componentClassName}_${LIBRARY_COMPONENT_METADATA_SUFFIX}=${JSON.stringify(
      insertComponentData
    )}`;
  }
Example #27
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
workspaceRoot = join(normalize(__dirname), `../hello-world-app/`)
Example #28
Source File: library.spec.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
describeBuilder(execute, LIBRARY_BUILDER_INFO, (harness) => {
  describe('test-library', () => {
    it('运行', async () => {
      harness.useTarget('library', DEFAULT_ANGULAR_LIBRARY_CONFIG);
      const result = await harness.executeOnce();
      expect(result).toBeTruthy();
      expect(result.result).toBeTruthy();
      expect(result.result.success).toBeTruthy();
      if (!result.result.success) {
        console.error(result.result.error);
      }
      const workspaceRoot: string = (result.result as any).workspaceRoot;
      const outputPath = normalize(`dist/test-library`);
      const output = path.join(workspaceRoot, outputPath);
      const entryFile = harness.expectFile(
        join(outputPath, 'esm2020', 'test-library.mjs')
      );
      entryFile.toExist();
      entryFile.content.toContain(`$self_Global_Template`);
      const globalSelfTemplate = harness.expectFile(
        join(
          outputPath,
          'esm2020',
          'global-self-template',
          'global-self-template.component.mjs'
        )
      );
      globalSelfTemplate.toExist();
      globalSelfTemplate.content.toContain(
        `GlobalSelfTemplateComponent_${LIBRARY_COMPONENT_METADATA_SUFFIX}`
      );
      fs.copySync(
        output,
        path.resolve(
          process.cwd(),
          'test',
          'hello-world-app',
          'node_modules',
          'test-library'
        )
      );
    });
  });
});
Example #29
Source File: get-library-path.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
export function getComponentOutputPath(entry: string, className: string) {
  return join(
    normalize(entry),
    dasherize(camelize(className)),
    dasherize(camelize(className))
  );
}