Best JavaScript code snippet using storybook-root
organizeImports.ts
Source:organizeImports.ts
1namespace ts {2 describe("Organize imports", () => {3 describe("Sort imports", () => {4 it("Sort - non-relative vs non-relative", () => {5 assertSortsBefore(6 `import y from "lib1";`,7 `import x from "lib2";`);8 });910 it("Sort - relative vs relative", () => {11 assertSortsBefore(12 `import y from "./lib1";`,13 `import x from "./lib2";`);14 });1516 it("Sort - relative vs non-relative", () => {17 assertSortsBefore(18 `import y from "lib";`,19 `import x from "./lib";`);20 });2122 it("Sort - case-insensitive", () => {23 assertSortsBefore(24 `import y from "a";`,25 `import x from "Z";`);26 assertSortsBefore(27 `import y from "A";`,28 `import x from "z";`);29 });3031 function assertSortsBefore(importString1: string, importString2: string) {32 const [{moduleSpecifier: moduleSpecifier1}, {moduleSpecifier: moduleSpecifier2}] = parseImports(importString1, importString2);33 assert.equal(OrganizeImports.compareModuleSpecifiers(moduleSpecifier1, moduleSpecifier2), Comparison.LessThan);34 assert.equal(OrganizeImports.compareModuleSpecifiers(moduleSpecifier2, moduleSpecifier1), Comparison.GreaterThan);35 }36 });3738 describe("Coalesce imports", () => {39 it("No imports", () => {40 assert.isEmpty(OrganizeImports.coalesceImports([]));41 });4243 it("Sort specifiers - case-insensitive", () => {44 const sortedImports = parseImports(`import { default as M, a as n, B, y, Z as O } from "lib";`);45 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);46 const expectedCoalescedImports = parseImports(`import { a as n, B, default as M, y, Z as O } from "lib";`);47 assertListEqual(actualCoalescedImports, expectedCoalescedImports);48 });4950 it("Combine side-effect-only imports", () => {51 const sortedImports = parseImports(52 `import "lib";`,53 `import "lib";`);54 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);55 const expectedCoalescedImports = parseImports(`import "lib";`);56 assertListEqual(actualCoalescedImports, expectedCoalescedImports);57 });5859 it("Combine namespace imports", () => {60 const sortedImports = parseImports(61 `import * as x from "lib";`,62 `import * as y from "lib";`);63 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);64 const expectedCoalescedImports = sortedImports;65 assertListEqual(actualCoalescedImports, expectedCoalescedImports);66 });6768 it("Combine default imports", () => {69 const sortedImports = parseImports(70 `import x from "lib";`,71 `import y from "lib";`);72 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);73 const expectedCoalescedImports = parseImports(`import { default as x, default as y } from "lib";`);74 assertListEqual(actualCoalescedImports, expectedCoalescedImports);75 });7677 it("Combine property imports", () => {78 const sortedImports = parseImports(79 `import { x } from "lib";`,80 `import { y as z } from "lib";`);81 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);82 const expectedCoalescedImports = parseImports(`import { x, y as z } from "lib";`);83 assertListEqual(actualCoalescedImports, expectedCoalescedImports);84 });8586 it("Combine side-effect-only import with namespace import", () => {87 const sortedImports = parseImports(88 `import "lib";`,89 `import * as x from "lib";`);90 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);91 const expectedCoalescedImports = sortedImports;92 assertListEqual(actualCoalescedImports, expectedCoalescedImports);93 });9495 it("Combine side-effect-only import with default import", () => {96 const sortedImports = parseImports(97 `import "lib";`,98 `import x from "lib";`);99 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);100 const expectedCoalescedImports = sortedImports;101 assertListEqual(actualCoalescedImports, expectedCoalescedImports);102 });103104 it("Combine side-effect-only import with property import", () => {105 const sortedImports = parseImports(106 `import "lib";`,107 `import { x } from "lib";`);108 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);109 const expectedCoalescedImports = sortedImports;110 assertListEqual(actualCoalescedImports, expectedCoalescedImports);111 });112113 it("Combine namespace import with default import", () => {114 const sortedImports = parseImports(115 `import * as x from "lib";`,116 `import y from "lib";`);117 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);118 const expectedCoalescedImports = parseImports(119 `import y, * as x from "lib";`);120 assertListEqual(actualCoalescedImports, expectedCoalescedImports);121 });122123 it("Combine namespace import with property import", () => {124 const sortedImports = parseImports(125 `import * as x from "lib";`,126 `import { y } from "lib";`);127 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);128 const expectedCoalescedImports = sortedImports;129 assertListEqual(actualCoalescedImports, expectedCoalescedImports);130 });131132 it("Combine default import with property import", () => {133 const sortedImports = parseImports(134 `import x from "lib";`,135 `import { y } from "lib";`);136 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);137 const expectedCoalescedImports = parseImports(138 `import x, { y } from "lib";`);139 assertListEqual(actualCoalescedImports, expectedCoalescedImports);140 });141142 it("Combine many imports", () => {143 const sortedImports = parseImports(144 `import "lib";`,145 `import * as y from "lib";`,146 `import w from "lib";`,147 `import { b } from "lib";`,148 `import "lib";`,149 `import * as x from "lib";`,150 `import z from "lib";`,151 `import { a } from "lib";`);152 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);153 const expectedCoalescedImports = parseImports(154 `import "lib";`,155 `import * as x from "lib";`,156 `import * as y from "lib";`,157 `import { a, b, default as w, default as z } from "lib";`);158 assertListEqual(actualCoalescedImports, expectedCoalescedImports);159 });160161 // This is descriptive, rather than normative162 it("Combine two namespace imports with one default import", () => {163 const sortedImports = parseImports(164 `import * as x from "lib";`,165 `import * as y from "lib";`,166 `import z from "lib";`);167 const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);168 const expectedCoalescedImports = sortedImports;169 assertListEqual(actualCoalescedImports, expectedCoalescedImports);170 });171 });172173 describe("Coalesce exports", () => {174 it("No exports", () => {175 assert.isEmpty(OrganizeImports.coalesceExports([]));176 });177178 it("Sort specifiers - case-insensitive", () => {179 const sortedExports = parseExports(`export { default as M, a as n, B, y, Z as O } from "lib";`);180 const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);181 const expectedCoalescedExports = parseExports(`export { a as n, B, default as M, y, Z as O } from "lib";`);182 assertListEqual(actualCoalescedExports, expectedCoalescedExports);183 });184185 it("Combine namespace re-exports", () => {186 const sortedExports = parseExports(187 `export * from "lib";`,188 `export * from "lib";`);189 const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);190 const expectedCoalescedExports = parseExports(`export * from "lib";`);191 assertListEqual(actualCoalescedExports, expectedCoalescedExports);192 });193194 it("Combine property exports", () => {195 const sortedExports = parseExports(196 `export { x };`,197 `export { y as z };`);198 const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);199 const expectedCoalescedExports = parseExports(`export { x, y as z };`);200 assertListEqual(actualCoalescedExports, expectedCoalescedExports);201 });202203 it("Combine property re-exports", () => {204 const sortedExports = parseExports(205 `export { x } from "lib";`,206 `export { y as z } from "lib";`);207 const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);208 const expectedCoalescedExports = parseExports(`export { x, y as z } from "lib";`);209 assertListEqual(actualCoalescedExports, expectedCoalescedExports);210 });211212 it("Combine namespace re-export with property re-export", () => {213 const sortedExports = parseExports(214 `export * from "lib";`,215 `export { y } from "lib";`);216 const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);217 const expectedCoalescedExports = sortedExports;218 assertListEqual(actualCoalescedExports, expectedCoalescedExports);219 });220221 it("Combine many exports", () => {222 const sortedExports = parseExports(223 `export { x };`,224 `export { y as w, z as default };`,225 `export { w as q };`);226 const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);227 const expectedCoalescedExports = parseExports(228 `export { w as q, x, y as w, z as default };`);229 assertListEqual(actualCoalescedExports, expectedCoalescedExports);230 });231232 it("Combine many re-exports", () => {233 const sortedExports = parseExports(234 `export { x as a, y } from "lib";`,235 `export * from "lib";`,236 `export { z as b } from "lib";`);237 const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);238 const expectedCoalescedExports = parseExports(239 `export * from "lib";`,240 `export { x as a, y, z as b } from "lib";`);241 assertListEqual(actualCoalescedExports, expectedCoalescedExports);242 });243 });244245 describe("Baselines", () => {246247 const libFile = {248 path: "/lib.ts",249 content: `250export function F1();251export default function F2();252`,253 };254255 const reactLibFile = {256 path: "/react.ts",257 content: `258export const React = {259createElement: (_type, _props, _children) => {},260};261262export const Other = 1;263`,264 };265266 // Don't bother to actually emit a baseline for this.267 it("NoImports", () => {268 const testFile = {269 path: "/a.ts",270 content: "function F() { }",271 };272 const languageService = makeLanguageService(testFile);273 const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, testFormatSettings, emptyOptions);274 assert.isEmpty(changes);275 });276277 testOrganizeImports("Renamed_used",278 {279 path: "/test.ts",280 content: `281import { F1 as EffOne, F2 as EffTwo } from "lib";282EffOne();283`,284 },285 libFile);286287 testOrganizeImports("Simple",288 {289 path: "/test.ts",290 content: `291import { F1, F2 } from "lib";292import * as NS from "lib";293import D from "lib";294295NS.F1();296D();297F1();298F2();299`,300 },301 libFile);302303 testOrganizeImports("Unused_Some",304 {305 path: "/test.ts",306 content: `307import { F1, F2 } from "lib";308import * as NS from "lib";309import D from "lib";310311D();312`,313 },314 libFile);315316 testOrganizeImports("Unused_All",317 {318 path: "/test.ts",319 content: `320import { F1, F2 } from "lib";321import * as NS from "lib";322import D from "lib";323`,324 },325 libFile);326327 testOrganizeImports("Unused_Empty",328 {329 path: "/test.ts",330 content: `331import { } from "lib";332`,333 },334 libFile);335336 testOrganizeImports("Unused_false_positive_shorthand_assignment",337 {338 path: "/test.ts",339 content: `340import { x } from "a";341const o = { x };342`343 });344345 testOrganizeImports("Unused_false_positive_export_shorthand",346 {347 path: "/test.ts",348 content: `349import { x } from "a";350export { x };351`352 });353354 testOrganizeImports("MoveToTop",355 {356 path: "/test.ts",357 content: `358import { F1, F2 } from "lib";359F1();360F2();361import * as NS from "lib";362NS.F1();363import D from "lib";364D();365`,366 },367 libFile);368369 // tslint:disable no-invalid-template-strings370 testOrganizeImports("MoveToTop_Invalid",371 {372 path: "/test.ts",373 content: `374import { F1, F2 } from "lib";375F1();376F2();377import * as NS from "lib";378NS.F1();379import b from ${"`${'lib'}`"};380import a from ${"`${'lib'}`"};381import D from "lib";382D();383`,384 },385 libFile);386 // tslint:enable no-invalid-template-strings387388 testOrganizeImports("CoalesceMultipleModules",389 {390 path: "/test.ts",391 content: `392import { d } from "lib1";393import { b } from "lib1";394import { c } from "lib2";395import { a } from "lib2";396a + b + c + d;397`,398 },399 { path: "/lib1.ts", content: "export const b = 1, d = 2;" },400 { path: "/lib2.ts", content: "export const a = 3, c = 4;" });401402 testOrganizeImports("CoalesceTrivia",403 {404 path: "/test.ts",405 content: `406/*A*/import /*B*/ { /*C*/ F2 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I407/*J*/import /*K*/ { /*L*/ F1 /*M*/ } /*N*/ from /*O*/ "lib" /*P*/;/*Q*/ //R408409F1();410F2();411`,412 },413 libFile);414415 testOrganizeImports("SortTrivia",416 {417 path: "/test.ts",418 content: `419/*A*/import /*B*/ "lib2" /*C*/;/*D*/ //E420/*F*/import /*G*/ "lib1" /*H*/;/*I*/ //J421`,422 },423 { path: "/lib1.ts", content: "" },424 { path: "/lib2.ts", content: "" });425426 testOrganizeImports("UnusedTrivia1",427 {428 path: "/test.ts",429 content: `430/*A*/import /*B*/ { /*C*/ F1 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I431`,432 },433 libFile);434435 testOrganizeImports("UnusedTrivia2",436 {437 path: "/test.ts",438 content: `439/*A*/import /*B*/ { /*C*/ F1 /*D*/, /*E*/ F2 /*F*/ } /*G*/ from /*H*/ "lib" /*I*/;/*J*/ //K440441F1();442`,443 },444 libFile);445446 testOrganizeImports("UnusedHeaderComment",447 {448 path: "/test.ts",449 content: `450// Header451import { F1 } from "lib";452`,453 },454 libFile);455456 testOrganizeImports("SortHeaderComment",457 {458 path: "/test.ts",459 content: `460// Header461import "lib2";462import "lib1";463`,464 },465 { path: "/lib1.ts", content: "" },466 { path: "/lib2.ts", content: "" });467468 testOrganizeImports("AmbientModule",469 {470 path: "/test.ts",471 content: `472declare module "mod" {473 import { F1 } from "lib";474 import * as NS from "lib";475 import { F2 } from "lib";476477 function F(f1: {} = F1, f2: {} = F2) {}478}479`,480 },481 libFile);482483 testOrganizeImports("TopLevelAndAmbientModule",484 {485 path: "/test.ts",486 content: `487import D from "lib";488489declare module "mod" {490 import { F1 } from "lib";491 import * as NS from "lib";492 import { F2 } from "lib";493494 function F(f1: {} = F1, f2: {} = F2) {}495}496497import E from "lib";498import "lib";499500D();501`,502 },503 libFile);504505 testOrganizeImports("JsxFactoryUsedJsx",506 {507 path: "/test.jsx",508 content: `509import { React, Other } from "react";510511<div/>;512`,513 },514 reactLibFile);515516 testOrganizeImports("JsxFactoryUsedJs",517 {518 path: "/test.js",519 content: `520import { React, Other } from "react";521522<div/>;523`,524 },525 reactLibFile);526527 testOrganizeImports("JsxFactoryUsedTsx",528 {529 path: "/test.tsx",530 content: `531import { React, Other } from "react";532533<div/>;534`,535 },536 reactLibFile);537538 // TS files are not JSX contexts, so the parser does not treat539 // `<div/>` as a JSX element.540 testOrganizeImports("JsxFactoryUsedTs",541 {542 path: "/test.ts",543 content: `544import { React, Other } from "react";545546<div/>;547`,548 },549 reactLibFile);550551 testOrganizeImports("JsxFactoryUnusedJsx",552 {553 path: "/test.jsx",554 content: `555import { React, Other } from "react";556`,557 },558 reactLibFile);559560 // Note: Since the file extension does not end with "x", the jsx compiler option561 // will not be enabled. The import should be retained regardless.562 testOrganizeImports("JsxFactoryUnusedJs",563 {564 path: "/test.js",565 content: `566import { React, Other } from "react";567`,568 },569 reactLibFile);570571 testOrganizeImports("JsxFactoryUnusedTsx",572 {573 path: "/test.tsx",574 content: `575import { React, Other } from "react";576`,577 },578 reactLibFile);579580 testOrganizeImports("JsxFactoryUnusedTs",581 {582 path: "/test.ts",583 content: `584import { React, Other } from "react";585`,586 },587 reactLibFile);588589 describe("Exports", () => {590591 testOrganizeExports("MoveToTop",592 {593 path: "/test.ts",594 content: `595export { F1, F2 } from "lib";5961;597export * from "lib";5982;599`,600 },601 libFile);602603 // tslint:disable no-invalid-template-strings604 testOrganizeExports("MoveToTop_Invalid",605 {606 path: "/test.ts",607 content: `608export { F1, F2 } from "lib";6091;610export * from "lib";6112;612export { b } from ${"`${'lib'}`"};613export { a } from ${"`${'lib'}`"};614export { D } from "lib";6153;616`,617 },618 libFile);619 // tslint:enable no-invalid-template-strings620621 testOrganizeExports("MoveToTop_WithImportsFirst",622 {623 path: "/test.ts",624 content: `625import { F1, F2 } from "lib";6261;627export { F1, F2 } from "lib";6282;629import * as NS from "lib";6303;631export * from "lib";6324;633F1(); F2(); NS.F1();634`,635 },636 libFile);637638 testOrganizeExports("MoveToTop_WithExportsFirst",639 {640 path: "/test.ts",641 content: `642export { F1, F2 } from "lib";6431;644import { F1, F2 } from "lib";6452;646export * from "lib";6473;648import * as NS from "lib";6494;650F1(); F2(); NS.F1();651`,652 },653 libFile);654655 testOrganizeExports("CoalesceMultipleModules",656 {657 path: "/test.ts",658 content: `659export { d } from "lib1";660export { b } from "lib1";661export { c } from "lib2";662export { a } from "lib2";663`,664 },665 { path: "/lib1.ts", content: "export const b = 1, d = 2;" },666 { path: "/lib2.ts", content: "export const a = 3, c = 4;" });667668 testOrganizeExports("CoalesceTrivia",669 {670 path: "/test.ts",671 content: `672/*A*/export /*B*/ { /*C*/ F2 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I673/*J*/export /*K*/ { /*L*/ F1 /*M*/ } /*N*/ from /*O*/ "lib" /*P*/;/*Q*/ //R674`,675 },676 libFile);677678 testOrganizeExports("SortTrivia",679 {680 path: "/test.ts",681 content: `682/*A*/export /*B*/ * /*C*/ from /*D*/ "lib2" /*E*/;/*F*/ //G683/*H*/export /*I*/ * /*J*/ from /*K*/ "lib1" /*L*/;/*M*/ //N684`,685 },686 { path: "/lib1.ts", content: "" },687 { path: "/lib2.ts", content: "" });688689 testOrganizeExports("SortHeaderComment",690 {691 path: "/test.ts",692 content: `693// Header694export * from "lib2";695export * from "lib1";696`,697 },698 { path: "/lib1.ts", content: "" },699 { path: "/lib2.ts", content: "" });700701 testOrganizeExports("AmbientModule",702 {703 path: "/test.ts",704 content: `705declare module "mod" {706 export { F1 } from "lib";707 export * from "lib";708 export { F2 } from "lib";709}710 `,711 },712 libFile);713714 testOrganizeExports("TopLevelAndAmbientModule",715 {716 path: "/test.ts",717 content: `718export { D } from "lib";719720declare module "mod" {721 export { F1 } from "lib";722 export * from "lib";723 export { F2 } from "lib";724}725726export { E } from "lib";727export * from "lib";728`,729 },730 libFile);731 });732733 function testOrganizeExports(testName: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) {734 testOrganizeImports(`${testName}.exports`, testFile, ...otherFiles);735 }736737 function testOrganizeImports(testName: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) {738 it(testName, () => runBaseline(`organizeImports/${testName}.ts`, testFile, ...otherFiles));739 }740741 function runBaseline(baselinePath: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) {742 const { path: testPath, content: testContent } = testFile;743 const languageService = makeLanguageService(testFile, ...otherFiles);744 const changes = languageService.organizeImports({ type: "file", fileName: testPath }, testFormatSettings, emptyOptions);745 assert.equal(changes.length, 1);746 assert.equal(changes[0].fileName, testPath);747748 const newText = textChanges.applyChanges(testContent, changes[0].textChanges);749 Harness.Baseline.runBaseline(baselinePath, [750 "// ==ORIGINAL==",751 testContent,752 "// ==ORGANIZED==",753 newText,754 ].join(newLineCharacter));755 }756757 function makeLanguageService(...files: TestFSWithWatch.File[]) {758 const host = projectSystem.createServerHost(files);759 const projectService = projectSystem.createProjectService(host, { useSingleInferredProject: true });760 projectService.setCompilerOptionsForInferredProjects({ jsx: files.some(f => f.path.endsWith("x")) ? JsxEmit.React : JsxEmit.None });761 files.forEach(f => projectService.openClientFile(f.path));762 return projectService.inferredProjects[0].getLanguageService();763 }764 });765766 function parseImports(...importStrings: string[]): ReadonlyArray<ImportDeclaration> {767 const sourceFile = createSourceFile("a.ts", importStrings.join("\n"), ScriptTarget.ES2015, /*setParentNodes*/ true, ScriptKind.TS);768 const imports = filter(sourceFile.statements, isImportDeclaration);769 assert.equal(imports.length, importStrings.length);770 return imports;771 }772773 function parseExports(...exportStrings: string[]): ReadonlyArray<ExportDeclaration> {774 const sourceFile = createSourceFile("a.ts", exportStrings.join("\n"), ScriptTarget.ES2015, /*setParentNodes*/ true, ScriptKind.TS);775 const exports = filter(sourceFile.statements, isExportDeclaration);776 assert.equal(exports.length, exportStrings.length);777 return exports;778 }779780 function assertEqual(node1?: Node, node2?: Node) {781 if (node1 === undefined) {782 assert.isUndefined(node2);783 return;784 }785 else if (node2 === undefined) {786 assert.isUndefined(node1); // Guaranteed to fail787 return;788 }789790 assert.equal(node1.kind, node2.kind);791792 switch (node1.kind) {793 case SyntaxKind.ImportDeclaration:794 const decl1 = node1 as ImportDeclaration;795 const decl2 = node2 as ImportDeclaration;796 assertEqual(decl1.importClause, decl2.importClause);797 assertEqual(decl1.moduleSpecifier, decl2.moduleSpecifier);798 break;799 case SyntaxKind.ImportClause:800 const clause1 = node1 as ImportClause;801 const clause2 = node2 as ImportClause;802 assertEqual(clause1.name, clause2.name);803 assertEqual(clause1.namedBindings, clause2.namedBindings);804 break;805 case SyntaxKind.NamespaceImport:806 const nsi1 = node1 as NamespaceImport;807 const nsi2 = node2 as NamespaceImport;808 assertEqual(nsi1.name, nsi2.name);809 break;810 case SyntaxKind.NamedImports:811 const ni1 = node1 as NamedImports;812 const ni2 = node2 as NamedImports;813 assertListEqual(ni1.elements, ni2.elements);814 break;815 case SyntaxKind.ImportSpecifier:816 const is1 = node1 as ImportSpecifier;817 const is2 = node2 as ImportSpecifier;818 assertEqual(is1.name, is2.name);819 assertEqual(is1.propertyName, is2.propertyName);820 break;821 case SyntaxKind.ExportDeclaration:822 const ed1 = node1 as ExportDeclaration;823 const ed2 = node2 as ExportDeclaration;824 assertEqual(ed1.exportClause, ed2.exportClause);825 assertEqual(ed1.moduleSpecifier, ed2.moduleSpecifier);826 break;827 case SyntaxKind.NamedExports:828 const ne1 = node1 as NamedExports;829 const ne2 = node2 as NamedExports;830 assertListEqual(ne1.elements, ne2.elements);831 break;832 case SyntaxKind.ExportSpecifier:833 const es1 = node1 as ExportSpecifier;834 const es2 = node2 as ExportSpecifier;835 assertEqual(es1.name, es2.name);836 assertEqual(es1.propertyName, es2.propertyName);837 break;838 case SyntaxKind.Identifier:839 const id1 = node1 as Identifier;840 const id2 = node2 as Identifier;841 assert.equal(id1.text, id2.text);842 break;843 case SyntaxKind.StringLiteral:844 case SyntaxKind.NoSubstitutionTemplateLiteral:845 const sl1 = node1 as LiteralLikeNode;846 const sl2 = node2 as LiteralLikeNode;847 assert.equal(sl1.text, sl2.text);848 break;849 default:850 assert.equal(node1.getText(), node2.getText());851 break;852 }853 }854855 function assertListEqual(list1: ReadonlyArray<Node>, list2: ReadonlyArray<Node>) {856 if (list1 === undefined || list2 === undefined) {857 assert.isUndefined(list1);858 assert.isUndefined(list2);859 return;860 }861862 assert.equal(list1.length, list2.length);863 for (let i = 0; i < list1.length; i++) {864 assertEqual(list1[i], list2[i]);865 }866 }867 });
...
fuzz_shell.js
Source:fuzz_shell.js
1// Shell integration.2if (typeof console === 'undefined') {3 console = { log: print };4}5var tempRet0;6var binary;7if (typeof process === 'object' && typeof require === 'function' /* node.js detection */) {8 var args = process.argv.slice(2);9 binary = require('fs').readFileSync(args[0]);10 if (!binary.buffer) binary = new Uint8Array(binary);11} else {12 var args;13 if (typeof scriptArgs != 'undefined') {14 args = scriptArgs;15 } else if (typeof arguments != 'undefined') {16 args = arguments;17 }18 if (typeof readbuffer === 'function') {19 binary = new Uint8Array(readbuffer(args[0]));20 } else {21 binary = read(args[0], 'binary');22 }23}24// Utilities.25function assert(x, y) {26 if (!x) throw (y || 'assertion failed');// + new Error().stack;27}28// Deterministic randomness.29var detrand = (function() {30 var hash = 5381; // TODO DET_RAND_SEED;31 var x = 0;32 return function() {33 hash = (((hash << 5) + hash) ^ (x & 0xff)) >>> 0;34 x = (x + 1) % 256;35 return (hash % 256) / 256;36 };37})();38// Asyncify integration.39var Asyncify = {40 sleeping: false,41 sleepingFunction: null,42 sleeps: 0,43 maxDepth: 0,44 DATA_ADDR: 4,45 DATA_MAX: 65536,46 savedMemory: null,47 instrumentImports: function(imports) {48 var ret = {};49 for (var module in imports) {50 ret[module] = {};51 for (var i in imports[module]) {52 if (typeof imports[module][i] === 'function') {53 (function(module, i) {54 ret[module][i] = function() {55 if (!Asyncify.sleeping) {56 // Sleep if asyncify support is present, and at a certain57 // probability.58 if (exports.asyncify_start_unwind && 59 detrand() < 0.5) {60 // We are called in order to start a sleep/unwind.61 console.log('asyncify: sleep in ' + i + '...');62 Asyncify.sleepingFunction = i;63 Asyncify.sleeps++;64 var depth = new Error().stack.split('\n').length - 6;65 Asyncify.maxDepth = Math.max(Asyncify.maxDepth, depth);66 // Save the memory we use for data, so after we restore it later, the67 // sleep/resume appears to have had no change to memory.68 Asyncify.savedMemory = new Int32Array(view.subarray(Asyncify.DATA_ADDR >> 2, Asyncify.DATA_MAX >> 2));69 // Unwinding.70 // Fill in the data structure. The first value has the stack location,71 // which for simplicity we can start right after the data structure itself.72 view[Asyncify.DATA_ADDR >> 2] = Asyncify.DATA_ADDR + 8;73 // The end of the stack will not be reached here anyhow.74 view[Asyncify.DATA_ADDR + 4 >> 2] = Asyncify.DATA_MAX;75 exports.asyncify_start_unwind(Asyncify.DATA_ADDR);76 Asyncify.sleeping = true;77 } else {78 // Don't sleep, normal execution.79 return imports[module][i].apply(null, arguments);80 }81 } else {82 // We are called as part of a resume/rewind. Stop sleeping.83 console.log('asyncify: resume in ' + i + '...');84 assert(Asyncify.sleepingFunction === i);85 exports.asyncify_stop_rewind();86 // The stack should have been all used up, and so returned to the original state.87 assert(view[Asyncify.DATA_ADDR >> 2] == Asyncify.DATA_ADDR + 8);88 assert(view[Asyncify.DATA_ADDR + 4 >> 2] == Asyncify.DATA_MAX);89 Asyncify.sleeping = false;90 // Restore the memory to the state from before we slept.91 view.set(Asyncify.savedMemory, Asyncify.DATA_ADDR >> 2);92 return imports[module][i].apply(null, arguments);93 }94 };95 })(module, i);96 } else {97 ret[module][i] = imports[module][i];98 }99 }100 }101 // Add ignored.print, which is ignored by asyncify, and allows debugging of asyncified code.102 ret['ignored'] = { 'print': function(x, y) { console.log(x, y) } };103 return ret;104 },105 instrumentExports: function(exports) {106 var ret = {};107 for (var e in exports) {108 if (typeof exports[e] === 'function' &&109 !e.startsWith('asyncify_')) {110 (function(e) {111 ret[e] = function() {112 while (1) {113 var ret = exports[e].apply(null, arguments);114 // If we are sleeping, then the stack was unwound; rewind it.115 if (Asyncify.sleeping) {116 console.log('asyncify: stop unwind; rewind');117 assert(!ret, 'results during sleep are meaningless, just 0');118 //console.log('asyncify: after unwind', view[Asyncify.DATA_ADDR >> 2], view[Asyncify.DATA_ADDR + 4 >> 2]);119 try {120 exports.asyncify_stop_unwind();121 exports.asyncify_start_rewind(Asyncify.DATA_ADDR);122 } catch (e) {123 console.log('error in unwind/rewind switch', e);124 }125 continue;126 }127 return ret;128 }129 };130 })(e);131 } else {132 ret[e] = exports[e];133 }134 }135 return ret;136 },137 check: function() {138 assert(!Asyncify.sleeping);139 },140 finish: function() {141 if (Asyncify.sleeps > 0) {142 print('asyncify:', 'sleeps:', Asyncify.sleeps, 'max depth:', Asyncify.maxDepth);143 }144 },145};146// Fuzz integration.147function logValue(x, y) {148 if (typeof y !== 'undefined') {149 console.log('[LoggingExternalInterface logging ' + x + ' ' + y + ']');150 } else {151 console.log('[LoggingExternalInterface logging ' + x + ']');152 }153}154// Set up the imports.155var imports = {156 'fuzzing-support': {157 'log-i32': logValue,158 'log-i64': logValue,159 'log-f32': logValue,160 'log-f64': logValue,161 },162 'env': {163 'setTempRet0': function(x) { tempRet0 = x },164 'getTempRet0': function() { return tempRet0 },165 },166};167imports = Asyncify.instrumentImports(imports);168// Create the wasm.169var instance = new WebAssembly.Instance(new WebAssembly.Module(binary), imports);170// Handle the exports.171var exports = instance.exports;172exports = Asyncify.instrumentExports(exports);173if (exports.memory) {174 var view = new Int32Array(exports.memory.buffer);175}176// Run the wasm.177var sortedExports = [];178for (var e in exports) {179 sortedExports.push(e);180}181sortedExports.sort();182sortedExports = sortedExports.filter(function(e) {183 // Filter special intrinsic functions.184 return !e.startsWith('asyncify_');185});186sortedExports.forEach(function(e) {187 Asyncify.check();188 if (typeof exports[e] !== 'function') return;189 try {190 console.log('[fuzz-exec] calling ' + e);191 var result = exports[e]();192 if (typeof result !== 'undefined') {193 console.log('[fuzz-exec] note result: $' + e + ' => ' + result);194 }195 } catch (e) {196 console.log('exception!');// + [e, e.stack]);197 }198});199// Finish up...
Using AI Code Generation
1const storybookRoot = require('storybook-root');2console.log(storybookRoot.sortedExports);3const storybookRoot = require('storybook-root');4console.log(storybookRoot.sortedExports);5const storybookRoot = require('storybook-root');6console.log(storybookRoot.sortedExports);7const storybookRoot = require('storybook-root');8console.log(storybookRoot.sortedExports);9const storybookRoot = require('storybook-root');10console.log(storybookRoot.sortedExports);11const storybookRoot = require('storybook-root');12console.log(storybookRoot.sortedExports);13const storybookRoot = require('storybook-root');14console.log(storybookRoot.sortedExports);15const storybookRoot = require('storybook-root');16console.log(storybookRoot.sortedExports);17const storybookRoot = require('storybook-root');18console.log(storybookRoot.sortedExports);19const storybookRoot = require('storybook-root');20console.log(storybookRoot.sortedExports);21const storybookRoot = require('storybook-root');22console.log(storybookRoot.sortedExports);23const storybookRoot = require('storybook-root');24console.log(storybookRoot.sortedExports);25const storybookRoot = require('storybook-root');26console.log(storybookRoot.sortedExports);27const storybookRoot = require('storybook-root');28console.log(storybookRoot.sortedExports
Using AI Code Generation
1import { sortedExports } from 'storybook-root';2const sortedComponents = sortedExports(require.context('./src/components', true, /stories\.js$/));3const sortedViews = sortedExports(require.context('./src/views', true, /stories\.js$/));4export default {5};6export const components = () => sortedComponents;7export const views = () => sortedViews;8{9 "scripts": {10 },11 "devDependencies": {12 }13}14import { configure } from '@storybook/react';15const req = require.context('../src', true, /stories\.js$/);16function loadStories() {17 req.keys().forEach(filename => req(filename));18}19configure(loadStories, module);20const path = require('path');21module.exports = async ({ config, mode }) => {22 config.module.rules.push({23 include: path.resolve(__dirname, '../'),24 loader: require.resolve('babel-loader'),25 options: {26 presets: [['react-app', { flow: false, typescript: true }]],27 },28 });29 return config;30};31import 'storybook-root/register';32import { addons } from '@storybook/addons';33import { themes } from '@storybook/theming';34addons.setConfig({35});36import React from 'react';37import { ThemeProvider } from 'styled-components';38import { theme } from '../src/theme';39 Story => (40 <ThemeProvider theme={theme}>41];42module.exports = {43};44import React from 'react';45import { addons, types } from '@storybook/addons';46import { AddonPanel } from '@storybook/components';47import { useChannel } from '@storybook
Using AI Code Generation
1import { sortedExports } from 'storybook-root-exports';2export default sortedExports(require.context('../src', true, /story\.js$/));3import { sortedExports } from 'storybook-root-exports';4export default sortedExports(require.context('./', true, /story\.js$/));5import { sortedExports } from 'storybook-root-exports';6export default sortedExports(require.context('./', true, /story\.js$/));7import { sortedExports } from 'storybook-root-exports';8export default sortedExports(require.context('./', true, /story\.js$/));9import { sortedExports } from 'storybook-root-exports';10export default sortedExports(require.context('./', true, /story\.js$/));11import { sortedExports } from 'storybook-root-exports';12export default sortedExports(require.context('./', true, /story\.js$/));13import { sortedExports } from 'storybook-root-exports';14export default sortedExports(require.context('./', true, /story\.js$/));15import { sortedExports } from 'storybook-root-exports';16export default sortedExports(require.context('./', true, /story\.js$/));
Using AI Code Generation
1const { sortedExports } = require('storybook-root')2const { default: Component } = require('./Component')3const { default: OtherComponent } = require('./OtherComponent')4module.exports = sortedExports({5})6const { addStoriesFromModuleExports } = require('storybook-root')7const test = require('./test')8addStoriesFromModuleExports(test)9const { addStoriesFromModuleExports } = require('storybook-root')10const test = require('./test')11addStoriesFromModuleExports(test)12const { addStoriesFromModuleExports } = require('storybook-root')13const test = require('./test')14addStoriesFromModuleExports(test)15const { addStoriesFromModuleExports } = require('storybook-root')16const test = require('./test')17addStoriesFromModuleExports(test)18const { addStoriesFromModuleExports } = require('storybook-root')19const test = require('./test')20addStoriesFromModuleExports(test)21const { addStoriesFromModuleExports } = require('storybook-root')22const test = require('./test')23addStoriesFromModuleExports(test)24const { addStoriesFromModuleExports } = require('storybook-root')25const test = require('./test')26addStoriesFromModuleExports(test)27const { addStoriesFromModuleExports } = require('storybook-root')28const test = require('./test')29addStoriesFromModuleExports(test)30const { addStoriesFromModuleExports } = require('storybook-root')31const test = require('./test')32addStoriesFromModuleExports(test)33const { addStoriesFromModuleExports } = require('storybook-root')34const test = require('./test')35addStoriesFromModuleExports(test)36const { addStoriesFromModuleExports } = require('storybook-root')37const test = require('./test')38addStoriesFromModuleExports(test)39const { addStoriesFromModuleExports } = require('storybook-root')40const test = require('./test')41addStoriesFromModuleExports(test)42const { addStoriesFromModuleExports } = require
Using AI Code Generation
1import { sortedExports } from '@storybook/react-native/dist/preview';2import { storiesOf } from '@storybook/react-native';3import { Text } from 'react-native';4import React from 'react';5import { View } from 'react-native';6import { Button } from 'react-native';7import { TouchableOpacity } from 'react-native';8import { TouchableHighlight } from 'react-native';9import { Image } from 'react-native';10import { ScrollView } from 'react-native';11import { FlatList } from 'react-native';12import { SectionList } from 'react-native';13import { TextInput } from 'react-native';14import { Textinput } from 'react-native';15import { ActivityIndicator } from 'react-native';16import { Switch } from 'react-native';17import { Slider } from 'react-native';18import { Picker } from 'react-native';19import { PickerIOS } from 'react-native';20import { DatePickerIOS } from 'react-native';21import { DatePickerAndroid } from 'react-native';22import { TimePickerAndroid } from 'react-native';23import { KeyboardAvoidingView } from 'react-native';24import { WebView } from 'react-native';25import { WebViewIOS } from 'react-native';26import { MaskedViewIOS } from 'react-native';27import { ProgressViewIOS } from 'react-native';28import { SegmentedControlIOS } from 'react-native';29import { TabBarIOS } from 'react-native';30import { SafeAreaView } from 'react-native';31import { StatusBar } from 'react-native';32import { ToolbarAndroid } from 'react-native';33import { ViewPagerAndroid } from 'react-native';34import { DrawerLayoutAndroid } from 'react-native';35import { ToastAndroid } from 'react-native';36import { AsyncStorage } from 'react-native';37import { Clipboard } from 'react-native';38import { DatePic
Using AI Code Generation
1const path = require('path');2const { sortedExports } = require('storybook-root-module');3const stories = sortedExports(path.resolve(__dirname, './stories'));4console.log('stories', stories);5export default {6};7export const Default = () => ({8 components: { HelloWorld },9});10export default {11};12export const Default = () => ({13 components: { HelloWorld },14});15export default {16};17export const Default = () => ({18 components: { HelloWorld },19});20export default {21};22export const Default = () => ({23 components: { HelloWorld },24});25export default {26};27export const Default = () => ({28 components: { HelloWorld },29});30export default {31};32export const Default = () => ({33 components: { HelloWorld },34});35export default {36};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!