text: #!/usr/bin/env node
  
  /**
  * @license Apache-2.0
  *
  * Copyright (c) 2021 The Stdlib Authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *    http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
  
  /* eslint-disable no-sync, no-console, max-statements, max-lines-per-function */
  
  'use strict';
  
  // MODULES //
  
  var join = require( 'path' ).join;
  var shell = require( 'child_process' ).execSync;
  var fs = require( 'fs' );
  var tmpdir = require( 'os' ).tmpdir;
  var logger = require( 'debug' );
  var ghpages = require( 'gh-pages' );
  var semver = require( 'semver' );
  var CLI = require( '@stdlib/cli/ctor' );
  var repos = require( '@stdlib/_tools/github/org-repos' );
  var setTopics = require( '@stdlib/_tools/github/set-topics' );
  var createRepo = require( '@stdlib/_tools/github/create-repo' );
  var writeFileSync = require( '@stdlib/fs/write-file' ).sync;
  var readFileSync = require( '@stdlib/fs/read-file' ).sync;
  var readJSON = require( '@stdlib/fs/read-json' ).sync;
  var existsSync = require( '@stdlib/fs/exists' ).sync;
  var contains = require( '@stdlib/assert/contains' );
  var repeat = require( '@stdlib/string/repeat' );
  var endsWith = require( '@stdlib/string/ends-with' );
  var trim = require( '@stdlib/string/trim' );
  var replace = require( '@stdlib/string/replace' );
  var removeFirst = require( '@stdlib/string/remove-first' );
  var startsWith = require( '@stdlib/string/starts-with' );
  var namespaceDeps = require( '@stdlib/_tools/pkgs/namespace-deps' );
  var depList = require( '@stdlib/_tools/pkgs/dep-list' );
  var name2standalone = require( '@stdlib/_tools/pkgs/name2standalone' );
  var toposort = require( '@stdlib/_tools/pkgs/toposort' ).sync;
  var ENV = require( '@stdlib/process/env' );
  
  
  // VARIABLES //
  
  var cli = new CLI();
  var flags = cli.flags();
  var args = cli.args();
  
  var debug = logger( 'scripts:publish-packages' );
  
  var START_PKG_INDEX = 0;
  var END_PKG_INDEX = 5000;
  var MAX_TREE_DEPTH = 99;
  
  var topics = setTopics.factory( {
  	'token': ENV.GITHUB_TOKEN
  }, onTopics );
  
  var INSTALLATION_SECTION = [
  	'<section class="installation">',
  	'',
  	'## Installation',
  	'',
  	'```bash',
  	'npm install @stdlib/<pkg>',
  	'```',
  	'',
  	'</section>',
  	''
  ].join( '\n' );
  var CLI_INSTALLATION_SECTION = [
  	'<section class="installation">',
  	'',
  	'## Installation',
  	'',
  	'To use the module as a general utility, install the module globally',
  	'',
  	'```bash',
  	'npm install -g @stdlib/<pkg>',
  	'```',
  	'',
  	'</section>',
  	''
  ].join( '\n' );
  
  var mainDir = join( __dirname, '..', '..', '..', '..', '..' );
  var DOTFILES = [ '.editorconfig', '.gitignore', '.gitattributes', '.npmrc', 'CONTRIBUTORS', 'NOTICE' ];
  
  var WORKFLOW_CLOSE_PULLS = [
  	'#/',
  	'# @license Apache-2.0',
  	'#',
  	'# Copyright (c) 2021 The Stdlib Authors.',
  	'#',
  	'# Licensed under the Apache License, Version 2.0 (the "License");',
  	'# you may not use this file except in compliance with the License.',
  	'# You may obtain a copy of the License at',
  	'#',
  	'#    http://www.apache.org/licenses/LICENSE-2.0',
  	'#',
  	'# Unless required by applicable law or agreed to in writing, software',
  	'# distributed under the License is distributed on an "AS IS" BASIS,',
  	'# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
  	'# See the License for the specific language governing permissions and',
  	'# limitations under the License.',
  	'#/',
  	'',
  	'# Workflow name:',
  	'name: Close Pull Requests',
  	'',
  	'# Workflow triggers:',
  	'on:',
  	'  pull_request_target:',
  	'    types: [opened]',
  	'',
  	'# Workflow jobs:',
  	'jobs:',
  	'  run:',
  	'    runs-on: ubuntu-latest',
  	'    steps:',
  	'    - uses: superbrothers/close-pull-request@v3',
  	'      with:',
  	'        comment: |',
  	'          Thank you for submitting a pull request. :raised_hands:',
  	'          ',
  	'          We greatly appreciate your willingness to submit a contribution. However, we are not accepting pull requests against this repository, as all development happens on the [main project repository](https://github.com/stdlib-js/stdlib).',
  	'          ',
  	'          We kindly request that you submit this pull request against the [respective directory](<pkg-path>) of the main repository where we’ll review and provide feedback. If this is your first stdlib contribution, be sure to read the [contributing guide](https://github.com/stdlib-js/stdlib/blob/develop/CONTRIBUTING.md) which provides guidelines and instructions for submitting contributions.',
  	'          ',
  	'          Thank you again, and we look forward to receiving your contribution! :smiley:',
  	'          ',
  	'          Best,',
  	'          The stdlib team'
  ].join( '\n' );
  var PULL_REQUEST_TEMPLATE = [
  	'<!-- ----------^ Click "Preview"! -->',
  	'',
  	'We are excited about your pull request, but unfortunately we are not accepting pull requests against this repository, as all development happens on the [main project repository](https://github.com/stdlib-js/stdlib). We kindly request that you submit this pull request against the [respective directory](<pkg-path>) of the main repository where we’ll review and provide feedback. ',
  	'',
  	'If this is your first stdlib contribution, be sure to read the [contributing guide](https://github.com/stdlib-js/stdlib/blob/develop/CONTRIBUTING.md) which provides guidelines and instructions for submitting contributions. You may also consult the [development guide](https://github.com/stdlib-js/stdlib/blob/develop/docs/development.md) for help on developing stdlib.',
  	'',
  	'We look forward to receiving your contribution! :smiley:'
  ].join( '\n' );
  var FUNDING = {
  	'type': 'patreon',
  	'url': 'https://www.patreon.com/athan'
  };
  var CHANGELOG = [
  	'# CHANGELOG',
  	'',
  	'> Package changelog.',
  	'',
  	'See [GitHub Releases](https://github.com/stdlib-js/<pkg>/releases) for the changelog.'
  ].join( '\n' );
  
  var EXISTING_REPOS = {};
  var RE_USAGE_SECTION = /(## CLI\n\n)?(<!-- CLI usage documentation. -->\n\n)?<section class="usage">/g;
  var BASIC_GITHUB_TOPICS = [
  	'nodejs',
  	'javascript',
  	'stdlib',
  	'node',
  	'node-js'
  ];
  var RE_ALLOWED_TOPIC_CHARS = /^[A-Z0-9-]+$/i;
  
  
  // FUNCTIONS //
  
  /**
  * Cleans up the `gh-pages` cache directory.
  *
  * @private
  * @returns {void}
  */
  function cleanCache() {
  	var command = 'rm -rf '+join( mainDir, 'node_modules', '.cache', 'gh-pages' );
  	console.log( 'Clean-up cached gh-pages files: %s', command );
  	console.log( shell( command ).toString() );
  }
  
  /**
  * Returns a section for the main project to be appended to the standalone package README.md files.
  *
  * @private
  * @param {boolean} customLicense - boolean indicating whether the standalone package contains a custom license file
  * @returns {string} main repo section
  */
  function mainRepoSection( customLicense ) {
  	/* eslint-disable function-call-argument-newline, function-paren-newline */
  	var out = [
  		'',
  		'<section class="main-repo" >',
  		'',
  		'* * *',
  		'',
  		'## Notice',
  		'',
  		'This package is part of [stdlib][stdlib], a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.',
  		'',
  		'For more information on the project, filing bug reports and feature requests, and guidance on how to develop [stdlib][stdlib], see the main project [repository][stdlib].',
  		'',
  		'#### Community',
  		'',
  		'[![Chat][chat-image]][chat-url]',
  		'',
  		'---'
  	];
  	if ( !customLicense ) {
  		out.push(
  			'',
  			'## License',
  			'',
  			'See [LICENSE][stdlib-license].',
  			''
  		);
  	}
  	out.push(
  		'',
  		'## Copyright',
  		'',
  		'Copyright &copy; 2016-2021. The Stdlib [Authors][stdlib-authors].',
  		'',
  		'</section>',
  		'',
  		'<!-- /.stdlib -->',
  		'',
  		'<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->',
  		'',
  		'<section class="links">',
  		'',
  		'[npm-image]: http://img.shields.io/npm/v/@stdlib/<pkg>.svg',
  		'[npm-url]: https://npmjs.org/package/@stdlib/<pkg>',
  		'',
  		'[test-image]: https://github.com/stdlib-js/<pkg>/actions/workflows/test.yml/badge.svg',
  		'[test-url]: https://github.com/stdlib-js/<pkg>/actions/workflows/test.yml',
  		'',
  		'[coverage-image]: https://img.shields.io/codecov/c/github/stdlib-js/<pkg>/main.svg',
  		'[coverage-url]: https://codecov.io/github/stdlib-js/<pkg>?branch=main',
  		'',
  		'<!--',
  		'',
  		'[dependencies-image]: https://img.shields.io/david/stdlib-js/<pkg>.svg',
  		'[dependencies-url]: https://david-dm.org/stdlib-js/<pkg>/main',
  		'',
  		'-->',
  		'',
  		'[chat-image]: https://img.shields.io/gitter/room/stdlib-js/stdlib.svg',
  		'[chat-url]: https://gitter.im/stdlib-js/stdlib/',
  		'',
  		'[stdlib]: https://github.com/stdlib-js/stdlib',
  		'',
  		'[stdlib-authors]: https://github.com/stdlib-js/stdlib/graphs/contributors'
  	);
  	if ( !customLicense ) {
  		out.push(
  			'',
  			'[stdlib-license]: https://raw.githubusercontent.com/stdlib-js/<pkg>/main/LICENSE'
  		);
  	}
  	return out.join( '\n' );
  
  	/* eslint-enable function-call-argument-newline, function-paren-newline */
  }
  
  /**
  * Creates a list of GitHub topics.
  *
  * @private
  * @param {StringArray} words - list of keywords
  * @returns {StringArray} list of topics
  */
  function createTopics( words ) {
  	var word;
  	var out;
  	var i;
  
  	out = [];
  	for ( i = 0; i < words.length; i++ ) {
  		word = words[ i ];
  		if (
  			!startsWith( word, 'std' ) &&
  			word.length <= 35 // GitHub topics may not have more than 35 characters
  		) {
  			word = replace( word, ' ', '-' ); // GitHub topics may not include spaces, but allow hyphens
  			if ( RE_ALLOWED_TOPIC_CHARS.test( word ) ) {
  				out.push( word );
  			}
  		}
  	}
  	return BASIC_GITHUB_TOPICS.concat( out ).slice( 0, 20 ); // GitHub repositories may not have more than 20 topics
  }
  
  /**
  * Function invoked upon replacing the topics of a repository.
  *
  * @private
  * @param {(Error|null)} error - encountered error
  * @param {Object} data - response data
  * @param {Object} info - response info
  * @returns {void}
  */
  function onTopics( error, data, info ) {
  	if ( error ) {
  		return console.error( error );
  	}
  	console.log( 'Replaced topics for repository.' );
  	console.log( 'Response data: '+JSON.stringify( data ) );
  	console.log( 'Rate limit: '+JSON.stringify( info ) );
  }
  
  /**
  * Replacer function for inserting an install section before a usage section.
  *
  * @private
  * @param {string} match - entire match
  * @param {string} p1 - first capture group
  * @returns {string} replacement
  */
  function replacer( match, p1 ) {
  	if ( p1 && endsWith( p1, '## CLI\n\n' ) ) {
  		return p1 + CLI_INSTALLATION_SECTION+'\n<section class="usage">';
  	}
  	return INSTALLATION_SECTION + '\n<section class="usage">';
  }
  
  /**
  * Publishes a package to the respective GitHub repository.
  *
  * @private
  * @param {string} pkg - package name
  * @param {Function} clbk - callback function
  * @throws {Error} no input files
  * @returns {void}
  */
  function publish( pkg, clbk ) {
  	var customLicense;
  	var isTopLevelNS;
  	var workflowPath;
  	var ghpagesOpts;
  	var pkgJsonPath;
  	var mainVersion;
  	var readmePath;
  	var mainJSON;
  	var command;
  	var devDeps;
  	var distPkg;
  	var pkgJSON;
  	var version;
  	var badges;
  	var nLines;
  	var readme;
  	var mdPath;
  	var deps;
  	var dist;
  	var file;
  	var dep;
  	var src;
  	var pth;
  	var i;
  
  	src = join( mainDir, 'lib/node_modules', '@stdlib', pkg );
  	distPkg = replace( pkg, /\//g, '-' );
  
  	dist = join( mainDir, 'build', '@stdlib', distPkg );
  	mainJSON = readJSON( join( mainDir, 'package.json' ) );
  
  	console.log( 'Creating directory and copying source files...' );
  
  	command = 'mkdir -p '+dist;
  	debug( 'Creating build directory: %s', command );
  	shell( command );
  
  	isTopLevelNS = !contains( pkg, '/' );
  	if ( isTopLevelNS ) {
  		// Copy all files and subdirectories:
  		command = 'cp -r '+src+'/* '+dist;
  	}
  	else {
  		// Do not copy nested packages which will instead be pulled in as separate dependencies:
  		command = 'rsync -r --ignore-missing-args --include=\'benchmark/***\' --include=\'bin/***\' --include=\'data/***\' --include=\'docs/***\' --include=\'etc/***\' --include=\'examples/***\' --include=\'lib/***\' --include=\'include/***\' --include=\'scripts/***\' --include=\'src/***\' --include=\'test/***\' --exclude=\'*/***\' '+src+'/*** '+dist;
  	}
  	debug( 'Copying files: %s', command );
  	shell( command );
  
  	debug( 'Copying configuration files...' );
  	for ( i = 0; i < DOTFILES.length; i++ ) {
  		file = DOTFILES[ i ];
  		fs.copyFileSync( join( mainDir, file ), join( dist, file ) );
  	}
  	if ( existsSync( join( dist, 'LICENSE' ) ) ) {
  		customLicense = true;
  	} else {
  		fs.copyFileSync( join( mainDir, 'LICENSE' ), join( dist, 'LICENSE' ) );
  		customLicense = false;
  	}
  	fs.copyFileSync( join( __dirname, 'templates', '.npmignore.txt' ), join( dist, '.npmignore' ) );
  	fs.copyFileSync( join( __dirname, 'templates', 'Makefile.txt' ), join( dist, 'Makefile' ) );
  	fs.copyFileSync( join( __dirname, 'templates', '.eslintrc.js.txt' ), join( dist, '.eslintrc.js' ) );
  	writeFileSync( join( dist, 'CHANGELOG.md' ), replace( CHANGELOG, '<pkg>', distPkg ) );
  
  	if ( isTopLevelNS ) {
  		deps = namespaceDeps( '@stdlib/'+pkg, {
  			'level': 1,
  			'dev': false
  		});
  		deps = name2standalone( deps );
  		devDeps = namespaceDeps( '@stdlib/'+pkg, {
  			'level': 1,
  			'dev': true
  		});
  		devDeps = name2standalone( devDeps );
  	} else {
  		deps = depList( '@stdlib/'+pkg, {
  			'dev': false
  		});
  		deps = name2standalone( deps );
  		devDeps = depList( '@stdlib/'+pkg, {
  			'dev': true
  		});
  		devDeps = name2standalone( devDeps );
  	}
  
  	command = 'grep -r proxyquire '+dist+' | wc -l';
  	debug( 'Count the number of lines including `proxyquire`: %s', command );
  	nLines = shell( command ).toString();
  	if ( parseInt( nLines, 10 ) > 0 && !contains( devDeps, 'proxyquire' ) ) {
  		// Case: `proxyquire` is used outside of package code, e.g. in test fixtures, and has to be separately included in the list of development dependencies
  		devDeps.push( 'proxyquire' );
  	}
  
  	debug( 'Copying and populating README.md file...' );
  	readmePath = join( dist, 'README.md' );
  	readme = readFileSync( readmePath, 'utf-8' );
  	readme = replace( readme, RE_USAGE_SECTION, replacer );
  	badges = '[![NPM version][npm-image]][npm-url]';
  	badges += ' ';
  	if ( contains( devDeps, 'tape' ) ) {
  		badges += '[![Build Status][test-image]][test-url]';
  		badges += ' ';
  		badges += '[![Coverage Status][coverage-image]][coverage-url]';
  		badges += ' ';
  	}
  	badges += '<!-- '
  	badges += '[![dependencies][dependencies-image]][dependencies-url]';
  	badges += ' -->';
  	readme = replace( readme, /\n>/, '\n'+badges+'\n\n>' );
  	readme = replace( readme, '\'@stdlib/'+pkg, '\'@stdlib/'+distPkg );
  	if ( contains( readme, '<section class="links">' ) ) {
  		readme = replace( readme, '<section class="links">', mainRepoSection( customLicense ) );
  	} else {
  		readme += mainRepoSection( customLicense );
  		readme += '\n\n';
  		readme += '</section>';
  		readme += '\n\n';
  		readme += '<!-- /.links -->';
  	}
  	readme = replace( readme, '<pkg>', distPkg );
  	writeFileSync( readmePath, readme );
  
  	command = [
  		'find '+dist+' -type f -name \'*.md\' -print0 ', // Find all regular Markdown files in the destination directory and print their full names to standard output...
  		'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
  		'sed -Ei ', // Edit files in-place without creating a backup...
  		'\'s/',
  		'(@stdlib\\/'+distPkg+')([^:]*)\\]: https.*$', // Match start of internal package link until end of line...
  		'/',
  		'\\1\\2]: https:\\/\\/github.com\\/stdlib-js\\/'+distPkg+'\\/tree\\/main\\2', // Replacement string generated via back-referencing the two created capture groups...
  		'/g\'' // Replace all occurrences and not just the first...
  	].join( '' );
  	debug( 'Executing command: %s', command );
  	shell( command );
  
  	command = [
  		'find '+dist+' -type f -name \'*.md\' -print0 ', // Find all regular Markdown files in the destination directory and print their full names to standard output...
  		'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
  		'sed -Ei ', // Edit files in-place without creating a backup...
  		'"/',
  		'^[^:]+: https:\\/\\/github.com\\/stdlib-js\\/stdlib\\/tree\\/develop\\/lib\\/node_modules\\/%40stdlib\\/', // Match start of external `@stdlib` package link (as internal ones are already processed) until end of line...
  		'/ ',
  		[
  			'{',
  			'    h', // Copy pattern space to hold space...
  			'    s/:.*/: https:\\/\\/github.com\\/stdlib-js\\//', // Replace everything after the colon in the matched pattern with the beginning of new replacement URL...
  			'    x', // Exchange the contents of the hold and pattern spaces...
  			'    s/[^:]+: https:\\/\\/github.com\\/stdlib-js\\/stdlib\\/tree\\/develop\\/lib\\/node_modules\\/%40stdlib\\///', // Remove everything up to the beginning of the existing main project URL in the pattern space...
  			'    s/\\//-/g', // Replace all occurrences of `/` with `-`...
  			'    H', // Append pattern space to hold space...
  			'    g', // Copy hold space to pattern space...
  			'    s/\\n//', // Remove newline character added when appending pattern space to hold space
  			'}'
  		].join( '\n' ),
  		'"'
  	].join( '' );
  	debug( 'Executing command: %s', command );
  	shell( command );
  
  	if ( isTopLevelNS ) {
  		// Rewrite internal packages as relative paths outside of documentation:
  		for ( i = 0; i < MAX_TREE_DEPTH; i++ ) {
  			command = [
  				'find '+dist+' -mindepth '+(1+i)+' -maxdepth '+(2+i)+' -type f \\( -name \'*.[jt]s\' \\) -print0 ', // Find all JavaScript and TypeScript files in the destination directory at the respective depth and print their full names to standard output...
  				'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
  				'sed -Ei ', // Edit files in-place without creating a backup...
  				'"/',
  				'\'@stdlib\\/types', // Skip over `@stdlib/types`...
  				'/b; ',
  				'/',
  				'^[^\\*].+\'@stdlib\\/'+pkg, // Match internal packages outside of JSDoc comments...
  				'/',
  				[
  					'{',
  					'    s/\'@stdlib\\/'+pkg+'(.+)/\'.'+repeat( '\\/..', i+1 )+'\\1/', // Replace the start of internal package requires with a relative path of the respective depth
  					'}'
  				].join( '\n' ),
  				'"'
  			].join( '' );
  			debug( 'Executing command: %s', command );
  			try {
  				shell( command );
  			} catch ( err ) {
  				// Break out of loop in case of no input files...
  				debug( 'Encountered an error: %s', err.message );
  				break;
  			}
  		}
  	}
  	else {
  		command = [
  			'find '+dist+' -type f \\( -name \'*.[jt]s\' -o -name \'*.md\' -o -name \'cli\' -o -name \'*.js.txt\' \\) -print0 ', // Find all JavaScript and TypeScript files in the destination directory and print their full names to standard output...
  			'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
  			'sed -Ei ', // Edit files in-place without creating a backup...
  			'"/',
  			'\'@stdlib\\/types', // Skip over `@stdlib/types`...
  			'/b; ',
  			'/',
  			'\'@stdlib\\/', // Match `@stdlib` packages...
  			'/ ',
  			[
  				'{',
  				'    h', // Copy pattern space to hold space...
  				'    s/^.+(\'.*$)/\\1/', // Remove everything before the last single quote
  				'    x', // Exchange the contents of the hold and pattern spaces...
  				'    s/\'[^\']*$//', // Remove everything after the last single quote
  				'    s/\\//-/2g', // Replace any but the first occurrence of `/` with `-`...
  				'    s/-data-([^\']*[.][^\']*)/\\/data\\/\\1/', // Revert back to backslashes for part of require path loading files from a package's `data` directory
  				'    G', // Append hold space to pattern space...
  				'    s/\\n//', // Remove newline character added when appending hold space to pattern space
  				'}'
  			].join( '\n' ),
  			'"'
  		].join( '' );
  		debug( 'Executing command: %s', command );
  		shell( command );
  
  		command = [
  			'find '+dist+' -type f -name \'*.js\' -print0 ', // Find all JavaScript files in the destination directory and print their full names to standard output...
  			'| xargs -0 ', // Convert standard input to the arguments for following `sed` command...
  			'sed -Ei ', // Edit files in-place without creating a backup...
  			'"/',
  			'@module @stdlib\\/', // Match @stdlib packages in JSDoc @module comment...
  			'/s/',
  			'\\/',
  			'/',
  			'-',
  			'/2g"' // Replace all forward slashes in package name except the first one...
  		].join( '' );
  		debug( 'Executing command: %s', command );
  		shell( command );
  
  		command = [
  			'find '+dist+' -type f -name \'include.gypi\' -print0 ', // Find all `include.gypi` files in the destination directory and print their full names to standard output...
  			'| xargs -r -0 ', // Convert standard input to the arguments for following `sed` command...
  			'sed -Ei ', // Edit files in-place without creating a backup...
  			'"s/',
  			'@stdlib\\/utils\\/library-manifest',
  			'/',
  			'@stdlib\\/utils-library-manifest', // Replace with standalone `library-manifest` package
  			'/"'
  		].join( '' );
  		debug( 'Executing command: %s', command );
  		shell( command );
  
  		command = [
  			'find '+dist+' -type f -name \'manifest.json\' -print0 ', // Find all `manifest.json` files in the destination directory and print their full names to standard output...
  			'| xargs -r -0 ', // Convert standard input to the arguments for following `sed` command if `find` returns output...
  			'sed -Ei ', // Edit files in-place without creating a backup...
  			'"/',
  			'@stdlib\\/[^ ]+', // Match @stdlib package names in dependencies
  			'/s/',
  			'\\/',
  			'/',
  			'-',
  			'/2g"' // Replace all forward slashes in package names except the first one...
  		].join( '' );
  		debug( 'Executing command: %s', command );
  		shell( command );
  	}
  
  	pkgJsonPath = join( dist, 'package.json' );
  	pkgJSON = readJSON( pkgJsonPath );
  	pkgJSON.name = '@stdlib/'+distPkg;
  	pkgJSON.homepage = 'https://stdlib.io';
  	pkgJSON.repository.url = 'git://github.com/stdlib-js/'+distPkg+'.git';
  
  	// Ensure `npm install` does not automatically build a native add-on...
  	if ( pkgJSON.gypfile ) {
  		// TODO: consider removing this once we have determined our native add-on story for individual packages
  		pkgJSON.gypfile = false;
  	}
  	command = 'git ls-remote --tags --sort="v:refname" git://github.com/stdlib-js/'+distPkg+'.git | tail -n1 | sed \'s/.*\\///; s/\\^{}//\'';
  	debug( 'Executing command to retrieve last version: %s', command );
  	version = shell( command ).toString();
  	version = trim( removeFirst( version ) ); // Remove leading `v`...
  	if ( !version ) {
  		version = '0.0.0';
  	}
  	if ( flags.patch ) {
  		version = semver.inc( version, 'patch' );
  	}
  	pkgJSON.version = version;
  	pkgJSON.funding = FUNDING;
  	for ( i = 0; i < deps.length; i++ ) {
  		dep = deps[ i ];
  		if ( startsWith( dep, '@stdlib' ) ) {
  			if (
  				!contains( dep, '_tools' ) &&
  				( !contains( dep, 'plot' ) || dep === '@stdlib/plot' )
  			) {
  				pkgJSON.dependencies[ dep ] = ( isTopLevelNS ) ?
  					'github:stdlib-js/' + replace( dep, '@stdlib/', '' ) + '#main' :
  					'^0.0.x';
  			}
  		} else {
  			pkgJSON.dependencies[ dep ] = mainJSON.dependencies[ dep ];
  		}
  	}
  	for ( i = 0; i < devDeps.length; i++ ) {
  		dep = devDeps[ i ];
  		if (
  			!contains( deps, dep )
  		) {
  			if (
  				startsWith( dep, '@stdlib' )
  			) {
  				if (
  					!contains( dep, '_tools' ) &&
  					( !contains( dep, 'plot' ) || dep === '@stdlib/plot' )
  				) {
  					pkgJSON.devDependencies[ dep ] = ( isTopLevelNS ) ?
  						'github:stdlib-js/' + replace( dep, '@stdlib/', '' ) :
  						'^0.0.x';
  				}
  			} else {
  				mainVersion = mainJSON.devDependencies[ dep ];
  				pkgJSON.devDependencies[ dep ] = mainVersion;
  			}
  		}
  	}
  	fs.mkdirSync( join( dist, '.github', 'workflows' ), {
  		'recursive': true
  	});
  	fs.copyFileSync( join( __dirname, 'templates', 'workflow_publish.yml.txt' ), join( dist, '.github', 'workflows', 'publish.yml' ) );
  	fs.copyFileSync( join( __dirname, 'templates', 'workflow_test_install.yml.txt' ), join( dist, '.github', 'workflows', 'test_install.yml' ) );
  
  	workflowPath = join( dist, '.github', 'workflows', 'close_pull_requests.yml' );
  	pth = 'https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/'+pkg;
  	writeFileSync( workflowPath, replace( WORKFLOW_CLOSE_PULLS, '<pkg-path>', pth ) );
  	if ( contains( devDeps, 'tape' ) ) {
  		workflowPath = join( dist, '.github', 'workflows', 'test.yml' );
  		fs.copyFileSync( join( __dirname, 'templates', 'workflow_test.yml.txt' ), join( dist, '.github', 'workflows', 'test.yml' ) );
  		pkgJSON.scripts[ 'test' ] = 'make test';
  		pkgJSON.scripts[ 'test-cov' ] = 'make test-cov';
  
  		pkgJSON.devDependencies[ 'istanbul' ] = '^0.4.1';
  		pkgJSON.devDependencies[ 'tap-spec' ] = '5.x.x';
  		fs.copyFileSync( join( __dirname, 'templates', 'workflow_test_coverage.yml.txt' ), join( dist, '.github', 'workflows', 'test_coverage.yml' ) );
  	}
  	if ( existsSync( join( dist, 'examples' ) ) ) {
  		fs.copyFileSync( join( __dirname, 'templates', 'workflow_examples.yml.txt' ), join( dist, '.github', 'workflows', 'examples.yml' ) );
  		pkgJSON.scripts.examples = 'make examples';
  	}
  	if ( contains( devDeps, '@stdlib/bench' ) ) {
  		fs.copyFileSync( join( __dirname, 'templates', 'workflow_benchmark.yml.txt' ), join( dist, '.github', 'workflows', 'benchmark.yml' ) );
  		pkgJSON.scripts.benchmark = 'make benchmark';
  	}
  	fs.copyFileSync( join( __dirname, 'templates', 'workflow_cancel.yml.txt' ), join( dist, '.github', 'workflows', 'cancel.yml' ) );
  	fs.copyFileSync( join( __dirname, 'templates', 'workflow_bundle.yml.txt' ), join( dist, '.github', 'workflows', 'bundle.yml' ) );
  
  	// Write the current date to the `.keepalive` file...
  	if ( flags[ 'keep-alive' ] ) {
  		fs.writeFileSync( join( dist, '.github', '.keepalive' ), new Date().toISOString() + '\n' );
  	}
  
  	debug( 'Saving `package.json` file...' );
  	writeFileSync( pkgJsonPath, JSON.stringify( pkgJSON, null, '  ' ).concat( '\n' ) );
  
  	fs.copyFileSync( join( __dirname, 'templates', 'CODE_OF_CONDUCT.md.txt' ), join( dist, 'CODE_OF_CONDUCT.md' ) );
  	fs.copyFileSync( join( __dirname, 'templates', 'CONTRIBUTING.md.txt' ), join( dist, 'CONTRIBUTING.md' ) );
  	mdPath = join( dist, '.github', 'PULL_REQUEST_TEMPLATE.md' );
  	writeFileSync( mdPath, replace( PULL_REQUEST_TEMPLATE, '<pkg-path>', pth ) );
  	if ( flags[ 'skip-upload' ] ) {
  		return invokeCallback();
  	}
  	ghpagesOpts = {
  		'branch': 'main',
  		'dotfiles': true,
  		'src': [
  			'**/*',
  			'!**/.cache/**'
  		],
  		'repo': 'https://'+ ENV.GITHUB_TOKEN + '@github.com/stdlib-js/' + distPkg,
  		'user': {
  			'name': 'stdlib-bot',
  			'email': 'noreply@stdlib.io'
  		},
  		'history': true,
  		'beforeAdd': updatePermissions
  	};
  	if ( flags.patch ) {
  		ghpagesOpts.tag = 'v'+version;
  		ghpagesOpts.message = 'Release v'+version;
  	} else {
  		ghpagesOpts.message = 'Auto-generated commit';
  	}
  	if ( EXISTING_REPOS[ distPkg ] ) {
  		console.log( 'Publishing '+dist+' to GitHub...' );
  		ghpages.publish( dist, ghpagesOpts, invokeCallback );
  		if ( flags[ 'overwrite-topics' ] ) {
  			topics( 'stdlib-js/' + distPkg, createTopics( pkgJSON.keywords ) );
  		}
  	} else {
  		console.log( 'Creating new remote repository: stdlib-js/'+distPkg );
  		createRepo( distPkg, {
  			'org': 'stdlib-js',
  			'desc': pkgJSON.description,
  			'homepage': 'https://github.com/stdlib-js/stdlib',
  			'issues': false,
  			'wiki': false,
  			'projects': false,
  			'private': false,
  			'token': ENV.GITHUB_TOKEN,
  			'allowSquashMerge': true,
  			'allowRebaseMerge': false,
  			'allowMergeCommit': false
  		}, onRepoCreation );
  	}
  
  	/**
  	* Adds executable permission to `bin/cli` files.
  	*
  	* @private
  	* @param {Object} git - `git` class instance
  	*/
  	function updatePermissions( git ) {
  		shell( 'find '+git.cwd+' -regex \'.*/bin/cli\' -print0 | xargs -r -0 chmod +x' );
  	}
  
  	/**
  	* Callback invoked upon pushing package contents to remote GitHub repository.
  	*
  	* @private
  	* @param {(Error|null)} error - encountered error
  	* @returns {void}
  	*/
  	function invokeCallback( error ) {
  		var pkgInfo = {
  			'name': pkgJSON.name,
  			'description': pkgJSON.description
  		};
  		clbk( error, pkgInfo );
  	}
  
  	/**
  	* Callback invoked upon creating GitHub repository.
  	*
  	* @private
  	* @param {(Error|null)} error - encountered error
  	* @param {Object} repo - repo data
  	* @param {Object} info - rate limit info
  	* @returns {void}
  	*/
  	function onRepoCreation( error, repo, info ) {
  		var currentTime;
  		var waitTime;
  		if ( error ) {
  			return console.error( error );
  		}
  		console.log( 'GitHub repository '+repo.full_name+' has been successfully created.' );
  		console.log( 'Rate limit information: '+JSON.stringify( info ) );
  
  		topics( 'stdlib-js/' + distPkg, createTopics( pkgJSON.keywords ) );
  		if ( info.remaining === 0 ) {
  			currentTime = new Date().getTime();
  			waitTime = new Date( info.reset * 1000 ).getTime() - currentTime;
  			ghpages.publish( dist, ghpagesOpts, withDelay );
  		} else {
  			ghpages.publish( dist, ghpagesOpts, invokeCallback );
  		}
  
  		/**
  		* Invokes callback for once pushing package contents to remote GitHub repository after a specified delay.
  		*
  		* @private
  		* @param {(Error|null)} err - error object or `null`
  		* @returns {void}
  		*/
  		function withDelay( err ) {
  			if ( err ) {
  				return console.log( err );
  			}
  			console.log( 'Waiting '+waitTime+'ms before moving to next package...' );
  			setTimeout( invokeCallback, waitTime );
  		}
  	}
  }
  
  
  // MAIN //
  
  /**
  * Main execution sequence.
  *
  * @private
  * @throws {Error} unexpected error
  * @returns {void}
  */
  function main() {
  	var repeatedTry;
  	var fpath;
  	var opts;
  	var pkgs;
  	var idx;
  	var pkg;
  	var tmp;
  	var err;
  	var i;
  
  	if ( !args || args.length === 0 ) {
  		debug( 'Creating an ordered package list...' );
  		pkgs = toposort({
  			'ignore': [
  				'**/_tools/**'
  			]
  		});
  		if ( pkgs instanceof Error ) {
  			debug( 'Unable to create an ordered package list. Error: %s', pkgs.message );
  			throw pkgs;
  		}
  		debug( 'Successfully created an ordered package list.' );
  
  		debug( 'Writing list to file...' );
  		fpath = join( tmpdir(), 'stdlib_ordered_pkg_list.json' );
  		err = writeFileSync( fpath, JSON.stringify( pkgs, null, '  ' )+'\n', {
  			'encoding': 'utf8'
  		});
  		if ( err instanceof Error ) {
  			debug( 'Unable to write list to file. Error: %s', err.message );
  			throw err;
  		}
  		debug( 'Successfully wrote list to file.' );
  
  		pkgs = pkgs.slice( START_PKG_INDEX, END_PKG_INDEX );
  		for ( i = 0; i < pkgs.length; i++ ) {
  			pkgs[ i ] = replace( pkgs[ i ], '@stdlib/', '' );
  		}
  	} else {
  		pkgs = args;
  		for ( i = 0; i < pkgs.length; i++ ) {
  			pkgs[ i ] = replace( pkgs[ i ], '@stdlib/', '' );
  			pkgs[ i ] = trim( pkgs[ i ] );
  		}
  	}
  
  	// Filter out packages:
  	tmp = [];
  	for ( i = 0; i < pkgs.length; i++ ) {
  		if (
  			!startsWith( pkgs[ i ], '_tools' ) && // Do not publish internal `stdlib` tooling packages
  			!startsWith( pkgs[ i ], 'plot/' ) && // Do not publish individual `plot` package but do publish overall namespace
  			!startsWith( pkgs[ i ], 'strided/common' ) // Do not publish namespace slated to go away
  		) {
  			tmp.push( pkgs[ i ] );
  		}
  	}
  	pkgs = tmp;
  	if ( flags[ 'skip-individual' ] ) {
  		console.log( 'Do not publish individual packages...' );
  		tmp = [];
  		for ( i = 0; i < pkgs.length; i++ ) {
  			if ( !contains( pkgs[ i ], '/' ) ) {
  				tmp.push( pkgs[ i ] );
  			}
  		}
  		pkgs = tmp;
  	}
  	if ( flags[ 'skip-toplevel' ] ) {
  		console.log( 'Do not publish toplevel packages...' );
  		tmp = [];
  		for ( i = 0; i < pkgs.length; i++ ) {
  			if ( contains( pkgs[ i ], '/' ) ) {
  				tmp.push( pkgs[ i ] );
  			}
  		}
  		pkgs = tmp;
  	}
  	console.log( 'Publishing %d `stdlib` packages...', pkgs.length );
  	idx = 0;
  	pkg = pkgs[ idx ];
  
  	cleanCache();
  
  	debug( 'Clean-up existing build directory...' );
  	fs.rmSync( join( mainDir, 'build' ), {
  		'recursive': true,
  		'force': true
  	});
  
  	opts = {
  		'org': 'stdlib-js',
  		'token': ENV.GITHUB_TOKEN
  	};
  	repos( opts, onRepos );
  
  	/**
  	* Callback invoked after resolving resources.
  	*
  	* @private
  	* @param {(Error|null)} err - error object
  	* @param {ObjectArray} results - query data
  	* @returns {void}
  	*/
  	function onRepos( err, results ) {
  		var i;
  		if ( err ) {
  			return console.error( err );
  		}
  		for ( i = 0; i < results.length; i++ ) {
  			EXISTING_REPOS[ results[ i ].name ] = true;
  		}
  		publish( pkg, onCallback );
  	}
  
  	/**
  	* Callback invoked once pushing package contents to remote GitHub repository.
  	*
  	* @private
  	* @param {(Error|null)} err - error object or `null`
  	* @param {Object} pkgInfo - package information
  	* @returns {void}
  	*/
  	function onCallback( err, pkgInfo ) {
  		var fpath;
  		if ( err && !repeatedTry ) {
  			console.log( err );
  			cleanCache();
  			console.log( 'Trying again once more to process the following package: %s', pkg );
  			repeatedTry = true;
  			publish( pkg, onCallback );
  		} else {
  			console.log( 'Package contents successfully pushed to GitHub...' );
  			pkgs[ idx ] = pkgInfo;
  			idx += 1;
  			pkg = pkgs[ idx ];
  			repeatedTry = false;
  			if ( pkg ) {
  				console.log( 'Now processing the following package: %s', pkg );
  				publish( pkg, onCallback );
  			} else {
  				console.log( 'All `stdlib` packages successfully pushed to GitHub...' );
  				fpath = join( tmpdir(), 'stdlib_published_pkg_list.json' );
  				writeFileSync( fpath, JSON.stringify( pkgs, null, '\t' ) );
  			}
  		}
  	}
  }
  
  main();
  