[
  {
    "path": ".eslintignore",
    "content": "docs\nnode_modules\ncoverage\ntemp\ndist\netc\ncoverage\nbuild\nfixtures\nexample"
  },
  {
    "path": ".eslintrc",
    "content": "{\n  \"parser\": \"@typescript-eslint/parser\",\n  \"plugins\": [\n    \"prettier\",\n    \"@typescript-eslint\"\n  ],\n  \"extends\": [\n    \"eslint:recommended\",\n    \"plugin:prettier/recommended\",\n    \"plugin:@typescript-eslint/eslint-recommended\",\n    \"plugin:@typescript-eslint/recommended\"\n  ]\n}"
  },
  {
    "path": ".git-package.meta",
    "content": "\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "# This is a basic workflow to help you get started with Actions\n\nname: CI\n\n# Controls when the workflow will run\non:\n  # Triggers the workflow on push or pull request events but only for the main branch\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\n  # Allows you to run this workflow manually from the Actions tab\n  workflow_dispatch:\n\n# A workflow run is made up of one or more jobs that can run sequentially or in parallel\njobs:\n  lint:\n    name: 'Lint'\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v1\n      - uses: volta-cli/action@v1\n        with:\n          node-version: ${{ matrix.node }}\n      - name: install dependencies\n        run: npm i\n      - name: lint\n        run: npm run lint\n        env:\n          CI: true\n\n  test:\n    name: 'Node ${{ matrix.node }} - ${{ matrix.os }}'\n    runs-on: ${{ matrix.os }}-latest\n\n    strategy:\n      matrix:\n        node: ['16', 'latest']\n        os: [ubuntu, macOS, windows]\n\n    steps:\n      - uses: actions/checkout@v1\n      - uses: volta-cli/action@v1\n        with:\n          node-version: ${{ matrix.node }}\n      - name: install dependencies\n        run: npm i\n      - name: test\n        run: npm test\n        env:\n          CI: true\n\n  gh-release:\n    if: github.event_name != 'pull_request'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v2\n        with:\n          node-version: '16.x'\n      - uses: webfactory/ssh-agent@v0.5.3\n        with:\n          ssh-private-key: ${{ secrets.GH_PAGES_DEPLOY }}\n      - name: Release to GitHub Pages\n        env:\n          USE_SSH: true\n          GIT_USER: git\n        run: |\n          git config --global user.email \"gabecsapo@gmail.com\"\n          git config --global user.name \"Gabriel J. Csapo\"\n          npm install\n          npm run build\n          cd website\n          npm install\n          npm run deploy\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\n.DS_Store\nnpm-debug.log\ncoverage\n.nyc_output\nexample/test\nexample/tmp\npackage-lock.json\n.vs/\ndist\ntemp\netc\nbuild-complete.meta"
  },
  {
    "path": ".husky/pre-commit",
    "content": "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\n\nnpm run build\nnpm run lint\n\n"
  },
  {
    "path": ".npmignore",
    "content": ".git-package.meta\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n    \"singleQuote\": true\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# 1.0.0 (07/10/2022)\n\n- Removes node support from node@<16 (@gabrielcsapo)\n- Bugfix: Fix logging on response streams. (#96) (@willstott101)\n- Avoid using self in service.ts - to avoid issue with through (#95) (@willstott101)\n- Migrates to typescript (@5GameMaker @gabrielcsapo)\n- Removes node support from node@<14\n\n# 1.0.0-beta.31 (07/10/2022)\n\n- Removes node support from node@<16 (@gabrielcsapo)\n\n# 1.0.0-beta.30 (01/26/2022)\n\n- Bugfix: Fix logging on response streams. (#96) (@willstott101)\n\n# 1.0.0-beta.21 (01/24/2022)\n\n- Avoid using self in service.ts - to avoid issue with through (#95) (@willstott101)\n\n# 1.0.0-beta.1 (01/02/2022)\n\n- Migrates to typescript (@5GameMaker @gabrielcsapo)\n- Removes node support from node@<14\n\n# 0.6.1 (03/03/2019)\n\n- Fixes bug with being able to overwrite git repos that a user doesn't have access to. @masasron\n\n# 0.6.0 (03/03/2019)\n\n- Augments the authenticate function declaration to accept an object as the first argument and a callback for the second. This allows us to make changes without having to cause breaking changes.\n  - Adds the ability to introspect on the header (fixes #49)\n\n# 0.5.1 (03/03/2019)\n\n- bump dependencies\n  - tap `^11.0.1` -> `^12.5.3`\n  - tryitout `^2.0.6` -> `^2.1.1`\n\n# 0.5.0 (11/27/2018)\n\n- adds `log` functionality for event streams and response streams\n\n# 0.4.3 (04/30/2018)\n\n- removes deprecated `Buffer` interface\n\n# 0.4.2 (12/07/2017)\n\n- adds https support\n\n# 0.4.1 (12/04/2017)\n\n- fixes type to be the same as the event names\n\n# 0.4.0 (12/03/2017)\n\n- [BREAKING] changes the interface for authentication to make it more flexible\n- when error is sent back to client ensure error is string\n\n# 0.3.4 (11/10/2017)\n\n- updates duplex lib to fix cork, uncork and add some chaining\n- adds extensive docs to Git, Util and Service\n- adds named function to events to trace errors more easily\n\n# 0.3.3 (11/05/2017)\n\n- Removes dependency on http-duplex package replacing w/ internal replacement lib\n- updates tryitout@1.0.0 and updates Docs\n\n# 0.3.2 (11/02/2017)\n\n- fixes pathing issues on non linux/unix based operating systems (windows)\n\n# 0.3.1 (10/17/2017)\n\n- allow authenticate to handle promises\n\n# 0.3.0\n\n- removes authentication logic and makes it a configurable middleware\n- passes username to listener objects\n\n# 0.2.1 (09/15/2017)\n\n- fixes bug that would let anyone publish to a repo regardless of permissions that were set\n- fixes bug in test that didn't properly test auth based operations\n\n# 0.2.0 (09/05/2017)\n\n- abstracts server into lib/git.js\n- fixes list to only return valid .git directories\n- adds tests for basicAuth middleware\n- isolate helper functions into util.js\n- refactor unit tests to subside in files they are relevant to\n- adds jsdoc\n\n# 0.1.0 (05/08/2017)\n\n- adds basic authentication protection for repositories\n- updates docs to expose information\n\n# 0.0.3 (05/08/2017)\n\n- fixes bug with `mkdir` function that caused random directories to be created\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Gabriel Csapo\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# node-git-server\n\n> 🎡 A configurable git server written in Node.js\n\n[![Npm Version](https://img.shields.io/npm/v/node-git-server.svg)](https://www.npmjs.com/package/node-git-server)\n[![Build Status](https://travis-ci.org/gabrielcsapo/node-git-server.svg?branch=master)](https://travis-ci.org/gabrielcsapo/node-git-server)\n[![Dependency Status](https://starbuck.gabrielcsapo.com/badge/github/gabrielcsapo/node-git-server/status.svg)](https://starbuck.gabrielcsapo.com/github/gabrielcsapo/node-git-server)\n[![devDependency Status](https://starbuck.gabrielcsapo.com/badge/github/gabrielcsapo/node-git-server/dev-status.svg)](https://starbuck.gabrielcsapo.com/github/gabrielcsapo/node-git-server#info=devDependencies)\n[![npm](https://img.shields.io/npm/dt/node-git-server.svg)]()\n[![npm](https://img.shields.io/npm/dm/node-git-server.svg)]()\n\n## Install\n\n```shell\nnpm install node-git-server\n```\n\n## Usage\n\nPlease visit our docs [https://gabrielcsapo.github.io/node-git-server](https://gabrielcsapo.github.io/node-git-server)!\n\n## Philosophy\n\nThis library is aimed to have a zero dependency footprint. If you are reading this and you see dependencies, help to remove them 🐒.\n\n## Thanks\n\nThis is a hard fork from [pushover](https://github.com/substack/pushover).\n"
  },
  {
    "path": "example/certificate.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIIB0TCCAToCCQCvzaaNTZEFTDANBgkqhkiG9w0BAQUFADAtMQswCQYDVQQGEwJV\nUzELMAkGA1UECAwCQ0ExETAPBgNVBAcMCFNhbiBKb3NlMB4XDTE3MTIwNzE5MTI0\nNloXDTE4MDEwNjE5MTI0NlowLTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMREw\nDwYDVQQHDAhTYW4gSm9zZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAplVm\nUrhFbgb+g7gHDjfdTZUwqNnJ6AajytmqmzV7ceTeXKtKfNAN7i2DyFxf/IwQWoxs\n0g7MOE8UP19GCInK0I5T9svvbtSVEfxrtGLMBY7qnojN7Q+DIjdvM7f/m5W8oNkQ\nqb3EzkBKX6A5HobxKqTdu40IBLBkxa0faEmU84MCAwEAATANBgkqhkiG9w0BAQUF\nAAOBgQAzN5VrWE0bFT/UZgUCHrR6h+EQRfGCybAq6MmS1hEoHkLyLPIjokcRWxFe\neufVyxesJaUiO6f3W34J2NoZK4NsEF931t/n12bB8Ku8H1tokNsyWqJns2Whj+bR\n012osVh6ghdOvKD0yrnv6oLjMU51A8UKuxh51xoMThU0vBwvDg==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "example/index.js",
    "content": "// You Can Use The Commands Below To Generate A Self Signed Certificate For Use With This Tutorial\n// These Commands Require That You have 'openssl' installed on your system\n// openssl genrsa -out privatekey.pem 1024\n// openssl req -new -key privatekey.pem -out certrequest.csr\n// openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem\n\nlet type = 'http';\n\nprocess.argv.slice(2).forEach((arg) => {\n  switch (arg) {\n    case 'https':\n    case '--https':\n      type = 'https';\n      break;\n  }\n});\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst { Git: Server } = require('../');\n\nconst port = process.env.PORT || 7005;\n\nconst repos = new Server(path.normalize(path.resolve(__dirname, 'tmp')), {\n  autoCreate: true,\n  authenticate: ({ type, repo, user, headers }, next) => {\n    console.log(type, repo, headers); // eslint-disable-line\n    if (type == 'push') {\n      // Decide if this user is allowed to perform this action against this repo.\n      user((username, password) => {\n        if (username === '42' && password === '42') {\n          next();\n        } else {\n          next('wrong password');\n        }\n      });\n    } else {\n      // Check these credentials are correct for this user.\n      next();\n    }\n  },\n});\n\nrepos.on('push', (push) => {\n  console.log(`push ${push.repo} / ${push.commit} ( ${push.branch} )`); // eslint-disable-line\n\n  repos.list((err, results) => {\n    push.log(' ');\n    push.log('Hey!');\n    push.log('Checkout these other repos:');\n    for (const repo of results) {\n      push.log(`- ${repo}`);\n    }\n    push.log(' ');\n  });\n\n  push.accept();\n});\n\nrepos.on('fetch', (fetch) => {\n  console.log(`username ${fetch.username}`); // eslint-disable-line\n  console.log(`fetch ${fetch.repo}/${fetch.commit}`); // eslint-disable-line\n  fetch.accept();\n});\n\nrepos.listen(\n  port,\n  {\n    type,\n    key: fs.readFileSync(path.resolve(__dirname, 'privatekey.pem')),\n    cert: fs.readFileSync(path.resolve(__dirname, 'certificate.pem')),\n  },\n  (error) => {\n    if (error)\n      return console.error(\n        `failed to start git-server because of error ${error}`\n      ); // eslint-disable-line\n    console.log(`node-git-server running at ${type}://localhost:${port}`); // eslint-disable-line\n    repos.list((err, result) => {\n      if (!result) {\n        console.log('No repositories available...'); // eslint-disable-line\n      } else {\n        console.log(result); // eslint-disable-line\n      }\n    });\n  }\n);\n"
  },
  {
    "path": "example/privatekey.pem",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIICWwIBAAKBgQCmVWZSuEVuBv6DuAcON91NlTCo2cnoBqPK2aqbNXtx5N5cq0p8\n0A3uLYPIXF/8jBBajGzSDsw4TxQ/X0YIicrQjlP2y+9u1JUR/Gu0YswFjuqeiM3t\nD4MiN28zt/+blbyg2RCpvcTOQEpfoDkehvEqpN27jQgEsGTFrR9oSZTzgwIDAQAB\nAoGAb3gr6qOzY9ksF/nsQIsPtD6XLZFGzkgk3Hyi6QEeiWVn35KriJmlvEikWFIP\nwZ/cFdKl2uAv3EyitRWUSYSOdcD+tri253WkwpKr8qEq3MKdEsQGZlPiO2MJpWsa\n4vsy1bleUxqbB2TYIIXdjgD8TpTCh8sc8pVxEWEuEThxIIECQQDY9TSZkZHqsqpC\nbK/VUpluj3coZJcczk64ZAdkWYlXfNpvgdT3ViPjpdEYeabzTP0xI7OHkx6fVLiS\n87Y6EwWfAkEAxEQKhgj+saudBzl2EUQW5qntdJh3Fr+OLErSHb4M5E/nWvxW6il0\nXWRE3b7KrikThPkwUtXPTBNGiZ7D1dvfnQJAHMLk5jbWETb+OzANX0pD7NQ4B7LO\nFZOD/A3GrRbxjhePHZkokmFpAJTK02PNLhPWvNzuv9pRBO5GSbTlQ22iIQJAQiEy\n8oqhVrgeRsrjr1mj5cCn07tzlOSiQOZM+dyJd3w81flkR64EGVupoJWisSACBbH4\nyFBmcpmkEMa/8ZUOOQJAfAqyF5aCRh4MbPT7pCGSf0gckc3p6qISb1Zodh7GLSdb\nf/VvQzhRG3MKnSl+ZQ+GQT+F+FeZl0/ZPjVRYG/Avw==\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/HEAD",
    "content": "ref: refs/heads/master\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/config",
    "content": "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n\tignorecase = true\n\tprecomposeunicode = true\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/description",
    "content": "Unnamed repository; edit this file 'description' to name the repository.\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/applypatch-msg.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.  The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/commit-msg.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to check the commit log message.\n# Called by \"git commit\" with one argument, the name of the file\n# that has the commit message.  The hook should exit with non-zero\n# status after issuing an appropriate message if it wants to stop the\n# commit.  The hook is allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"commit-msg\".\n\n# Uncomment the below to add a Signed-off-by line to the message.\n# Doing this in a hook is a bad idea in general, but the prepare-commit-msg\n# hook is more suited to it.\n#\n# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\\(.*>\\).*$/Signed-off-by: \\1/p')\n# grep -qs \"^$SOB\" \"$1\" || echo \"$SOB\" >> \"$1\"\n\n# This example catches duplicate Signed-off-by lines.\n\ntest \"\" = \"$(grep '^Signed-off-by: ' \"$1\" |\n\t sort | uniq -c | sed -e '/^[ \t]*1[ \t]/d')\" || {\n\techo >&2 Duplicate Signed-off-by lines.\n\texit 1\n}\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/post-update.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to prepare a packed repository for use over\n# dumb transports.\n#\n# To enable this hook, rename this file to \"post-update\".\n\nexec git update-server-info\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/pre-applypatch.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/pre-commit.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed.\n# Called by \"git commit\" with no arguments.  The hook should\n# exit with non-zero status after issuing an appropriate message if\n# it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-commit\".\n\nif git rev-parse --verify HEAD >/dev/null 2>&1\nthen\n\tagainst=HEAD\nelse\n\t# Initial commit: diff against an empty tree object\n\tagainst=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\n# If you want to allow non-ASCII filenames set this variable to true.\nallownonascii=$(git config --bool hooks.allownonascii)\n\n# Redirect output to stderr.\nexec 1>&2\n\n# Cross platform projects tend to avoid non-ASCII filenames; prevent\n# them from being added to the repository. We exploit the fact that the\n# printable range starts at the space character and ends with tilde.\nif [ \"$allownonascii\" != \"true\" ] &&\n\t# Note that the use of brackets around a tr range is ok here, (it's\n\t# even required, for portability to Solaris 10's /usr/bin/tr), since\n\t# the square bracket bytes happen to fall in the designated range.\n\ttest $(git diff --cached --name-only --diff-filter=A -z $against |\n\t  LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0\nthen\n\tcat <<\\EOF\nError: Attempt to add a non-ASCII file name.\n\nThis can cause problems if you want to work with people on other platforms.\n\nTo be portable it is advisable to rename the file.\n\nIf you know what you are doing you can disable this check using:\n\n  git config hooks.allownonascii true\nEOF\n\texit 1\nfi\n\n# If there are whitespace errors, print the offending file names and fail.\nexec git diff-index --check --cached $against --\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/pre-push.sample",
    "content": "#!/bin/sh\n\n# An example hook script to verify what is about to be pushed.  Called by \"git\n# push\" after it has checked the remote status, but before anything has been\n# pushed.  If this script exits with a non-zero status nothing will be pushed.\n#\n# This hook is called with the following parameters:\n#\n# $1 -- Name of the remote to which the push is being done\n# $2 -- URL to which the push is being done\n#\n# If pushing without using a named remote those arguments will be equal.\n#\n# Information about the commits which are being pushed is supplied as lines to\n# the standard input in the form:\n#\n#   <local ref> <local sha1> <remote ref> <remote sha1>\n#\n# This sample shows how to prevent push of commits where the log message starts\n# with \"WIP\" (work in progress).\n\nremote=\"$1\"\nurl=\"$2\"\n\nz40=0000000000000000000000000000000000000000\n\nwhile read local_ref local_sha remote_ref remote_sha\ndo\n\tif [ \"$local_sha\" = $z40 ]\n\tthen\n\t\t# Handle delete\n\t\t:\n\telse\n\t\tif [ \"$remote_sha\" = $z40 ]\n\t\tthen\n\t\t\t# New branch, examine all commits\n\t\t\trange=\"$local_sha\"\n\t\telse\n\t\t\t# Update to existing branch, examine new commits\n\t\t\trange=\"$remote_sha..$local_sha\"\n\t\tfi\n\n\t\t# Check for WIP commit\n\t\tcommit=`git rev-list -n 1 --grep '^WIP' \"$range\"`\n\t\tif [ -n \"$commit\" ]\n\t\tthen\n\t\t\techo >&2 \"Found WIP commit in $local_ref, not pushing\"\n\t\t\texit 1\n\t\tfi\n\tfi\ndone\n\nexit 0\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/pre-rebase.sample",
    "content": "#!/bin/sh\n#\n# Copyright (c) 2006, 2008 Junio C Hamano\n#\n# The \"pre-rebase\" hook is run just before \"git rebase\" starts doing\n# its job, and can prevent the command from running by exiting with\n# non-zero status.\n#\n# The hook is called with the following parameters:\n#\n# $1 -- the upstream the series was forked from.\n# $2 -- the branch being rebased (or empty when rebasing the current branch).\n#\n# This sample shows how to prevent topic branches that are already\n# merged to 'next' branch from getting rebased, because allowing it\n# would result in rebasing already published history.\n\npublish=next\nbasebranch=\"$1\"\nif test \"$#\" = 2\nthen\n\ttopic=\"refs/heads/$2\"\nelse\n\ttopic=`git symbolic-ref HEAD` ||\n\texit 0 ;# we do not interrupt rebasing detached HEAD\nfi\n\ncase \"$topic\" in\nrefs/heads/??/*)\n\t;;\n*)\n\texit 0 ;# we do not interrupt others.\n\t;;\nesac\n\n# Now we are dealing with a topic branch being rebased\n# on top of master.  Is it OK to rebase it?\n\n# Does the topic really exist?\ngit show-ref -q \"$topic\" || {\n\techo >&2 \"No such branch $topic\"\n\texit 1\n}\n\n# Is topic fully merged to master?\nnot_in_master=`git rev-list --pretty=oneline ^master \"$topic\"`\nif test -z \"$not_in_master\"\nthen\n\techo >&2 \"$topic is fully merged to master; better remove it.\"\n\texit 1 ;# we could allow it, but there is no point.\nfi\n\n# Is topic ever merged to next?  If so you should not be rebasing it.\nonly_next_1=`git rev-list ^master \"^$topic\" ${publish} | sort`\nonly_next_2=`git rev-list ^master           ${publish} | sort`\nif test \"$only_next_1\" = \"$only_next_2\"\nthen\n\tnot_in_topic=`git rev-list \"^$topic\" master`\n\tif test -z \"$not_in_topic\"\n\tthen\n\t\techo >&2 \"$topic is already up-to-date with master\"\n\t\texit 1 ;# we could allow it, but there is no point.\n\telse\n\t\texit 0\n\tfi\nelse\n\tnot_in_next=`git rev-list --pretty=oneline ^${publish} \"$topic\"`\n\t/usr/bin/perl -e '\n\t\tmy $topic = $ARGV[0];\n\t\tmy $msg = \"* $topic has commits already merged to public branch:\\n\";\n\t\tmy (%not_in_next) = map {\n\t\t\t/^([0-9a-f]+) /;\n\t\t\t($1 => 1);\n\t\t} split(/\\n/, $ARGV[1]);\n\t\tfor my $elem (map {\n\t\t\t\t/^([0-9a-f]+) (.*)$/;\n\t\t\t\t[$1 => $2];\n\t\t\t} split(/\\n/, $ARGV[2])) {\n\t\t\tif (!exists $not_in_next{$elem->[0]}) {\n\t\t\t\tif ($msg) {\n\t\t\t\t\tprint STDERR $msg;\n\t\t\t\t\tundef $msg;\n\t\t\t\t}\n\t\t\t\tprint STDERR \" $elem->[1]\\n\";\n\t\t\t}\n\t\t}\n\t' \"$topic\" \"$not_in_next\" \"$not_in_master\"\n\texit 1\nfi\n\nexit 0\n\n################################################################\n\nThis sample hook safeguards topic branches that have been\npublished from being rewound.\n\nThe workflow assumed here is:\n\n * Once a topic branch forks from \"master\", \"master\" is never\n   merged into it again (either directly or indirectly).\n\n * Once a topic branch is fully cooked and merged into \"master\",\n   it is deleted.  If you need to build on top of it to correct\n   earlier mistakes, a new topic branch is created by forking at\n   the tip of the \"master\".  This is not strictly necessary, but\n   it makes it easier to keep your history simple.\n\n * Whenever you need to test or publish your changes to topic\n   branches, merge them into \"next\" branch.\n\nThe script, being an example, hardcodes the publish branch name\nto be \"next\", but it is trivial to make it configurable via\n$GIT_DIR/config mechanism.\n\nWith this workflow, you would want to know:\n\n(1) ... if a topic branch has ever been merged to \"next\".  Young\n    topic branches can have stupid mistakes you would rather\n    clean up before publishing, and things that have not been\n    merged into other branches can be easily rebased without\n    affecting other people.  But once it is published, you would\n    not want to rewind it.\n\n(2) ... if a topic branch has been fully merged to \"master\".\n    Then you can delete it.  More importantly, you should not\n    build on top of it -- other people may already want to\n    change things related to the topic as patches against your\n    \"master\", so if you need further changes, it is better to\n    fork the topic (perhaps with the same name) afresh from the\n    tip of \"master\".\n\nLet's look at this example:\n\n\t\t   o---o---o---o---o---o---o---o---o---o \"next\"\n\t\t  /       /           /           /\n\t\t /   a---a---b A     /           /\n\t\t/   /               /           /\n\t       /   /   c---c---c---c B         /\n\t      /   /   /             \\         /\n\t     /   /   /   b---b C     \\       /\n\t    /   /   /   /             \\     /\n    ---o---o---o---o---o---o---o---o---o---o---o \"master\"\n\n\nA, B and C are topic branches.\n\n * A has one fix since it was merged up to \"next\".\n\n * B has finished.  It has been fully merged up to \"master\" and \"next\",\n   and is ready to be deleted.\n\n * C has not merged to \"next\" at all.\n\nWe would want to allow C to be rebased, refuse A, and encourage\nB to be deleted.\n\nTo compute (1):\n\n\tgit rev-list ^master ^topic next\n\tgit rev-list ^master        next\n\n\tif these match, topic has not merged in next at all.\n\nTo compute (2):\n\n\tgit rev-list master..topic\n\n\tif this is empty, it is fully merged to \"master\".\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/pre-receive.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to make use of push options.\n# The example simply echoes all push options that start with 'echoback='\n# and rejects all pushes when the \"reject\" push option is used.\n#\n# To enable this hook, rename this file to \"pre-receive\".\n\nif test -n \"$GIT_PUSH_OPTION_COUNT\"\nthen\n\ti=0\n\twhile test \"$i\" -lt \"$GIT_PUSH_OPTION_COUNT\"\n\tdo\n\t\teval \"value=\\$GIT_PUSH_OPTION_$i\"\n\t\tcase \"$value\" in\n\t\techoback=*)\n\t\t\techo \"echo from the pre-receive-hook: ${value#*=}\" >&2\n\t\t\t;;\n\t\treject)\n\t\t\texit 1\n\t\tesac\n\t\ti=$((i + 1))\n\tdone\nfi\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/prepare-commit-msg.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to prepare the commit log message.\n# Called by \"git commit\" with the name of the file that has the\n# commit message, followed by the description of the commit\n# message's source.  The hook's purpose is to edit the commit\n# message file.  If the hook fails with a non-zero status,\n# the commit is aborted.\n#\n# To enable this hook, rename this file to \"prepare-commit-msg\".\n\n# This hook includes three examples.  The first comments out the\n# \"Conflicts:\" part of a merge commit.\n#\n# The second includes the output of \"git diff --name-status -r\"\n# into the message, just before the \"git status\" output.  It is\n# commented because it doesn't cope with --amend or with squashed\n# commits.\n#\n# The third example adds a Signed-off-by line to the message, that can\n# still be edited.  This is rarely a good idea.\n\ncase \"$2,$3\" in\n  merge,)\n    /usr/bin/perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' \"$1\" ;;\n\n# ,|template,)\n#   /usr/bin/perl -i.bak -pe '\n#      print \"\\n\" . `git diff --cached --name-status -r`\n#\t if /^#/ && $first++ == 0' \"$1\" ;;\n\n  *) ;;\nesac\n\n# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\\(.*>\\).*$/Signed-off-by: \\1/p')\n# grep -qs \"^$SOB\" \"$1\" || echo \"$SOB\" >> \"$1\"\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/hooks/update.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to block unannotated tags from entering.\n# Called by \"git receive-pack\" with arguments: refname sha1-old sha1-new\n#\n# To enable this hook, rename this file to \"update\".\n#\n# Config\n# ------\n# hooks.allowunannotated\n#   This boolean sets whether unannotated tags will be allowed into the\n#   repository.  By default they won't be.\n# hooks.allowdeletetag\n#   This boolean sets whether deleting tags will be allowed in the\n#   repository.  By default they won't be.\n# hooks.allowmodifytag\n#   This boolean sets whether a tag may be modified after creation. By default\n#   it won't be.\n# hooks.allowdeletebranch\n#   This boolean sets whether deleting branches will be allowed in the\n#   repository.  By default they won't be.\n# hooks.denycreatebranch\n#   This boolean sets whether remotely creating branches will be denied\n#   in the repository.  By default this is allowed.\n#\n\n# --- Command line\nrefname=\"$1\"\noldrev=\"$2\"\nnewrev=\"$3\"\n\n# --- Safety check\nif [ -z \"$GIT_DIR\" ]; then\n\techo \"Don't run this script from the command line.\" >&2\n\techo \" (if you want, you could supply GIT_DIR then run\" >&2\n\techo \"  $0 <ref> <oldrev> <newrev>)\" >&2\n\texit 1\nfi\n\nif [ -z \"$refname\" -o -z \"$oldrev\" -o -z \"$newrev\" ]; then\n\techo \"usage: $0 <ref> <oldrev> <newrev>\" >&2\n\texit 1\nfi\n\n# --- Config\nallowunannotated=$(git config --bool hooks.allowunannotated)\nallowdeletebranch=$(git config --bool hooks.allowdeletebranch)\ndenycreatebranch=$(git config --bool hooks.denycreatebranch)\nallowdeletetag=$(git config --bool hooks.allowdeletetag)\nallowmodifytag=$(git config --bool hooks.allowmodifytag)\n\n# check for no description\nprojectdesc=$(sed -e '1q' \"$GIT_DIR/description\")\ncase \"$projectdesc\" in\n\"Unnamed repository\"* | \"\")\n\techo \"*** Project description file hasn't been set\" >&2\n\texit 1\n\t;;\nesac\n\n# --- Check types\n# if $newrev is 0000...0000, it's a commit to delete a ref.\nzero=\"0000000000000000000000000000000000000000\"\nif [ \"$newrev\" = \"$zero\" ]; then\n\tnewrev_type=delete\nelse\n\tnewrev_type=$(git cat-file -t $newrev)\nfi\n\ncase \"$refname\",\"$newrev_type\" in\n\trefs/tags/*,commit)\n\t\t# un-annotated tag\n\t\tshort_refname=${refname##refs/tags/}\n\t\tif [ \"$allowunannotated\" != \"true\" ]; then\n\t\t\techo \"*** The un-annotated tag, $short_refname, is not allowed in this repository\" >&2\n\t\t\techo \"*** Use 'git tag [ -a | -s ]' for tags you want to propagate.\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/tags/*,delete)\n\t\t# delete tag\n\t\tif [ \"$allowdeletetag\" != \"true\" ]; then\n\t\t\techo \"*** Deleting a tag is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/tags/*,tag)\n\t\t# annotated tag\n\t\tif [ \"$allowmodifytag\" != \"true\" ] && git rev-parse $refname > /dev/null 2>&1\n\t\tthen\n\t\t\techo \"*** Tag '$refname' already exists.\" >&2\n\t\t\techo \"*** Modifying a tag is not allowed in this repository.\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/heads/*,commit)\n\t\t# branch\n\t\tif [ \"$oldrev\" = \"$zero\" -a \"$denycreatebranch\" = \"true\" ]; then\n\t\t\techo \"*** Creating a branch is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/heads/*,delete)\n\t\t# delete branch\n\t\tif [ \"$allowdeletebranch\" != \"true\" ]; then\n\t\t\techo \"*** Deleting a branch is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/remotes/*,commit)\n\t\t# tracking branch\n\t\t;;\n\trefs/remotes/*,delete)\n\t\t# delete tracking branch\n\t\tif [ \"$allowdeletebranch\" != \"true\" ]; then\n\t\t\techo \"*** Deleting a tracking branch is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\t*)\n\t\t# Anything else (is there anything else?)\n\t\techo \"*** Update hook: unknown type of update to ref $refname of type $newrev_type\" >&2\n\t\texit 1\n\t\t;;\nesac\n\n# --- Finished\nexit 0\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/info/exclude",
    "content": "# git ls-files --others --exclude-from=.git/info/exclude\n# Lines that start with '#' are comments.\n# For a project mostly in C, the following would be a good set of\n# exclude patterns (uncomment them if you want to use them):\n# *.[oa]\n# *~\n"
  },
  {
    "path": "fixtures/server/tmp/test.git/refs/heads/master",
    "content": "0e60b9add392cd124fbf8e994bdbbde7a3192572\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"node-git-server\",\n  \"version\": \"1.0.0\",\n  \"description\": \"🎡 A configurable git server written in Node.js\",\n  \"author\": \"Gabriel J. Csapo <gabecsapo@gmail.com>\",\n  \"contributors\": [\n    {\n      \"name\": \"echopoint\",\n      \"email\": \"echopoint@tutanota.com\"\n    },\n    {\n      \"name\": \"Buj Itself\",\n      \"email\": \"primary@buj-dev.site\"\n    }\n  ],\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/gabrielcsapo/node-git-server/issues\"\n  },\n  \"homepage\": \"https://github.com/gabrielcsapo/node-git-server#readme\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/gabrielcsapo/node-git-server.git\"\n  },\n  \"main\": \"dist/index.js\",\n  \"engine\": {\n    \"node\": \">= 16\"\n  },\n  \"scripts\": {\n    \"lint\": \"eslint .\",\n    \"test\": \"vitest src/*.test.ts\",\n    \"build\": \"echo \\\"\\\" > ./build-complete.meta && tsc\",\n    \"prepublish\": \"npm run build\",\n    \"coverage\": \"vitest --coverage\",\n    \"install\": \"( [ -f ./git-package.meta ] && [ ! -f ./build-complete.meta ] && echo \\\"\\\" > ./build-complete.meta && npm install . && tsc ) || echo \\\"\\\" > ./build-complete.meta\",\n    \"prepare\": \"husky install\"\n  },\n  \"dependencies\": {\n    \"through\": \"^2.3.8\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^18.0.3\",\n    \"@types/node-fetch\": \"^2.6.2\",\n    \"@types/through\": \"^0.0.30\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.30.5\",\n    \"@typescript-eslint/parser\": \"^5.30.5\",\n    \"eslint\": \"^8.19.0\",\n    \"eslint-config-prettier\": \"^8.5.0\",\n    \"eslint-plugin-prettier\": \"^4.2.1\",\n    \"husky\": \"^8.0.1\",\n    \"node-fetch\": \"^3.2.6\",\n    \"prettier\": \"^2.7.1\",\n    \"typescript\": \"^4.7.4\",\n    \"vitest\": \"^0.18.0\"\n  },\n  \"volta\": {\n    \"node\": \"16.15.1\"\n  }\n}\n"
  },
  {
    "path": "src/git.test.ts",
    "content": "import fs from 'fs';\nimport path from 'path';\nimport { spawn, exec, SpawnOptionsWithoutStdio } from 'child_process';\nimport http from 'http';\n\nimport { Git } from './git';\n\nconst wrapCallback = (func: { (callback: any): void }) => {\n  return new Promise((resolve) => {\n    func(resolve);\n  });\n};\n\ndescribe('git', () => {\n  test('create, push to, and clone a repo', async () => {\n    expect.assertions(11);\n\n    let lastCommit: string;\n\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    const server = http\n      .createServer((req, res) => {\n        repos.handle(req, res);\n      })\n      .listen(port);\n\n    repos.on('push', (push) => {\n      expect(push.repo).toBe('xyz/doom');\n      expect(push.commit).toBe(lastCommit);\n      expect(push.branch).toBe('master');\n\n      expect(push.headers.host).toBe('localhost:' + port);\n      expect(push.method).toBe('POST');\n      expect(push.url).toBe('/xyz/doom/git-receive-pack');\n\n      push.accept();\n    });\n\n    await wrapCallback((callback: () => void) => {\n      repos.mkdir('xyz');\n      callback();\n    });\n\n    await wrapCallback((callback: () => void) => {\n      repos.create('xyz/doom', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'abcd', () => {\n        callback();\n      });\n    });\n\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on('exit', () => {\n        exec('git log | head -n1', { cwd: srcDir }, (err, stdout) => {\n          lastCommit = stdout.split(/\\s+/)[1];\n          callback();\n        });\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn(\n        'git',\n        ['push', 'http://localhost:' + port + '/xyz/doom', 'master'],\n        { cwd: srcDir }\n      ).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['clone', 'http://localhost:' + port + '/xyz/doom'], {\n        cwd: dstDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n\n    const ex = fs.existsSync(dstDir + '/doom/a.txt');\n    expect(ex).toBeTruthy();\n\n    server.close();\n  });\n\n  test('create, push to, and clone a repo successful', async () => {\n    expect.assertions(8);\n\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir);\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    const server = http.createServer((req, res) => {\n      repos.handle(req, res);\n    });\n    server.listen(port);\n\n    repos.on('push', (push) => {\n      expect(push.repo).toBe('doom');\n      push.accept();\n    });\n\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => {\n        expect(!err).toBeTruthy();\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on(\n        'exit',\n        (code) => {\n          expect(code).toBe(0);\n          callback();\n        }\n      );\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['push', 'http://localhost:' + port + '/doom', 'master'], {\n        cwd: srcDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['clone', 'http://localhost:' + port + '/doom'], {\n        cwd: dstDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.stat(dstDir + '/doom/a.txt', (ex) => {\n        expect(!ex).toBeTruthy();\n        callback();\n      });\n    });\n\n    server.close();\n  });\n\n  test('clone into programatic directories', async () => {\n    expect.assertions(19);\n\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const targetDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n    fs.mkdirSync(targetDir, '0700');\n\n    const server = new Git((dir?: string) => {\n      expect(dir).toBe('doom.git');\n\n      return path.join(targetDir, dir || '');\n    });\n\n    server.listen(port);\n\n    server.on('push', (push) => {\n      expect(push.repo).toBe('doom.git');\n      push.accept();\n    });\n\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => {\n        expect(!err).toBeTruthy();\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['add', 'a.txt'], {\n        cwd: srcDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['commit', '-am', 'a!!'], {\n        cwd: srcDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn(\n        'git',\n        ['push', 'http://localhost:' + port + '/doom.git', 'master'],\n        {\n          cwd: srcDir,\n        }\n      ).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['clone', 'http://localhost:' + port + '/doom.git'], {\n        cwd: dstDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.stat(dstDir + '/doom/a.txt', (ex) => {\n        expect(!ex).toBeTruthy();\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.stat(targetDir + '/doom.git/HEAD', (ex) => {\n        expect(!ex).toBeTruthy();\n        callback();\n      });\n    });\n\n    server.close();\n  });\n\n  test('test tagging', async () => {\n    expect.assertions(27);\n\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    let lastCommit: string;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    const server = http.createServer((req, res) => {\n      repos.handle(req, res);\n    });\n    server.listen(port);\n\n    repos.on('push', (push) => {\n      expect(push.repo).toBe('doom');\n      expect(push.commit).toBe(lastCommit);\n      expect(push.branch).toBe('master');\n\n      expect(push.headers.host).toBe('localhost:' + port);\n      expect(push.method).toBe('POST');\n      expect(push.url).toBe('/doom/git-receive-pack');\n\n      push.accept();\n    });\n\n    let firstTag = true;\n    repos.on('tag', (tag) => {\n      expect(tag.repo).toBe('doom');\n      expect(tag.version).toBe('0.0.' + (firstTag ? 1 : 2));\n\n      expect(tag.headers.host).toBe('localhost:' + port);\n      expect(tag.method).toBe('POST');\n      expect(tag.url).toBe('/doom/git-receive-pack');\n\n      tag.accept();\n      firstTag = false;\n    });\n\n    await wrapCallback((callback: () => void) => {\n      repos.create('doom', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => {\n        expect(!err).toBeTruthy();\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on(\n        'exit',\n        (code) => {\n          expect(code).toBe(0);\n          callback();\n        }\n      );\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['tag', '0.0.1'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'efgh', (err) => {\n        expect(!err).toBeTruthy();\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on('exit', () => {\n        exec('git log | head -n1', { cwd: srcDir }, (err, stdout) => {\n          lastCommit = stdout.split(/\\s+/)[1];\n          callback();\n        });\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['tag', '0.0.2'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn(\n        'git',\n        ['push', '--tags', 'http://localhost:' + port + '/doom', 'master'],\n        { cwd: srcDir }\n      ).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['clone', 'http://localhost:' + port + '/doom'], {\n        cwd: dstDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.exists(dstDir + '/doom/a.txt', (ex) => {\n        expect(ex).toBeTruthy();\n        callback();\n      });\n    });\n    server.close();\n  });\n\n  describe('repos list', () => {\n    const workingRepoDir = path.resolve(\n      __dirname,\n      '..',\n      'fixtures',\n      'server',\n      'tmp'\n    );\n    const notWorkingRepoDir = path.resolve(\n      __dirname,\n      '..',\n      'fixtures',\n      'server',\n      'temp'\n    );\n\n    test('should return back with one directory in server', async () => {\n      expect.assertions(2);\n\n      await new Promise((resolve) => {\n        const repos = new Git(workingRepoDir, {\n          autoCreate: true,\n        });\n\n        repos.list((err, results) => {\n          expect(err).toBeFalsy();\n          expect(['test.git']).toEqual(results);\n          resolve('passed');\n        });\n      });\n    }, 15000);\n\n    test('should return back error directory does not exist', async () => {\n      expect.assertions(2);\n\n      await new Promise((resolve) => {\n        const repos = new Git(notWorkingRepoDir, {\n          autoCreate: true,\n        });\n\n        repos.list((err, results) => {\n          expect(err !== null).toBeTruthy();\n          expect(results === undefined).toBeTruthy();\n          resolve('passed');\n        });\n      });\n    });\n  });\n\n  test('create, push to, and clone a repo reject', async () => {\n    expect.assertions(12);\n\n    function _spawn(\n      cmd: string,\n      args: any[] | readonly string[] | undefined,\n      opts: SpawnOptionsWithoutStdio | undefined\n    ) {\n      const ps = spawn(cmd, args, opts);\n      ps.on('error', (err) => {\n        console.error(\n          // eslint-disable-line\n          err.message + ' while executing: ' + cmd + ' ' + args?.join(' ')\n        );\n      });\n      return ps;\n    }\n\n    let lastCommit: string;\n\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    const server = http.createServer((req, res) => {\n      repos.handle(req, res);\n    });\n    server.listen(port);\n\n    repos.on('push', (push) => {\n      expect(push.repo).toBe('doom');\n      expect(push.commit).toBe(lastCommit);\n      expect(push.branch).toBe('master');\n\n      expect(push.headers.host).toBe('localhost:' + port);\n      expect(push.method).toBe('POST');\n      expect(push.url).toBe('/doom/git-receive-pack');\n\n      push.reject(500, 'ACCESS DENIED');\n    });\n\n    await wrapCallback((callback: () => void) => {\n      repos.create('doom', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      _spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => {\n        expect(!err).toBeTruthy();\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      _spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      _spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on(\n        'exit',\n        () => {\n          exec('git log | head -n1', { cwd: srcDir }, (err, stdout) => {\n            lastCommit = stdout.split(/\\s+/)[1];\n            callback();\n          });\n        }\n      );\n    });\n    await wrapCallback((callback: () => void) => {\n      _spawn('git', ['push', 'http://localhost:' + port + '/doom', 'master'], {\n        cwd: srcDir,\n      }).on('exit', (code) => {\n        expect(code).not.toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      const glog = _spawn('git', ['log'], {\n        cwd: repoDir + '/doom.git',\n      });\n      glog.on('exit', (code) => {\n        expect(code).toBe(128);\n        callback();\n      });\n      let data = '';\n      glog.stderr.on('data', (buf) => (data += buf));\n      glog.stderr.on('end', () => {\n        const res =\n          /fatal: bad default revision 'HEAD'/.test(data) ||\n          /fatal: your current branch 'master' does not have any commits yet/.test(\n            data\n          );\n        expect(res).toBeTruthy();\n      });\n    });\n    server.close();\n  });\n\n  test('create git server via listen() command', async () => {\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir);\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    expect(repos.listen(port)).toBe(repos);\n\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['clone', 'http://localhost:' + port + '/doom'], {\n        cwd: dstDir,\n      }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    repos.close();\n  });\n\n  test('should return promise that resolves when server is closed if no callback specified', async () => {\n    await new Promise((resolve) => {\n      const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n        16\n      )}`;\n\n      fs.mkdirSync(repoDir, '0700');\n\n      const repos = new Git(repoDir);\n      const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n      repos.listen(port, undefined, () => {\n        repos.close().then(() => {\n          resolve('passed');\n        });\n      });\n    });\n  });\n\n  test('should be able to protect certain routes', async () => {\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n      authenticate: ({ type, repo, user }, next) => {\n        if (type === 'fetch' && repo === 'doom') {\n          user((username, password) => {\n            if (username == 'root' && password == 'root') {\n              next();\n            } else {\n              next(new Error('that is not the correct password'));\n            }\n          });\n        } else {\n          next(new Error('that is not the correct password'));\n        }\n      },\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    repos.listen(port);\n\n    await wrapCallback((callback: () => void) => {\n      const clone = spawn(\n        'git',\n        ['clone', `http://root:root@localhost:${port}/doom.git`],\n        { cwd: dstDir }\n      );\n\n      clone.on('close', function (code) {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      const clone = spawn(\n        'git',\n        ['clone', `http://root:world@localhost:${port}/doom.git doom1`],\n        { cwd: dstDir }\n      );\n      let error = '';\n\n      clone.stderr.on('data', (d) => {\n        error += d.toString('utf8');\n      });\n\n      clone.on('close', function (code) {\n        expect(error).toBe(\n          `Cloning into 'doom.git doom1'...\\nfatal: unable to access 'http://localhost:${port}/doom.git doom1/': URL using bad/illegal format or missing URL\\n`\n        );\n        expect(code).toBe(128);\n        callback();\n      });\n    });\n    repos.close();\n  });\n\n  test('should be able to access headers in authenticate', async () => {\n    expect.assertions(13);\n\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n      authenticate: ({ type, repo, user, headers }, next) => {\n        if (type === 'fetch' && repo === 'doom') {\n          expect(headers['host']).toBeTruthy();\n          expect(headers['user-agent']).toBeTruthy();\n          expect(headers['accept']).toBeTruthy();\n          expect(headers['pragma']).toBeTruthy();\n          expect(headers['accept-encoding']).toBeTruthy();\n\n          user((username, password) => {\n            if (username == 'root' && password == 'root') {\n              next();\n            } else {\n              next(new Error('that is not the correct password'));\n            }\n          });\n        } else {\n          next(new Error('that is not the correct password'));\n        }\n      },\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    repos.listen(port);\n\n    await wrapCallback((callback: () => void) => {\n      const clone = spawn(\n        'git',\n        ['clone', `http://root:root@localhost:${port}/doom.git`],\n        { cwd: dstDir }\n      );\n\n      clone.on('close', function (code) {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      const clone = spawn(\n        'git',\n        ['clone', `http://root:world@localhost:${port}/doom.git doom1`],\n        { cwd: dstDir }\n      );\n      let error = '';\n\n      clone.stderr.on('data', (d) => {\n        error += d.toString('utf8');\n      });\n\n      clone.on('close', function (code) {\n        expect(error).toBe(\n          `Cloning into 'doom.git doom1'...\\nfatal: unable to access 'http://localhost:${port}/doom.git doom1/': URL using bad/illegal format or missing URL\\n`\n        );\n        expect(code).toBe(128);\n        callback();\n      });\n    });\n    repos.close();\n  });\n\n  test('should be able to protect certain routes with a promised authenticate', async () => {\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n      authenticate: ({ type, repo, user }) => {\n        return new Promise(function (resolve, reject) {\n          if (type === 'fetch' && repo === 'doom') {\n            user((username, password) => {\n              if (username == 'root' && password == 'root') {\n                return resolve(void 0);\n              } else {\n                return reject('that is not the correct password');\n              }\n            });\n          } else {\n            return reject('that is not the correct password');\n          }\n        });\n      },\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n    repos.listen(port);\n\n    await wrapCallback((callback: () => void) => {\n      const clone = spawn(\n        'git',\n        ['clone', `http://root:root@localhost:${port}/doom.git`],\n        { cwd: dstDir }\n      );\n\n      clone.on('close', function (code) {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      const clone = spawn(\n        'git',\n        ['clone', `http://root:world@localhost:${port}/doom.git doom1`],\n        { cwd: dstDir }\n      );\n      let error = '';\n\n      clone.stderr.on('data', (d) => {\n        error += d.toString('utf8');\n      });\n\n      clone.on('close', function (code) {\n        expect(error).toBe(\n          `Cloning into 'doom.git doom1'...\\nfatal: unable to access 'http://localhost:${port}/doom.git doom1/': URL using bad/illegal format or missing URL\\n`\n        );\n        expect(code).toBe(128);\n        callback();\n      });\n    });\n    repos.close();\n  });\n\n  test('should be able to send custom messages to git client (main stream)', async () => {\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n\n    repos.on('push', (push) => {\n      push.log(' ');\n      push.log('Have a great day!');\n      push.log(' ');\n\n      push.accept();\n    });\n\n    repos.listen(port);\n\n    await wrapCallback((callback: () => void) => {\n      repos.create('doom', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'abcd', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['commit', '-m', 'a!!'], { cwd: srcDir }).on('exit', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      const logs: any[] = [];\n      const push = spawn(\n        'git',\n        ['push', 'http://localhost:' + port + '/doom.git', 'master'],\n        { cwd: srcDir }\n      );\n\n      push.stdout.on('data', (data) => {\n        if (data.toString() !== '') {\n          logs.push(data.toString());\n        }\n      });\n\n      push.stderr.on('data', (data) => {\n        if (data.toString() !== '') {\n          logs.push(data.toString());\n        }\n      });\n\n      push.on('exit', () => {\n        expect(\n          logs.join(' ').indexOf('remote: Have a great day!') > -1\n        ).toBeTruthy();\n        callback();\n      });\n    });\n\n    repos.close();\n  });\n\n  test('should be able to send custom messages to git client (response stream)', async () => {\n    const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(\n      16\n    )}`;\n    const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n    const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`;\n\n    fs.mkdirSync(repoDir, '0700');\n    fs.mkdirSync(srcDir, '0700');\n    fs.mkdirSync(dstDir, '0700');\n\n    const repos = new Git(repoDir, {\n      autoCreate: true,\n    });\n    const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4;\n\n    repos.on('push', (push) => {\n      console.log(`push ${push.repo}/${push.commit}`); // eslint-disable-line\n\n      push.on('response', (stream: { log: (arg0: string) => void }) => {\n        stream.log(' ');\n        stream.log('Have a great day!');\n        stream.log(' ');\n      });\n\n      push.accept();\n    });\n\n    repos.listen(port);\n\n    await wrapCallback((callback: () => void) => {\n      repos.create('doom', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      fs.writeFile(srcDir + '/a.txt', 'abcd', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => {\n        expect(code).toBe(0);\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      spawn('git', ['commit', '-m', 'a!!'], { cwd: srcDir }).on('exit', () => {\n        callback();\n      });\n    });\n    await wrapCallback((callback: () => void) => {\n      const logs: any[] = [];\n      const push = spawn(\n        'git',\n        ['push', 'http://localhost:' + port + '/doom.git', 'master'],\n        { cwd: srcDir }\n      );\n\n      push.stdout.on('data', (data) => {\n        if (data.toString() !== '') {\n          logs.push(data.toString());\n        }\n      });\n\n      push.stderr.on('data', (data) => {\n        if (data.toString() !== '') {\n          logs.push(data.toString());\n        }\n      });\n\n      push.on('exit', () => {\n        expect(\n          logs.join(' ').indexOf('remote: Have a great day!') > -1\n        ).toBeTruthy();\n        callback();\n      });\n    });\n    repos.close();\n  });\n});\n"
  },
  {
    "path": "src/git.ts",
    "content": "import fs from 'fs';\n\nimport path from 'path';\nimport http, { ServerOptions } from 'http';\nimport https from 'https';\nimport url from 'url';\nimport qs from 'querystring';\nimport { HttpDuplex } from './http-duplex';\n\nimport { spawn } from 'child_process';\nimport { EventEmitter } from 'events';\n\nimport {\n  parseGitName,\n  createAction,\n  infoResponse,\n  basicAuth,\n  noCache,\n} from './util';\nimport { ServiceString } from './types';\n\nconst services = ['upload-pack', 'receive-pack'];\n\ninterface GitServerOptions extends ServerOptions {\n  type: 'http' | 'https';\n}\n\nexport interface GitOptions {\n  autoCreate?: boolean;\n  authenticate?: (\n    options: GitAuthenticateOptions,\n    callback: (error?: Error) => void | undefined\n  ) => void | Promise<Error | undefined | void> | undefined;\n  checkout?: boolean;\n}\n\nexport interface GitAuthenticateOptions {\n  type: string;\n  repo: string;\n  user: (() => Promise<[string | undefined, string | undefined]>) &\n    ((\n      callback: (\n        username?: string | undefined,\n        password?: string | undefined\n      ) => void\n    ) => void);\n  headers: http.IncomingHttpHeaders;\n}\n\n/**\n * An http duplex object (see below) with these extra properties:\n */\nexport interface TagData extends HttpDuplex {\n  repo: string; // The string that defines the repo\n  commit: string; // The string that defines the commit sha\n  version: string; // The string that defines the tag being pushed\n}\n\n/**\n * Is a http duplex object (see below) with these extra properties\n */\nexport interface PushData extends HttpDuplex {\n  repo: string; // The string that defines the repo\n  commit: string; // The string that defines the commit sha\n  branch: string; // The string that defines the branch\n}\n\n/**\n * an http duplex object (see below) with these extra properties\n */\nexport interface FetchData extends HttpDuplex {\n  repo: string; // The string that defines the repo\n  commit: string; //  The string that defines the commit sha\n}\n\n/**\n * an http duplex object (see below) with these extra properties\n */\nexport interface InfoData extends HttpDuplex {\n  repo: string; // The string that defines the repo\n}\n\n/**\n * an http duplex object (see below) with these extra properties\n */\nexport interface HeadData extends HttpDuplex {\n  repo: string; // The string that defines the repo\n}\n\nexport interface GitEvents {\n  /**\n   * @example\n   * repos.on('push', function (push) { ... }\n   *\n   * Emitted when somebody does a `git push` to the repo.\n   *\n   * Exactly one listener must call `push.accept()` or `push.reject()`. If there are\n   * no listeners, `push.accept()` is called automatically.\n   **/\n  on(event: 'push', listener: (push: PushData) => void): this;\n\n  /**\n   * @example\n   * repos.on('tag', function (tag) { ... }\n   *\n   * Emitted when somebody does a `git push --tags` to the repo.\n   * Exactly one listener must call `tag.accept()` or `tag.reject()`. If there are\n   * No listeners, `tag.accept()` is called automatically.\n   **/\n  on(event: 'tag', listener: (tag: TagData) => void): this;\n\n  /**\n   * @example\n   * repos.on('fetch', function (fetch) { ... }\n   *\n   * Emitted when somebody does a `git fetch` to the repo (which happens whenever you\n   * do a `git pull` or a `git clone`).\n   *\n   * Exactly one listener must call `fetch.accept()` or `fetch.reject()`. If there are\n   * no listeners, `fetch.accept()` is called automatically.\n   **/\n  on(event: 'fetch', listener: (fetch: FetchData) => void): this;\n\n  /**\n   * @example\n   * repos.on('info', function (info) { ... }\n   *\n   * Emitted when the repo is queried for info before doing other commands.\n   *\n   * Exactly one listener must call `info.accept()` or `info.reject()`. If there are\n   * no listeners, `info.accept()` is called automatically.\n   **/\n  on(event: 'info', listener: (info: InfoData) => void): this;\n\n  /**\n   * @example\n   * repos.on('head', function (head) { ... }\n   *\n   * Emitted when the repo is queried for HEAD before doing other commands.\n   *\n   * Exactly one listener must call `head.accept()` or `head.reject()`. If there are\n   * no listeners, `head.accept()` is called automatically.\n   *\n   **/\n  on(event: 'head', listener: (head: HeadData) => void): this;\n}\nexport class Git extends EventEmitter implements GitEvents {\n  dirMap: (dir?: string) => string;\n\n  authenticate:\n    | ((\n        options: GitAuthenticateOptions,\n        callback: (error?: Error) => void | undefined\n      ) => void | Promise<Error | undefined | void> | undefined)\n    | undefined;\n\n  autoCreate: boolean;\n  checkout: boolean | undefined;\n  server: https.Server | http.Server | undefined;\n\n  /**\n   *\n   * Handles invoking the git-*-pack binaries\n   * @param  repoDir   - Create a new repository collection from the directory `repoDir`. `repoDir` should be entirely empty except for git repo directories. If `repoDir` is a function, `repoDir(repo)` will be used to dynamically resolve project directories. The return value of `repoDir(repo)` should be a string path specifying where to put the string `repo`. Make sure to return the same value for `repo` every time since `repoDir(repo)` will be called multiple times.\n   * @param  options - options that can be applied on the new instance being created\n   * @param  options.autoCreate - By default, repository targets will be created if they don't exist. You can\n   disable that behavior with `options.autoCreate = true`\n   * @param  options.authenticate - a function that has the following arguments ({ type, repo, username, password, headers }, next) and will be called when a request comes through if set\n   *\n     authenticate: ({ type, repo, username, password, headers }, next) => {\n       console.log(type, repo, username, password);\n       next();\n     }\n     // alternatively you can also pass authenticate a promise\n     authenticate: ({ type, repo, username, password, headers }, next) => {\n       console.log(type, repo, username, password);\n       return new Promise((resolve, reject) => {\n        if(username === 'foo') {\n          return resolve();\n        }\n        return reject(\"sorry you don't have access to this content\");\n       });\n     }\n   * @param  options.checkout - If `opts.checkout` is true, create and expected checked-out repos instead of bare repos\n  */\n  constructor(\n    repoDir: string | ((dir?: string) => string),\n    options: GitOptions = {}\n  ) {\n    super();\n\n    if (typeof repoDir === 'function') {\n      this.dirMap = repoDir;\n    } else {\n      this.dirMap = (dir?: string): string => {\n        return path.normalize(\n          (dir ? path.join(repoDir, dir) : repoDir) as string\n        );\n      };\n    }\n\n    if (options.authenticate) {\n      this.authenticate = options.authenticate;\n    }\n\n    this.autoCreate = options.autoCreate === false ? false : true;\n    this.checkout = options.checkout;\n  }\n  /**\n   * Get a list of all the repositories\n   * @param  {Function} callback function to be called when repositories have been found `function(error, repos)`\n   */\n  list(callback: (error: Error | undefined, repos?: string[]) => void): void;\n  list(): Promise<string[]>;\n  list(\n    callback?: (error: Error | undefined, repos?: string[]) => void\n  ): Promise<string[]> | void {\n    const execf = (res: (repos: string[]) => void, rej: (err: Error) => void) =>\n      fs.readdir(this.dirMap(), (error, results) => {\n        if (error) return rej(error);\n        const repos = results.filter((r) => {\n          return r.substring(r.length - 3, r.length) == 'git';\n        }, []);\n\n        res(repos);\n      });\n    if (callback)\n      return execf(\n        (repos) => callback(void 0, repos),\n        (err) => callback(err, void 0)\n      );\n    else return new Promise<string[]>((res, rej) => execf(res, rej));\n  }\n  /**\n   * Find out whether `repoName` exists in the callback `cb(exists)`.\n   * @param  repo - name of the repo\n   * @param  callback - function to be called when finished\n   */\n  exists(repo: string): boolean {\n    return fs.existsSync(this.dirMap(repo));\n  }\n  /**\n   * Create a subdirectory `dir` in the repo dir with a callback.\n   * @param  dir - directory name\n   * @param  callback  - callback to be called when finished\n   */\n  mkdir(dir: string) {\n    fs.mkdirSync(path.dirname(dir), { recursive: true });\n  }\n  /**\n   * Create a new bare repository `repoName` in the instance repository directory.\n   * @param  repo - the name of the repo\n   * @param  callback - Optionally get a callback `cb(err)` to be notified when the repository was created.\n   */\n  create(repo: string, callback: (error?: Error) => void) {\n    function next(self: Git) {\n      let ps;\n      let _error = '';\n\n      const dir = self.dirMap(repo);\n\n      if (self.checkout) {\n        ps = spawn('git', ['init', dir]);\n      } else {\n        ps = spawn('git', ['init', '--bare', dir]);\n      }\n\n      ps.stderr.on('data', function (chunk: string) {\n        _error += chunk;\n      });\n\n      ps.on('exit', (code) => {\n        if (!callback) {\n          return;\n        } else if (code) {\n          callback(new Error(_error));\n        } else {\n          callback();\n        }\n      });\n    }\n\n    if (typeof callback !== 'function')\n      callback = () => {\n        return;\n      };\n\n    if (!/\\.git$/.test(repo)) repo += '.git';\n\n    const exists = this.exists(repo);\n\n    if (!exists) {\n      this.mkdir(repo);\n    }\n\n    next(this);\n  }\n  /**\n   * returns the typeof service being process. This will respond with either fetch or push.\n   * @param  service - the service type\n   */\n  getType(service: string): string {\n    switch (service) {\n      case 'upload-pack':\n        return 'fetch';\n      case 'receive-pack':\n        return 'push';\n      default:\n        return 'unknown';\n    }\n  }\n\n  /**\n   * Handle incoming HTTP requests with a connect-style middleware\n   * @param  http request object\n   * @param  http response object\n   */\n  handle(req: http.IncomingMessage, res: http.ServerResponse) {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const self = this;\n\n    const handlers = [\n      (req: http.IncomingMessage, res: http.ServerResponse) => {\n        if (req.method !== 'GET') return false;\n\n        // eslint-disable-next-line @typescript-eslint/no-this-alias\n        const u = url.parse(req?.url || '');\n        const m = u.pathname?.match(/\\/(.+)\\/info\\/refs$/);\n        if (!m) return false;\n        if (/\\.\\./.test(m[1])) return false;\n\n        const repo = m[1];\n        const params = qs.parse(u?.query || '');\n        if (!params.service || typeof params.service !== 'string') {\n          res.statusCode = 400;\n          res.end('service parameter required');\n          return;\n        }\n\n        const service = params.service.replace(/^git-/, '');\n\n        if (services.indexOf(service) < 0) {\n          res.statusCode = 405;\n          res.end('service not available');\n          return;\n        }\n\n        const repoName = parseGitName(m[1]);\n        const next = (error?: Error | void) => {\n          if (error) {\n            res.setHeader('Content-Type', 'text/plain');\n            res.setHeader(\n              'WWW-Authenticate',\n              'Basic realm=\"authorization needed\"'\n            );\n            res.writeHead(401);\n            res.end(typeof error === 'string' ? error : error.toString());\n            return;\n          } else {\n            return infoResponse(this, repo, service as ServiceString, req, res);\n          }\n        };\n\n        // check if the repo is authenticated\n        if (this.authenticate) {\n          const type = this.getType(service);\n          const headers = req.headers;\n          const user = (\n            callback?: (username?: string, password?: string) => void\n          ) =>\n            callback\n              ? basicAuth(req, res, callback)\n              : new Promise<[string | undefined, string | undefined]>(\n                  (resolve) => basicAuth(req, res, (u, p) => resolve([u, p]))\n                );\n\n          const promise = this.authenticate(\n            {\n              type,\n              repo: repoName,\n              user: user as unknown as GitAuthenticateOptions['user'],\n              headers,\n            },\n            (error?: Error) => {\n              return next(error);\n            }\n          );\n\n          if (promise instanceof Promise) {\n            return promise.then(next).catch(next);\n          }\n        } else {\n          return next();\n        }\n      },\n      (req: http.IncomingMessage, res: http.ServerResponse) => {\n        if (req.method !== 'GET') return false;\n\n        const u = url.parse(req.url || '');\n        const m = u.pathname?.match(/^\\/(.+)\\/HEAD$/);\n        if (!m) return false;\n        if (/\\.\\./.test(m[1])) return false;\n\n        const repo = m[1];\n\n        const next = () => {\n          const file = this.dirMap(path.join(m[1], 'HEAD'));\n          const exists = this.exists(file);\n\n          if (exists) {\n            fs.createReadStream(file).pipe(res);\n          } else {\n            res.statusCode = 404;\n            res.end('not found');\n          }\n        };\n\n        const exists = this.exists(repo);\n        const anyListeners = self.listeners('head').length > 0;\n        const dup = new HttpDuplex(req, res);\n        dup.exists = exists;\n        dup.repo = repo;\n        dup.cwd = this.dirMap(repo);\n\n        dup.accept = dup.emit.bind(dup, 'accept');\n        dup.reject = dup.emit.bind(dup, 'reject');\n\n        dup.once('reject', (code: number) => {\n          dup.statusCode = code || 500;\n          dup.end();\n        });\n\n        if (!exists && self.autoCreate) {\n          dup.once('accept', (dir: string) => {\n            self.create(dir || repo, next);\n          });\n          self.emit('head', dup);\n          if (!anyListeners) dup.accept();\n        } else if (!exists) {\n          res.statusCode = 404;\n          res.setHeader('content-type', 'text/plain');\n          res.end('repository not found');\n        } else {\n          dup.once('accept', next);\n          self.emit('head', dup);\n          if (!anyListeners) dup.accept();\n        }\n      },\n      (req: http.IncomingMessage, res: http.ServerResponse) => {\n        if (req.method !== 'POST') return false;\n        const m = req.url?.match(/\\/(.+)\\/git-(.+)/);\n        if (!m) return false;\n        if (/\\.\\./.test(m[1])) return false;\n\n        const repo = m[1],\n          service = m[2];\n\n        if (services.indexOf(service) < 0) {\n          res.statusCode = 405;\n          res.end('service not available');\n          return;\n        }\n\n        res.setHeader(\n          'content-type',\n          'application/x-git-' + service + '-result'\n        );\n        noCache(res);\n\n        const action = createAction(\n          {\n            repo: repo,\n            service: service as ServiceString,\n            cwd: self.dirMap(repo),\n          },\n          req,\n          res\n        );\n\n        action.on('header', () => {\n          const evName = action.evName;\n          if (evName) {\n            const anyListeners = self.listeners(evName).length > 0;\n            self.emit(evName, action);\n            if (!anyListeners) action.accept();\n          }\n        });\n      },\n      (req: http.IncomingMessage, res: http.ServerResponse) => {\n        if (req.method !== 'GET' && req.method !== 'POST') {\n          res.statusCode = 405;\n          res.end('method not supported');\n        } else {\n          return false;\n        }\n      },\n      (req: http.IncomingMessage, res: http.ServerResponse) => {\n        res.statusCode = 404;\n        res.end('not found');\n      },\n    ];\n    res.setHeader('connection', 'close');\n\n    (function next(ix) {\n      const x = handlers[ix].call(self, req, res);\n      if (x === false) next(ix + 1);\n    })(0);\n  }\n  /**\n   * starts a git server on the given port\n   * @param  port  - the port to start the server on\n   * @param  options  - the options to add extended functionality to the server\n   * @param  options.type - this is either https or http (the default is http)\n   * @param  options.key - private key in PEM format for the https server\n   * @param  options.cert - cert chains in PEM format for the https server\n   * @param  callback - the function to call when server is started or error has occurred\n   */\n  listen(port: number, options?: GitServerOptions, callback?: () => void): Git {\n    if (!options) {\n      options = { type: 'http' };\n    }\n\n    const createServer =\n      options.type == 'http'\n        ? http.createServer\n        : https.createServer.bind(this, options);\n\n    this.server = createServer((req, res) => {\n      this.handle(req, res);\n    });\n\n    this.server.listen(port, callback);\n\n    return this;\n  }\n  /**\n   * closes the server instance\n   * @param will resolve or reject when the server closes or fails to close.\n   */\n  close(): Promise<string> {\n    return new Promise<string>((resolve, reject) => {\n      this.server?.close((err) => {\n        err ? reject(err) : resolve('Success');\n      });\n    });\n  }\n}\n"
  },
  {
    "path": "src/http-duplex.test.ts",
    "content": "import { HttpDuplex } from './http-duplex';\nimport http, { Server } from 'http';\nimport fetch from 'node-fetch';\nimport { readFileSync } from 'fs';\nimport { AddressInfo } from 'net';\n\n// eslint-disable-next-line no-undef\nconst selfSrc = readFileSync(__filename);\n\ndeclare global {\n  interface Object {\n    serialize(): string;\n    filterKeys(keys: string): object;\n  }\n  interface String {\n    format(...args: any[]): string;\n    streamlineLineEndings(ending?: string): string;\n    streamlineSpace(): string;\n    streamline(ending?: string): string;\n  }\n}\n\nObject.prototype.serialize = (): string => {\n  return JSON.stringify(this, null, 4);\n};\n\nObject.prototype.filterKeys = function (key: string) {\n  Object.keys(this).forEach((i) => {\n    if (i == key) delete (this as any)[i];\n  });\n\n  return this;\n};\n\nString.prototype.format = function () {\n  // eslint-disable-next-line prefer-rest-params\n  const args = Array.from(arguments);\n  return this.replace(/{(\\d+)}/g, function (match, number) {\n    return typeof args[number] != 'undefined' ? args[number] : match;\n  });\n};\n\nString.prototype.streamlineLineEndings = function (ending = '\\n') {\n  return this.replace(/[\\r\\n,\\r,\\n]+/g, ending);\n};\n\nString.prototype.streamlineSpace = function () {\n  return this.replace(/[\\f\\t\\v ]{2,}/g, ' ');\n};\n\nString.prototype.streamline = function (ending = '\\n') {\n  return this.streamlineSpace().streamlineLineEndings(ending);\n};\n\ndescribe('http-duplex', () => {\n  let server: Server;\n\n  beforeEach(() => {\n    console.log('create server');\n    server = http.createServer(function (req, res) {\n      const dup = new HttpDuplex(req, res);\n      console.log(dup.method + ' ' + dup.url); // eslint-disable-line\n      switch (dup.url) {\n        case '/':\n          dup.setHeader('content-type', 'text/plain');\n          if (dup.method === 'POST') {\n            dup.end(dup.headers['content-length']);\n          } else {\n            dup.end(readFileSync(__filename));\n          }\n          break;\n        case '/info':\n          if (dup.method == 'GET') {\n            dup.setHeader('content-type', 'text/plain');\n            const output = (\n              'Method: {0}\\n' +\n              'Path: {1}\\n' +\n              'Status: {2}\\n' +\n              'Http Version 1: {3}\\n' +\n              'Http Version 2: {4}\\n' +\n              'Headers: \\n{5}\\n' +\n              'Trailers: {6}\\n' +\n              'Complete: {7}\\n' +\n              'Readable: {8}\\n' +\n              'Writeable: {9}\\n' +\n              'Connection: {10}\\n' +\n              'Socket: {11}\\n'\n            ).format(\n              dup.method,\n              dup.url,\n              dup.statusCode,\n              dup.httpVersion,\n              '{0}.{1}'.format(dup.httpVersionMajor, dup.httpVersionMinor),\n              JSON.stringify(dup.headers),\n              JSON.stringify(dup.trailers),\n              dup.complete,\n              dup.readable,\n              dup.writable,\n              dup.connection,\n              dup.socket\n            );\n            dup.end(output.streamline());\n          } else {\n            dup.statusCode = 400;\n            dup.end('Bad Request');\n          }\n          break;\n        default:\n          dup.statusCode = 404;\n          dup.end(\"File doesn't exist\");\n          break;\n      }\n    });\n    server.listen();\n  });\n\n  afterEach(() => {\n    server.close();\n  });\n\n  test('should be able to handle requests', async () => {\n    expect.assertions(3);\n\n    await new Promise((resolve) => {\n      server.on('error', (e) => {\n        console.log('error', e);\n      });\n\n      server.on('listening', async function () {\n        const { port } = server.address() as AddressInfo;\n\n        const u = `http://localhost:${port}/`;\n        const response = await fetch(u);\n        const body = await response.text();\n\n        expect(String(body)).toBe(String(selfSrc));\n\n        const response1 = await fetch(u, {\n          method: 'POST',\n          body: 'beep boop\\n',\n          headers: { 'Content-Type': 'text/plain' },\n        });\n        const body1 = await response1.text();\n        expect(body1).toBe('10');\n\n        const response2 = await fetch(u + 'info');\n        const body2 = await response2.text();\n\n        expect(String(body2.streamline())).toMatchInlineSnapshot(`\n          \"Method: GET\n          Path: /info\n          Status: 200\n          Http Version 1: 1.1\n          Http Version 2: 1.1\n          Headers: \n          {\\\\\"accept\\\\\":\\\\\"*/*\\\\\"\n          \\\\\"user-agent\\\\\":\\\\\"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)\\\\\"\n          \\\\\"accept-encoding\\\\\":\\\\\"gzip\n          deflate\\\\\"\n          \\\\\"connection\\\\\":\\\\\"close\\\\\"\n          \\\\\"host\\\\\":\\\\\"localhost:${port}\\\\\"}\n          Trailers: {}\n          Complete: false\n          Readable: true\n          Writeable: true\n          Connection: [object Object]\n          Socket: [object Object]\n          \"\n        `);\n        resolve('passed');\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "src/http-duplex.ts",
    "content": "import http from 'http';\nimport EventEmitter from 'events';\n\nexport class HttpDuplex extends EventEmitter {\n  setHeader(arg0: string, arg1: string) {\n    throw new Error('Method not implemented.');\n  }\n  end(reason?: any) {\n    throw new Error('Method not implemented.');\n  }\n  destroy() {\n    throw new Error('Method not implemented.');\n  }\n  accept() {\n    throw new Error('Method not implemented.');\n  }\n  reject(code: number, msg: string) {\n    throw new Error('Method not implemented.');\n  }\n\n  /**\n   * A IncomingMessage created by http.Server or http.ClientRequest usually passed as the\n   * first parameter to the 'request' and 'response' events. Implements Readable Stream interface\n   * but may not be a decendant thereof.\n   * @see {@link https://nodejs.org/api/http.html#http_event_request|request}\n   * @see {@link https://nodejs.org/api/http.html#http_class_http_incomingmessage|http.IncomingMessage}\n   *\n   */\n  req: http.IncomingMessage;\n\n  /**\n   * Created http.server. Passed as the second parameter to the 'request' event.\n   * The response implements Writable Stream interface but isn't a descendent thereof.\n   * @see {@link https://nodejs.org/api/http.html#http_event_request|request}\n   * @see {@link https://nodejs.org/api/http.html#http_class_http_serverresponse|http.ServerResponse}\n   */\n  res: http.ServerResponse;\n  cwd: string | undefined;\n  repo: string | undefined;\n  exists: boolean | undefined;\n\n  /**\n   * Constructs a proxy object over input and output resulting in a unified stream.\n   * Generally meant to combine request and response streams in the http.request event\n   * @see {@link https://nodejs.org/api/http.html#http_event_request|request}\n   * @see {@link https://nodejs.org/api/http.html#http_class_http_incomingmessage|http.IncomingMessage}\n   * @see {@link https://nodejs.org/api/http.html#http_class_http_serverresponse|http.ServerResponse}\n   * @example <caption> A simple example is shown below </caption>\n\n    ```js\n    http.createServer(function (req, res) {\n        var dup = new HttpDuplex(req, res);\n        res.end(\"Request: \" + req.method + \" \" + req.url);\n    }).listen(80);\n    ```\n   */\n  constructor(input: http.IncomingMessage, output: http.ServerResponse) {\n    super();\n\n    this.req = input;\n    this.res = output;\n\n    // request / input proxy events\n    ['data', 'end', 'error', 'close'].forEach((name) => {\n      this.req.on(name, this.emit.bind(this, name));\n    });\n\n    // respone / output proxy events\n    ['error', 'drain'].forEach((name) => {\n      this.res.on(name, this.emit.bind(this, name));\n    });\n  }\n\n  get complete() {\n    return this.req.complete;\n  }\n\n  /**\n   * Reference to the underlying socket for the request connection.\n   * @readonly\n   * @see {@link https://nodejs.org/api/http.html#http_request_socket|request.Socket}\n   */\n  get connection() {\n    return this.req.connection;\n  }\n\n  /**\n   * Request/response headers. Key-value pairs of header names and values. Header names are always lower-case.\n   * @readonly\n   * @see {@link https://nodejs.org/api/http.html#http_message_headers|message.headers}\n   */\n  get headers() {\n    return this.req.headers;\n  }\n\n  /**\n   * Requested HTTP Version sent by the client. Usually either '1.0' or '1.1'\n   * @see {@link https://nodejs.org/api/http.html#http_message_httpversion|message.httpVersion}\n   * @readonly\n   */\n  get httpVersion() {\n    return this.req.httpVersion;\n  }\n\n  /**\n   * First integer in the httpVersion string\n   * @see httpVersion\n   * @readonly\n   */\n  get httpVersionMajor() {\n    return this.req.httpVersionMajor;\n  }\n\n  /**\n   * Second integer ni the httpVersion string\n   * @see httpVersion\n   * @readonly\n   */\n  get httpVersionMinor() {\n    return this.req.httpVersionMinor;\n  }\n\n  /**\n   * Request method of the incoming request.\n   * @see {@link https://nodejs.org/api/http.html#http_event_request|request}\n   * @see {@link https://nodejs.org/api/http.html#http_class_http_serverresponse|http.ServerResponse}\n   * @example 'GET', 'DELETE'\n   * @readonly\n   */\n  get method() {\n    return this.req.method;\n  }\n\n  /**\n   * Is this stream readable.\n   * @readonly\n   */\n  get readable() {\n    return this.req.readable;\n  }\n\n  /**\n   * net.Socket object associated with the connection.\n   * @see {@link https://nodejs.org/api/net.html#net_class_net_socket|net.Socket}\n   * @readonly\n   */\n  get socket() {\n    return this.req.socket;\n  }\n\n  /**\n   * The HTTP status code. Generally assigned before sending headers for a response to a client.\n   * @see {@link https://nodejs.org/api/http.html#http_response_statuscode|response.statusCode}\n   * @example request.statusCode = 404;\n   */\n  get statusCode() {\n    return this.res.statusCode;\n  }\n\n  set statusCode(val) {\n    this.res.statusCode = val;\n  }\n\n  /**\n   * Controls the status message sent to the client as long as an explicit call to response.writeHead() isn't made\n   * If ignored or the value is undefined, the default message corresponding to the status code will be used.\n   * @see {@link https://nodejs.org/api/http.html#http_response_statusmessage|response.statusMessage}\n   * @example request.statusMessage = 'Document Not found';\n   */\n  get statusMessage() {\n    return this.res.statusMessage;\n  }\n\n  set statusMessage(val) {\n    this.res.statusMessage = val;\n  }\n\n  /**\n   * Request/response trailer headers. Just like {@link headers} except these are only written\n   * after the initial response to the client.\n   * This object is only populated at the 'end' event and only work if a 'transfer-encoding: chunked'\n   * header is sent in the initial response.\n   * @readonly\n   * @see headers\n   * @see addTrailers\n   * @see {@link https://nodejs.org/api/http.html#http_message_trailers|message.trailers}\n   * @see {@link https://nodejs.org/api/http.html#http_response_addtrailers_headers|response.addTrailers}\n   */\n  get trailers() {\n    return this.req.trailers;\n  }\n\n  /**\n   * Request URL string.\n   * @example <caption>A request made as:</caption>\n   * GET /info?check=none HTTP/1.1\n   * @example <caption>Will return the string</caption>\n   * '/info?check=none'\n   * @readonly\n   */\n  get url() {\n    return this.req.url;\n  }\n\n  // output / response wrapping\n  get writable() {\n    return this.res.writable;\n  }\n\n  /**\n   * Sends a response header to the client request. Must only be called one time and before calling response.end().\n   * @param statusCode 3-digit HTTP status code, like 404\n   * @param statusMessage - An optional human readable status message to send with the status code\n   * @param headers - An object containing the response headers to send\n   * @see {@link https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers|response.writeHead}\n   * @example var content = 'Under Construction...';\n   * response.writeHead(200, {\n   *     'Content-Length': Buffer.byteLength(content),\n   *     'Content-Type': 'text/plain'\n   * });\n   * response.end(content);\n   */\n  writeHead(statusCode: number, statusMessage: string, headers: string[]) {\n    this.res.writeHead(statusCode, statusMessage, headers);\n    return this;\n  }\n\n  /**\n   * Buffers written data in memory. This data will be flushed when either the uncork or end methods are called.\n   * @see uncork\n   * @see {@link https://nodejs.org/api/stream.html#stream_writable_cork|stream.Writeable.cork}\n   * @example\n   * request.cork();\n   * request.write('buffer data ');\n   * request.write('before sending ');\n   * request.uncork();\n   */\n  cork() {\n    this.res.socket?.cork();\n    return this;\n  }\n\n  /**\n   * Flushes all data buffered since cork() was called.\n   * @see cork\n   * @see {@link https://nodejs.org/api/stream.html#stream_writable_uncork|stream.Writeable.uncork}\n   */\n  uncork() {\n    this.res.socket?.uncork();\n    return this;\n  }\n}\n\n// proxy request methods\n['pause', 'resume', 'setEncoding'].forEach(function (name) {\n  (HttpDuplex.prototype as any)[name] = function () {\n    // eslint-disable-next-line prefer-rest-params\n    return (this.req as any)[name].apply(this.req, Array.from(arguments));\n  };\n});\n\n// proxy respone methods\n[\n  'setDefaultEncoding',\n  'write',\n  'end',\n  'flush',\n  'writeHeader',\n  'writeContinue',\n  'setHeader',\n  'getHeader',\n  'removeHeader',\n  'addTrailers',\n].forEach(function (name) {\n  (HttpDuplex.prototype as any)[name] = function () {\n    // eslint-disable-next-line prefer-rest-params\n    return (this.res as any)[name].apply(this.res, Array.from(arguments));\n  };\n});\n\n/**\n * Destroys object and it's bound streams\n */\nHttpDuplex.prototype.destroy = function () {\n  this.req.destroy();\n  this.res.destroy();\n};\n"
  },
  {
    "path": "src/index.ts",
    "content": "export * from './git';\nexport * from './http-duplex';\nexport * from './service';\nexport * from './types';\nexport * from './util';\n"
  },
  {
    "path": "src/service.ts",
    "content": "import http from 'http';\nimport zlib from 'zlib';\nimport through from 'through';\nimport util from 'util';\nimport os from 'os';\nimport { spawn } from 'child_process';\n\nimport { HttpDuplex } from './http-duplex';\nimport { ServiceString } from './types';\nimport { packSideband } from './util';\n\nconst headerRegex: { [key: string]: string } = {\n  'receive-pack': '([0-9a-fA-F]+) ([0-9a-fA-F]+) refs\\/(heads|tags)\\/(.*?)( |00|\\u0000)|^(0000)$', // eslint-disable-line\n  'upload-pack': '^\\\\S+ ([0-9a-fA-F]+)',\n};\n\nconst decoder: { [key: string]: () => zlib.Gunzip | zlib.Deflate } = {\n  gzip: (): zlib.Gunzip => zlib.createGunzip(),\n  deflate: (): zlib.Deflate => zlib.createDeflate(),\n};\nexport interface ServiceOptions {\n  repo: string;\n  cwd: string;\n  service: ServiceString;\n}\n\nexport class Service extends HttpDuplex {\n  status: string;\n  repo: string;\n  service: string;\n  cwd: string;\n  logs: string[];\n  last: string | undefined;\n  commit: string | undefined;\n  evName: string | undefined;\n  username: string | undefined;\n\n  /**\n   * Handles invoking the git-*-pack binaries\n   * @param  opts - options to bootstrap the service object\n   * @param  req  - http request object\n   * @param  res  - http response\n   */\n  constructor(\n    opts: ServiceOptions,\n    req: http.IncomingMessage,\n    res: http.ServerResponse\n  ) {\n    super(req, res);\n\n    let data = '';\n\n    this.status = 'pending';\n    this.repo = opts.repo;\n    this.service = opts.service;\n    this.cwd = opts.cwd;\n    this.logs = [];\n\n    const buffered = through().pause();\n\n    // stream needed to receive data after decoding, but before accepting\n    const ts = through();\n\n    const encoding = req.headers['content-encoding'];\n\n    if (encoding && decoder[encoding]) {\n      // data is compressed with gzip or deflate\n      req.pipe(decoder[encoding]()).pipe(ts).pipe(buffered);\n    } else {\n      // data is not compressed\n      req.pipe(ts).pipe(buffered);\n    }\n\n    if (req.headers['authorization']) {\n      const tokens = req.headers['authorization'].split(' ');\n      if (tokens[0] === 'Basic') {\n        const splitHash = Buffer.from(tokens[1], 'base64')\n          .toString('utf8')\n          .split(':');\n        this.username = splitHash.shift();\n      }\n    }\n\n    ts.once('data', (chunk: string) => {\n      data += chunk;\n\n      const ops = data.match(new RegExp(headerRegex[this.service], 'gi'));\n      if (!ops) return;\n      data = '';\n\n      ops.forEach((op) => {\n        let type;\n        const m = op.match(new RegExp(headerRegex[this.service]));\n\n        if (!m) return;\n\n        if (this.service === 'receive-pack') {\n          this.last = m[1];\n          this.commit = m[2];\n\n          if (m[3] == 'heads') {\n            type = 'branch';\n            this.evName = 'push';\n          } else {\n            type = 'version';\n            this.evName = 'tag';\n          }\n\n          const headers: { [key: string]: string } = {\n            last: this.last,\n            commit: this.commit,\n          };\n          headers[type] = (this as any)[type] = m[4];\n          this.emit('header', headers);\n        } else if (this.service === 'upload-pack') {\n          this.commit = m[1];\n          this.evName = 'fetch';\n          this.emit('header', {\n            commit: this.commit,\n          });\n        }\n      });\n    });\n\n    this.once('accept', () => {\n      process.nextTick(() => {\n        const cmd =\n          os.platform() == 'win32'\n            ? ['git', opts.service, '--stateless-rpc', opts.cwd]\n            : ['git-' + opts.service, '--stateless-rpc', opts.cwd];\n\n        const ps = spawn(cmd[0], cmd.slice(1));\n\n        ps.on('error', (error: Error) => {\n          this.emit(\n            'error',\n            new Error(`${error.message} running command ${cmd.join(' ')}`)\n          );\n        });\n\n        this.emit('service', ps);\n\n        const respStream = through(\n          // write\n          (c: any) => {\n            if (this.listeners('response').length === 0) {\n              if (this.logs.length > 0) {\n                while (this.logs.length > 0) {\n                  respStream.queue(this.logs.pop());\n                }\n              }\n\n              return respStream.queue(c);\n            }\n            // prevent git from sending the close signal\n            if (c.length === 4 && c.toString() === '0000') return;\n            respStream.queue(c);\n          },\n          // read\n          () => {\n            if (this.listeners('response').length > 0) return;\n\n            respStream.queue(null);\n          }\n        );\n\n        (respStream as any).log = this.log.bind(this);\n\n        this.emit('response', respStream, function endResponse() {\n          (res as any).queue(Buffer.from('0000'));\n          (res as any).queue(null);\n        });\n\n        ps.stdout.pipe(respStream).pipe(res);\n\n        buffered.pipe(ps.stdin);\n        buffered.resume();\n\n        ps.on('exit', () => {\n          if (this.logs.length > 0) {\n            while (this.logs.length > 0) {\n              respStream.queue(this.logs.pop());\n            }\n            respStream.queue(Buffer.from('0000'));\n            respStream.queue(null);\n          }\n\n          this.emit('exit');\n        });\n      });\n    });\n\n    this.once('reject', function onReject(code: number, msg: string) {\n      res.statusCode = code;\n      res.end(msg);\n    });\n  }\n\n  log() {\n    // eslint-disable-next-line prefer-rest-params\n    const _log = util.format(...arguments);\n    const SIDEBAND = String.fromCharCode(2); // PROGRESS\n    const message = `${SIDEBAND}${_log}\\n`;\n    const formattedMessage = Buffer.from(packSideband(message));\n\n    this.logs.unshift(formattedMessage.toString());\n  }\n  /**\n   * reject request in flight\n   * @param  code - http response code\n   * @param  msg  - message that should be displayed on the client\n   */\n  reject(code: number, msg: string) {\n    if (this.status !== 'pending') return;\n\n    if (msg === undefined && typeof code === 'string') {\n      msg = code;\n      code = 500;\n    }\n    this.status = 'rejected';\n    this.emit('reject', code || 500, msg);\n  }\n  /**\n   * accepts request to access resource\n   */\n  accept() {\n    if (this.status !== 'pending') return;\n\n    this.status = 'accepted';\n    this.emit('accept');\n  }\n}\n"
  },
  {
    "path": "src/types.ts",
    "content": "export type ServiceString = 'upload-pack' | 'receive-pack';\n"
  },
  {
    "path": "src/util.test.ts",
    "content": "import { basicAuth, noCache, parseGitName } from './util';\n\ndescribe('util', () => {\n  describe('basicAuth', () => {\n    test('should send back basic auth headers', async () => {\n      await new Promise((resolve, reject) => {\n        const headers: any = {};\n\n        const req: any = {\n          headers: {},\n        };\n\n        const res: any = {\n          writeHead: function (_code: number) {\n            code = _code;\n          },\n          setHeader: function (key: string | number, value: any) {\n            headers[key] = value;\n          },\n          end: function (_status: number) {\n            status = _status;\n            expect(code).toBe(401);\n            expect(headers).toEqual({\n              'Content-Type': 'text/plain',\n              'WWW-Authenticate': 'Basic realm=\"authorization needed\"',\n            });\n            expect(status).toBe('401 Unauthorized');\n            resolve('passed');\n          },\n        };\n\n        let code = 0;\n        let status = 0;\n\n        basicAuth(req, res, () => {\n          reject('should not have entered this callback');\n        });\n      });\n    });\n\n    test('should accept headers and call callback', async () => {\n      await new Promise((resolve) => {\n        const req: any = {\n          headers: {\n            authorization: 'Basic T3BlbjpTZXNhbWU=',\n          },\n        };\n\n        const res: any = {};\n\n        basicAuth(req, res, (username, password) => {\n          expect(username).toBe('Open');\n          expect(password).toBe('Sesame');\n          resolve('passed');\n        });\n      });\n    });\n  });\n\n  describe('noCache', () => {\n    test('should honor noCache', () => {\n      const headers: any = {\n        'persisted-header': 'I have been here foreveeeerrr',\n      };\n\n      const res: any = {\n        setHeader: function (key: string | number, value: any) {\n          headers[key] = value;\n        },\n      };\n      noCache(res);\n      expect(headers).toEqual({\n        'persisted-header': 'I have been here foreveeeerrr',\n        expires: 'Fri, 01 Jan 1980 00:00:00 GMT',\n        pragma: 'no-cache',\n        'cache-control': 'no-cache, max-age=0, must-revalidate',\n      });\n    });\n  });\n\n  describe('parseGitName', () => {\n    test('should remove .git from repo name', () => {\n      expect(parseGitName('test.git')).toBe('test');\n    });\n\n    test('should remove .git from the end of repo name but not in the middle', () => {\n      expect(parseGitName('test.git.git')).toBe('test.git');\n    });\n\n    test(\"if .git does not exist in the string, don't remove it\", () => {\n      expect(parseGitName('test')).toBe('test');\n    });\n  });\n});\n"
  },
  {
    "path": "src/util.ts",
    "content": "import http from 'http';\nimport { spawn } from 'child_process';\n\nimport { Git } from './git';\nimport { HttpDuplex } from './http-duplex';\nimport { Service, ServiceOptions } from './service';\nimport { ServiceString } from './types';\n\nexport function packSideband(s: string): string {\n  const n = (4 + s.length).toString(16);\n  return Array(4 - n.length + 1).join('0') + n + s;\n}\n\n/**\n * adds headers to the response object to add cache control\n * @param  res  - http response\n */\nexport function noCache(res: http.ServerResponse) {\n  res.setHeader('expires', 'Fri, 01 Jan 1980 00:00:00 GMT');\n  res.setHeader('pragma', 'no-cache');\n  res.setHeader('cache-control', 'no-cache, max-age=0, must-revalidate');\n}\n\n/**\n * sets and parses basic auth headers if they exist\n * @param  req  - http request object\n * @param  res  - http response\n * @param  callback - function(username, password)\n */\nexport function basicAuth(\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  callback: (username?: string, password?: string) => void\n) {\n  if (!req.headers['authorization']) {\n    res.setHeader('Content-Type', 'text/plain');\n    res.setHeader('WWW-Authenticate', 'Basic realm=\"authorization needed\"');\n    res.writeHead(401);\n    res.end('401 Unauthorized');\n  } else {\n    const tokens = req.headers['authorization'].split(' ');\n    if (tokens[0] === 'Basic') {\n      const splitHash = Buffer.from(tokens[1], 'base64')\n        .toString('utf8')\n        .split(':');\n      const username = splitHash.shift();\n      const password = splitHash.join(':');\n\n      callback(username, password);\n    }\n  }\n}\n/**\n * execute given git operation and respond\n * @param  dup  - duplex object to catch errors\n * @param  service - the method that is responding infoResponse (push, pull, clone)\n * @param  repoLocation - the repo path on disk\n * @param  res  - http response\n */\nexport function serviceRespond(\n  dup: HttpDuplex | Git,\n  service: ServiceString,\n  repoLocation: string,\n  res: http.ServerResponse\n) {\n  res.write(packSideband('# service=git-' + service + '\\n'));\n  res.write('0000');\n\n  const isWin = /^win/.test(process.platform);\n\n  const cmd = isWin\n    ? ['git', service, '--stateless-rpc', '--advertise-refs', repoLocation]\n    : ['git-' + service, '--stateless-rpc', '--advertise-refs', repoLocation];\n\n  const ps = spawn(cmd[0], cmd.slice(1));\n\n  ps.on('error', (err) => {\n    dup.emit(\n      'error',\n      new Error(`${err.message} running command ${cmd.join(' ')}`)\n    );\n  });\n  ps.stdout.pipe(res);\n}\n/**\n * sends http response using the appropriate output from service call\n * @param  git     - an instance of git object\n * @param  repo    - the repository\n * @param  service - the method that is responding infoResponse (push, pull, clone)\n * @param  req  - http request object\n * @param  res  - http response\n */\nexport function infoResponse(\n  git: Git,\n  repo: string,\n  service: ServiceString,\n  req: http.IncomingMessage,\n  res: http.ServerResponse\n) {\n  function next() {\n    res.setHeader(\n      'content-type',\n      'application/x-git-' + service + '-advertisement'\n    );\n    noCache(res);\n    serviceRespond(git, service, git.dirMap(repo), res);\n  }\n\n  const dup = new HttpDuplex(req, res);\n  dup.cwd = git.dirMap(repo);\n  dup.repo = repo;\n\n  dup.accept = dup.emit.bind(dup, 'accept');\n  dup.reject = dup.emit.bind(dup, 'reject');\n\n  dup.once('reject', (code: number) => {\n    res.statusCode = code || 500;\n    res.end();\n  });\n\n  const anyListeners = git.listeners('info').length > 0;\n\n  const exists = git.exists(repo);\n  dup.exists = exists;\n\n  if (!exists && git.autoCreate) {\n    dup.once('accept', () => {\n      git.create(repo, next);\n    });\n\n    git.emit('info', dup);\n    if (!anyListeners) dup.accept();\n  } else if (!exists) {\n    res.statusCode = 404;\n    res.setHeader('content-type', 'text/plain');\n    res.end('repository not found');\n  } else {\n    dup.once('accept', next);\n    git.emit('info', dup);\n\n    if (!anyListeners) dup.accept();\n  }\n}\n/**\n * parses a git string and returns the repo name\n * @param  repo - the raw repo name containing .git\n */\nexport function parseGitName(repo: string): string {\n  const locationOfGit = repo.lastIndexOf('.git');\n  return repo.slice(0, locationOfGit > 0 ? locationOfGit : repo.length);\n}\n/**\n * responds with the correct service depending on the action\n * @param  opts - options to pass Service\n * @param  req  - http request object\n * @param  res  - http response\n */\nexport function createAction(\n  opts: ServiceOptions,\n  req: http.IncomingMessage,\n  res: http.ServerResponse\n): Service {\n  const service = new Service(opts, req, res);\n\n  // TODO: see if this works or not\n  // Object.keys(opts).forEach((key) => {\n  //   service[key] = opts[key];\n  // });\n\n  return service;\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"lib\": [\"esnext\"],\n    \"target\": \"es2020\",\n    \"module\": \"commonjs\",\n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"noImplicitAny\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"types\": [\"node\", \"vitest/globals\", \"node-fetch\"],\n    \"allowJs\": true,\n    \"checkJs\": false\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "vitest.config.js",
    "content": "import { defineConfig } from 'vitest/config';\n\nexport default defineConfig({\n  test: {\n    clearMocks: true,\n    globals: true,\n    environment: 'node',\n    testTimeout: 150000,\n  },\n});\n"
  },
  {
    "path": "website/.gitignore",
    "content": "# Dependencies\n/node_modules\n\n# Production\n/build\n\n# Generated files\n.docusaurus\n.cache-loader\n\n# Misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "website/README.md",
    "content": "# Website\n\nThis website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.\n\n### Installation\n\n```\n$ yarn\n```\n\n### Local Development\n\n```\n$ yarn start\n```\n\nThis command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.\n\n### Build\n\n```\n$ yarn build\n```\n\nThis command generates static content into the `build` directory and can be served using any static contents hosting service.\n\n### Deployment\n\n```\n$ GIT_USER=<Your GitHub username> USE_SSH=true yarn deploy\n```\n\nIf you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.\n"
  },
  {
    "path": "website/babel.config.js",
    "content": "/* eslint-disable no-undef */\nmodule.exports = {\n  presets: [require.resolve('@docusaurus/core/lib/babel/preset')],\n};\n"
  },
  {
    "path": "website/docs/intro.md",
    "content": "# Introduction\n\n## Install\n\n```bash\nnpm install node-git-server\n```\n\n## Usage\n\n### Simple\n\n```typescript\nimport { Git } from 'node-git-server';\nimport { join } from 'path';\n\nconst port =\n  !process.env.PORT || isNaN(process.env.PORT)\n    ? 7005\n    : parseInt(process.env.PORT);\n\nconst repos = new Git(join(__dirname, '../repo'), {\n  autoCreate: true,\n});\n\nrepos.on('push', (push) => {\n  console.log(`push ${push.repo}/${push.commit} ( ${push.branch} )`);\n  push.accept();\n});\n\nrepos.on('fetch', (fetch) => {\n  console.log(`fetch ${fetch.commit}`);\n  fetch.accept();\n});\n\nrepos.listen(port, () => {\n  console.log(`node-git-server running at http://localhost:${port}`);\n});\n```\n\nthen start up the node-git-server server...\n\n```bash\n$ node example/index.js\nnode-git-server running at http://localhost:7005\n```\n\nmeanwhile...\n\n```bash\n$ git push http://localhost:7005/beep master\nCounting objects: 356, done.\nDelta compression using up to 2 threads.\nCompressing objects: 100% (133/133), done.\nWriting objects: 100% (356/356), 46.20 KiB, done.\nTotal 356 (delta 210), reused 355 (delta 210)\nTo http://localhost:7005/beep\n * [new branch]      master -> master\n```\n\n### Sending logs\n\n```typescript\nimport { Git } from 'node-git-server';\nimport { join } from 'path';\n\nconst port =\n  !process.env.PORT || isNaN(process.env.PORT)\n    ? 7005\n    : parseInt(process.env.PORT);\n\nconst repos = new Git(join(__dirname, '../repo'), {\n  autoCreate: true,\n});\n\nrepos.on('push', async (push) => {\n  console.log(`push ${push.repo}/${push.commit} ( ${push.branch} )`);\n\n  push.log();\n  push.log('Hey!');\n  push.log('Checkout these other repos:');\n  for (const repo of await repo.list()) {\n    push.log(`- ${repo}`);\n  }\n  push.log();\n  push.accept();\n});\n\nrepos.on('fetch', (fetch) => {\n  console.log(`fetch ${fetch.commit}`);\n  fetch.accept();\n});\n\nrepos.listen(port, () => {\n  console.log(`node-git-server running at http://localhost:${port}`);\n});\n```\n\nthen start up the node-git-server server...\n\n```bash\n$ node example/index.js\nnode-git-server running at http://localhost:7005\n```\n\nmeanwhile...\n\n```bash\n$ git push http://localhost:7005/beep master\nCounting objects: 356, done.\nDelta compression using up to 2 threads.\nCompressing objects: 100% (133/133), done.\nWriting objects: 100% (356/356), 46.20 KiB, done.\nTotal 356 (delta 210), reused 355 (delta 210)\nremote:\nremote: Hey!\nremote: Checkout these other repos:\nremote: - test.git\nremote:\nTo http://localhost:7005/test\n   77bb26e..22918d5  master -> master\n```\n\n#### Authentication\n\n```typescript\nimport { Git } from 'node-git-server';\nimport { join } from 'path';\n\nconst port =\n  !process.env.PORT || isNaN(process.env.PORT)\n    ? 7005\n    : parseInt(process.env.PORT);\n\nconst repos = new Git(join(__dirname, '../repo'), {\n  autoCreate: true,\n  autheficate: ({ type, user }, next) =>\n    type == 'push'\n      ? user(([username, password]) => {\n          console.log(username, password);\n          next();\n        })\n      : next(),\n});\n\nrepos.on('push', (push) => {\n  console.log(`push ${push.repo}/${push.commit} ( ${push.branch} )`);\n  push.accept();\n});\n\nrepos.on('fetch', (fetch) => {\n  console.log(`fetch ${fetch.commit}`);\n  fetch.accept();\n});\n\nrepos.listen(port, () => {\n  console.log(`node-git-server running at http://localhost:${port}`);\n});\n```\n\nthen start up the node-git-server server...\n\n```bash\n$ node example/index.js\nnode-git-server running at http://localhost:7005\n```\n\nmeanwhile...\n\n```bash\n$ git push http://localhost:7005/beep master\nCounting objects: 356, done.\nDelta compression using up to 2 threads.\nCompressing objects: 100% (133/133), done.\nWriting objects: 100% (356/356), 46.20 KiB, done.\nTotal 356 (delta 210), reused 355 (delta 210)\nTo http://localhost:7005/beep\n * [new branch]      master -> master\n```\n\n## Example\n\nRunning the following command will start up a simple http server:\n\n```bash\nnode example/index.js\n```\n\nIf you want to try using https run the following\n\n```bash\nnode example/index.js --https\n```\n\n> When running https with self-signed certs there are two ways to override the git-clients behavior using `git config http.sslVerify false` or `git config --global http.sslCAInfo /path/to/cert.pem`\n\nFor more information please visit the [docs](http://www.gabrielcsapo.com/node-git-server/code/index.html)\n"
  },
  {
    "path": "website/docusaurus.config.js",
    "content": "/* eslint-disable @typescript-eslint/no-var-requires */\n/* eslint-disable no-undef */\n// @ts-check\n// Note: type annotations allow type checking and IDEs autocompletion\n\nconst path = require('path');\nconst lightCodeTheme = require('prism-react-renderer/themes/github');\nconst darkCodeTheme = require('prism-react-renderer/themes/dracula');\n\n/** @type {import('@docusaurus/types').Config} */\nconst config = {\n  title: 'node-git-server',\n  tagline: '🎡 A configurable git server written in Node.js',\n  url: 'https://gabrielcsapo.github.io',\n  baseUrl: '/node-git-server/',\n  onBrokenLinks: 'throw',\n  onBrokenMarkdownLinks: 'warn',\n  favicon: 'img/favicon.ico',\n  organizationName: 'gabrielcsapo',\n  projectName: 'node-git-server',\n  plugins: [\n    [\n      require.resolve('docusaurus-plugin-search-local'),\n      {\n        highlightSearchTermsOnTargetPage: true,\n        docsRouteBasePath: ['docs', 'api'],\n      },\n    ],\n    [\n      'docusaurus-plugin-typedoc-api',\n      {\n        projectRoot: path.join(__dirname, '..'),\n        packages: ['.'],\n      },\n    ],\n  ],\n  presets: [\n    [\n      '@docusaurus/preset-classic',\n      /** @type {import('@docusaurus/preset-classic').Options} */\n      ({\n        docs: {\n          editUrl:\n            'https://github.com/gabrielcsapo/node-git-server/edit/main/website/',\n        },\n        blog: {\n          showReadingTime: true,\n          editUrl:\n            'https://github.com/gabrielcsapo/node-git-server/edit/main/website/blog/',\n        },\n        theme: {\n          customCss: require.resolve('./src/css/custom.css'),\n        },\n      }),\n    ],\n  ],\n\n  themeConfig:\n    /** @type {import('@docusaurus/preset-classic').ThemeConfig} */\n    ({\n      navbar: {\n        title: 'node-git-server',\n        logo: {\n          alt: 'node-git-server logo',\n          src: 'img/apple-touch-icon.png',\n        },\n        items: [\n          {\n            type: 'doc',\n            docId: 'intro',\n            position: 'left',\n            label: 'Documentation',\n          },\n          {\n            to: 'api',\n            label: 'API',\n            position: 'left',\n          },\n          {\n            href: 'https://github.com/gabrielcsapo/node-git-server',\n            label: 'GitHub',\n            position: 'right',\n          },\n        ],\n      },\n      footer: {\n        style: 'dark',\n        links: [\n          {\n            title: 'Docs',\n            items: [\n              {\n                label: 'Getting Started',\n                to: '/docs/intro',\n              },\n            ],\n          },\n          {\n            title: 'More',\n            items: [\n              {\n                label: 'GitHub',\n                href: 'https://github.com/gabrielcsapo/node-git-server',\n              },\n            ],\n          },\n        ],\n        copyright: `Copyright © ${new Date().getFullYear()} node-git-server, Inc. Built with Docusaurus.`,\n      },\n      prism: {\n        theme: lightCodeTheme,\n        darkTheme: darkCodeTheme,\n      },\n    }),\n};\n\nmodule.exports = config;\n"
  },
  {
    "path": "website/package.json",
    "content": "{\n  \"name\": \"node-git-server\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"docusaurus\": \"docusaurus\",\n    \"start\": \"docusaurus start\",\n    \"build\": \"docusaurus build\",\n    \"swizzle\": \"docusaurus swizzle\",\n    \"deploy\": \"docusaurus deploy\",\n    \"clear\": \"docusaurus clear\",\n    \"serve\": \"docusaurus serve\",\n    \"write-translations\": \"docusaurus write-translations\",\n    \"write-heading-ids\": \"docusaurus write-heading-ids\"\n  },\n  \"dependencies\": {\n    \"@docusaurus/core\": \"2.0.1\",\n    \"@docusaurus/preset-classic\": \"2.0.1\",\n    \"docusaurus-plugin-typedoc-api\": \"^2.3.0\",\n    \"@mdx-js/react\": \"^1.6.21\",\n    \"@svgr/webpack\": \"^5.5.0\",\n    \"clsx\": \"^1.1.1\",\n    \"docusaurus-plugin-search-local\": \"^0.8.2\",\n    \"file-loader\": \"^6.2.0\",\n    \"prism-react-renderer\": \"^1.2.1\",\n    \"react\": \"^17.0.1\",\n    \"react-dom\": \"^17.0.1\",\n    \"url-loader\": \"^4.1.1\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.5%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"volta\": {\n    \"node\": \"16.15.1\"\n  }\n}\n"
  },
  {
    "path": "website/src/css/custom.css",
    "content": "/**\n * Any CSS included here will be global. The classic template\n * bundles Infima by default. Infima is a CSS framework designed to\n * work well for content-centric websites.\n */\n\n/* You can override the default Infima variables here. */\n:root {\n  --ifm-color-primary: #25c2a0;\n  --ifm-color-primary-dark: rgb(33, 175, 144);\n  --ifm-color-primary-darker: rgb(31, 165, 136);\n  --ifm-color-primary-darkest: rgb(26, 136, 112);\n  --ifm-color-primary-light: rgb(70, 203, 174);\n  --ifm-color-primary-lighter: rgb(102, 212, 189);\n  --ifm-color-primary-lightest: rgb(146, 224, 208);\n  --ifm-code-font-size: 95%;\n}\n\n.docusaurus-highlight-code-line {\n  background-color: rgba(0, 0, 0, 0.1);\n  display: block;\n  margin: 0 calc(-1 * var(--ifm-pre-padding));\n  padding: 0 var(--ifm-pre-padding);\n}\n\nhtml[data-theme='dark'] .docusaurus-highlight-code-line {\n  background-color: rgba(0, 0, 0, 0.3);\n}\n\n.main-wrapper {\n  display: flex;\n}"
  },
  {
    "path": "website/src/pages/index.js",
    "content": "import React from 'react';\nimport clsx from 'clsx';\nimport Layout from '@theme/Layout';\nimport Link from '@docusaurus/Link';\nimport useDocusaurusContext from '@docusaurus/useDocusaurusContext';\nimport styles from './index.module.css';\n\nfunction HomepageHeader() {\n  const { siteConfig } = useDocusaurusContext();\n  return (\n    <header className={clsx('hero hero--primary', styles.heroBanner)}>\n      <div className=\"container\">\n        <h1 className=\"hero__title\">{siteConfig.title}</h1>\n        <p className=\"hero__subtitle\">{siteConfig.tagline}</p>\n        <div className={styles.buttons}>\n          <Link\n            className=\"button button--secondary button--lg\"\n            to=\"/docs/intro\"\n          >\n            Quick Start\n          </Link>\n        </div>\n      </div>\n    </header>\n  );\n}\n\nexport default function Home() {\n  const { siteConfig } = useDocusaurusContext();\n  return (\n    <Layout\n      title={`Hello from ${siteConfig.title}`}\n      description=\"Description will go into a meta tag in <head />\"\n    >\n      <HomepageHeader />\n    </Layout>\n  );\n}\n"
  },
  {
    "path": "website/src/pages/index.module.css",
    "content": "/**\n * CSS files with the .module.css suffix will be treated as CSS modules\n * and scoped locally.\n */\n\n.heroBanner {\n  padding: 4rem 0;\n  text-align: center;\n  position: relative;\n  overflow: hidden;\n  display: flex;\n  width: 100%;\n  height: 100vh;\n}\n\n@media screen and (max-width: 966px) {\n  .heroBanner {\n    padding: 2rem;\n  }\n}\n\n.buttons {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n"
  },
  {
    "path": "website/static/.nojekyll",
    "content": ""
  }
]