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,EAAkB,QAClB,GACE,EACE,EAAe,EAAqB,kBAAkB,EAAoB,EAAM,GAAO,GAC7F,QAAQ,MAAM,CACZ,GACA,MAAM,IAAI,gBAAgB,KAC1B,WAAW,MAAM,QAAQ,iBAAoB,MAAM,QAAQ,yBAC3D,EACA,IACA,KAAK,MACT,MACE,QAAQ,MAAM,KAAK,EAAI,qBAEhB,EACT,QAAQ,MAAM,CACZ,GACA,MAAM,IAAI,GACV,GACA,OAAO,EAAM,OAAO,MAAM,MAAM,MAAM,EAAG,IAAI,KAAK,QAClD,IACA,KAAK,OAEP,QAAQ,MAAM,EAChB","file":"/npm/canvas-sketch-cli@1.15.0/src/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/canvas-sketch-cli@1.15.0/src/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","#!/usr/bin/env node\nconst path = require('path');\nconst budo = require('budo');\nconst defined = require('defined');\nconst parseArgs = require('subarg');\nconst rightNow = require('right-now');\nconst prettyBytes = require('pretty-bytes');\nconst prettyMs = require('pretty-ms');\nconst downloads = require('./downloads-folder');\nconst getStdin = require('get-stdin');\nconst esmify = require('esmify');\nconst fs = require('fs');\nconst chalk = require('chalk');\nconst { promisify } = require('util');\nconst { generateFileName, readPackage, isCanvasSketchPackage } = require('./util');\nconst mkdirp = promisify(require('mkdirp'));\nconst writeFile = promisify(fs.writeFile);\nconst install = require('./install');\nconst resolve = require('resolve');\nconst browserifyFromArgs = require('browserify/bin/args');\nconst createMiddleware = require('./middleware');\nconst { createLogger, getErrorDetails } = require('./logger');\nconst html = require('./html');\nconst terser = require('terser');\nconst SourceMapUtil = require('convert-source-map');\nconst { EventEmitter } = require('events');\nconst pluginEnv = require('./plugins/plugin-env');\nconst pluginResolve = require('./plugins/plugin-resolve');\nconst pluginGLSL = require('./plugins/plugin-glsl');\n// const transformInstaller = require('./plugins/transform-installer');\n\nconst DEFAULT_GENERATED_FILENAME = '_generated.js';\n\nconst bundleAsync = (bundler) => {\n  return new Promise((resolve, reject) => {\n    bundler.bundle((err, src) => {\n      if (err) reject(err);\n      else resolve(src);\n    });\n  });\n};\n\nconst start = async (args, overrides = {}) => {\n  const argv = parseArgs(args, {\n    string: ['template'],\n    boolean: [\n      'hot',\n      'open',\n      'force',\n      'pushstate',\n      'install',\n      'quiet',\n      'build',\n      'version',\n      'inline',\n      'watching',\n      'client',\n      'help'\n    ],\n    alias: {\n      sourceMap: 'source-map',\n      version: 'v',\n      port: 'p',\n      pushstate: 'P',\n      build: 'b',\n      dir: 'd',\n      open: 'o',\n      install: 'I',\n      force: 'f',\n      template: 't',\n      stream: 'S',\n      new: 'n',\n      'help': 'h'\n    },\n    '--': true,\n    default: {\n      watching: true,\n      install: true,\n      client: true,\n      template: 'default'\n    }\n  });\n\n  // Merge in user options\n  Object.assign(argv, overrides);\n\n  // Handle stream subargs\n  if (typeof argv.stream === 'string') {\n    argv.stream = {\n      format: argv.stream\n    };\n  } else if (argv.stream === true) {\n    argv.stream = {\n      format: 'mp4'\n    };\n  } else if (argv.stream && typeof argv.stream === 'object') {\n    if (argv.stream._) {\n      if (!argv.stream.format) argv.stream.format = argv.stream._;\n      delete argv.stream._;\n    }\n  }\n\n  // Handle array -> single string\n  if (argv.stream) {\n    if (Array.isArray(argv.stream.format)) {\n      argv.stream.format = argv.stream.format[0] || 'mp4';\n    }\n  }\n\n  if (argv.help) {\n    const help = path.join(__dirname, '..', 'bin', 'help.txt');\n    fs.createReadStream(help)\n      .pipe(process.stdout);\n    return null;\n  }\n\n  if (argv.version) {\n    console.log(require('../package.json').version);\n    process.exit(0);\n  }\n\n  const templateDirectory = 'templates';\n  const sketchDirectory = 'sketches';\n  const defaultDir = '.';\n\n  const cwd = argv.cwd || process.cwd();\n\n  let dir;\n  if (argv.dir) {\n    dir = path.isAbsolute(argv.dir) ? argv.dir : path.resolve(cwd, argv.dir);\n  } else {\n    dir = path.resolve(cwd, defaultDir);\n  }\n\n  const templateHtmlFile = path.resolve(__dirname, 'templates/index.html');\n  let htmlFile;\n  if (argv.html) {\n    htmlFile = path.isAbsolute(argv.html) ? path.resolve(argv.html) : path.resolve(cwd, argv.html);\n  } else {\n    htmlFile = templateHtmlFile;\n  }\n\n  const logger = createLogger(argv);\n  let opt;\n  try {\n    opt = await prepare(logger);\n  } catch (err) {\n    throw err;\n  }\n\n  const stripJSExt = (name) => {\n    return /\\.(ts|js|mjs|es|jsx|tsx|es6)$/i.test(name) ? path.basename(name, path.extname(name)) : name;\n  };\n\n  const fileName = (opt.name && typeof opt.name === 'string') ? opt.name : path.basename(opt.entry);\n\n  const fileNameBase = stripJSExt(fileName);\n  const fileNameJS = opt.js || `${fileNameBase}.js`;\n\n  let jsUrl = opt.js || encodeURIComponent(fileNameJS);\n  const htmlOpts = { file: htmlFile, src: jsUrl, title: opt.title || fileName };\n\n  if (opt.build) {\n    const compressJS = argv.compress !== 'html' && argv.compress !== false;\n    const compressHTML = argv.compress !== 'js' && argv.compress !== false;\n\n    const jsOutFile = path.resolve(dir, fileNameJS);\n    if (jsOutFile === opt.entry) {\n      throw new Error(`The input and ouput JS files are the same: ${chalk.bold(path.relative(cwd, jsOutFile))}`);\n    }\n\n    const htmlOutFile = path.resolve(dir, `${fileNameBase}.html`);\n    if (htmlOutFile === htmlOpts.file) {\n      throw new Error(`The input and ouput HTML files are the same: ${chalk.bold(path.relative(cwd, htmlOpts.file))}`);\n    }\n\n    // Start building our static contents\n    let timeStart = Date.now();\n    logger.log('Building...');\n\n    const inline = opt.inline;\n\n    let sourceMapOption = opt.sourceMap;\n    // parse CLI string\n    if (sourceMapOption === 'true' || sourceMapOption === 'false') {\n      sourceMapOption = sourceMapOption === 'true';\n    }\n    if (sourceMapOption == null || sourceMapOption === 'auto' || sourceMapOption === true) {\n      sourceMapOption = true;\n      // By default, sourceMap: true will also be inlined on --inline\n      // But user can still override with {sourceMap: 'external'}\n      if (inline) {\n        sourceMapOption = 'inline';\n      }\n    }\n\n    // Create bundler from CLI options\n    let debug = typeof opt.debug === 'boolean' ? opt.debug : true;\n    if (sourceMapOption === false) debug = false;\n    const bundler = browserifyFromArgs(opt.browserifyArgs, {\n      debug,\n      entries: opt.entry\n    });\n\n    // First, make sure our output (public) dir exists\n    await mkdirp(dir);\n\n    // Now bundle up our code into a string\n    let buffer;\n    try {\n      buffer = await bundleAsync(bundler);\n    } catch (err) {\n      throw err;\n    }\n    let code = buffer.toString();\n\n    const sourceMapFile = `${jsOutFile}.map`;\n\n    // Get initial source map from browserify\n    let sourceMapJSON;\n    const sourceMapConverter = SourceMapUtil.fromSource(code);\n    if (sourceMapConverter) sourceMapJSON = sourceMapConverter.toJSON();\n\n    if (sourceMapOption && !sourceMapJSON) {\n      sourceMapOption = false;\n      // Maybe it would be good to warn why a .map file is not generated? Or maybe too heavy handed...\n      // console.warn('Note: Source map not generated because browserify did not emit an inline source map.\\nTo hide this warning, use {sourceMap: false} or --source-map=false');\n    }\n\n    if (compressJS) {\n      // Strip browserify inline source map if it exists\n      code = SourceMapUtil.removeComments(code);\n\n      try {\n        const terserOpt = {};\n        terserOpt[path.basename(jsOutFile)] = code;\n\n        const sourceMap = sourceMapOption && debug && sourceMapJSON ? {\n          content: sourceMapJSON,\n          url: path.basename(sourceMapFile)\n        } : false;\n\n        const terserResult = await terser.minify(terserOpt, {\n          sourceMap,\n          output: { comments: false },\n          compress: {\n            keep_infinity: true,\n            pure_getters: true\n          },\n          // warnings: true,\n          ecma: 5,\n          toplevel: false,\n          mangle: {\n            properties: false\n          }\n        });\n        if (terserResult.error) {\n          terserResult.error.originalSourceCode = code;\n          throw terserResult.error;\n        }\n        code = terserResult.code;\n        if (sourceMapOption) sourceMapJSON = terserResult.map;\n      } catch (err) {\n        throw err;\n      }\n    }\n\n    // strip any subsequently added source maps\n    code = SourceMapUtil.removeComments(code);\n    code = SourceMapUtil.removeMapFileComments(code);\n\n    // now add them back in as per our options\n    if (sourceMapOption && sourceMapJSON && debug) {\n      let relSrcMapFile = path.relative(dir, sourceMapFile);\n      // if (!path.isAbsolute(relSrcMapFile)) {\n      //   relSrcMapFile = `./${encodeURIComponent(relSrcMapFile)}`;\n      // }\n      const isInline = sourceMapOption === 'inline';\n      const comment = isInline\n        ? SourceMapUtil.fromJSON(sourceMapJSON).toComment()\n        : SourceMapUtil.generateMapFileComment(relSrcMapFile);\n      if (!code.endsWith('\\n')) code += '\\n';\n      code += comment + '\\n';\n    }\n\n    // In --stdout mode, just output the code\n    if (opt.stdout) {\n      throw new Error('--stdout is not yet supported');\n    } else {\n      // A util to log the output of a file\n      const logFile = (type, file, data) => {\n        const bytes = chalk.dim(`(${prettyBytes(data.length)})`);\n        logger.log(`${type} → ${chalk.bold(path.relative(cwd, file))} ${bytes}`, { leadingSpace: false });\n      };\n\n      // Read the templated HTML, transform it and write it out\n      const htmlData = await html.read(Object.assign({}, htmlOpts, {\n        inline,\n        code,\n        compress: compressHTML\n      }));\n      await writeFile(htmlOutFile, htmlData);\n      logFile('HTML  ', htmlOutFile, htmlData);\n\n      // Write bundled JS\n      if (!inline) {\n        await writeFile(jsOutFile, code);\n        logFile('JS    ', jsOutFile, code);\n      }\n\n      if (sourceMapOption !== false && sourceMapOption !== 'inline' && sourceMapJSON) {\n        await writeFile(sourceMapFile, sourceMapJSON);\n        logFile('SrcMap', sourceMapFile, sourceMapJSON);\n      }\n\n      const ms = (Date.now() - timeStart);\n      logger.log(`Finished in ${chalk.magenta(prettyMs(ms))}`, { leadingSpace: false });\n      logger.pad();\n    }\n\n    return null;\n  } else {\n    // pad the previous logs if necessary\n    logger.pad();\n\n    const browserifyArgs = opt.browserifyArgs;\n    const clientMiddleware = createMiddleware(opt);\n\n    const hotReloading = opt.hot;\n    const entries = [\n      // Could find a cleaner way to pass down props\n      // to client scripts...\n      opt.output ? require.resolve('./instrumentation/client-enable-output.js') : undefined,\n      hotReloading ? require.resolve('./instrumentation/client-enable-hot.js') : undefined,\n      opt.client !== false ? require.resolve('./instrumentation/client.js') : undefined,\n      opt.entry\n    ].filter(Boolean);\n\n    const applyReload = (app, wss) => {\n      // Because some editors & operating systems do atomic updates\n      // very quickly together on file save, you can end up with duplicate\n      // file change events from chokidar in some cases. We guard against\n      // this by not evaluating duplicate code that is run within a fraction\n      // of a second.\n      const chokidarThreshold = 150;\n\n      let lastTime = Date.now();\n      let chokidarDelta = Infinity;\n\n      var lastBundle;\n      var hasError = false;\n\n      // Tell the active instances whether to enable or disable hot reloading\n      wss.on('connection', (socket) => {\n        socket.send(JSON.stringify({ event: 'hot-reload', enabled: hotReloading }));\n      });\n\n      // Hot reloading reacts on update, after bundle is finished\n      app.on('update', (code) => {\n        lastTime = rightNow();\n\n        if (hotReloading) {\n          code = code.toString();\n          if (chokidarDelta < chokidarThreshold && code === lastBundle) {\n            // We only do this chokidar guard when the bundle is the same.\n            // If the bundle is different, we definitely want to apply the changes!\n            return;\n          }\n\n          wss.clients.forEach(socket => {\n            socket.send(JSON.stringify({\n              event: 'eval',\n              src: jsUrl,\n              error: hasError,\n              code\n            }));\n          });\n          lastBundle = code;\n        }\n      });\n\n      // Non-hot reloading reacts on pending, before bundle starts updating\n      // This makes the experience feel more instant\n      app.on('pending', () => {\n        const now = rightNow();\n        chokidarDelta = now - lastTime;\n        if (!hotReloading && chokidarDelta > chokidarThreshold) {\n          // We avoid duplicate reload events here with the chokidar threshold\n          app.reload();\n        }\n      });\n\n      app.on('pending', () => {\n        hasError = false;\n      });\n\n      app.on('bundle-error', () => {\n        hasError = true;\n      });\n    };\n\n    const app = budo(entries, {\n      browserifyArgs,\n      open: argv.open,\n      serve: jsUrl,\n      ssl: argv.https,\n      port: argv.port || 9966,\n      pushstate: argv.pushstate,\n      middleware: clientMiddleware.middleware,\n      ignoreLog: clientMiddleware.ignoreLog,\n      forceDefaultIndex: true,\n      defaultIndex: () => html.stream(htmlOpts),\n      dir,\n      stream: argv.quiet ? null : process.stdout\n    })\n      .on('watch', (ev, file) => {\n        app.reload(file);\n      })\n      .on('connect', ev => {\n        // Here we do some things like notify the clients that a module is being\n        // installed.\n        const wss = ev.webSocketServer;\n        if (wss) {\n          const installEvents = ['install-start', 'install-end'];\n          installEvents.forEach(key => {\n            opt.installer.on(key, ({ modules }) => {\n              app.error(key === 'install-start'\n                ? `Installing modules from npm: ${modules.join(', ')}`\n                : `Reloading...`);\n              wss.clients.forEach(socket => {\n                socket.send(JSON.stringify({ event: key }));\n              });\n            });\n          });\n          applyReload(app, wss);\n        }\n      });\n\n    if (argv.watching !== false) {\n      app.live().watch();\n    }\n\n    return app;\n  }\n\n  async function prepare(logger) {\n    // Write a new package, but first check for collision\n    const dirName = path.basename(cwd);\n    if (dirName === 'canvas-sketch') {\n      const pkg = await readPackage({ cwd }, true);\n      if (!pkg || !isCanvasSketchPackage(pkg)) {\n        throw new Error(`Your folder name is ${chalk.bold('canvas-sketch')} which may lead to conflicts when using this tool. Please choose another folder name and run the command again.`);\n      }\n    }\n\n    if (argv._.length > 1) {\n      throw new Error('Currently only one entry is supported.\\n\\nExample usage:\\n    canvas-sketch src/index.js');\n    }\n\n    let entry = argv._[0];\n    delete argv._;\n    const browserifyArgs = argv['--'] || [];\n    delete argv['--'];\n\n    let entrySrc;\n    if (argv.new) {\n      const prefix = typeof argv.new === 'string' ? argv.new : undefined;\n      let filepath;\n      if (entry) {\n        filepath = path.isAbsolute(entry) ? path.resolve(entry) : path.resolve(cwd, entry);\n\n        // ensure a file extension is present. If not, automatically add .js\n        if (!path.extname(entry)) {\n          filepath = `${filepath}.js`;\n        }\n      } else {\n        filepath = path.resolve(cwd, sketchDirectory, generateFileName(prefix));\n      }\n\n      if (!argv.force && fs.existsSync(filepath)) {\n        throw new Error(`The file already exists: ${path.relative(cwd, filepath)} (use -f to overwrite)`);\n      }\n\n      // Ensure the folder path exists\n      const fileDir = path.dirname(filepath);\n      await mkdirp(fileDir);\n\n      // Get stdin for piping\n      const stdin = (await getStdin()).trim();\n\n      if (stdin && (!argv.template || argv.template === 'default')) {\n        // Allow the user to pass in piped code\n        entrySrc = stdin;\n      } else {\n        let templateFile;\n        if (/^[\\\\/.]/.test(argv.template)) {\n          templateFile = path.isAbsolute(argv.template)\n            ? argv.template\n            : path.resolve(cwd, argv.template);\n          if (!fs.existsSync(templateFile)) {\n            throw new Error(`Couldn't find a template at ${argv.template}`);\n          }\n        } else {\n          templateFile = path.resolve(__dirname, templateDirectory, `${argv.template}.js`);\n          if (!fs.existsSync(templateFile)) {\n            throw new Error(`Couldn't find a template by the key ${argv.template}`);\n          }\n        }\n\n        try {\n          entrySrc = fs.readFileSync(templateFile, 'utf-8');\n        } catch (err) {\n          throw new Error(`Error while reading the template ${argv.template}`);\n        }\n      }\n\n      logger.log(`Writing file: ${chalk.bold(path.relative(cwd, filepath))}`);\n      fs.writeFileSync(filepath, entrySrc);\n      entry = filepath;\n    }\n\n    if (!entry) {\n      logger.error('No entry file specified!', `Example usage:\\n    canvas-sketch src/index.js\\n    canvas-sketch --new --template=regl`);\n      process.exit(1);\n    }\n\n    // Read source code\n    if (!entrySrc) {\n      try {\n        const entryPath = /^[.\\//]/.test(entry) ? entry : ('./' + entry);\n        entry = resolve.sync(entryPath, { basedir: cwd });\n      } catch (err) {\n        logger.error(`Cannot find file \"${chalk.bold(entry)}\"`);\n        logger.pad();\n        process.exit(1);\n      }\n\n      try {\n        entrySrc = fs.readFileSync(entry, 'utf-8');\n      } catch (err) {\n        logger.error(`Cannot read entry file \"${chalk.bold(path.relative(cwd, entry))}\"`, err);\n        logger.pad();\n        process.exit(1);\n      }\n    }\n\n    // Install dependencies from the template if needed\n    // Note: this was a regretful decision! A little difficult to remove entirely\n    // as one of the primary entrypoints is `canvas-sketch sketch.js --new` which requires\n    // installation of canvas-sketch itself. In future it would be good to get more granular;\n    // perhaps auto-installing canvas-sketch but no other libraries unless specified.\n    const shouldInstall = argv.install !== false;\n    if (shouldInstall) {\n      try {\n        await install(entry, { entrySrc, logger, cwd });\n      } catch (err) {\n        console.error(err.toString());\n      }\n    }\n\n    let output = typeof argv.output !== 'undefined' ? argv.output : true;\n    if (typeof output === 'string' && /^(true|false)$/.test(output)) {\n      // handle string argv parsing\n      output = output === 'true';\n    }\n    if (output == null || output === true) {\n      // Default to downloads\n      output = downloads({ logger });\n    } else if (output === '.') {\n      // Accept '.' as current dir\n      output = cwd;\n    }\n\n    const mode = defined(argv.mode, argv.build ? 'production' : 'development');\n    const hot = Boolean(argv.hot);\n    const params = Object.assign({}, argv, {\n      mode,\n      browserifyArgs,\n      extensions: pluginGLSL.extensions,\n      output,\n      logger,\n      hot,\n      entry,\n      cwd,\n      installer: new EventEmitter()\n    });\n\n    browserifyArgs.push(\n      // Add in ESM support\n      '-p', (bundler, opts) => {\n        return esmify(bundler, Object.assign({}, opts, {\n          // Disable \"module\" field since it is brutally annoying :(\n          // Basically it changes the way CommonJS-authored code needs to\n          // be written, forcing authors to update their code paths to use:\n          //   require('blah').default\n          // The added benefit of tree-shaking ES Modules isn't even used here (no rollup/webpack)\n          // so we will just discard it altogether for a cleaner developer & user experience.\n          mainFields: ['browser', 'main'],\n          // This is a bit frustrating, as well. Babel-ifying the entire node_modules\n          // tree is extremely slow, and only fixes a few problematic modules\n          // that have decided to publish with ESM, which isn't even standard yet!\n          // So, we will only support ESM in local code for canvas-sketch.\n          nodeModules: false,\n          logFile: argv.logFile\n        }));\n      },\n      '-g', pluginGLSL(params),\n      // Add in glslify and make it resolve to here\n      '-g', require.resolve('glslify'),\n      // A plugin that handles resolving some modules to this CLI tool\n      '-p', pluginResolve(params),\n      // Also add in some envify tools\n      '-p', pluginEnv(params)\n    );\n\n    // TODO: Figure out a nice way to install automatically\n    // if (argv.install !== false) {\n    //   browserifyArgs.push('-t', transformInstaller(params));\n    // }\n\n    return params;\n  }\n};\n\nmodule.exports = start;\n\nif (!module.parent) {\n  module.exports(process.argv.slice(2)).catch(err => {\n    const { message, stack } = getErrorDetails(err);\n    if (err instanceof SyntaxError || err.name === 'SyntaxError') {\n      if (typeof err.line === 'number' && isFinite(err.line) &&\n        typeof err.col === 'number' && isFinite(err.col)) {\n        const {\n          line,\n          col,\n          originalSourceCode,\n          message\n        } = err;\n        const formattedSrc = originalSourceCode ? formatSyntaxError(originalSourceCode, line, col) : '';\n        console.error([\n          '',\n          chalk.red(`SyntaxError: ${message}`),\n          `At line ${chalk.magenta(line)} and column ${chalk.magenta(col)} of generated bundle`,\n          formattedSrc,\n          ''\n        ].join('\\n'));\n      } else {\n        console.error(`\\n${err.toString()}\\n`);\n      }\n    } else if (stack) {\n      console.error([\n        '',\n        chalk.red(message),\n        '',\n        `    ${stack.trim().split('\\n').slice(0, 10).join('\\n')}`,\n        ''\n      ].join('\\n'));\n    } else {\n      console.error(err);\n    }\n  });\n}\n\nfunction formatSyntaxError (code, line, col, buffer = 2) {\n  const lineIndex = line - 1;\n  let lines = code.split('\\n').map((line, index) => {\n    return { line, index };\n  });\n  const minLine = Math.max(0, lineIndex - buffer);\n  const maxLine = Math.min(lines.length, lineIndex + buffer + 1);\n  const msg = [\n    '  ...',\n    ...lines.slice(minLine, maxLine).map(line => {\n      const prefix = `  ${line.index + 1}: `;\n      const lines = [\n        `${prefix}${line.line}`\n      ];\n      if (lineIndex === line.index) {\n        const cursor = chalk.bold(chalk.red('^'));\n        lines[0] = chalk.red(lines[0]);\n        const colCount = Math.max(0, col - 1);\n        const prefixSpaces = repeatCharacters(colCount + prefix.length, ' ');\n        lines.push(`${prefixSpaces}${cursor}`);\n      }\n      return lines.join('\\n');\n    }),\n    '  ...'\n  ].join('\\n');\n  return msg;\n}\n\nfunction repeatCharacters (count, char = ' ') {\n  return Array.from(new Array(count)).map(() => char).join('');\n}\n"]}