@vite-hub/forge 0.7.0 → 0.9.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 (26) hide show
  1. package/README.md +8 -2
  2. package/dist/build/node.js +0 -6
  3. package/dist/{webhooks-Bc6QhmI8-CvF2iFBp.js → define-C9xZZNVR-C-oojQRP.js} +3 -997
  4. package/dist/{definition-BQFdu9ti-BURTyX81.js → definition-BQFdu9ti-BZgR-gkB.js} +5 -4
  5. package/dist/{github-Csy_qzZc.js → definition-s83gxg2p-JwDgFji9.js} +26 -28
  6. package/dist/{events-BL0zcgMf-DGySmhNt.js → events-BL0zcgMf-Exs7JLX1.js} +4 -2
  7. package/dist/{events-DDdJnmD2-BhNdO8U_.js → events-DDdJnmD2-CdPFePvp.js} +4 -3
  8. package/dist/{events-DHqSJ5KI-DfFbbwBb.js → events-DHqSJ5KI-mRtn-qQ0.js} +4 -3
  9. package/dist/{events-DXE-Ul2S-U2BH_jTW.js → events-DXE-Ul2S-BEUw4sQF.js} +4 -3
  10. package/dist/{feed-B1OiHFg0-a2dzl1Va.js → feed-B1OiHFg0-ppQHqkxG.js} +4 -2
  11. package/dist/{feed-DROLF1tb-A1eZev0R.js → feed-DROLF1tb-CMAanXw8.js} +4 -2
  12. package/dist/{feed-iWegqepj-id4yPYnY.js → feed-iWegqepj-DKBLqhvD.js} +4 -2
  13. package/dist/{forgejo-aZiaqKRW.js → forgejo-Deckk49p.js} +2 -2
  14. package/dist/{gitea-CCZ3fS7H.js → gitea-ChQKeRrf.js} +2 -2
  15. package/dist/{gitee-CKt4pEC0-dsy0hiLG.js → gitee-CKt4pEC0-BuzC1PrM.js} +1 -1
  16. package/dist/{gitlab-AAJN-eVR.js → gitlab-CzCikZzN.js} +5 -4
  17. package/dist/{graphql-DxRA9BGO-CiA7HWVp.js → graphql-DxRA9BGO-Cy511t8-.js} +2 -1
  18. package/dist/index.d.ts +50 -8
  19. package/dist/index.js +187 -20
  20. package/dist/kit-CrquHPqr.js +4 -0
  21. package/dist/{templates-0m5QBVIh-Bop0TOo9.js → templates-0m5QBVIh-C1DcQ_yo.js} +1 -2
  22. package/dist/utils-DEwhctg5-BM3AMnSs.js +1213 -0
  23. package/dist/webhooks-Bc6QhmI8-CgoCnwj1.js +71 -0
  24. package/package.json +2 -2
  25. package/dist/kit-UEdJKGws.js +0 -3
  26. package/dist/model-Biiu1CfI-CVLamGai.js +0 -288
package/dist/index.js CHANGED
@@ -1,9 +1,22 @@
1
- import { b as NotFoundError, c as repoRef, g as ForgeTimeoutError, p as ForgeApiError, u as BranchMovedError, v as MergeBlockedError, x as RateLimitedError } from "./model-Biiu1CfI-CVLamGai.js";
1
+ import { i as defineForgeProvider } from "./define-C9xZZNVR-C-oojQRP.js";
2
+ import { n as githubDefinition, t as GITHUB_PROFILE } from "./definition-s83gxg2p-JwDgFji9.js";
3
+ import { Y as repoRef, Z as BranchMovedError, et as ForgeApiError, it as MergeBlockedError, nt as ForgeTimeoutError, ot as NotFoundError, st as RateLimitedError } from "./utils-DEwhctg5-BM3AMnSs.js";
2
4
  import { AsyncLocalStorage } from "node:async_hooks";
3
5
  import { defineErrors, isRuntimeDiagnostic } from "@vite-hub/runtime";
4
6
  import { defineDiagnostics } from "nostics";
5
7
  import { createHash } from "node:crypto";
6
- import { Buffer } from "node:buffer";
8
+ import { Buffer as Buffer$1 } from "node:buffer";
9
+ // \0rolldown/runtime.js
10
+ var __defProp = Object.defineProperty;
11
+ var __exportAll = (all, no_symbols) => {
12
+ let target = {};
13
+ for (var name in all) __defProp(target, name, {
14
+ get: all[name],
15
+ enumerable: true
16
+ });
17
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ return target;
19
+ };
7
20
  // ../internal/src/runtime/cloudflare-env-lookup.ts
8
21
  /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
9
22
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
@@ -42,6 +55,15 @@ const forgeEnv = {
42
55
  names: ["VITEHUB_GITHUB_BASE_URL", "FORGES_GITHUB_BASE_URL"],
43
56
  description: "GitHub API URL for GitHub Enterprise Server."
44
57
  },
58
+ clientId: {
59
+ names: ["VITEHUB_GITHUB_CLIENT_ID", "FORGES_GITHUB_CLIENT_ID"],
60
+ description: "Client ID of the GitHub App that signs a person in to act as themselves."
61
+ },
62
+ clientSecret: {
63
+ names: ["VITEHUB_GITHUB_CLIENT_SECRET", "FORGES_GITHUB_CLIENT_SECRET"],
64
+ secret: true,
65
+ description: "Client secret of the GitHub App that trades a sign-in code for a user token."
66
+ },
45
67
  installationId: {
46
68
  names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"],
47
69
  description: "GitHub App installation ID for the repositories of one owner."
@@ -152,6 +174,10 @@ const forgeErrors = /*#__PURE__*/ defineErrors({
152
174
  why: ({ operation, status }) => status === void 0 ? `${operation} failed.` : `${operation} failed with HTTP ${status}.`,
153
175
  fix: "Read `error.cause` for the Forge error. A 401 means that the App ID, the private key, or the token is wrong. Retry after a 5xx or a network error."
154
176
  },
177
+ FORGE_USER_AUTH_FAILED: {
178
+ why: ({ reason }) => `GitHub refused the user authorization: ${reason}`,
179
+ fix: "Send the person through the GitHub authorization again. Check that the client ID and secret belong to the GitHub App, and that the redirect URI is one of its callback URLs."
180
+ },
155
181
  FORGE_MISSING_ENV: {
156
182
  why: ({ forge, names }) => `The ${forge} Forge has no credentials. It reads ${names}.`,
157
183
  fix: "Set the variables in the host environment, or pass `env` to `useForge()`."
@@ -322,14 +348,15 @@ function conditionalFetch(fetcher, options = {}) {
322
348
  };
323
349
  }
324
350
  // src/provider.ts
325
- async function forgeProvider(connection) {
351
+ /** The `forges` options of one connection, for a provider made without the dynamic import of `forgeProvider()`. */
352
+ function forgeProviderOptions(connection) {
326
353
  const auth = connection.token ? {
327
354
  type: "token",
328
355
  token: connection.token
329
356
  } : { type: "anonymous" };
330
357
  const conditional = connection.conditionalRequests ?? connection.forge === "github";
331
358
  const fetcher = conditional ? conditionalFetch(connection.fetch ?? ((input, init) => globalThis.fetch(input, init)), conditional === true ? {} : conditional) : connection.fetch;
332
- const options = {
359
+ return {
333
360
  ...connection.baseUrl ? { baseUrl: connection.baseUrl } : {},
334
361
  ...fetcher ? { fetch: fetcher } : {},
335
362
  userAgent: connection.userAgent ?? "vitehub",
@@ -337,21 +364,24 @@ async function forgeProvider(connection) {
337
364
  ...connection.readOnly === void 0 ? {} : { readOnly: connection.readOnly },
338
365
  auth
339
366
  };
367
+ }
368
+ async function forgeProvider(connection) {
369
+ const options = forgeProviderOptions(connection);
340
370
  switch (connection.forge) {
341
371
  case "github": {
342
- const { github } = await import("./github-Csy_qzZc.js");
372
+ const { github } = await Promise.resolve().then(() => github_exports);
343
373
  return github(options);
344
374
  }
345
375
  case "gitlab": {
346
- const { gitlab } = await import("./gitlab-AAJN-eVR.js");
376
+ const { gitlab } = await import("./gitlab-CzCikZzN.js");
347
377
  return gitlab(options);
348
378
  }
349
379
  case "forgejo": {
350
- const { forgejo } = await import("./forgejo-aZiaqKRW.js");
380
+ const { forgejo } = await import("./forgejo-Deckk49p.js");
351
381
  return forgejo(options);
352
382
  }
353
383
  case "gitea": {
354
- const { gitea } = await import("./gitea-CCZ3fS7H.js");
384
+ const { gitea } = await import("./gitea-ChQKeRrf.js");
355
385
  const { webhookSecret } = connection;
356
386
  return gitea({
357
387
  ...options,
@@ -458,7 +488,7 @@ function appProvider(input, installationId = "", refresh = false) {
458
488
  if (refresh) appProviders.delete(key);
459
489
  const cached = appProviders.get(key);
460
490
  if (cached) return cached;
461
- const pending = import("./github-Csy_qzZc.js").then(({ github }) => github({
491
+ const pending = Promise.resolve().then(() => github_exports).then(({ github }) => github({
462
492
  ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
463
493
  ...input.fetch ? { fetch: input.fetch } : {},
464
494
  userAgent: input.userAgent ?? "vitehub",
@@ -483,7 +513,7 @@ async function appIdentity(input) {
483
513
  if (!id) throw forgeResponseError("GitHub App metadata did not include an ID.");
484
514
  if (!slug) throw forgeResponseError("GitHub App response did not include a slug.");
485
515
  const login = `${slug}[bot]`;
486
- const { github } = await import("./github-Csy_qzZc.js");
516
+ const { github } = await Promise.resolve().then(() => github_exports);
487
517
  const userId = await github({
488
518
  ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
489
519
  ...input.fetch ? { fetch: input.fetch } : {},
@@ -694,6 +724,120 @@ function githubInstallationFor(routing, repository) {
694
724
  const owner = repository.split("/", 1)[0].toLowerCase();
695
725
  return (Object.hasOwn(routing.installations, owner) ? routing.installations[owner] : void 0) ?? (owner === routing.owner ? routing.installationId : void 0);
696
726
  }
727
+ // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/github/index.mjs
728
+ var github_exports = /* @__PURE__ */ __exportAll({ github: () => github });
729
+ /** Creates a GitHub provider for github.com or a GitHub Enterprise Server instance. */
730
+ const github = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ githubDefinition(GITHUB_PROFILE));
731
+ // src/github-user.ts
732
+ function githubWebUrl(baseUrl) {
733
+ if (!baseUrl) return "https://github.com";
734
+ const url = new URL(baseUrl);
735
+ if (url.hostname === "api.github.com" || /^api\.[a-z0-9-]+\.ghe\.com$/.test(url.hostname)) url.hostname = url.hostname.slice(4);
736
+ return url.origin;
737
+ }
738
+ function expiry(seconds, now) {
739
+ return typeof seconds === "number" && seconds > 0 ? new Date(now + seconds * 1e3) : void 0;
740
+ }
741
+ /** `forge.user` of a GitHub Forge. */
742
+ function githubUser(input) {
743
+ const web = githubWebUrl(input.baseUrl);
744
+ const fetcher = input.fetch ?? ((url, init) => globalThis.fetch(url, init));
745
+ function provider(token) {
746
+ return github(forgeProviderOptions({
747
+ forge: "github",
748
+ token,
749
+ userAgent: input.userAgent,
750
+ ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
751
+ ...input.fetch ? { fetch: input.fetch } : {},
752
+ ...input.conditionalRequests === false ? { conditionalRequests: false } : {}
753
+ }));
754
+ }
755
+ function failed(operation, cause, signal) {
756
+ if (signal?.aborted) throw abortError(signal);
757
+ const status = forgeErrorStatus(cause);
758
+ return forgeErrors.FORGE_REQUEST_FAILED({
759
+ cause,
760
+ operation,
761
+ ...status === void 0 ? {} : { status }
762
+ });
763
+ }
764
+ async function grant(params, signal) {
765
+ if (signal?.aborted) throw abortError(signal);
766
+ const operation = "POST /login/oauth/access_token";
767
+ const now = Date.now();
768
+ let body;
769
+ try {
770
+ const response = await fetcher(`${web}/login/oauth/access_token`, {
771
+ method: "POST",
772
+ headers: {
773
+ "accept": "application/json",
774
+ "content-type": "application/x-www-form-urlencoded",
775
+ "user-agent": input.userAgent
776
+ },
777
+ body: new URLSearchParams({
778
+ client_id: input.clientId,
779
+ client_secret: input.clientSecret,
780
+ ...params
781
+ }),
782
+ ...signal ? { signal } : {}
783
+ });
784
+ if (!response.ok) return [forgeErrors.FORGE_REQUEST_FAILED({
785
+ operation,
786
+ status: response.status
787
+ }), void 0];
788
+ body = await response.json();
789
+ } catch (cause) {
790
+ return [failed(operation, cause, signal), void 0];
791
+ }
792
+ if (typeof body.error === "string") {
793
+ const reason = typeof body.error_description === "string" ? `${body.error_description} (${body.error})` : body.error;
794
+ return [forgeErrors.FORGE_USER_AUTH_FAILED({ reason }), void 0];
795
+ }
796
+ if (typeof body.access_token !== "string" || !body.access_token) return [failed(operation, forgeResponseError("GitHub user token response did not include access_token."), signal), void 0];
797
+ const token = body.access_token;
798
+ let user;
799
+ try {
800
+ user = (await provider(token).request("GET", "/user", signal ? { signal } : {})).data;
801
+ } catch (cause) {
802
+ return [failed("GET /user", cause, signal), void 0];
803
+ }
804
+ if (typeof user.login !== "string" || typeof user.id !== "number") return [failed("GET /user", forgeResponseError("GitHub user response did not include login and id."), signal), void 0];
805
+ return [void 0, {
806
+ token,
807
+ expiresAt: expiry(body.expires_in, now),
808
+ refreshToken: typeof body.refresh_token === "string" && body.refresh_token ? body.refresh_token : void 0,
809
+ refreshTokenExpiresAt: expiry(body.refresh_token_expires_in, now),
810
+ login: user.login,
811
+ id: user.id
812
+ }];
813
+ }
814
+ return {
815
+ authorizeUrl({ redirectUri, state }) {
816
+ const url = new URL("/login/oauth/authorize", web);
817
+ url.search = new URLSearchParams({
818
+ client_id: input.clientId,
819
+ redirect_uri: redirectUri,
820
+ state
821
+ }).toString();
822
+ return url.toString();
823
+ },
824
+ exchange({ code, redirectUri, signal }) {
825
+ return grant({
826
+ code,
827
+ redirect_uri: redirectUri
828
+ }, signal);
829
+ },
830
+ refresh({ refreshToken, signal }) {
831
+ return grant({
832
+ grant_type: "refresh_token",
833
+ refresh_token: refreshToken
834
+ }, signal);
835
+ },
836
+ provider({ token }) {
837
+ return provider(token);
838
+ }
839
+ };
840
+ }
697
841
  // src/use-forge.ts
698
842
  function hostEnv(name) {
699
843
  return getActiveCloudflareBinding(name) ?? globalThis.process?.env?.[name];
@@ -726,6 +870,16 @@ function readGitHubApp(env) {
726
870
  privateKeyPath
727
871
  };
728
872
  }
873
+ function readGitHubUser(env) {
874
+ const { github } = forgeEnv;
875
+ const clientId = readForgeEnv(github.clientId, env);
876
+ const clientSecret = readForgeEnv(github.clientSecret, env);
877
+ if (!clientId || !clientSecret) return void 0;
878
+ return {
879
+ clientId,
880
+ clientSecret
881
+ };
882
+ }
729
883
  async function readAppPrivateKey(config) {
730
884
  const name = primaryName(forgeEnv.github.privateKeyPath);
731
885
  const privateKey = await readGitHubAppPrivateKey(config.privateKey, config.privateKeyPath).catch((cause) => {
@@ -754,6 +908,7 @@ function resolveForgeConfig(options) {
754
908
  const kind = options.forge ?? "github";
755
909
  const env = options.env ?? hostEnv;
756
910
  const githubApp = kind === "github" ? readGitHubApp(env) : void 0;
911
+ const githubUserConfig = kind === "github" ? readGitHubUser(env) : void 0;
757
912
  const configuredToken = githubApp ? void 0 : readForgeEnv(forgeEnv[kind].token, env);
758
913
  const credential = githubApp ? { app: githubApp } : configuredToken ? { token: configuredToken } : void 0;
759
914
  if (!credential) {
@@ -767,7 +922,8 @@ function resolveForgeConfig(options) {
767
922
  kind,
768
923
  credential,
769
924
  baseUrl: options.baseUrl ?? readForgeEnv(forgeEnv[kind].baseUrl, env),
770
- webhookSecret: kind === "gitea" ? readForgeEnv(forgeEnv.gitea.webhookSecret, env) : void 0
925
+ webhookSecret: kind === "gitea" ? readForgeEnv(forgeEnv.gitea.webhookSecret, env) : void 0,
926
+ githubUserConfig
771
927
  };
772
928
  }
773
929
  /**
@@ -780,8 +936,15 @@ function resolveForgeConfig(options) {
780
936
  * ```
781
937
  */
782
938
  function useForge(options = {}) {
783
- const { kind, credential, baseUrl, webhookSecret } = resolveForgeConfig(options);
939
+ const { kind, credential, baseUrl, webhookSecret, githubUserConfig } = resolveForgeConfig(options);
784
940
  const userAgent = options.userAgent ?? "vitehub";
941
+ const user = githubUserConfig ? githubUser({
942
+ ...githubUserConfig,
943
+ userAgent,
944
+ ...baseUrl ? { baseUrl } : {},
945
+ ...options.fetch ? { fetch: options.fetch } : {},
946
+ ...options.conditionalRequests === false ? { conditionalRequests: false } : {}
947
+ }) : void 0;
785
948
  let credentials;
786
949
  function appCredentials(config) {
787
950
  credentials ??= readAppPrivateKey(config).then((privateKey) => githubAppCredentials({
@@ -834,6 +997,7 @@ function useForge(options = {}) {
834
997
  kind,
835
998
  auth: "app" in credential ? "app" : "token",
836
999
  baseUrl,
1000
+ user,
837
1001
  async token(call = {}) {
838
1002
  if (call.signal?.aborted) throw abortError(call.signal);
839
1003
  if (!("app" in credential)) return [void 0, {
@@ -878,7 +1042,7 @@ function useForge(options = {}) {
878
1042
  };
879
1043
  }
880
1044
  /**
881
- * Checks the Forge env and sends no request, for example for a Setup page. It returns `[undefined, { kind, auth }]`
1045
+ * Checks the Forge env and sends no request, for example for a Setup page. It returns `[undefined, { kind, auth, user }]`
882
1046
  * when local configuration is valid, or `[error, undefined]` with a configuration error. It checks the base URL
883
1047
  * and signs locally with the GitHub App private key, but does not check that the forge accepts the credentials.
884
1048
  *
@@ -889,7 +1053,8 @@ function useForge(options = {}) {
889
1053
  */
890
1054
  async function checkForge(options = {}) {
891
1055
  try {
892
- const { kind, credential, baseUrl } = resolveForgeConfig(options);
1056
+ const { kind, credential, baseUrl, githubUserConfig } = resolveForgeConfig(options);
1057
+ const user = githubUserConfig !== void 0;
893
1058
  if (baseUrl) try {
894
1059
  await forgeProvider({
895
1060
  forge: kind,
@@ -906,11 +1071,12 @@ async function checkForge(options = {}) {
906
1071
  }
907
1072
  if (!("app" in credential)) return [void 0, {
908
1073
  kind,
909
- auth: "token"
1074
+ auth: "token",
1075
+ user
910
1076
  }];
911
1077
  const { app } = credential;
912
1078
  const privateKey = await readAppPrivateKey(app);
913
- const { signRs256Jwt } = await import("./kit-UEdJKGws.js");
1079
+ const { signRs256Jwt } = await import("./kit-CrquHPqr.js");
914
1080
  try {
915
1081
  const now = Math.floor(Date.now() / 1e3);
916
1082
  await signRs256Jwt(privateKey, {
@@ -928,7 +1094,8 @@ async function checkForge(options = {}) {
928
1094
  }
929
1095
  return [void 0, {
930
1096
  kind,
931
- auth: "app"
1097
+ auth: "app",
1098
+ user
932
1099
  }];
933
1100
  } catch (error) {
934
1101
  if (forgeErrors.FORGE_MISSING_ENV.is(error) || forgeErrors.FORGE_INVALID_ENV.is(error)) return [error, void 0];
@@ -1028,7 +1195,7 @@ function decodeBase64Blob(value) {
1028
1195
  const content = value.content.replace(/\s+/g, "");
1029
1196
  if (content.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(content)) return void 0;
1030
1197
  try {
1031
- const bytes = Buffer.from(content, "base64");
1198
+ const bytes = Buffer$1.from(content, "base64");
1032
1199
  return bytes.toString("base64") === content ? bytes : void 0;
1033
1200
  } catch {
1034
1201
  return;
@@ -1155,7 +1322,7 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
1155
1322
  sha: null,
1156
1323
  type: "blob"
1157
1324
  };
1158
- const content = Buffer.from(change.content).toString("base64");
1325
+ const content = Buffer$1.from(change.content).toString("base64");
1159
1326
  let blob = blobs.get(content);
1160
1327
  if (!blob) {
1161
1328
  blob = provider.request("POST", `${base}/blobs`, {
@@ -1292,7 +1459,7 @@ function forgeGitCredentials(input) {
1292
1459
  */
1293
1460
  function forgeGitAuthHeader(credentials) {
1294
1461
  if (!credentials.password) return void 0;
1295
- const basic = Buffer.from(`${credentials.username ?? ""}:${credentials.password}`).toString("base64");
1462
+ const basic = Buffer$1.from(`${credentials.username ?? ""}:${credentials.password}`).toString("base64");
1296
1463
  return {
1297
1464
  key: `http.${credentials.url}.extraheader`,
1298
1465
  value: `AUTHORIZATION: basic ${basic}`
@@ -0,0 +1,4 @@
1
+ export { i as signRs256Jwt } from "./crypto-DydCoK4e-BCG61qh5.js";
2
+ import "./utils-DEwhctg5-BM3AMnSs.js";
3
+ import "./define-C9xZZNVR-C-oojQRP.js";
4
+ import "./webhooks-Bc6QhmI8-CgoCnwj1.js";
@@ -1,5 +1,4 @@
1
- import { b as NotFoundError } from "./model-Biiu1CfI-CVLamGai.js";
2
- import { H as mapConcurrent } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
1
+ import { ot as NotFoundError, v as mapConcurrent } from "./utils-DEwhctg5-BM3AMnSs.js";
3
2
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/templates-0m5QBVIh.mjs
4
3
  /** Where GitHub looks for a pull request template and the legacy issue template, in its order of precedence. */
5
4
  const LOCATIONS = [