@backstage/integration 1.17.1 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/ScmIntegrations.cjs.js.map +1 -1
  3. package/dist/ScmIntegrations.esm.js.map +1 -1
  4. package/dist/awsCodeCommit/AwsCodeCommitIntegration.cjs.js.map +1 -1
  5. package/dist/awsCodeCommit/AwsCodeCommitIntegration.esm.js.map +1 -1
  6. package/dist/awsCodeCommit/config.cjs.js.map +1 -1
  7. package/dist/awsCodeCommit/config.esm.js.map +1 -1
  8. package/dist/awsS3/AwsS3Integration.cjs.js.map +1 -1
  9. package/dist/awsS3/AwsS3Integration.esm.js.map +1 -1
  10. package/dist/awsS3/config.cjs.js.map +1 -1
  11. package/dist/awsS3/config.esm.js.map +1 -1
  12. package/dist/azure/AzureIntegration.cjs.js.map +1 -1
  13. package/dist/azure/AzureIntegration.esm.js.map +1 -1
  14. package/dist/azure/AzureUrl.cjs.js.map +1 -1
  15. package/dist/azure/AzureUrl.esm.js.map +1 -1
  16. package/dist/azure/CachedAzureDevOpsCredentialsProvider.cjs.js.map +1 -1
  17. package/dist/azure/CachedAzureDevOpsCredentialsProvider.esm.js.map +1 -1
  18. package/dist/azure/DefaultAzureDevOpsCredentialsProvider.cjs.js.map +1 -1
  19. package/dist/azure/DefaultAzureDevOpsCredentialsProvider.esm.js.map +1 -1
  20. package/dist/azure/ManagedIdentityClientAssertion.cjs.js.map +1 -1
  21. package/dist/azure/ManagedIdentityClientAssertion.esm.js.map +1 -1
  22. package/dist/azure/config.cjs.js.map +1 -1
  23. package/dist/azure/config.esm.js.map +1 -1
  24. package/dist/azure/core.cjs.js.map +1 -1
  25. package/dist/azure/core.esm.js.map +1 -1
  26. package/dist/azure/deprecated.cjs.js.map +1 -1
  27. package/dist/azure/deprecated.esm.js.map +1 -1
  28. package/dist/azureBlobStorage/AzureBlobStorageIntegration.cjs.js.map +1 -1
  29. package/dist/azureBlobStorage/AzureBlobStorageIntegration.esm.js.map +1 -1
  30. package/dist/azureBlobStorage/DefaultAzureCredentialsProvider.cjs.js.map +1 -1
  31. package/dist/azureBlobStorage/DefaultAzureCredentialsProvider.esm.js.map +1 -1
  32. package/dist/azureBlobStorage/config.cjs.js.map +1 -1
  33. package/dist/azureBlobStorage/config.esm.js.map +1 -1
  34. package/dist/bitbucket/BitbucketIntegration.cjs.js.map +1 -1
  35. package/dist/bitbucket/BitbucketIntegration.esm.js.map +1 -1
  36. package/dist/bitbucket/config.cjs.js.map +1 -1
  37. package/dist/bitbucket/config.esm.js.map +1 -1
  38. package/dist/bitbucket/core.cjs.js.map +1 -1
  39. package/dist/bitbucket/core.esm.js.map +1 -1
  40. package/dist/bitbucketCloud/BitbucketCloudIntegration.cjs.js.map +1 -1
  41. package/dist/bitbucketCloud/BitbucketCloudIntegration.esm.js.map +1 -1
  42. package/dist/bitbucketCloud/config.cjs.js.map +1 -1
  43. package/dist/bitbucketCloud/config.esm.js.map +1 -1
  44. package/dist/bitbucketCloud/core.cjs.js.map +1 -1
  45. package/dist/bitbucketCloud/core.esm.js.map +1 -1
  46. package/dist/bitbucketServer/BitbucketServerIntegration.cjs.js.map +1 -1
  47. package/dist/bitbucketServer/BitbucketServerIntegration.esm.js.map +1 -1
  48. package/dist/bitbucketServer/config.cjs.js.map +1 -1
  49. package/dist/bitbucketServer/config.esm.js.map +1 -1
  50. package/dist/bitbucketServer/core.cjs.js.map +1 -1
  51. package/dist/bitbucketServer/core.esm.js.map +1 -1
  52. package/dist/gerrit/GerritIntegration.cjs.js.map +1 -1
  53. package/dist/gerrit/GerritIntegration.esm.js.map +1 -1
  54. package/dist/gerrit/config.cjs.js.map +1 -1
  55. package/dist/gerrit/config.esm.js.map +1 -1
  56. package/dist/gerrit/core.cjs.js.map +1 -1
  57. package/dist/gerrit/core.esm.js.map +1 -1
  58. package/dist/gitea/GiteaIntegration.cjs.js.map +1 -1
  59. package/dist/gitea/GiteaIntegration.esm.js.map +1 -1
  60. package/dist/gitea/config.cjs.js.map +1 -1
  61. package/dist/gitea/config.esm.js.map +1 -1
  62. package/dist/gitea/core.cjs.js.map +1 -1
  63. package/dist/gitea/core.esm.js.map +1 -1
  64. package/dist/github/DefaultGithubCredentialsProvider.cjs.js.map +1 -1
  65. package/dist/github/DefaultGithubCredentialsProvider.esm.js.map +1 -1
  66. package/dist/github/GithubIntegration.cjs.js.map +1 -1
  67. package/dist/github/GithubIntegration.esm.js.map +1 -1
  68. package/dist/github/SingleInstanceGithubCredentialsProvider.cjs.js +8 -4
  69. package/dist/github/SingleInstanceGithubCredentialsProvider.cjs.js.map +1 -1
  70. package/dist/github/SingleInstanceGithubCredentialsProvider.esm.js +8 -4
  71. package/dist/github/SingleInstanceGithubCredentialsProvider.esm.js.map +1 -1
  72. package/dist/github/config.cjs.js.map +1 -1
  73. package/dist/github/config.esm.js.map +1 -1
  74. package/dist/github/core.cjs.js.map +1 -1
  75. package/dist/github/core.esm.js.map +1 -1
  76. package/dist/gitlab/DefaultGitlabCredentialsProvider.cjs.js.map +1 -1
  77. package/dist/gitlab/DefaultGitlabCredentialsProvider.esm.js.map +1 -1
  78. package/dist/gitlab/GitLabIntegration.cjs.js.map +1 -1
  79. package/dist/gitlab/GitLabIntegration.esm.js.map +1 -1
  80. package/dist/gitlab/SingleInstanceGitlabCredentialsProvider.cjs.js.map +1 -1
  81. package/dist/gitlab/SingleInstanceGitlabCredentialsProvider.esm.js.map +1 -1
  82. package/dist/gitlab/config.cjs.js.map +1 -1
  83. package/dist/gitlab/config.esm.js.map +1 -1
  84. package/dist/gitlab/core.cjs.js.map +1 -1
  85. package/dist/gitlab/core.esm.js.map +1 -1
  86. package/dist/googleGcs/config.cjs.js.map +1 -1
  87. package/dist/googleGcs/config.esm.js.map +1 -1
  88. package/dist/harness/HarnessIntegration.cjs.js.map +1 -1
  89. package/dist/harness/HarnessIntegration.esm.js.map +1 -1
  90. package/dist/harness/config.cjs.js.map +1 -1
  91. package/dist/harness/config.esm.js.map +1 -1
  92. package/dist/harness/core.cjs.js.map +1 -1
  93. package/dist/harness/core.esm.js.map +1 -1
  94. package/dist/helpers.cjs.js.map +1 -1
  95. package/dist/helpers.esm.js.map +1 -1
  96. package/dist/index.d.ts +1 -1
  97. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"core.cjs.js","sources":["../../src/gitea/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { GiteaIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a file, returns a URL\n * for editing the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname/path/to/c.yaml\n * or: https://gitea.com/a/b/_edit/branchname/path/to/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaEditContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/${giteaUrl.owner}/${giteaUrl.name}/_edit/${giteaUrl.ref}/${giteaUrl.path}`;\n}\n\n/**\n * Given a URL pointing to a file, returns an api URL\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branch/branchname/path/to/c.yaml\n * to: https://gitea.com/api/v1/repos/a/b/contents/path/to/c.yaml?ref=branchname\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaFileContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/contents/${giteaUrl.path}?ref=${giteaUrl.ref}`;\n}\n\n/**\n * Given a URL pointing to a repository/path, returns a URL\n * for archive contents of the repository.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/archive/branchname.tar.gz\n *\n * @param url - A URL pointing to a repository/path\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaArchiveUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/archive/${giteaUrl.ref}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a repository branch, returns a URL\n * for latest commit information.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/git/commits/branchname\n *\n * @param url - A URL pointing to a repository branch\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaLatestCommitUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/git/commits/${giteaUrl.ref}`;\n}\n\n/**\n * Return request headers for a Gitea provider.\n *\n * @param config - A Gitea provider config\n * @public\n */\nexport function getGiteaRequestOptions(config: GiteaIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n const { username, password } = config;\n\n if (!password) {\n return headers;\n }\n\n if (username) {\n headers.Authorization = `basic ${Buffer.from(\n `${username}:${password}`,\n ).toString('base64')}`;\n } else {\n headers.Authorization = `token ${password}`;\n }\n\n return {\n headers,\n };\n}\n\n/**\n * Return parsed git url properties.\n *\n * @param config - A Gitea provider config\n * @param url - A URL pointing to a repository\n * @public\n */\nexport function parseGiteaUrl(\n config: GiteaIntegrationConfig,\n url: string,\n): {\n url: string;\n owner: string;\n name: string;\n ref: string;\n path: string;\n} {\n const baseUrl = config.baseUrl ?? `https://${config.host}`;\n try {\n const [_blank, owner, name, _src, _branch, ref, ...path] = url\n .replace(baseUrl, '')\n .split('/');\n const pathWithoutSlash = path.join('/').replace(/^\\//, '');\n\n return {\n url: baseUrl,\n owner: owner,\n name: name,\n ref: ref,\n path: pathWithoutSlash,\n };\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n"],"names":[],"mappings":";;AA+BgB,SAAA,uBAAA,CACd,QACA,GACA,EAAA;AACA,EAAM,MAAA,QAAA,GAAW,aAAc,CAAA,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAG,EAAA,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,KAAK,CAAA,CAAA,EAAI,QAAS,CAAA,IAAI,CAAU,OAAA,EAAA,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,IAAI,CAAA,CAAA;AAClG;AAgBgB,SAAA,uBAAA,CACd,QACA,GACA,EAAA;AACA,EAAM,MAAA,QAAA,GAAW,aAAc,CAAA,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAG,EAAA,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,SAAS,KAAK,CAAA,CAAA,EAAI,QAAS,CAAA,IAAI,CAAa,UAAA,EAAA,QAAA,CAAS,IAAI,CAAA,KAAA,EAAQ,SAAS,GAAG,CAAA,CAAA;AACtH;AAgBgB,SAAA,kBAAA,CACd,QACA,GACA,EAAA;AACA,EAAM,MAAA,QAAA,GAAW,aAAc,CAAA,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAO,OAAA,CAAA,EAAG,QAAS,CAAA,GAAG,CAAiB,cAAA,EAAA,QAAA,CAAS,KAAK,CAAA,CAAA,EAAI,QAAS,CAAA,IAAI,CAAY,SAAA,EAAA,QAAA,CAAS,GAAG,CAA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E,CAAA,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEzD,IAAO,OAAA;AAAA,MACL,GAAK,EAAA,OAAA;AAAA,MACL,KAAA;AAAA,MACA,IAAA;AAAA,MACA,GAAA;AAAA,MACA,IAAM,EAAA;AAAA,KACR;AAAA,WACO,CAAG,EAAA;AACV,IAAA,MAAM,IAAI,KAAM,CAAA,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAE,CAAA,CAAA;AAAA;AAEjD;;;;;;;;;"}
1
+ {"version":3,"file":"core.cjs.js","sources":["../../src/gitea/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { GiteaIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a file, returns a URL\n * for editing the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname/path/to/c.yaml\n * or: https://gitea.com/a/b/_edit/branchname/path/to/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaEditContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/${giteaUrl.owner}/${giteaUrl.name}/_edit/${giteaUrl.ref}/${giteaUrl.path}`;\n}\n\n/**\n * Given a URL pointing to a file, returns an api URL\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branch/branchname/path/to/c.yaml\n * to: https://gitea.com/api/v1/repos/a/b/contents/path/to/c.yaml?ref=branchname\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaFileContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/contents/${giteaUrl.path}?ref=${giteaUrl.ref}`;\n}\n\n/**\n * Given a URL pointing to a repository/path, returns a URL\n * for archive contents of the repository.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/archive/branchname.tar.gz\n *\n * @param url - A URL pointing to a repository/path\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaArchiveUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/archive/${giteaUrl.ref}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a repository branch, returns a URL\n * for latest commit information.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/git/commits/branchname\n *\n * @param url - A URL pointing to a repository branch\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaLatestCommitUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/git/commits/${giteaUrl.ref}`;\n}\n\n/**\n * Return request headers for a Gitea provider.\n *\n * @param config - A Gitea provider config\n * @public\n */\nexport function getGiteaRequestOptions(config: GiteaIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n const { username, password } = config;\n\n if (!password) {\n return headers;\n }\n\n if (username) {\n headers.Authorization = `basic ${Buffer.from(\n `${username}:${password}`,\n ).toString('base64')}`;\n } else {\n headers.Authorization = `token ${password}`;\n }\n\n return {\n headers,\n };\n}\n\n/**\n * Return parsed git url properties.\n *\n * @param config - A Gitea provider config\n * @param url - A URL pointing to a repository\n * @public\n */\nexport function parseGiteaUrl(\n config: GiteaIntegrationConfig,\n url: string,\n): {\n url: string;\n owner: string;\n name: string;\n ref: string;\n path: string;\n} {\n const baseUrl = config.baseUrl ?? `https://${config.host}`;\n try {\n const [_blank, owner, name, _src, _branch, ref, ...path] = url\n .replace(baseUrl, '')\n .split('/');\n const pathWithoutSlash = path.join('/').replace(/^\\//, '');\n\n return {\n url: baseUrl,\n owner: owner,\n name: name,\n ref: ref,\n path: pathWithoutSlash,\n };\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n"],"names":[],"mappings":";;AA+BO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,OAAA,EAAU,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,IAAI,CAAA,CAAA;AAClG;AAgBO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,UAAA,EAAa,QAAA,CAAS,IAAI,CAAA,KAAA,EAAQ,SAAS,GAAG,CAAA,CAAA;AACtH;AAgBO,SAAS,kBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,cAAA,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,CAAQ,OAAA,EAAS,EAAE,CAAA,CACnB,MAAM,GAAG,CAAA;AACZ,IAAA,MAAM,mBAAmB,IAAA,CAAK,IAAA,CAAK,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEzD,IAAA,OAAO;AAAA,MACL,GAAA,EAAK,OAAA;AAAA,MACL,KAAA;AAAA,MACA,IAAA;AAAA,MACA,GAAA;AAAA,MACA,IAAA,EAAM;AAAA,KACR;AAAA,EACF,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"core.esm.js","sources":["../../src/gitea/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { GiteaIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a file, returns a URL\n * for editing the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname/path/to/c.yaml\n * or: https://gitea.com/a/b/_edit/branchname/path/to/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaEditContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/${giteaUrl.owner}/${giteaUrl.name}/_edit/${giteaUrl.ref}/${giteaUrl.path}`;\n}\n\n/**\n * Given a URL pointing to a file, returns an api URL\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branch/branchname/path/to/c.yaml\n * to: https://gitea.com/api/v1/repos/a/b/contents/path/to/c.yaml?ref=branchname\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaFileContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/contents/${giteaUrl.path}?ref=${giteaUrl.ref}`;\n}\n\n/**\n * Given a URL pointing to a repository/path, returns a URL\n * for archive contents of the repository.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/archive/branchname.tar.gz\n *\n * @param url - A URL pointing to a repository/path\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaArchiveUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/archive/${giteaUrl.ref}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a repository branch, returns a URL\n * for latest commit information.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/git/commits/branchname\n *\n * @param url - A URL pointing to a repository branch\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaLatestCommitUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/git/commits/${giteaUrl.ref}`;\n}\n\n/**\n * Return request headers for a Gitea provider.\n *\n * @param config - A Gitea provider config\n * @public\n */\nexport function getGiteaRequestOptions(config: GiteaIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n const { username, password } = config;\n\n if (!password) {\n return headers;\n }\n\n if (username) {\n headers.Authorization = `basic ${Buffer.from(\n `${username}:${password}`,\n ).toString('base64')}`;\n } else {\n headers.Authorization = `token ${password}`;\n }\n\n return {\n headers,\n };\n}\n\n/**\n * Return parsed git url properties.\n *\n * @param config - A Gitea provider config\n * @param url - A URL pointing to a repository\n * @public\n */\nexport function parseGiteaUrl(\n config: GiteaIntegrationConfig,\n url: string,\n): {\n url: string;\n owner: string;\n name: string;\n ref: string;\n path: string;\n} {\n const baseUrl = config.baseUrl ?? `https://${config.host}`;\n try {\n const [_blank, owner, name, _src, _branch, ref, ...path] = url\n .replace(baseUrl, '')\n .split('/');\n const pathWithoutSlash = path.join('/').replace(/^\\//, '');\n\n return {\n url: baseUrl,\n owner: owner,\n name: name,\n ref: ref,\n path: pathWithoutSlash,\n };\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n"],"names":[],"mappings":"AA+BgB,SAAA,uBAAA,CACd,QACA,GACA,EAAA;AACA,EAAM,MAAA,QAAA,GAAW,aAAc,CAAA,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAG,EAAA,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,KAAK,CAAA,CAAA,EAAI,QAAS,CAAA,IAAI,CAAU,OAAA,EAAA,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,IAAI,CAAA,CAAA;AAClG;AAgBgB,SAAA,uBAAA,CACd,QACA,GACA,EAAA;AACA,EAAM,MAAA,QAAA,GAAW,aAAc,CAAA,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAG,EAAA,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,SAAS,KAAK,CAAA,CAAA,EAAI,QAAS,CAAA,IAAI,CAAa,UAAA,EAAA,QAAA,CAAS,IAAI,CAAA,KAAA,EAAQ,SAAS,GAAG,CAAA,CAAA;AACtH;AAgBgB,SAAA,kBAAA,CACd,Q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;AACF,IAAA,MAAM,CAAC,MAAQ,EAAA,KAAA,EAAO,IAAM,EAAA,IAAA,EAAM,SAAS,GAAK,EAAA,GAAG,IAAI,CAAA,GAAI,IACxD,OAAQ,CAAA,OAAA,EAAS,EAAE,CAAA,CACnB,MAAM,GAAG,CAAA;AACZ,IAAA,MAAM,mBAAmB,IAAK,CAAA,IAAA,CAAK,GAAG,CAAE,CAAA,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEzD,IAAO,OAAA;AAAA,MACL,GAAK,EAAA,OAAA;AAAA,MACL,KAAA;AAAA,MACA,IAAA;AAAA,MACA,GAAA;AAAA,MACA,IAAM,EAAA;AAAA,KACR;AAAA,WACO,CAAG,EAAA;AACV,IAAA,MAAM,IAAI,KAAM,CAAA,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAE,CAAA,CAAA;AAAA;AAEjD;;;;"}
1
+ {"version":3,"file":"core.esm.js","sources":["../../src/gitea/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { GiteaIntegrationConfig } from './config';\n\n/**\n * Given a URL pointing to a file, returns a URL\n * for editing the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname/path/to/c.yaml\n * or: https://gitea.com/a/b/_edit/branchname/path/to/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaEditContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/${giteaUrl.owner}/${giteaUrl.name}/_edit/${giteaUrl.ref}/${giteaUrl.path}`;\n}\n\n/**\n * Given a URL pointing to a file, returns an api URL\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branch/branchname/path/to/c.yaml\n * to: https://gitea.com/api/v1/repos/a/b/contents/path/to/c.yaml?ref=branchname\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaFileContentsUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/contents/${giteaUrl.path}?ref=${giteaUrl.ref}`;\n}\n\n/**\n * Given a URL pointing to a repository/path, returns a URL\n * for archive contents of the repository.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/archive/branchname.tar.gz\n *\n * @param url - A URL pointing to a repository/path\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaArchiveUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/archive/${giteaUrl.ref}.tar.gz`;\n}\n\n/**\n * Given a URL pointing to a repository branch, returns a URL\n * for latest commit information.\n *\n * @remarks\n *\n * Converts\n * from: https://gitea.com/a/b/src/branchname\n * or: https://gitea.com/api/v1/repos/a/b/git/commits/branchname\n *\n * @param url - A URL pointing to a repository branch\n * @param config - The relevant provider config\n * @public\n */\nexport function getGiteaLatestCommitUrl(\n config: GiteaIntegrationConfig,\n url: string,\n) {\n const giteaUrl = parseGiteaUrl(config, url);\n return `${giteaUrl.url}/api/v1/repos/${giteaUrl.owner}/${giteaUrl.name}/git/commits/${giteaUrl.ref}`;\n}\n\n/**\n * Return request headers for a Gitea provider.\n *\n * @param config - A Gitea provider config\n * @public\n */\nexport function getGiteaRequestOptions(config: GiteaIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n const { username, password } = config;\n\n if (!password) {\n return headers;\n }\n\n if (username) {\n headers.Authorization = `basic ${Buffer.from(\n `${username}:${password}`,\n ).toString('base64')}`;\n } else {\n headers.Authorization = `token ${password}`;\n }\n\n return {\n headers,\n };\n}\n\n/**\n * Return parsed git url properties.\n *\n * @param config - A Gitea provider config\n * @param url - A URL pointing to a repository\n * @public\n */\nexport function parseGiteaUrl(\n config: GiteaIntegrationConfig,\n url: string,\n): {\n url: string;\n owner: string;\n name: string;\n ref: string;\n path: string;\n} {\n const baseUrl = config.baseUrl ?? `https://${config.host}`;\n try {\n const [_blank, owner, name, _src, _branch, ref, ...path] = url\n .replace(baseUrl, '')\n .split('/');\n const pathWithoutSlash = path.join('/').replace(/^\\//, '');\n\n return {\n url: baseUrl,\n owner: owner,\n name: name,\n ref: ref,\n path: pathWithoutSlash,\n };\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n"],"names":[],"mappings":"AA+BO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,OAAA,EAAU,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI,SAAS,IAAI,CAAA,CAAA;AAClG;AAgBO,SAAS,uBAAA,CACd,QACA,GAAA,EACA;AACA,EAAA,MAAM,QAAA,GAAW,aAAA,CAAc,MAAA,EAAQ,GAAG,CAAA;AAC1C,EAAA,OAAO,CAAA,EAAG,QAAA,CAAS,GAAG,CAAA,cAAA,EAAiB,SAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,IAAI,CAAA,UAAA,EAAa,Q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,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,IAAW,CAAA,QAAA,EAAW,OAAO,IAAI,CAAA,CAAA;AACxD,EAAA,IAAI;AACF,IAAA,MAAM,CAAC,MAAA,EAAQ,KAAA,EAAO,IAAA,EAAM,IAAA,EAAM,SAAS,GAAA,EAAK,GAAG,IAAI,CAAA,GAAI,IACxD,OAAA,CAAQ,OAAA,EAAS,EAAE,CAAA,CACnB,MAAM,GAAG,CAAA;AACZ,IAAA,MAAM,mBAAmB,IAAA,CAAK,IAAA,CAAK,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEzD,IAAA,OAAO;AAAA,MACL,GAAA,EAAK,OAAA;AAAA,MACL,KAAA;AAAA,MACA,IAAA;AAAA,MACA,GAAA;AAAA,MACA,IAAA,EAAM;AAAA,KACR;AAAA,EACF,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"DefaultGithubCredentialsProvider.cjs.js","sources":["../../src/github/DefaultGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n private constructor(\n private readonly providers: Map<string, GithubCredentialsProvider>,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":["SingleInstanceGithubCredentialsProvider"],"mappings":";;;;AA4BO,MAAM,gCAEb,CAAA;AAAA,EAaU,YACW,SACjB,EAAA;AADiB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA;AAChB,EAdH,OAAO,iBAAiB,YAAsC,EAAA;AAC5D,IAAM,MAAA,oBAAA,uBACA,GAAuC,EAAA;AAE7C,IAAA,YAAA,CAAa,MAAO,CAAA,IAAA,EAAO,CAAA,OAAA,CAAQ,CAAe,WAAA,KAAA;AAChD,MAAA,MAAM,mBACJ,GAAAA,+EAAA,CAAwC,MAAO,CAAA,WAAA,CAAY,MAAM,CAAA;AACnE,MAAA,oBAAA,CAAqB,GAAI,CAAA,WAAA,CAAY,MAAO,CAAA,IAAA,EAAM,mBAAmB,CAAA;AAAA,KACtE,CAAA;AACD,IAAO,OAAA,IAAI,iCAAiC,oBAAoB,CAAA;AAAA;AAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BA,MAAM,eAAe,IAAmD,EAAA;AACtE,IAAA,MAAM,MAAS,GAAA,IAAI,GAAI,CAAA,IAAA,CAAK,GAAG,CAAA;AAC/B,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,SAAU,CAAA,GAAA,CAAI,OAAO,IAAI,CAAA;AAE/C,IAAA,IAAI,CAAC,QAAU,EAAA;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,GAAG,CAAA,gDAAA;AAAA,OACzD;AAAA;AAGF,IAAO,OAAA,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA;AAEvC;;;;"}
1
+ {"version":3,"file":"DefaultGithubCredentialsProvider.cjs.js","sources":["../../src/github/DefaultGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n private constructor(\n private readonly providers: Map<string, GithubCredentialsProvider>,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":["SingleInstanceGithubCredentialsProvider"],"mappings":";;;;AA4BO,MAAM,gCAAA,CAEb;AAAA,EAaU,YACW,SAAA,EACjB;AADiB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA,EAChB;AAAA,EAdH,OAAO,iBAAiB,YAAA,EAAsC;AAC5D,IAAA,MAAM,oBAAA,uBACA,GAAA,EAAuC;AAE7C,IAAA,YAAA,CAAa,MAAA,CAAO,IAAA,EAAK,CAAE,OAAA,CAAQ,CAAA,WAAA,KAAe;AAChD,MAAA,MAAM,mBAAA,GACJA,+EAAA,CAAwC,MAAA,CAAO,WAAA,CAAY,MAAM,CAAA;AACnE,MAAA,oBAAA,CAAqB,GAAA,CAAI,WAAA,CAAY,MAAA,CAAO,IAAA,EAAM,mBAAmB,CAAA;AAAA,IACvE,CAAC,CAAA;AACD,IAAA,OAAO,IAAI,iCAAiC,oBAAoB,CAAA;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BA,MAAM,eAAe,IAAA,EAAmD;AACtE,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,IAAA,CAAK,GAAG,CAAA;AAC/B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,OAAO,IAAI,CAAA;AAE/C,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,GAAG,CAAA,gDAAA;AAAA,OACzD;AAAA,IACF;AAEA,IAAA,OAAO,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA,EACrC;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"DefaultGithubCredentialsProvider.esm.js","sources":["../../src/github/DefaultGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n private constructor(\n private readonly providers: Map<string, GithubCredentialsProvider>,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":[],"mappings":";;AA4BO,MAAM,gCAEb,CAAA;AAAA,EAaU,YACW,SACjB,EAAA;AADiB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA;AAChB,EAdH,OAAO,iBAAiB,YAAsC,EAAA;AAC5D,IAAM,MAAA,oBAAA,uBACA,GAAuC,EAAA;AAE7C,IAAA,YAAA,CAAa,MAAO,CAAA,IAAA,EAAO,CAAA,OAAA,CAAQ,CAAe,WAAA,KAAA;AAChD,MAAA,MAAM,mBACJ,GAAA,uCAAA,CAAwC,MAAO,CAAA,WAAA,CAAY,MAAM,CAAA;AACnE,MAAA,oBAAA,CAAqB,GAAI,CAAA,WAAA,CAAY,MAAO,CAAA,IAAA,EAAM,mBAAmB,CAAA;AAAA,KACtE,CAAA;AACD,IAAO,OAAA,IAAI,iCAAiC,oBAAoB,CAAA;AAAA;AAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BA,MAAM,eAAe,IAAmD,EAAA;AACtE,IAAA,MAAM,MAAS,GAAA,IAAI,GAAI,CAAA,IAAA,CAAK,GAAG,CAAA;AAC/B,IAAA,MAAM,QAAW,GAAA,IAAA,CAAK,SAAU,CAAA,GAAA,CAAI,OAAO,IAAI,CAAA;AAE/C,IAAA,IAAI,CAAC,QAAU,EAAA;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,GAAG,CAAA,gDAAA;AAAA,OACzD;AAAA;AAGF,IAAO,OAAA,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA;AAEvC;;;;"}
1
+ {"version":3,"file":"DefaultGithubCredentialsProvider.esm.js","sources":["../../src/github/DefaultGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GithubCredentials, GithubCredentialsProvider } from './types';\nimport { ScmIntegrationRegistry } from '../registry';\nimport { SingleInstanceGithubCredentialsProvider } from './SingleInstanceGithubCredentialsProvider';\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class DefaultGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static fromIntegrations(integrations: ScmIntegrationRegistry) {\n const credentialsProviders: Map<string, GithubCredentialsProvider> =\n new Map<string, GithubCredentialsProvider>();\n\n integrations.github.list().forEach(integration => {\n const credentialsProvider =\n SingleInstanceGithubCredentialsProvider.create(integration.config);\n credentialsProviders.set(integration.config.host, credentialsProvider);\n });\n return new DefaultGithubCredentialsProvider(credentialsProviders);\n }\n\n private constructor(\n private readonly providers: Map<string, GithubCredentialsProvider>,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage/foobar'\n * })\n *\n * const { token, headers } = await getCredentials({\n * url: 'https://github.com/backstage'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = new URL(opts.url);\n const provider = this.providers.get(parsed.host);\n\n if (!provider) {\n throw new Error(\n `There is no GitHub integration that matches ${opts.url}. Please add a configuration for an integration.`,\n );\n }\n\n return provider.getCredentials(opts);\n }\n}\n"],"names":[],"mappings":";;AA4BO,MAAM,gCAAA,CAEb;AAAA,EAaU,YACW,SAAA,EACjB;AADiB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA,EAChB;AAAA,EAdH,OAAO,iBAAiB,YAAA,EAAsC;AAC5D,IAAA,MAAM,oBAAA,uBACA,GAAA,EAAuC;AAE7C,IAAA,YAAA,CAAa,MAAA,CAAO,IAAA,EAAK,CAAE,OAAA,CAAQ,CAAA,WAAA,KAAe;AAChD,MAAA,MAAM,mBAAA,GACJ,uCAAA,CAAwC,MAAA,CAAO,WAAA,CAAY,MAAM,CAAA;AACnE,MAAA,oBAAA,CAAqB,GAAA,CAAI,WAAA,CAAY,MAAA,CAAO,IAAA,EAAM,mBAAmB,CAAA;AAAA,IACvE,CAAC,CAAA;AACD,IAAA,OAAO,IAAI,iCAAiC,oBAAoB,CAAA;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BA,MAAM,eAAe,IAAA,EAAmD;AACtE,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,IAAA,CAAK,GAAG,CAAA;AAC/B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,OAAO,IAAI,CAAA;AAE/C,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,4CAAA,EAA+C,KAAK,GAAG,CAAA,gDAAA;AAAA,OACzD;AAAA,IACF;AAEA,IAAA,OAAO,QAAA,CAAS,eAAe,IAAI,CAAA;AAAA,EACrC;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"GithubIntegration.cjs.js","sources":["../../src/github/GithubIntegration.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}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AA;AACR,EAAA,OAAO,GAAI,CAAA,OAAA;AAAA,IACT,mDAAA;AAAA,IACA,CAAC,CAAA,EAAG,IAAM,EAAA,KAAA,EAAO,IAAS,KAAA;AACxB,MAAA,OAAO,KAAK,IAAI,CAAA,CAAA,EAAI,KAAK,CAAI,CAAA,EAAA,IAAI,IAAI,IAAI,CAAA,CAAA,CAAA;AAAA;AAC3C,GACF;AACF;;;;;"}
1
+ {"version":3,"file":"GithubIntegration.cjs.js","sources":["../../src/github/GithubIntegration.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}/`;\n },\n );\n}\n"],"names":["config","readGithubIntegrationConfigs","basicIntegrations","defaultScmResolveUrl"],"mappings":";;;;;AAiCO,MAAM,iBAAA,CAA4C;AAAA,EAWvD,YAA6B,iBAAA,EAA4C;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA,EAA6C;AAAA,EAV1E,OAAO,OAAA,GAAqD,CAAC,UAAEA,UAAO,KAAM;AAC1E,IAAA,MAAM,OAAA,GAAUC,mCAAA;AAAA,MACdD,QAAA,CAAO,sBAAA,CAAuB,qBAAqB,CAAA,IAAK;AAAC,KAC3D;AACA,IAAA,OAAOE,yBAAA;AAAA,MACL,QAAQ,GAAA,CAAI,CAAA,CAAA,KAAK,IAAI,iBAAA,CAAkB,CAAC,CAAC,CAAA;AAAA,MACzC,CAAA,CAAA,KAAK,EAAE,MAAA,CAAO;AAAA,KAChB;AAAA,EACF,CAAA;AAAA,EAIA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,IAAI,KAAA,GAAgB;AAClB,IAAA,OAAO,KAAK,iBAAA,CAAkB,IAAA;AAAA,EAChC;AAAA,EAEA,IAAI,MAAA,GAAkC;AACpC,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EACd;AAAA,EAEA,WAAW,OAAA,EAIA;AAIT,IAAA,OAAO,oBAAA,CAAqBC,4BAAA,CAAqB,OAAO,CAAA,EAAG,MAAM,CAAA;AAAA,EACnE;AAAA,EAEA,eAAe,GAAA,EAAqB;AAClC,IAAA,OAAO,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAAA,EACzC;AAAA,EAEA,mBAAmB,QAAA,EAA2C;AAC5D,IAAA,OAAO;AAAA,MACL,aAAA,EACE,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,uBAAuB,CAAA,KAAM;AAAA,KACxD;AAAA,EACF;AACF;AASO,SAAS,oBAAA,CACd,KACA,IAAA,EACQ;AACR,EAAA,OAAO,GAAA,CAAI,OAAA;AAAA,IACT,mDAAA;AAAA,IACA,CAAC,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,KAAS;AACxB,MAAA,OAAO,KAAK,IAAI,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,EAAI,IAAI,IAAI,IAAI,CAAA,CAAA,CAAA;AAAA,IAC3C;AAAA,GACF;AACF;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"GithubIntegration.esm.js","sources":["../../src/github/GithubIntegration.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}/`;\n },\n );\n}\n"],"names":[],"mappings":";;;AAiCO,MAAM,iBAA4C,CAAA;AAAA,EAWvD,YAA6B,iBAA4C,EAAA;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I,CAAA,CAAA,EAAI,KAAK,CAAI,CAAA,EAAA,IAAI,IAAI,IAAI,CAAA,CAAA,CAAA;AAAA;AAC3C,GACF;AACF;;;;"}
1
+ {"version":3,"file":"GithubIntegration.esm.js","sources":["../../src/github/GithubIntegration.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations, defaultScmResolveUrl } from '../helpers';\nimport {\n RateLimitInfo,\n ScmIntegration,\n ScmIntegrationsFactory,\n} from '../types';\nimport {\n GithubIntegrationConfig,\n readGithubIntegrationConfigs,\n} from './config';\nimport { ConsumedResponse } from '@backstage/errors';\n\n/**\n * A GitHub based integration.\n *\n * @public\n */\nexport class GithubIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GithubIntegration> = ({ config }) => {\n const configs = readGithubIntegrationConfigs(\n config.getOptionalConfigArray('integrations.github') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GithubIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GithubIntegrationConfig) {}\n\n get type(): string {\n return 'github';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GithubIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n // GitHub uses blob URLs for files and tree urls for directory listings. But\n // there is a redirect from tree to blob for files, so we can always return\n // tree urls here.\n return replaceGithubUrlType(defaultScmResolveUrl(options), 'tree');\n }\n\n resolveEditUrl(url: string): string {\n return replaceGithubUrlType(url, 'edit');\n }\n\n parseRateLimitInfo(response: ConsumedResponse): RateLimitInfo {\n return {\n isRateLimited:\n response.status === 429 ||\n (response.status === 403 &&\n response.headers.get('x-ratelimit-remaining') === '0'),\n };\n }\n}\n\n/**\n * Takes a GitHub URL and replaces the type part (blob, tree etc).\n *\n * @param url - The original URL\n * @param type - The desired type, e.g. \"blob\"\n * @public\n */\nexport function replaceGithubUrlType(\n url: string,\n type: 'blob' | 'tree' | 'edit',\n): string {\n return url.replace(\n /\\/\\/([^/]+)\\/([^/]+)\\/([^/]+)\\/(blob|tree|edit)\\//,\n (_, host, owner, repo) => {\n return `//${host}/${owner}/${repo}/${type}/`;\n },\n );\n}\n"],"names":[],"mappings":";;;AAiCO,MAAM,iBAAA,CAA4C;AAAA,EAWvD,YAA6B,iBAAA,EAA4C;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA,EAA6C;AAAA,EAV1E,OAAO,OAAA,GAAqD,CAAC,EAAE,QAAO,KAAM;AAC1E,IAAA,MAAM,OAAA,GAAU,4BAAA;AAAA,MACd,MAAA,CAAO,sBAAA,CAAuB,qBAAqB,CAAA,IAAK;AAAC,KAC3D;AACA,IAAA,OAAO,iBAAA;AAAA,MACL,QAAQ,GAAA,CAAI,CAAA,CAAA,KAAK,IAAI,iBAAA,CAAkB,CAAC,CAAC,CAAA;AAAA,MACzC,CAAA,CAAA,KAAK,EAAE,MAAA,CAAO;AAAA,KAChB;AAAA,EACF,CAAA;AAAA,EAIA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,IAAI,KAAA,GAAgB;AAClB,IAAA,OAAO,KAAK,iBAAA,CAAkB,IAAA;AAAA,EAChC;AAAA,EAEA,IAAI,MAAA,GAAkC;AACpC,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EACd;AAAA,EAEA,WAAW,OAAA,EAIA;AAIT,IAAA,OAAO,oBAAA,CAAqB,oBAAA,CAAqB,OAAO,CAAA,EAAG,MAAM,CAAA;AAAA,EACnE;AAAA,EAEA,eAAe,GAAA,EAAqB;AAClC,IAAA,OAAO,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAAA,EACzC;AAAA,EAEA,mBAAmB,QAAA,EAA2C;AAC5D,IAAA,OAAO;AAAA,MACL,aAAA,EACE,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,MAAA,KAAW,GAAA,IACnB,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,uBAAuB,CAAA,KAAM;AAAA,KACxD;AAAA,EACF;AACF;AASO,SAAS,oBAAA,CACd,KACA,IAAA,EACQ;AACR,EAAA,OAAO,GAAA,CAAI,OAAA;AAAA,IACT,mDAAA;AAAA,IACA,CAAC,CAAA,EAAG,IAAA,EAAM,KAAA,EAAO,IAAA,KAAS;AACxB,MAAA,OAAO,KAAK,IAAI,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,EAAI,IAAI,IAAI,IAAI,CAAA,CAAA,CAAA;AAAA,IAC3C;AAAA,GACF;AACF;;;;"}
@@ -47,7 +47,9 @@ class GithubAppManager {
47
47
  allowedInstallationOwners;
48
48
  // undefined allows all installations
49
49
  constructor(config, baseUrl) {
50
- this.allowedInstallationOwners = config.allowedInstallationOwners;
50
+ this.allowedInstallationOwners = config.allowedInstallationOwners?.map(
51
+ (owner) => owner.toLocaleLowerCase("en-US")
52
+ );
51
53
  this.baseUrl = baseUrl;
52
54
  this.baseAuthConfig = {
53
55
  appId: config.appId,
@@ -62,7 +64,9 @@ class GithubAppManager {
62
64
  }
63
65
  async getInstallationCredentials(owner, repo) {
64
66
  if (this.allowedInstallationOwners) {
65
- if (!this.allowedInstallationOwners?.includes(owner)) {
67
+ if (!this.allowedInstallationOwners?.includes(
68
+ owner.toLocaleLowerCase("en-US")
69
+ )) {
66
70
  return { accessToken: void 0 };
67
71
  }
68
72
  }
@@ -119,8 +123,8 @@ class GithubAppManager {
119
123
  }
120
124
  class GithubAppCredentialsMux {
121
125
  apps;
122
- constructor(config) {
123
- this.apps = config.apps?.map((ac) => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];
126
+ constructor(config, appIds = []) {
127
+ this.apps = config.apps?.filter((app) => appIds.length ? appIds.includes(app.appId) : true).map((ac) => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];
124
128
  }
125
129
  async getAllInstallations() {
126
130
  if (!this.apps.length) {
@@ -1 +1 @@
1
- {"version":3,"file":"SingleInstanceGithubCredentialsProvider.cjs.js","sources":["../../src/github/SingleInstanceGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners;\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (!this.allowedInstallationOwners?.includes(owner)) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig) {\n this.apps =\n config.apps?.map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` }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A;AAAA;AAAA,EA2BA,MAAM,eAAe,IAAmD,EAAA;AACtE,IAAM,MAAA,MAAA,GAASG,4BAAY,CAAA,IAAA,CAAK,GAAG,CAAA;AAEnC,IAAM,MAAA,KAAA,GAAQ,MAAO,CAAA,KAAA,IAAS,MAAO,CAAA,IAAA;AACrC,IAAA,MAAM,IAAO,GAAA,MAAA,CAAO,KAAQ,GAAA,MAAA,CAAO,IAAO,GAAA,KAAA,CAAA;AAE1C,IAAA,IAAI,IAA6B,GAAA,KAAA;AACjC,IAAA,IAAI,QAAQ,MAAM,IAAA,CAAK,uBAAwB,CAAA,WAAA,CAAY,OAAO,IAAI,CAAA;AACtE,IAAA,IAAI,CAAC,KAAO,EAAA;AACV,MAAO,IAAA,GAAA,OAAA;AACP,MAAA,KAAA,GAAQ,IAAK,CAAA,KAAA;AAAA;AAGf,IAAO,OAAA;AAAA,MACL,SAAS,KAAQ,GAAA,EAAE,eAAe,CAAU,OAAA,EAAA,KAAK,IAAO,GAAA,KAAA,CAAA;AAAA,MACxD,KAAA;AAAA,MACA;AAAA,KACF;AAAA;AAEJ;;;;;"}
1
+ {"version":3,"file":"SingleInstanceGithubCredentialsProvider.cjs.js","sources":["../../src/github/SingleInstanceGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLocaleLowerCase('en-US'),\n );\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (\n !this.allowedInstallationOwners?.includes(\n owner.toLocaleLowerCase('en-US'),\n )\n ) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig, appIds: number[] = []) {\n this.apps =\n config.apps\n ?.filter(app => (appIds.length ? appIds.includes(app.appId) : true))\n .map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n}\n"],"names":["DateTime","Octokit","createAppAuth","parseGitUrl"],"mappings":";;;;;;;;;;;AAsCA,MAAM,KAAA,CAAM;AAAA,EACO,UAAA,uBAAiB,GAAA,EAAmC;AAAA,EAErE,MAAM,gBAAA,CACJ,KAAA,EACA,IAAA,EACA,QAAA,EACkC;AAClC,IAAA,IAAI,wBAAA,GAA2B,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA;AAExD,IAAA,IACE,CAAC,wBAAA,IACD,IAAA,CAAK,SAAA,CAAU,wBAAA,CAAyB,SAAS,CAAA,EACjD;AACA,MAAA,wBAAA,GAA2B,MAAM,QAAA,EAAS;AAE1C,MAAA,wBAAA,CAAyB,YACvB,wBAAA,CAAyB,SAAA,CAAU,MAAM,EAAE,OAAA,EAAS,IAAI,CAAA;AAC1D,MAAA,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAA,EAAO,wBAAwB,CAAA;AAAA,IACrD;AAEA,IAAA,IAAI,CAAC,IAAA,CAAK,aAAA,CAAc,wBAA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,IAAA,CAAK,uBAAA,CAAwB,WAAA,CAAY,OAAO,IAAI,CAAA;AACtE,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,IAAA,GAAO,OAAA;AACP,MAAA,KAAA,GAAQ,IAAA,CAAK,KAAA;AAAA,IACf;AAEA,IAAA,OAAO;AAAA,MACL,SAAS,KAAA,GAAQ,EAAE,eAAe,CAAA,OAAA,EAAU,KAAK,IAAG,GAAI,MAAA;AAAA,MACxD,KAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;;"}
@@ -41,7 +41,9 @@ class GithubAppManager {
41
41
  allowedInstallationOwners;
42
42
  // undefined allows all installations
43
43
  constructor(config, baseUrl) {
44
- this.allowedInstallationOwners = config.allowedInstallationOwners;
44
+ this.allowedInstallationOwners = config.allowedInstallationOwners?.map(
45
+ (owner) => owner.toLocaleLowerCase("en-US")
46
+ );
45
47
  this.baseUrl = baseUrl;
46
48
  this.baseAuthConfig = {
47
49
  appId: config.appId,
@@ -56,7 +58,9 @@ class GithubAppManager {
56
58
  }
57
59
  async getInstallationCredentials(owner, repo) {
58
60
  if (this.allowedInstallationOwners) {
59
- if (!this.allowedInstallationOwners?.includes(owner)) {
61
+ if (!this.allowedInstallationOwners?.includes(
62
+ owner.toLocaleLowerCase("en-US")
63
+ )) {
60
64
  return { accessToken: void 0 };
61
65
  }
62
66
  }
@@ -113,8 +117,8 @@ class GithubAppManager {
113
117
  }
114
118
  class GithubAppCredentialsMux {
115
119
  apps;
116
- constructor(config) {
117
- this.apps = config.apps?.map((ac) => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];
120
+ constructor(config, appIds = []) {
121
+ this.apps = config.apps?.filter((app) => appIds.length ? appIds.includes(app.appId) : true).map((ac) => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];
118
122
  }
119
123
  async getAllInstallations() {
120
124
  if (!this.apps.length) {
@@ -1 +1 @@
1
- {"version":3,"file":"SingleInstanceGithubCredentialsProvider.esm.js","sources":["../../src/github/SingleInstanceGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners;\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (!this.allowedInstallationOwners?.includes(owner)) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig) {\n this.apps =\n config.apps?.map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n}\n"],"names":[],"mappings":";;;;;AAsCA,MAAM,KAAM,CAAA;AAAA,EACO,UAAA,uBAAiB,GAAmC,EAAA;AAAA,EAErE,MAAM,gBAAA,CACJ,KACA,EAAA,IAAA,EACA,QACkC,EAAA;AAClC,IAAA,IAAI,wBAA2B,GAAA,IAAA,CAAK,UAAW,CAAA,GAAA,CAAI,KAAK,CAAA;AAExD,IAAA,IACE,CAAC,wBACD,IAAA,IAAA,CA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AM,IAAA,CAAK,uBAAwB,CAAA,WAAA,CAAY,OAAO,IAAI,CAAA;AACtE,IAAA,IAAI,CAAC,KAAO,EAAA;AACV,MAAO,IAAA,GAAA,OAAA;AACP,MAAA,KAAA,GAAQ,IAAK,CAAA,KAAA;AAAA;AAGf,IAAO,OAAA;AAAA,MACL,SAAS,KAAQ,GAAA,EAAE,eAAe,CAAU,OAAA,EAAA,KAAK,IAAO,GAAA,KAAA,CAAA;AAAA,MACxD,KAAA;AAAA,MACA;AAAA,KACF;AAAA;AAEJ;;;;"}
1
+ {"version":3,"file":"SingleInstanceGithubCredentialsProvider.esm.js","sources":["../../src/github/SingleInstanceGithubCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubAppConfig, GithubIntegrationConfig } from './config';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit, RestEndpointMethodTypes } from '@octokit/rest';\nimport { DateTime } from 'luxon';\nimport {\n GithubCredentials,\n GithubCredentialsProvider,\n GithubCredentialType,\n} from './types';\n\ntype InstallationData = {\n installationId: number;\n suspended: boolean;\n};\n\ntype InstallationTokenData = {\n token: string;\n expiresAt: DateTime;\n repositories?: String[];\n};\n\nclass Cache {\n private readonly tokenCache = new Map<string, InstallationTokenData>();\n\n async getOrCreateToken(\n owner: string,\n repo: string | undefined,\n supplier: () => Promise<InstallationTokenData>,\n ): Promise<{ accessToken: string }> {\n let existingInstallationData = this.tokenCache.get(owner);\n\n if (\n !existingInstallationData ||\n this.isExpired(existingInstallationData.expiresAt)\n ) {\n existingInstallationData = await supplier();\n // Allow 10 minutes grace to account for clock skew\n existingInstallationData.expiresAt =\n existingInstallationData.expiresAt.minus({ minutes: 10 });\n this.tokenCache.set(owner, existingInstallationData);\n }\n\n if (!this.appliesToRepo(existingInstallationData, repo)) {\n throw new Error(\n `The Backstage GitHub application used in the ${owner} organization does not have access to a repository with the name ${repo}`,\n );\n }\n\n return { accessToken: existingInstallationData.token };\n }\n\n private isExpired = (date: DateTime) => DateTime.local() > date;\n\n private appliesToRepo(tokenData: InstallationTokenData, repo?: string) {\n // If no specific repo has been requested the token is applicable\n if (repo === undefined) {\n return true;\n }\n // If the token is restricted to repositories, the token only applies if the repo is in the allow list\n if (tokenData.repositories !== undefined) {\n return tokenData.repositories.includes(repo);\n }\n // Otherwise the token is applicable\n return true;\n }\n}\n\n/**\n * This accept header is required when calling App APIs in GitHub Enterprise.\n * It has no effect on calls to github.com and can probably be removed entirely\n * once GitHub Apps is out of preview.\n */\nconst HEADERS = {\n Accept: 'application/vnd.github.machine-man-preview+json',\n};\n\n/**\n * GithubAppManager issues and caches tokens for a specific GitHub App.\n */\nclass GithubAppManager {\n private readonly appClient: Octokit;\n private readonly baseUrl?: string;\n private readonly baseAuthConfig: { appId: number; privateKey: string };\n private readonly cache = new Cache();\n private readonly allowedInstallationOwners: string[] | undefined; // undefined allows all installations\n\n constructor(config: GithubAppConfig, baseUrl?: string) {\n this.allowedInstallationOwners = config.allowedInstallationOwners?.map(\n owner => owner.toLocaleLowerCase('en-US'),\n );\n this.baseUrl = baseUrl;\n this.baseAuthConfig = {\n appId: config.appId,\n privateKey: config.privateKey.replace(/\\\\n/gm, '\\n'),\n };\n this.appClient = new Octokit({\n baseUrl,\n headers: HEADERS,\n authStrategy: createAppAuth,\n auth: this.baseAuthConfig,\n });\n }\n\n async getInstallationCredentials(\n owner: string,\n repo?: string,\n ): Promise<{ accessToken: string | undefined }> {\n if (this.allowedInstallationOwners) {\n if (\n !this.allowedInstallationOwners?.includes(\n owner.toLocaleLowerCase('en-US'),\n )\n ) {\n return { accessToken: undefined }; // An empty token allows anonymous access to public repos\n }\n }\n\n // Go and grab an access token for the app scoped to a repository if provided, if not use the organisation installation.\n return this.cache.getOrCreateToken(owner, repo, async () => {\n const { installationId, suspended } = await this.getInstallationData(\n owner,\n );\n if (suspended) {\n throw new Error(`The GitHub application for ${owner} is suspended`);\n }\n\n const result = await this.appClient.apps.createInstallationAccessToken({\n installation_id: installationId,\n headers: HEADERS,\n });\n\n let repositoryNames;\n\n if (result.data.repository_selection === 'selected') {\n const installationClient = new Octokit({\n baseUrl: this.baseUrl,\n auth: result.data.token,\n });\n const repos = await installationClient.paginate(\n installationClient.apps.listReposAccessibleToInstallation,\n );\n // The return type of the paginate method is incorrect.\n const repositories: RestEndpointMethodTypes['apps']['listReposAccessibleToInstallation']['response']['data']['repositories'] =\n repos.repositories ?? repos;\n\n repositoryNames = repositories.map(repository => repository.name);\n }\n return {\n token: result.data.token,\n expiresAt: DateTime.fromISO(result.data.expires_at),\n repositories: repositoryNames,\n };\n });\n }\n\n getInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n return this.appClient.paginate(this.appClient.apps.listInstallations);\n }\n\n private async getInstallationData(owner: string): Promise<InstallationData> {\n const allInstallations = await this.getInstallations();\n const installation = allInstallations.find(\n inst =>\n inst.account &&\n 'login' in inst.account &&\n inst.account.login?.toLocaleLowerCase('en-US') ===\n owner.toLocaleLowerCase('en-US'),\n );\n if (installation) {\n return {\n installationId: installation.id,\n suspended: Boolean(installation.suspended_by),\n };\n }\n const notFoundError = new Error(\n `No app installation found for ${owner} in ${this.baseAuthConfig.appId}`,\n );\n notFoundError.name = 'NotFoundError';\n throw notFoundError;\n }\n}\n\n/**\n * Corresponds to a Github installation which internally could hold several GitHub Apps.\n *\n * @public\n */\nexport class GithubAppCredentialsMux {\n private readonly apps: GithubAppManager[];\n\n constructor(config: GithubIntegrationConfig, appIds: number[] = []) {\n this.apps =\n config.apps\n ?.filter(app => (appIds.length ? appIds.includes(app.appId) : true))\n .map(ac => new GithubAppManager(ac, config.apiBaseUrl)) ?? [];\n }\n\n async getAllInstallations(): Promise<\n RestEndpointMethodTypes['apps']['listInstallations']['response']['data']\n > {\n if (!this.apps.length) {\n return [];\n }\n\n const installs = await Promise.all(\n this.apps.map(app => app.getInstallations()),\n );\n\n return installs.flat();\n }\n\n async getAppToken(owner: string, repo?: string): Promise<string | undefined> {\n if (this.apps.length === 0) {\n return undefined;\n }\n\n const results = await Promise.all(\n this.apps.map(app =>\n app.getInstallationCredentials(owner, repo).then(\n credentials => ({ credentials, error: undefined }),\n error => ({ credentials: undefined, error }),\n ),\n ),\n );\n\n const result = results.find(\n resultItem => resultItem.credentials?.accessToken,\n );\n if (result) {\n return result.credentials!.accessToken;\n }\n\n const errors = results.map(r => r.error);\n const notNotFoundError = errors.find(err => err?.name !== 'NotFoundError');\n if (notNotFoundError) {\n throw notNotFoundError;\n }\n\n return undefined;\n }\n}\n\n/**\n * Handles the creation and caching of credentials for GitHub integrations.\n *\n * @public\n * @remarks\n *\n * TODO: Possibly move this to a backend only package so that it's not used in the frontend by mistake\n */\nexport class SingleInstanceGithubCredentialsProvider\n implements GithubCredentialsProvider\n{\n static create: (\n config: GithubIntegrationConfig,\n ) => GithubCredentialsProvider = config => {\n return new SingleInstanceGithubCredentialsProvider(\n new GithubAppCredentialsMux(config),\n config.token,\n );\n };\n\n private constructor(\n private readonly githubAppCredentialsMux: GithubAppCredentialsMux,\n private readonly token?: string,\n ) {}\n\n /**\n * Returns {@link GithubCredentials} for a given URL.\n *\n * @remarks\n *\n * Consecutive calls to this method with the same URL will return cached\n * credentials.\n *\n * The shortest lifetime for a token returned is 10 minutes.\n *\n * @example\n * ```ts\n * const { token, headers } = await getCredentials({\n * url: 'github.com/backstage/foobar'\n * })\n * ```\n *\n * @param opts - The organization or repository URL\n * @returns A promise of {@link GithubCredentials}.\n */\n async getCredentials(opts: { url: string }): Promise<GithubCredentials> {\n const parsed = parseGitUrl(opts.url);\n\n const owner = parsed.owner || parsed.name;\n const repo = parsed.owner ? parsed.name : undefined;\n\n let type: GithubCredentialType = 'app';\n let token = await this.githubAppCredentialsMux.getAppToken(owner, repo);\n if (!token) {\n type = 'token';\n token = this.token;\n }\n\n return {\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n token,\n type,\n };\n }\n}\n"],"names":[],"mappings":";;;;;AAsCA,MAAM,KAAA,CAAM;AAAA,EACO,UAAA,uBAAiB,GAAA,EAAmC;AAAA,EAErE,MAAM,gBAAA,CACJ,KAAA,EACA,IAAA,EACA,QAAA,EACkC;AAClC,IAAA,IAAI,wBAAA,GAA2B,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAK,CAAA;AAExD,IAAA,IACE,CAAC,wBAAA,IACD,IAAA,CAAK,SAAA,CAAU,wBAAA,CAAyB,SAAS,CAAA,EACjD;AACA,MAAA,wBAAA,GAA2B,MAAM,QAAA,EAAS;AAE1C,MAAA,wBAAA,CAAyB,YACvB,wBAAA,CAAyB,SAAA,CAAU,MAAM,EAAE,OAAA,EAAS,IAAI,CAAA;AAC1D,MAAA,IAAA,CAAK,UAAA,CAAW,GAAA,CAAI,KAAA,EAAO,wBAAwB,CAAA;AAAA,IACrD;AAEA,IAAA,IAAI,CAAC,IAAA,CAAK,aAAA,CAAc,wBAAA,EAA0B,IAAI,CAAA,EAAG;AACvD,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,6CAAA,EAAgD,KAAK,CAAA,iEAAA,EAAoE,IAAI,CAAA;AAAA,OAC/H;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,WAAA,EAAa,wBAAA,CAAyB,KAAA,EAAM;AAAA,EACvD;AAAA,EAEQ,SAAA,GAAY,CAAC,IAAA,KAAmB,QAAA,CAAS,OAAM,GAAI,IAAA;AAAA,EAEnD,aAAA,CAAc,WAAkC,IAAA,EAAe;AAErE,IAAA,IAAI,SAAS,MAAA,EAAW;AACtB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.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\n host: GITHUB_HOST,\n apiBaseUrl: GITHUB_API_BASE_URL,\n rawBaseUrl: GITHUB_RAW_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":["isValidHost","trimEnd"],"mappings":";;;;;AAoBA,MAAM,WAAc,GAAA,YAAA;AACpB,MAAM,mBAAsB,GAAA,wBAAA;AAC5B,MAAM,mBAAsB,GAAA,mCAAA;AAiGrB,SAAS,4BACd,MACyB,EAAA;AACzB,EAAA,MAAM,IAAO,GAAA,MAAA,CAAO,iBAAkB,CAAA,MAAM,CAAK,IAAA,WAAA;AACjD,EAAI,IAAA,UAAA,GAAa,MAAO,CAAA,iBAAA,CAAkB,YAAY,CAAA;AACtD,EAAI,IAAA,UAAA,GAAa,MAAO,CAAA,iBAAA,CAAkB,YAAY,CAAA;AACtD,EAAA,MAAM,KAAQ,GAAA,MAAA,CAAO,iBAAkB,CAAA,OAAO,GAAG,IAAK,EAAA;AACtD,EAAA,MAAM,OAAO,MAAO,CAAA,sBAAA,CAAuB,MAAM,CAAA,EAAG,IAAI,CAAM,CAAA,MAAA;AAAA,IAC5D,KAAA,EAAO,CAAE,CAAA,SAAA,CAAU,OAAO,CAAA;AAAA,IAC1B,QAAA,EAAU,CAAE,CAAA,SAAA,CAAU,UAAU,CAAA;AAAA,IAChC,YAAA,EAAc,CAAE,CAAA,SAAA,CAAU,cAAc,CAAA;AAAA,IACxC,aAAA,EAAe,CAAE,CAAA,iBAAA,CAAkB,eAAe,CAAA;AAAA,IAClD,UAAA,EAAY,CAAE,CAAA,SAAA,CAAU,YAAY,CAAA;AAAA,IACpC,2BAA2B,CAAE,CAAA,sBAAA;AAAA,MAC3B;AAAA;AACF,GACA,CAAA,CAAA;AAEF,EAAI,IAAA,CAACA,mBAAY,CAAA,IAAI,CAAG,EAAA;AACtB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,qBAAA;AAAA,KAC7C;AAAA;AAGF,EAAA,IAAI,UAAY,EAAA;AACd,IAAa,UAAA,GAAAC,cAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,GACtC,MAAA,IAAW,SAAS,WAAa,EAAA;AAC/B,IAAa,UAAA,GAAA,mBAAA;AAAA;AAGf,EAAA,IAAI,UAAY,EAAA;AACd,IAAa,UAAA,GAAAA,cAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,GACtC,MAAA,IAAW,SAAS,WAAa,EAAA;AAC/B,IAAa,UAAA,GAAA,mBAAA;AAAA;AAGf,EAAA,OAAO,EAAE,IAAA,EAAM,UAAY,EAAA,UAAA,EAAY,OAAO,IAAK,EAAA;AACrD;AASO,SAAS,6BACd,OAC2B,EAAA;AAE3B,EAAM,MAAA,MAAA,GAAS,OAAQ,CAAA,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAO,CAAA,IAAA,CAAK,OAAK,CAAE,CAAA,IAAA,KAAS,WAAW,CAAG,EAAA;AAC7C,IAAA,MAAA,CAAO,IAAK,CAAA;AAAA,MACV,IAAM,EAAA,WAAA;AAAA,MACN,UAAY,EAAA,mBAAA;AAAA,MACZ,UAAY,EAAA;AAAA,KACb,CAAA;AAAA;AAGH,EAAO,OAAA,MAAA;AACT;;;;;"}
1
+ {"version":3,"file":"config.cjs.js","sources":["../../src/github/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\n host: GITHUB_HOST,\n apiBaseUrl: GITHUB_API_BASE_URL,\n rawBaseUrl: GITHUB_RAW_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":["isValidHost","trimEnd"],"mappings":";;;;;AAoBA,MAAM,WAAA,GAAc,YAAA;AACpB,MAAM,mBAAA,GAAsB,wBAAA;AAC5B,MAAM,mBAAA,GAAsB,mCAAA;AAiGrB,SAAS,4BACd,MAAA,EACyB;AACzB,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,iBAAA,CAAkB,MAAM,CAAA,IAAK,WAAA;AACjD,EAAA,IAAI,UAAA,GAAa,MAAA,CAAO,iBAAA,CAAkB,YAAY,CAAA;AACtD,EAAA,IAAI,UAAA,GAAa,MAAA,CAAO,iBAAA,CAAkB,YAAY,CAAA;AACtD,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,iBAAA,CAAkB,OAAO,GAAG,IAAA,EAAK;AACtD,EAAA,MAAM,OAAO,MAAA,CAAO,sBAAA,CAAuB,MAAM,CAAA,EAAG,IAAI,CAAA,CAAA,MAAM;AAAA,IAC5D,KAAA,EAAO,CAAA,CAAE,SAAA,CAAU,OAAO,CAAA;AAAA,IAC1B,QAAA,EAAU,CAAA,CAAE,SAAA,CAAU,UAAU,CAAA;AAAA,IAChC,YAAA,EAAc,CAAA,CAAE,SAAA,CAAU,cAAc,CAAA;AAAA,IACxC,aAAA,EAAe,CAAA,CAAE,iBAAA,CAAkB,eAAe,CAAA;AAAA,IAClD,UAAA,EAAY,CAAA,CAAE,SAAA,CAAU,YAAY,CAAA;AAAA,IACpC,2BAA2B,CAAA,CAAE,sBAAA;AAAA,MAC3B;AAAA;AACF,GACF,CAAE,CAAA;AAEF,EAAA,IAAI,CAACA,mBAAA,CAAY,IAAI,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,qBAAA;AAAA,KAC7C;AAAA,EACF;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAaC,cAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAaA,cAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,OAAO,IAAA,EAAK;AACrD;AASO,SAAS,6BACd,OAAA,EAC2B;AAE3B,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAA,CAAO,IAAA,CAAK,OAAK,CAAA,CAAE,IAAA,KAAS,WAAW,CAAA,EAAG;AAC7C,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,WAAA;AAAA,MACN,UAAA,EAAY,mBAAA;AAAA,MACZ,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"config.esm.js","sources":["../../src/github/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\n host: GITHUB_HOST,\n apiBaseUrl: GITHUB_API_BASE_URL,\n rawBaseUrl: GITHUB_RAW_BASE_URL,\n });\n }\n\n return result;\n}\n"],"names":[],"mappings":";;;AAoBA,MAAM,WAAc,GAAA,YAAA;AACpB,MAAM,mBAAsB,GAAA,wBAAA;AAC5B,MAAM,mBAAsB,GAAA,mCAAA;AAiGrB,SAAS,4BACd,MACyB,EAAA;AACzB,EAAA,MAAM,IAAO,GAAA,MAAA,CAAO,iBAAkB,CAAA,MAAM,CAAK,IAAA,WAAA;AACjD,EAAI,IAAA,UAAA,GAAa,MAAO,CAAA,iBAAA,CAAkB,YAAY,CAAA;AACtD,EAAI,IAAA,UAAA,GAAa,MAAO,CAAA,iBAAA,CAAkB,YAAY,CAAA;AACtD,EAAA,MAAM,KAAQ,GAAA,MAAA,CAAO,iBAAkB,CAAA,OAAO,GAAG,IAAK,EAAA;AACtD,EAAA,MAAM,OAAO,MAAO,CAAA,sBAAA,CAAuB,MAAM,CAAA,EAAG,IAAI,CAAM,CAAA,MAAA;AAAA,IAC5D,KAAA,EAAO,CAAE,CAAA,SAAA,CAAU,OAAO,CAAA;AAAA,IAC1B,QAAA,EAAU,CAAE,CAAA,SAAA,CAAU,UAAU,CAAA;AAAA,IAChC,YAAA,EAAc,CAAE,CAAA,SAAA,CAAU,cAAc,CAAA;AAAA,IACxC,aAAA,EAAe,CAAE,CAAA,iBAAA,CAAkB,eAAe,CAAA;AAAA,IAClD,UAAA,EAAY,CAAE,CAAA,SAAA,CAAU,YAAY,CAAA;AAAA,IACpC,2BAA2B,CAAE,CAAA,sBAAA;AAAA,MAC3B;AAAA;AACF,GACA,CAAA,CAAA;AAEF,EAAI,IAAA,CAAC,WAAY,CAAA,IAAI,CAAG,EAAA;AACtB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,qBAAA;AAAA,KAC7C;AAAA;AAGF,EAAA,IAAI,UAAY,EAAA;AACd,IAAa,UAAA,GAAA,OAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,GACtC,MAAA,IAAW,SAAS,WAAa,EAAA;AAC/B,IAAa,UAAA,GAAA,mBAAA;AAAA;AAGf,EAAA,IAAI,UAAY,EAAA;AACd,IAAa,UAAA,GAAA,OAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,GACtC,MAAA,IAAW,SAAS,WAAa,EAAA;AAC/B,IAAa,UAAA,GAAA,mBAAA;AAAA;AAGf,EAAA,OAAO,EAAE,IAAA,EAAM,UAAY,EAAA,UAAA,EAAY,OAAO,IAAK,EAAA;AACrD;AASO,SAAS,6BACd,OAC2B,EAAA;AAE3B,EAAM,MAAA,MAAA,GAAS,OAAQ,CAAA,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAO,CAAA,IAAA,CAAK,OAAK,CAAE,CAAA,IAAA,KAAS,WAAW,CAAG,EAAA;AAC7C,IAAA,MAAA,CAAO,IAAK,CAAA;AAAA,MACV,IAAM,EAAA,WAAA;AAAA,MACN,UAAY,EAAA,mBAAA;AAAA,MACZ,UAAY,EAAA;AAAA,KACb,CAAA;AAAA;AAGH,EAAO,OAAA,MAAA;AACT;;;;"}
1
+ {"version":3,"file":"config.esm.js","sources":["../../src/github/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost } from '../helpers';\n\nconst GITHUB_HOST = 'github.com';\nconst GITHUB_API_BASE_URL = 'https://api.github.com';\nconst GITHUB_RAW_BASE_URL = 'https://raw.githubusercontent.com';\n\n/**\n * The configuration parameters for a single GitHub integration.\n *\n * @public\n */\nexport type GithubIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"github.com\"\n */\n host: string;\n\n /**\n * The base URL of the API of this provider, e.g. \"https://api.github.com\",\n * with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n apiBaseUrl?: string;\n\n /**\n * The base URL of the raw fetch endpoint of this provider, e.g.\n * \"https://raw.githubusercontent.com\", with no trailing slash.\n *\n * May be omitted specifically for GitHub; then it will be deduced.\n *\n * The API will always be preferred if both its base URL and a token are\n * present.\n */\n rawBaseUrl?: string;\n\n /**\n * The authorization token to use for requests to this provider.\n *\n * If no token is specified, anonymous access is used.\n */\n token?: string;\n\n /**\n * The GitHub Apps configuration to use for requests to this provider.\n *\n * If no apps are specified, token or anonymous is used.\n */\n apps?: GithubAppConfig[];\n};\n\n/**\n * The configuration parameters for authenticating a GitHub Application.\n *\n * @remarks\n *\n * A GitHub Apps configuration can be generated using the `backstage-cli create-github-app` command.\n *\n * @public\n */\nexport type GithubAppConfig = {\n /**\n * Unique app identifier, found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n appId: number;\n /**\n * The private key is used by the GitHub App integration to authenticate the app.\n * A private key can be generated from the app at https://github.com/organizations/$org/settings/apps/$AppName\n */\n privateKey: string;\n /**\n * Webhook secret can be configured at https://github.com/organizations/$org/settings/apps/$AppName\n */\n webhookSecret?: string;\n /**\n * Found at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientId: string;\n /**\n * Client secrets can be generated at https://github.com/organizations/$org/settings/apps/$AppName\n */\n clientSecret: string;\n /**\n * List of installation owners allowed to be used by this GitHub app. The GitHub UI does not provide a way to list the installations.\n * However you can list the installations with the GitHub API. You can find the list of installations here:\n * https://api.github.com/app/installations\n * The relevant documentation for this is here.\n * https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app--code-samples\n */\n allowedInstallationOwners?: string[];\n};\n\n/**\n * Reads a single GitHub integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readGithubIntegrationConfig(\n config: Config,\n): GithubIntegrationConfig {\n const host = config.getOptionalString('host') ?? GITHUB_HOST;\n let apiBaseUrl = config.getOptionalString('apiBaseUrl');\n let rawBaseUrl = config.getOptionalString('rawBaseUrl');\n const token = config.getOptionalString('token')?.trim();\n const apps = config.getOptionalConfigArray('apps')?.map(c => ({\n appId: c.getNumber('appId'),\n clientId: c.getString('clientId'),\n clientSecret: c.getString('clientSecret'),\n webhookSecret: c.getOptionalString('webhookSecret'),\n privateKey: c.getString('privateKey'),\n allowedInstallationOwners: c.getOptionalStringArray(\n 'allowedInstallationOwners',\n ),\n }));\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid GitHub integration config, '${host}' is not a valid host`,\n );\n }\n\n if (apiBaseUrl) {\n apiBaseUrl = trimEnd(apiBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n apiBaseUrl = GITHUB_API_BASE_URL;\n }\n\n if (rawBaseUrl) {\n rawBaseUrl = trimEnd(rawBaseUrl, '/');\n } else if (host === GITHUB_HOST) {\n rawBaseUrl = GITHUB_RAW_BASE_URL;\n }\n\n return { host, apiBaseUrl, rawBaseUrl, token, apps };\n}\n\n/**\n * Reads a set of GitHub integration configs, and inserts some defaults for\n * public GitHub if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readGithubIntegrationConfigs(\n configs: Config[],\n): GithubIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readGithubIntegrationConfig);\n\n // If no explicit github.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === GITHUB_HOST)) {\n result.push({\n host: GITHUB_HOST,\n apiBaseUrl: GITHUB_API_BASE_URL,\n rawBaseUrl: GITHUB_RAW_BASE_URL,\n });\n }\n\n return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AA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,UAAA,GAAa,OAAA,CAAQ,YAAY,GAAG,CAAA;AAAA,EACtC,CAAA,MAAA,IAAW,SAAS,WAAA,EAAa;AAC/B,IAAA,UAAA,GAAa,mBAAA;AAAA,EACf;AAEA,EAAA,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,OAAO,IAAA,EAAK;AACrD;AASO,SAAS,6BACd,OAAA,EAC2B;AAE3B,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,2BAA2B,CAAA;AAItD,EAAA,IAAI,CAAC,MAAA,CAAO,IAAA,CAAK,OAAK,CAAA,CAAE,IAAA,KAAS,WAAW,CAAA,EAAG;AAC7C,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,IAAA,EAAM,WAAA;AAAA,MACN,UAAA,EAAY,mBAAA;AAAA,MACZ,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"core.cjs.js","sources":["../../src/github/core.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubIntegrationConfig } from './config';\nimport { GithubCredentials } from './types';\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n *\n * @deprecated This function is no longer used internally\n * @param config - The relevant provider config\n * @public\n */\nexport function getGitHubRequestOptions(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): { headers: Record<string, string> } {\n const headers: Record<string, string> = {};\n\n if (chooseEndpoint(config, credentials) === 'api') {\n headers.Accept = 'application/vnd.github.v3.raw';\n }\n\n if (credentials.token) {\n headers.Authorization = `token ${credentials.token}`;\n }\n\n return { headers };\n}\n\nexport function chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBaseUrl)) {\n return 'api';\n }\n return 'raw';\n}\n"],"names":["parseGitUrl"],"mappings":";;;;;;;;AAmCgB,SAAA,qBAAA,CACd,GACA,EAAA,MAAA,EACA,WACQ,EAAA;AACR,EAAI,IAAA;AACF,IAAM,MAAA,EAAE,OAAO,IA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ACnB;AAEgB,SAAA,cAAA,CACd,QACA,WACe,EAAA;AACf,EAAA,IAAI,OAAO,UAAe,KAAA,WAAA,CAAY,KAAS,IAAA,CAAC,OAAO,UAAa,CAAA,EAAA;AAClE,IAAO,OAAA,KAAA;AAAA;AAET,EAAO,OAAA,KAAA;AACT;;;;;;"}
1
+ {"version":3,"file":"core.cjs.js","sources":["../../src/github/core.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubIntegrationConfig } from './config';\nimport { GithubCredentials } from './types';\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n *\n * @deprecated This function is no longer used internally\n * @param config - The relevant provider config\n * @public\n */\nexport function getGitHubRequestOptions(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): { headers: Record<string, string> } {\n const headers: Record<string, string> = {};\n\n if (chooseEndpoint(config, credentials) === 'api') {\n headers.Accept = 'application/vnd.github.v3.raw';\n }\n\n if (credentials.token) {\n headers.Authorization = `token ${credentials.token}`;\n }\n\n return { headers };\n}\n\nexport function chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBaseUrl)) {\n return 'api';\n }\n return 'raw';\n}\n"],"names":["parseGitUrl"],"mappings":";;;;;;;;AAmCO,SAAS,qBAAA,CACd,GAAA,EACA,MAAA,EACA,WAAA,EACQ;AACR,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,OAAO,IAAA,EAAM,GAAA,EAAK,cAAc,QAAA,EAAS,GAAIA,6BAAY,GAAG,CAAA;AACpE,IAAA,IACE,CAAC,KAAA,IACD,CAAC,IAAA,IACD,CAAC,GAAA;AAAA;AAAA,IAGA,YAAA,KAAiB,MAAA,IAChB,YAAA,KAAiB,KAAA,IACjB,iBAAiB,MAAA,EACnB;AACA,MAAA,MAAM,IAAI,MAAM,iCAAiC,CAAA;AAAA,IACnD;AAEA,IAAA,MAAM,gBAAA,GAAmB,QAAA,CAAS,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACnD,IAAA,IAAI,cAAA,CAAe,MAAA,EAAQ,WAAW,CAAA,KAAM,KAAA,EAAO;AACjD,MAAA,OAAO,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,OAAA,EAAU,KAAK,IAAI,IAAI,CAAA,UAAA,EAAa,gBAAgB,CAAA,KAAA,EAAQ,GAAG,CAAA,CAAA;AAAA,IAC5F;AACA,IAAA,OAAO,CAAA,EAAG,MAAA,CAAO,UAAU,CAAA,CAAA,EAAI,KAAK,IAAI,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA,CAAA;AAAA,EACzE,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC/C;AACF;AASO,SAAS,uBAAA,CACd,QACA,WAAA,EACqC;AACrC,EAAA,MAAM,UAAkC,EAAC;AAEzC,EAAA,IAAI,cAAA,CAAe,MAAA,EAAQ,WAAW,CAAA,KAAM,KAAA,EAAO;AACjD,IAAA,OAAA,CAAQ,MAAA,GAAS,+BAAA;AAAA,EACnB;AAEA,EAAA,IAAI,YAAY,KAAA,EAAO;AACrB,IAAA,OAAA,CAAQ,aAAA,GAAgB,CAAA,MAAA,EAAS,WAAA,CAAY,KAAK,CAAA,CAAA;AAAA,EACpD;AAEA,EAAA,OAAO,EAAE,OAAA,EAAQ;AACnB;AAEO,SAAS,cAAA,CACd,QACA,WAAA,EACe;AACf,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,CAAY,KAAA,IAAS,CAAC,OAAO,UAAA,CAAA,EAAa;AAClE,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"core.esm.js","sources":["../../src/github/core.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubIntegrationConfig } from './config';\nimport { GithubCredentials } from './types';\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n *\n * @deprecated This function is no longer used internally\n * @param config - The relevant provider config\n * @public\n */\nexport function getGitHubRequestOptions(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): { headers: Record<string, string> } {\n const headers: Record<string, string> = {};\n\n if (chooseEndpoint(config, credentials) === 'api') {\n headers.Accept = 'application/vnd.github.v3.raw';\n }\n\n if (credentials.token) {\n headers.Authorization = `token ${credentials.token}`;\n }\n\n return { headers };\n}\n\nexport function chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBaseUrl)) {\n return 'api';\n }\n return 'raw';\n}\n"],"names":[],"mappings":";;AAmCgB,SAAA,qBAAA,CACd,GACA,EAAA,MAAA,EACA,WACQ,EAAA;AACR,EAAI,IAAA;AACF,IAAM,MAAA,EAAE,OAAO,IAAM,EAAA,GAAA,EAAK,cAAc,QAAS,EAAA,GAAI,YAAY,GAAG,CAAA;AACpE,IAAA,IACE,CAAC,KAAA,IACD,CAAC,IAAA,IACD,CAAC,GAAA;AAAA;AAAA,IAGA,YAAiB,KAAA,MAAA,IAChB,YAAiB,KAAA,KAAA,IACjB,iBAAiB,MACnB,EAAA;AACA,MAAM,MAAA,IAAI,MAAM,iCAAiC,CAAA;AAAA;AAGnD,IAAA,MAAM,gBAAmB,GAAA,QAAA,CAAS,OAAQ,CAAA,KAAA,EAAO,EAAE,CAAA;AACnD,IAAA,IAAI,cAAe,CAAA,MAAA,EAAQ,WAAW,CAAA,KAAM,KAAO,EAAA;AACjD,MAAO,OAAA,CAAA,EAAG,MAAO,CAAA,UAAU,CAAU,OAAA,EAAA,KAAK,IAAI,IAAI,CAAA,UAAA,EAAa,gBAAgB,CAAA,KAAA,EAAQ,GAAG,CAAA,CAAA;AAAA;AAE5F,IAAO,OAAA,CAAA,EAAG,MAAO,CAAA,UAAU,CAAI,CAAA,EAAA,KAAK,IAAI,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA,CAAA;AAAA,WAChE,CAAG,EAAA;AACV,IAAA,MAAM,IAAI,KAAM,CAAA,CAAA,eAAA,EAAkB,GAAG,CAAA,EAAA,EAAK,CAAC,CAAE,CAAA,CAAA;AAAA;AAEjD;AASgB,SAAA,uBAAA,CACd,QACA,WACqC,EAAA;AACrC,EAAA,MAAM,UAAkC,EAAC;AAEzC,EAAA,IAAI,cAAe,CAAA,MAAA,EAAQ,WAAW,CAAA,KAAM,KAAO,EAAA;AACjD,IAAA,OAAA,CAAQ,MAAS,GAAA,+BAAA;AAAA;AAGnB,EAAA,IAAI,YAAY,KAAO,EAAA;AACrB,IAAQ,OAAA,CAAA,aAAA,GAAgB,CAAS,MAAA,EAAA,WAAA,CAAY,KAAK,CAAA,CAAA;AAAA;AAGpD,EAAA,OAAO,EAAE,OAAQ,EAAA;AACnB;AAEgB,SAAA,cAAA,CACd,QACA,WACe,EAAA;AACf,EAAA,IAAI,OAAO,UAAe,KAAA,WAAA,CAAY,KAAS,IAAA,CAAC,OAAO,UAAa,CAAA,EAAA;AAClE,IAAO,OAAA,KAAA;AAAA;AAET,EAAO,OAAA,KAAA;AACT;;;;"}
1
+ {"version":3,"file":"core.esm.js","sources":["../../src/github/core.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport parseGitUrl from 'git-url-parse';\nimport { GithubIntegrationConfig } from './config';\nimport { GithubCredentials } from './types';\n\n/**\n * Given a URL pointing to a file on a provider, returns a URL that is suitable\n * for fetching the contents of the data.\n *\n * @remarks\n *\n * Converts\n * from: https://github.com/a/b/blob/branchname/path/to/c.yaml\n * to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname\n * or: https://raw.githubusercontent.com/a/b/branchname/c.yaml\n *\n * @param url - A URL pointing to a file\n * @param config - The relevant provider config\n * @public\n */\nexport function getGithubFileFetchUrl(\n url: string,\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): string {\n try {\n const { owner, name, ref, filepathtype, filepath } = parseGitUrl(url);\n if (\n !owner ||\n !name ||\n !ref ||\n // GitHub is automatically redirecting tree urls to blob urls so it's\n // fine to pass a tree url.\n (filepathtype !== 'blob' &&\n filepathtype !== 'raw' &&\n filepathtype !== 'tree')\n ) {\n throw new Error('Invalid GitHub URL or file path');\n }\n\n const pathWithoutSlash = filepath.replace(/^\\//, '');\n if (chooseEndpoint(config, credentials) === 'api') {\n return `${config.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`;\n }\n return `${config.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`;\n } catch (e) {\n throw new Error(`Incorrect URL: ${url}, ${e}`);\n }\n}\n\n/**\n * Gets the request options necessary to make requests to a given provider.\n *\n * @deprecated This function is no longer used internally\n * @param config - The relevant provider config\n * @public\n */\nexport function getGitHubRequestOptions(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): { headers: Record<string, string> } {\n const headers: Record<string, string> = {};\n\n if (chooseEndpoint(config, credentials) === 'api') {\n headers.Accept = 'application/vnd.github.v3.raw';\n }\n\n if (credentials.token) {\n headers.Authorization = `token ${credentials.token}`;\n }\n\n return { headers };\n}\n\nexport function chooseEndpoint(\n config: GithubIntegrationConfig,\n credentials: GithubCredentials,\n): 'api' | 'raw' {\n if (config.apiBaseUrl && (credentials.token || !config.rawBaseUrl)) {\n return 'api';\n }\n return 'raw';\n}\n"],"names":[],"mappings":";;AAmCO,SAAS,qBAAA,CACd,GAAA,EACA,MAAA,EACA,WAAA,EACQ;AACR,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,OAAO,IAAA,EAAM,GAAA,EAAK,cAAc,QAAA,EAAS,GAAI,YAAY,GAAG,CAAA;AACpE,IAAA,IACE,CAAC,KAAA,IACD,CAAC,IAAA,IACD,CAAC,GAAA;AAAA;AAAA,IAGA,YAAA,KAAiB,MAAA,IAChB,YAAA,KAAiB,KAAA,IACjB,iBAAiB,MAAA,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