Best JavaScript code snippet using storybook-root
media.ts
Source:media.ts
1import {Server} from '../../src/server';2import * as chai from 'chai';3import chaiHttp = require('chai-http');4import {TestHelper} from '../TestHelper';5import {FixtureUtils} from '../../fixtures/FixtureUtils';6import {JwtUtils} from '../../src/security/JwtUtils';7import {Directory} from '../../src/models/mediaManager/Directory';8import {File} from '../../src/models/mediaManager/File';9import {Course} from '../../src/models/Course';10import config from '../../src/config/main';11import * as fs from 'fs';12chai.use(chaiHttp);13const should = chai.should();14const app = new Server().app;15const BASE_URL = '/api/media';16const testHelper = new TestHelper(BASE_URL);17/**18 * Common unit test setup helper function.19 */20async function commonSetup () {21 const course = await FixtureUtils.getRandomCourse();22 const teacher = await FixtureUtils.getRandomTeacherForCourse(course);23 return {course, teacher};24}25describe('Media', async () => {26 beforeEach(() => testHelper.resetForNextTest());27 describe(`GET ${BASE_URL}`, async () => {28 async function commonGetSetup (withDirectories = true) {29 const {course, teacher} = await commonSetup();30 const file = await new File({31 _course: course._id.toString(),32 name: 'root',33 link: 'test/a',34 size: 12935 }).save();36 const subDirectory = withDirectories && await new Directory({37 _course: course._id.toString(),38 name: 'sub'39 }).save();40 const rootDirectory = withDirectories && await new Directory({41 _course: course._id.toString(),42 name: 'root',43 subDirectories: [subDirectory],44 files: [file]45 }).save();46 return {course, teacher, file, subDirectory, rootDirectory};47 }48 it('should get a directory', async () => {49 const {teacher, file, subDirectory, rootDirectory} = await commonGetSetup(true);50 const result = await testHelper.commonUserGetRequest(teacher, `/directory/${rootDirectory.id}`);51 result.status.should.be.equal(200,52 'could not get directory' +53 ' -> ' + result.body.message);54 result.body.name.should.equal(rootDirectory.name);55 result.body.subDirectories.should.be.instanceOf(Array)56 .and.have.lengthOf(1)57 .and.contains(subDirectory.id);58 result.body.files.should.be.instanceOf(Array)59 .and.have.lengthOf(1)60 .and.contains(file.id);61 });62 it('should fail to get a directory for an unauthorized user', async () => {63 const {course, rootDirectory} = await commonGetSetup(true);64 const unauthorizedUser = await FixtureUtils.getUnauthorizedTeacherForCourse(course);65 const result = await testHelper.commonUserGetRequest(unauthorizedUser, `/directory/${rootDirectory.id}`);66 result.status.should.be.equal(403);67 });68 it('should get a populated directory', async () => {69 const {teacher, file, subDirectory, rootDirectory} = await commonGetSetup(true);70 const result = await testHelper.commonUserGetRequest(teacher, `/directory/${rootDirectory.id}/lazy`);71 result.status.should.be.equal(200,72 'could not get directory' +73 ' -> ' + result.body.message);74 result.body._id.should.be.equal(rootDirectory.id);75 result.body.name.should.equal(rootDirectory.name);76 result.body.subDirectories.should.be.instanceOf(Array)77 .and.have.lengthOf(1);78 result.body.subDirectories[0]._id.should.be.equal(subDirectory.id);79 result.body.subDirectories[0].name.should.be.equal(subDirectory.name);80 result.body.subDirectories[0].subDirectories.should.be.instanceOf(Array)81 .and.have.lengthOf(subDirectory.subDirectories.length);82 result.body.subDirectories[0].files.should.be.instanceOf(Array)83 .and.have.lengthOf(subDirectory.files.length);84 result.body.files.should.be.instanceOf(Array)85 .and.have.lengthOf(1);86 result.body.files[0]._id.should.be.equal(file.id);87 result.body.files[0].name.should.be.equal(file.name);88 result.body.files[0].size.should.be.equal(file.size);89 result.body.files[0].link.should.be.equal(file.link);90 });91 it('should fail to get a populated directory for an unauthorized user', async () => {92 const {course, rootDirectory} = await commonGetSetup(true);93 const unauthorizedUser = await FixtureUtils.getUnauthorizedTeacherForCourse(course);94 const result = await testHelper.commonUserGetRequest(unauthorizedUser, `/directory/${rootDirectory.id}/lazy`);95 result.status.should.be.equal(403);96 });97 it('should get a file', async () => {98 const {teacher, file} = await commonGetSetup(false);99 const result = await testHelper.commonUserGetRequest(teacher, `/file/${file.id}`);100 result.status.should.be.equal(200,101 'could not get file' +102 ' -> ' + result.body.message);103 result.body._id.should.be.equal(file.id);104 result.body.name.should.be.equal(file.name);105 result.body.size.should.be.equal(file.size);106 result.body.link.should.be.equal(file.link);107 });108 it('should fail to get a file for an unauthorized user', async () => {109 const {course, file} = await commonGetSetup(false);110 const unauthorizedUser = await FixtureUtils.getUnauthorizedTeacherForCourse(course);111 const result = await testHelper.commonUserGetRequest(unauthorizedUser, `/file/${file.id}`);112 result.status.should.be.equal(403);113 });114 });115 describe(`POST ${BASE_URL}`, async () => {116 async function commonPostSetup () {117 const {course, teacher} = await commonSetup();118 const subDirectory = await new Directory({119 name: 'sub'120 });121 const rootDirectory = new Directory({122 _course: course._id.toString(),123 name: 'root'124 });125 return {course, teacher, subDirectory, rootDirectory};126 }127 it('should create a root directory', async () => {128 const {teacher, rootDirectory} = await commonPostSetup();129 const result = await testHelper.commonUserPostRequest(teacher, '/directory', rootDirectory);130 result.status.should.be.equal(200,131 'could not create root' +132 ' -> ' + result.body.message);133 result.body.__v.should.equal(0);134 result.body.name.should.equal(rootDirectory.name);135 result.body.subDirectories.should.be.instanceOf(Array)136 .and.have.lengthOf(0);137 result.body.files.should.be.instanceOf(Array).and.lengthOf(0);138 });139 it('should fail to create a root directory for an unauthorized teacher', async () => {140 const {course, rootDirectory} = await commonPostSetup();141 const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);142 const result = await testHelper.commonUserPostRequest(unauthorizedTeacher, '/directory', rootDirectory);143 result.status.should.be.equal(403);144 });145 it('should create a sub directory', async () => {146 const {teacher, rootDirectory, subDirectory} = await commonPostSetup();147 await rootDirectory.save();148 const result = await testHelper.commonUserPostRequest(teacher, `/directory/${rootDirectory._id}`, subDirectory);149 result.status.should.be.equal(200,150 'could not create subdirectory' +151 ' -> ' + result.body.message);152 result.body.__v.should.equal(0);153 result.body.name.should.equal(subDirectory.name);154 result.body.subDirectories.should.be.instanceOf(Array)155 .and.have.lengthOf(0);156 result.body.files.should.be.instanceOf(Array)157 .and.lengthOf(0);158 const updatedRoot = (await Directory.findById(rootDirectory));159 updatedRoot.subDirectories.should.be.instanceOf(Array)160 .and.have.lengthOf(1)161 .and.contains(result.body._id);162 });163 it('should fail to create a sub directory for an unauthorized teacher', async () => {164 const {course, rootDirectory, subDirectory} = await commonPostSetup();165 const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);166 await rootDirectory.save();167 const result = await testHelper.commonUserPostRequest(unauthorizedTeacher, `/directory/${rootDirectory._id}`, subDirectory);168 result.status.should.be.equal(403);169 });170 it('should upload a file', async () => {171 const {teacher, rootDirectory} = await commonPostSetup();172 await rootDirectory.save();173 const testFileName = 'test_file.txt';174 const testFile = fs.readFileSync('./test/resources/' + testFileName);175 const result = await chai.request(app)176 .post(`${BASE_URL}/file/${rootDirectory._id}`)177 .set('Cookie', `token=${JwtUtils.generateToken(teacher)}`)178 .attach('file', testFile, testFileName)179 .catch((err) => err.response);180 result.status.should.be.equal(200,181 'could not upload file' +182 ' -> ' + result.body.message);183 result.body.__v.should.equal(0);184 should.exist(result.body._id);185 should.exist(result.body.mimeType);186 should.exist(result.body.size);187 should.exist(result.body.link);188 result.body.name.should.be.equal(testFileName);189 const updatedRoot = (await Directory.findById(rootDirectory));190 updatedRoot.files.should.be.instanceOf(Array)191 .and.have.lengthOf(1)192 .and.contains(result.body._id);193 });194 it('should upload a file without extension', async () => {195 const {teacher, rootDirectory} = await commonPostSetup();196 await rootDirectory.save();197 const testFileName = 'test_file_without_extension';198 const testFile = fs.readFileSync('./test/resources/' + testFileName);199 const result = await chai.request(app)200 .post(`${BASE_URL}/file/${rootDirectory._id}`)201 .set('Cookie', `token=${JwtUtils.generateToken(teacher)}`)202 .attach('file', testFile, testFileName)203 .catch((err) => err.response);204 result.status.should.be.equal(200,205 'could not upload file' +206 ' -> ' + result.body.message);207 result.body.__v.should.equal(0);208 should.exist(result.body._id);209 should.exist(result.body.mimeType);210 should.exist(result.body.size);211 should.exist(result.body.link);212 result.body.name.should.be.equal(testFileName);213 const updatedRoot = (await Directory.findById(rootDirectory));214 updatedRoot.files.should.be.instanceOf(Array)215 .and.have.lengthOf(1)216 .and.contains(result.body._id);217 });218 it('should fail to upload a file for an unauthorized teacher', async () => {219 const {course, rootDirectory} = await commonPostSetup();220 const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);221 await rootDirectory.save();222 const testFileName = 'test_file.txt';223 const testFile = fs.readFileSync('./test/resources/' + testFileName);224 const result = await chai.request(app)225 .post(`${BASE_URL}/file/${rootDirectory._id}`)226 .set('Cookie', `token=${JwtUtils.generateToken(unauthorizedTeacher)}`)227 .attach('file', testFile, testFileName)228 .catch((err) => err.response);229 result.status.should.be.equal(403);230 });231 });232 describe(`PUT ${BASE_URL}`, async () => {233 async function commonPutSetup () {234 const {course, teacher} = await commonSetup();235 const file = new File({236 _course: course._id.toString(),237 name: 'file',238 link: 'test/a',239 size: 129240 });241 const subDirectory = await new Directory({242 _course: course._id.toString(),243 name: 'sub'244 });245 const rootDirectory = new Directory({246 _course: course._id.toString(),247 name: 'root'248 });249 return {course, teacher, file, subDirectory, rootDirectory};250 }251 it('should rename a directory', async () => {252 const {teacher, rootDirectory} = await commonPutSetup();253 await rootDirectory.save();254 const renamedDirectory = rootDirectory;255 renamedDirectory.name = 'renamedRoot';256 const result = await testHelper.commonUserPutRequest(teacher, `/directory/${rootDirectory._id}`, renamedDirectory);257 result.status.should.be.equal(200,258 'could not rename directory' +259 ' -> ' + result.body.message);260 result.body._id.should.equal(rootDirectory.id);261 result.body.name.should.equal(renamedDirectory.name);262 result.body.subDirectories.should.be.instanceOf(Array)263 .and.have.lengthOf(rootDirectory.subDirectories.length);264 result.body.files.should.be.instanceOf(Array)265 .and.lengthOf(rootDirectory.files.length);266 });267 it('should fail to update a directory for an unauthorized teacher', async () => {268 const {course, rootDirectory} = await commonPutSetup();269 const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);270 await rootDirectory.save();271 const renamedDirectory = rootDirectory;272 renamedDirectory.name = 'renamedRoot';273 const result = await testHelper.commonUserPutRequest(unauthorizedTeacher, `/directory/${rootDirectory._id}`, renamedDirectory);274 result.status.should.be.equal(403);275 });276 it('should fail to change the course of a directory to an unauthorized one', async () => {277 const {teacher, rootDirectory} = await commonPutSetup();278 await rootDirectory.save();279 const otherCourse = new Course({name: 'Unauthorized Test Course'});280 await otherCourse.save();281 const changedDirectory = rootDirectory;282 changedDirectory._course = otherCourse._id.toString();283 const result = await testHelper.commonUserPutRequest(teacher, `/directory/${rootDirectory._id}`, changedDirectory);284 result.status.should.be.equal(403);285 });286 it('should rename a file', async () => {287 const {teacher, file} = await commonPutSetup();288 await file.save();289 const renamedFile = file;290 file.name = 'renamedFile';291 const result = await testHelper.commonUserPutRequest(teacher, `/file/${file._id}`, renamedFile);292 result.status.should.be.equal(200,293 'could not rename file' +294 ' -> ' + result.body.message);295 result.body._id.should.equal(file.id);296 result.body.name.should.equal(renamedFile.name);297 result.body.link.should.equal(file.link);298 result.body.size.should.equal(file.size);299 });300 it('should fail to update a file for an unauthorized teacher', async () => {301 const {course, file} = await commonPutSetup();302 const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);303 await file.save();304 const renamedFile = file;305 file.name = 'renamedFile';306 const result = await testHelper.commonUserPutRequest(unauthorizedTeacher, `/file/${file._id}`, renamedFile);307 result.status.should.be.equal(403);308 });309 it('should fail to change the course of a file to an unauthorized one', async () => {310 const {teacher, file} = await commonPutSetup();311 await file.save();312 const otherCourse = new Course({name: 'Unauthorized Test Course'});313 await otherCourse.save();314 const changedFile = file;315 changedFile._course = otherCourse._id.toString();316 const result = await testHelper.commonUserPutRequest(teacher, `/file/${file._id}`, changedFile);317 result.status.should.be.equal(403);318 });319 });320 describe(`DELETE ${BASE_URL}`, async () => {321 async function commonDeleteSetup () {322 const {course, teacher} = await commonSetup();323 const subDirectory = await new Directory({324 _course: course._id.toString(),325 name: 'sub'326 }).save();327 const rootDirectory = await new Directory({328 _course: course._id.toString(),329 name: 'root',330 subDirectories: [subDirectory],331 }).save();332 return {course, teacher, subDirectory, rootDirectory};333 }334 async function commonDeleteFileSetup (withRootDirectory = true) {335 const {course, teacher} = await commonSetup();336 const testFileName = fs.readdirSync('./')[0];337 const testFile = fs.readFileSync(testFileName);338 fs.copyFileSync(testFileName, config.uploadFolder + '/test.file');339 const file = await new File({340 _course: course._id.toString(),341 name: 'root',342 physicalPath: config.uploadFolder + '/test.file',343 link: testFileName,344 size: testFile.length345 }).save();346 const rootDirectory = withRootDirectory && await new Directory({347 _course: course._id.toString(),348 name: 'root',349 files: [file]350 }).save();351 return {course, teacher, file, rootDirectory};352 }353 it('should delete a directory', async () => {354 const {teacher, rootDirectory} = await commonDeleteSetup();355 const result = await testHelper.commonUserDeleteRequest(teacher, `/directory/${rootDirectory._id}`);356 result.status.should.be.equal(200,357 'could not delete directory' +358 ' -> ' + result.body.message);359 should.not.exist(await Directory.findById(rootDirectory));360 });361 it('should delete a directory and its subdirectories', async () => {362 const {teacher, subDirectory, rootDirectory} = await commonDeleteSetup();363 const result = await testHelper.commonUserDeleteRequest(teacher, `/directory/${rootDirectory._id}`);364 result.status.should.be.equal(200,365 'could not delete directory' +366 ' -> ' + result.body.message);367 should.not.exist(await Directory.findById(rootDirectory));368 should.not.exist(await Directory.findById(subDirectory));369 });370 it('should delete a directory and its files', async () => {371 const {teacher, file, rootDirectory} = await commonDeleteFileSetup(true);372 const result = await testHelper.commonUserDeleteRequest(teacher, `/directory/${rootDirectory._id}`);373 result.status.should.be.equal(200,374 'could not delete directory' +375 ' -> ' + result.body.message);376 should.not.exist(await Directory.findById(rootDirectory));377 should.not.exist(await File.findById(file));378 });379 it('should delete a file', async () => {380 const {teacher, file} = await commonDeleteFileSetup(false);381 const result = await testHelper.commonUserDeleteRequest(teacher, `/file/${file._id}`);382 result.status.should.be.equal(200,383 'could not delete file' +384 ' -> ' + result.body.message);385 should.not.exist(await File.findById(file));386 fs.existsSync(config.uploadFolder + '/test.file').should.be.equal(false);387 });388 it('should fail to delete a directory for an unauthorized teacher', async () => {389 const {course, rootDirectory} = await commonDeleteSetup();390 const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);391 const result = await testHelper.commonUserDeleteRequest(unauthorizedTeacher, `/directory/${rootDirectory._id}`);392 result.status.should.be.equal(403);393 });394 it('should fail to delete a file for an unauthorized teacher', async () => {395 const {course, file} = await commonDeleteFileSetup(false);396 const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);397 const result = await testHelper.commonUserDeleteRequest(unauthorizedTeacher, `/file/${file._id}`);398 result.status.should.be.equal(403);399 });400 it('should fail when directory not found', async () => {401 const teacher = await FixtureUtils.getRandomTeacher();402 const result = await testHelper.commonUserDeleteRequest(teacher, '/directory/507f1f77bcf86cd799439011');403 result.status.should.be.equal(404);404 });405 it('should fail when file not found', async () => {406 const teacher = await FixtureUtils.getRandomTeacher();407 const result = await testHelper.commonUserDeleteRequest(teacher, '/file/507f1f77bcf86cd799439011');408 result.status.should.be.equal(404);409 });410 });...
index.js
Source:index.js
1/**2 * Barebones Stack3 * @author @dev-xo https://github.com/dev-xo4 *5 * Some of the Typescript related scripts, have been developed by other authors.6 * @author @kentcdodds https://github.com/kentcdodds7 * @author @MichaelDeBoey https://github.com/MichaelDeBoey8 */9const { execSync } = require("child_process")10const fs = require("fs/promises")11const path = require("path")12const crypto = require("crypto")13const toml = require("@iarna/toml")14const YAML = require("yaml")15const semver = require("semver")16const PackageJson = require("@npmcli/package-json")17/**18 * Helpers.19 */20const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")21const getRandomString = (length) => crypto.randomBytes(length).toString("hex")22/**23 * Returns the version of the package manager used in the workspace.24 * By default, the package manager is derived based on the lock file,25 * but it can also be passed in explicitly.26 */27const getPackageManagerVersion = (packageManager) =>28 execSync(`${packageManager} --version`).toString("utf-8").trim()29/**30 * Returns commands for the package manager used in the workspace.31 * By default, the package manager is derived based on the lock file,32 * but it can also be passed in explicitly.33 */34const getPackageManagerCommand = (packageManager) => {35 return {36 npm: () => ({37 exec: "npx",38 lockfile: "package-lock.json",39 run: (script, args) => `npm run ${script} ${args ? `-- ${args}` : ""}`,40 }),41 pnpm: () => {42 const pnpmVersion = getPackageManagerVersion("pnpm")43 const includeDoubleDashBeforeArgs = semver.lt(pnpmVersion, "7.0.0")44 const useExec = semver.gte(pnpmVersion, "6.13.0")45 return {46 exec: useExec ? "pnpm exec" : "pnpx",47 lockfile: "pnpm-lock.yaml",48 run: (script, args) =>49 includeDoubleDashBeforeArgs50 ? `pnpm run ${script} ${args ? `-- ${args}` : ""}`51 : `pnpm run ${script} ${args || ""}`,52 }53 },54 yarn: () => ({55 exec: "yarn",56 lockfile: "yarn.lock",57 run: (script, args) => `yarn ${script} ${args || ""}`,58 }),59 }[packageManager]()60}61/**62 * Filters out unused dependencies.63 */64const removeUnusedDependencies = (dependencies, unusedDependencies) =>65 Object.fromEntries(66 Object.entries(dependencies).filter(67 ([key]) => !unusedDependencies.includes(key)68 )69 )70/**71 * Cleans up Typescript references from Cypress folders.72 */73const cleanupCypressFiles = async (rootDirectory) => {74 const CYPRESS_CONFIG_PATH = path.join(rootDirectory, "cypress.config.js")75 // Reads, replaces and writes a new file.76 const cypressConfig = await fs.readFile(CYPRESS_CONFIG_PATH, "utf-8")77 const replacedCypressConfig = cypressConfig.replace(78 "export default",79 "module.exports ="80 )81 await fs.writeFile(CYPRESS_CONFIG_PATH, replacedCypressConfig)82}83/**84 * Cleans up Typescript references from Vitest config.85 */86const cleanupVitestConfigFile = async (rootDirectory) => {87 const VITEST_CONFIG_PATH = path.join(rootDirectory, "vitest.config.js")88 // Reads, replaces and writes a new file.89 const vitestConfig = await fs.readFile(VITEST_CONFIG_PATH, "utf-8")90 const replacedVitestConfig = vitestConfig.replace(91 "setup-test-env.ts",92 "setup-test-env.js"93 )94 await fs.writeFile(VITEST_CONFIG_PATH, replacedVitestConfig)95}96/**97 * Cleans up Typescript references from Github workflows.98 */99const cleanupDeployWorkflowFile = async (rootDirectory) => {100 const DEPLOY_WORKFLOW_PATH = path.join(101 rootDirectory,102 ".github",103 "workflows",104 "deploy.yml"105 )106 // Reads, parses, replaces and writes a new file.107 const deployWorkflow = await fs.readFile(DEPLOY_WORKFLOW_PATH, "utf-8")108 const parsedWorkflow = YAML.parse(deployWorkflow)109 delete parsedWorkflow.jobs.typecheck110 parsedWorkflow.jobs.deploy.needs = parsedWorkflow.jobs.deploy.needs.filter(111 (need) => need !== "typecheck"112 )113 return await fs.writeFile(114 DEPLOY_WORKFLOW_PATH,115 YAML.stringify(parsedWorkflow)116 )117}118/**119 * Updates package.json120 */121const updatePackageJson = async (rootDirectory, isTypeScript, APP_NAME) => {122 const packageJson = await PackageJson.load(rootDirectory)123 const {124 devDependencies,125 prisma: { seed: prismaSeed, ...prisma },126 scripts: { typecheck, validate, ...scripts },127 } = packageJson.content128 packageJson.update({129 name: APP_NAME,130 devDependencies: isTypeScript131 ? devDependencies132 : removeUnusedDependencies(devDependencies, ["ts-node"]),133 prisma: isTypeScript134 ? { ...prisma, seed: prismaSeed }135 : {136 ...prisma,137 seed: prismaSeed138 .replace("ts-node", "node")139 .replace("seed.ts", "seed.js"),140 },141 scripts: isTypeScript142 ? { ...scripts, typecheck, validate }143 : { ...scripts, validate: validate.replace(" typecheck", "") },144 })145 await packageJson.save()146}147/**148 * Creates and initiates a newly `.env` file,149 * with provided variables from `.env.example`.150 */151const replaceAndInitEnvFiles = async (rootDirectory) => {152 const ENV_PATH = path.join(rootDirectory, ".env")153 const EXAMPLE_ENV_PATH = path.join(rootDirectory, ".env.example")154 // Reads, replaces and writes a new `.env` file.155 const exampleEnv = await fs.readFile(EXAMPLE_ENV_PATH, "utf-8")156 const replacedExampleEnv = exampleEnv.replace(157 /^SESSION_SECRET=.*$/m,158 `SESSION_SECRET="${getRandomString(16)}"`159 )160 await fs.writeFile(ENV_PATH, replacedExampleEnv)161 // Removes `.env.example` file from directory.162 await fs.unlink(EXAMPLE_ENV_PATH)163}164/**165 * Replaces default project name for the one provided by `DIR_NAME`.166 *167 * Files that are being updated:168 * - fly.toml169 * - README.md170 */171const replaceProjectNameFromFiles = async (rootDirectory, APP_NAME) => {172 const FLY_TOML_PATH = path.join(rootDirectory, "fly.toml")173 const README_PATH = path.join(rootDirectory, "README.md")174 const REPLACER = /barebones[\s|-]stack/gim175 const [flyToml, readme] = await Promise.all([176 fs.readFile(FLY_TOML_PATH, "utf-8"),177 fs.readFile(README_PATH, "utf-8"),178 ])179 // Replaces Fly.toml file.180 const replacedFlyToml = toml.parse(flyToml)181 replacedFlyToml.app = replacedFlyToml.app.replace(REPLACER, APP_NAME)182 // Replaces README.md file.183 const replacedReadme = readme.replace(REPLACER, APP_NAME)184 await Promise.all([185 fs.writeFile(FLY_TOML_PATH, toml.stringify(replacedFlyToml)),186 fs.writeFile(README_PATH, replacedReadme),187 ])188}189/**190 * Replaces `lockfile` based on the package manager used in the workspace.191 */192const replaceDockerLockFile = async (rootDirectory, pm) => {193 const DOCKERFILE_PATH = path.join(rootDirectory, "Dockerfile")194 const dockerfile = await fs.readFile(DOCKERFILE_PATH, "utf-8")195 const replacedDockerFile = pm.lockfile196 ? dockerfile.replace(197 new RegExp(escapeRegExp("ADD package.json"), "g"),198 `ADD package.json ${pm.lockfile}`199 )200 : dockerfile201 await fs.writeFile(DOCKERFILE_PATH, replacedDockerFile)202}203/**204 * Runs after the project has been generated205 * and dependencies have been installed.206 */207const main = async ({ rootDirectory, packageManager, isTypeScript }) => {208 const DIR_NAME = path.basename(rootDirectory)209 const APP_NAME = DIR_NAME.replace(/[^a-zA-Z0-9-_]/g, "-")210 // Returns commands for the package manager used in the workspace.211 const pm = getPackageManagerCommand(packageManager)212 if (!isTypeScript) {213 // Cleans up all Typescript references from the project.214 await Promise.all([215 cleanupCypressFiles(rootDirectory),216 cleanupVitestConfigFile(rootDirectory),217 cleanupDeployWorkflowFile(rootDirectory),218 ])219 }220 await Promise.all([221 // Updates package.json.222 updatePackageJson(rootDirectory, isTypeScript, APP_NAME),223 // Creates and initiates a newly `.env` file,224 // with provided variables from `.env.example`.225 replaceAndInitEnvFiles(rootDirectory),226 // Replaces default project name for the one provided by `DIR_NAME`.227 replaceProjectNameFromFiles(rootDirectory, APP_NAME),228 // Replaces `lockfile` based on the package manager used in the workspace.229 replaceDockerLockFile(rootDirectory, pm),230 ])231 // Seeds database.232 execSync(pm.run("setup"), { cwd: rootDirectory, stdio: "inherit" })233 // Formats the entire project.234 execSync(pm.run("format", "--loglevel warn"), {235 cwd: rootDirectory,236 stdio: "inherit",237 })238 console.log(239 `240 ð Batteries has been successfully set.241 âï¸ Go ahead and build something amazing!242 243 ð Start development with \`${pm.run("dev")}\`244 245 `.trim()246 )247}...
application.js
Source:application.js
...24 createPathDirectory({ rootDirectory: currentDirectory, path });25 }26};27const createDirectory = ({ rootDirectory, newDirectory }) =>28 rootDirectory(GET_CHILDREN_COMMAND).add(newDirectory);29const findDirectory = ({ rootDirectory, pathToSearch = [] }) => {30 const directoryToFind = pathToSearch.shift();31 if (rootDirectory(GET_DATA_COMMAND) === directoryToFind) {32 return rootDirectory;33 }34 for (let child of rootDirectory(GET_CHILDREN_COMMAND)) {35 if (child(GET_DATA_COMMAND) === directoryToFind && pathToSearch.length == 0) {36 return child;37 }38 if (child(GET_DATA_COMMAND) === directoryToFind && pathToSearch.length != 0) {39 return findDirectory({ rootDirectory: child, pathToSearch });40 }41 }42 return null;43};44const printDirectory = ({ rootDirectory, result = "", deep = 0 }) => {45 result = result.concat(rootDirectory(GET_FORMATTED_DATA_COMMAND(deep)));46 for (let child of rootDirectory(GET_CHILDREN_COMMAND)) {47 result = printDirectory({ rootDirectory: child, result, deep: deep + 1 });48 }49 return result;50};51const head = DIRECTORY("root")(new Set());52module.exports = {53 create: ({ dir = "" }) => {54 createPathDirectory({ rootDirectory: head, path: dir.split("/") });55 return `CREATE ${dir}`;56 },57 list: () => `LIST ${printDirectory({ rootDirectory: head })}`,58 move: ({ source, target }) => {59 const sourceDir = source.split("/");60 const targetDir = target.split("/");...
Using AI Code Generation
1const rootDirectory = require('storybook-root-directory');2module.exports = {3 stories: [`${rootDirectory}/stories/**/*.stories.js`],4};5import { storiesOf } from '@storybook/html';6import { withKnobs, text } from '@storybook/addon-knobs';7import { rootDirectory } from 'storybook-root-directory';8const stories = storiesOf('Atoms', module);9stories.addDecorator(withKnobs);10stories.add('Button', () => {11 const label = text('Label', 'Click Me');12 return `<button type="button">${label}</button>`;13});14stories.add('Input', () => {15 const label = text('Label', 'Enter Text');16 return `<input type="text" placeholder="${label}" />`;17});18import { storiesOf } from '@storybook/html';19import { withKnobs, text } from '@storybook/addon-knobs';20import { rootDirectory } from 'storybook-root-directory';21const stories = storiesOf('Atoms/Button', module);22stories.addDecorator(withKnobs);23stories.add('Button', () => {24 const label = text('Label', 'Click Me');25 return `<button type="button">${label}</button>`;26});27import { storiesOf } from '@storybook/html';28import { withKnobs, text } from '@storybook/addon-knobs';29import { rootDirectory } from 'storybook-root-directory';30const stories = storiesOf('Atoms/Input', module);31stories.addDecorator(withKnobs);32stories.add('Input', () => {33 const label = text('Label', 'Enter Text');34 return `<input type="text" placeholder="${label}" />`;35});36import { storiesOf } from '@storybook/html';37import { withKnobs, text } from '@storybook/addon-knobs';38import { rootDirectory } from 'storybook-root-directory';39const stories = storiesOf('Molecules', module);
Using AI Code Generation
1const path = require('path');2const rootDirectory = require('storybook-root-directory');3module.exports = {4 webpackFinal: async config => {5 config.resolve.modules.push(path.resolve(rootDirectory, 'src'));6 return config;7 },8};9{10 "dependencies": {11 },12 "scripts": {13 },14 "devDependencies": {15 }16}17const path = require('path');18const rootDirectory = require('storybook-root-directory');19module.exports = async ({ config, mode }) => {20 config.resolve.modules.push(path.resolve(rootDirectory, 'src'));21 return config;22};23Module build failed (from ./node_modules/babel-loader/lib/index.js):
Using AI Code Generation
1import rootDirectory from 'storybook-root-decorator';2rootDirectory(__dirname);3import React from 'react';4import { storiesOf } from '@storybook/react';5storiesOf('Welcome', module).add('to Storybook', () => <div>Hello</div>);6import rootDirectory from 'storybook-root-decorator';7rootDirectory(__dirname);8import rootDirectory from 'storybook-root-decorator';9rootDirectory(__dirname);10import React from 'react';11import { storiesOf } from '@storybook/react';12storiesOf('Welcome', module).add('to Storybook', () => <div>Hello</div>);13import rootDirectory from 'storybook-root-decorator';14rootDirectory(__dirname);15import rootDirectory from 'storybook-root-decorator';16rootDirectory(__dirname);17import React from 'react';18import { storiesOf } from '@storybook/react';19storiesOf('Welcome', module).add('to Storybook', () => <div>Hello</div>);20import rootDirectory from 'storybook-root-decorator';21rootDirectory(__dirname);22import rootDirectory from 'storybook-root-decorator';23rootDirectory(__dirname);24import React from 'react';25import { storiesOf } from '@storybook/react';26storiesOf('Welcome', module).add
Using AI Code Generation
1import { rootDirectory } from 'storybook-root-decorator';2export default {3};4export const RootDirectory = () => {5 return <div>{rootDirectory()}</div>;6};7import { addDecorator } from '@storybook/react';8import rootDecorator from 'storybook-root-decorator';9addDecorator(rootDecorator);10const path = require('path');11module.exports = async ({ config, mode }) => {12 config.resolve.alias['storybook-root-decorator'] = path.resolve(__dirname, '../');13 return config;14};15module.exports = {16};17{18 {19 "targets": {20 }21 }22}23{24 "compilerOptions": {25 },26}27{28 "compilerOptions": {
Using AI Code Generation
1const { rootDirectory } = require('storybook-root-directory');2const rootDir = rootDirectory();3console.log(rootDir);4const { rootDirectory } = require('storybook-root-directory');5const rootDir = rootDirectory();6console.log(rootDir);7const { rootDirectory } = require('storybook-root-directory');8const rootDir = rootDirectory();9console.log(rootDir);10const { rootDirectory } = require('storybook-root-directory');11const rootDir = rootDirectory();12console.log(rootDir);13const { rootDirectory } = require('storybook-root-directory');14const rootDir = rootDirectory();15console.log(rootDir);16const { rootDirectory } = require('storybook-root-directory');17const rootDir = rootDirectory();18console.log(rootDir);19const { rootDirectory } = require('storybook-root-directory');20const rootDir = rootDirectory();21console.log(rootDir);22const { rootDirectory } = require('storybook-root-directory');23const rootDir = rootDirectory();24console.log(rootDir);25const { rootDirectory } = require('storybook-root-directory');26const rootDir = rootDirectory();27console.log(rootDir);28const { rootDirectory } = require('storybook-root-directory
Using AI Code Generation
1import {rootDirectory} from 'storybook-root-siblings';2import {StyleSheet, View, Text} from 'react-native';3import React, {Component} from 'react';4export default class RootSibling extends Component {5 render() {6 return (7 <View style={styles.container}>8 <Text style={styles.text}>Root Directory: {rootDirectory}</Text>9 );10 }11}12const styles = StyleSheet.create({13 container: {14 },15 text: {16 },17});18import {rootSibling} from 'storybook-root-siblings';19import React from 'react';20import {AppRegistry} from 'react-native';21import RootSibling from './test';22import {name as appName} from './app.json';23rootSibling(<RootSibling />);24AppRegistry.registerComponent(appName, () => RootSibling);
Using AI Code Generation
1const rootDirectory = require('storybook-root-require');2const path = require('path');3module.exports = {4 webpackFinal: async config => {5 config.module.rules.push({6 include: rootDirectory('src')7 });8 return config;9 }10};11const rootDirectory = require('storybook-root-require');12const path = require('path');13module.exports = {14 webpackFinal: async config => {15 config.module.rules.push({16 include: rootDirectory('src')17 });18 return config;19 }20};21const rootDirectory = require('storybook-root-require');22const path = require('path');23module.exports = {24 webpackFinal: async config => {25 config.module.rules.push({26 include: rootDirectory('src')27 });28 return config;29 }30};
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!!