@leed-ai/git-gateway-worker 0.0.0-stage → 0.1.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 (269) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +49 -2
  3. package/dist/audit/audit-recorder.d.ts +2 -0
  4. package/dist/audit/audit-recorder.js +53 -0
  5. package/dist/audit/audit-recorder.js.map +1 -0
  6. package/dist/audit/push-report.d.ts +13 -0
  7. package/dist/audit/push-report.js +66 -0
  8. package/dist/audit/push-report.js.map +1 -0
  9. package/dist/audit-recorder-K1Ns3tfC.d.ts +31 -0
  10. package/dist/auth/authenticate.d.ts +14 -0
  11. package/dist/auth/authenticate.js +59 -0
  12. package/dist/auth/authenticate.js.map +1 -0
  13. package/dist/auth/authorize.d.ts +12 -0
  14. package/dist/auth/authorize.js +57 -0
  15. package/dist/auth/authorize.js.map +1 -0
  16. package/dist/auth/read-token-auth.d.ts +60 -0
  17. package/dist/auth/read-token-auth.js +83 -0
  18. package/dist/auth/read-token-auth.js.map +1 -0
  19. package/dist/cache/decision-cache.d.ts +2 -0
  20. package/dist/cache/decision-cache.js +45 -0
  21. package/dist/cache/decision-cache.js.map +1 -0
  22. package/dist/commit-workflow-schemas-BWlg7bZR.d.ts +95 -0
  23. package/dist/decision-cache-87U32iSj.d.ts +24 -0
  24. package/dist/gateway-app.d.ts +69 -0
  25. package/dist/gateway-app.js +80 -0
  26. package/dist/gateway-app.js.map +1 -0
  27. package/dist/gateway-context-Boh9I0mk.d.ts +54 -0
  28. package/dist/gateway-env-DnsBU4Pq.d.ts +40 -0
  29. package/dist/gateway-worker.d.ts +13 -0
  30. package/dist/gateway-worker.js +22 -0
  31. package/dist/gateway-worker.js.map +1 -0
  32. package/dist/git-route-Spxi09Rm.d.ts +22 -0
  33. package/dist/health.d.ts +6 -0
  34. package/dist/health.js +16 -0
  35. package/dist/health.js.map +1 -0
  36. package/dist/logger-BZ1zyKLb.d.ts +27 -0
  37. package/dist/logging/logger.d.ts +2 -0
  38. package/dist/logging/logger.js +15 -0
  39. package/dist/logging/logger.js.map +1 -0
  40. package/dist/on-push-DTREOB__.d.ts +62 -0
  41. package/dist/policy/branch-policy.d.ts +24 -0
  42. package/dist/policy/branch-policy.js +125 -0
  43. package/dist/policy/branch-policy.js.map +1 -0
  44. package/dist/policy/enforce-branch-policy.d.ts +30 -0
  45. package/dist/policy/enforce-branch-policy.js +214 -0
  46. package/dist/policy/enforce-branch-policy.js.map +1 -0
  47. package/dist/policy/fast-forward.d.ts +32 -0
  48. package/dist/policy/fast-forward.js +95 -0
  49. package/dist/policy/fast-forward.js.map +1 -0
  50. package/dist/policy/ref-pattern.d.ts +7 -0
  51. package/dist/policy/ref-pattern.js +25 -0
  52. package/dist/policy/ref-pattern.js.map +1 -0
  53. package/dist/policy/rule-branch-policy.d.ts +17 -0
  54. package/dist/policy/rule-branch-policy.js +69 -0
  55. package/dist/policy/rule-branch-policy.js.map +1 -0
  56. package/dist/proxy/defer.d.ts +8 -0
  57. package/dist/proxy/defer.js +15 -0
  58. package/dist/proxy/defer.js.map +1 -0
  59. package/dist/proxy/forward-read.d.ts +11 -0
  60. package/dist/proxy/forward-read.js +53 -0
  61. package/dist/proxy/forward-read.js.map +1 -0
  62. package/dist/proxy/gateway-deps.d.ts +39 -0
  63. package/dist/proxy/gateway-deps.js +0 -0
  64. package/dist/proxy/gateway-env.d.ts +2 -0
  65. package/dist/proxy/gateway-env.js +0 -0
  66. package/dist/proxy/git-responses.d.ts +25 -0
  67. package/dist/proxy/git-responses.js +83 -0
  68. package/dist/proxy/git-responses.js.map +1 -0
  69. package/dist/proxy/git-route.d.ts +2 -0
  70. package/dist/proxy/git-route.js +34 -0
  71. package/dist/proxy/git-route.js.map +1 -0
  72. package/dist/proxy/push-events.d.ts +28 -0
  73. package/dist/proxy/push-events.js +65 -0
  74. package/dist/proxy/push-events.js.map +1 -0
  75. package/dist/proxy/push-guard.d.ts +43 -0
  76. package/dist/proxy/push-guard.js +81 -0
  77. package/dist/proxy/push-guard.js.map +1 -0
  78. package/dist/proxy/push-options.d.ts +16 -0
  79. package/dist/proxy/push-options.js +33 -0
  80. package/dist/proxy/push-options.js.map +1 -0
  81. package/dist/proxy/receive-pack.d.ts +17 -0
  82. package/dist/proxy/receive-pack.js +244 -0
  83. package/dist/proxy/receive-pack.js.map +1 -0
  84. package/dist/proxy/request-log.d.ts +13 -0
  85. package/dist/proxy/request-log.js +41 -0
  86. package/dist/proxy/request-log.js.map +1 -0
  87. package/dist/proxy/resolve-route.d.ts +9 -0
  88. package/dist/proxy/resolve-route.js +22 -0
  89. package/dist/proxy/resolve-route.js.map +1 -0
  90. package/dist/proxy/upstream-call.d.ts +23 -0
  91. package/dist/proxy/upstream-call.js +63 -0
  92. package/dist/proxy/upstream-call.js.map +1 -0
  93. package/dist/proxy/upstream.d.ts +2 -0
  94. package/dist/proxy/upstream.js +68 -0
  95. package/dist/proxy/upstream.js.map +1 -0
  96. package/dist/push-event-f-5TsFUY.d.ts +15 -0
  97. package/dist/push-policy/changed-paths.d.ts +26 -0
  98. package/dist/push-policy/changed-paths.js +117 -0
  99. package/dist/push-policy/changed-paths.js.map +1 -0
  100. package/dist/push-policy/pushed-objects.d.ts +30 -0
  101. package/dist/push-policy/pushed-objects.js +76 -0
  102. package/dist/push-policy/pushed-objects.js.map +1 -0
  103. package/dist/push-policy/run-push-policy.d.ts +35 -0
  104. package/dist/push-policy/run-push-policy.js +77 -0
  105. package/dist/push-policy/run-push-policy.js.map +1 -0
  106. package/dist/push-policy/tree-diff.d.ts +21 -0
  107. package/dist/push-policy/tree-diff.js +78 -0
  108. package/dist/push-policy/tree-diff.js.map +1 -0
  109. package/dist/push-policy/uncheckable.d.ts +14 -0
  110. package/dist/push-policy/uncheckable.js +25 -0
  111. package/dist/push-policy/uncheckable.js.map +1 -0
  112. package/dist/rpc/branch-methods.d.ts +16 -0
  113. package/dist/rpc/branch-methods.js +43 -0
  114. package/dist/rpc/branch-methods.js.map +1 -0
  115. package/dist/rpc/commit-attempt.d.ts +27 -0
  116. package/dist/rpc/commit-attempt.js +85 -0
  117. package/dist/rpc/commit-attempt.js.map +1 -0
  118. package/dist/rpc/commit-graph.d.ts +20 -0
  119. package/dist/rpc/commit-graph.js +38 -0
  120. package/dist/rpc/commit-graph.js.map +1 -0
  121. package/dist/rpc/commit-method.d.ts +13 -0
  122. package/dist/rpc/commit-method.js +30 -0
  123. package/dist/rpc/commit-method.js.map +1 -0
  124. package/dist/rpc/commit-source.d.ts +12 -0
  125. package/dist/rpc/commit-source.js +9 -0
  126. package/dist/rpc/commit-source.js.map +1 -0
  127. package/dist/rpc/gateway-context.d.ts +2 -0
  128. package/dist/rpc/gateway-context.js +30 -0
  129. package/dist/rpc/gateway-context.js.map +1 -0
  130. package/dist/rpc/gateway-rpc.d.ts +10 -0
  131. package/dist/rpc/gateway-rpc.js +48 -0
  132. package/dist/rpc/gateway-rpc.js.map +1 -0
  133. package/dist/rpc/gateway-service.d.ts +24 -0
  134. package/dist/rpc/gateway-service.js +63 -0
  135. package/dist/rpc/gateway-service.js.map +1 -0
  136. package/dist/rpc/history-page.d.ts +35 -0
  137. package/dist/rpc/history-page.js +122 -0
  138. package/dist/rpc/history-page.js.map +1 -0
  139. package/dist/rpc/lifecycle-methods.d.ts +12 -0
  140. package/dist/rpc/lifecycle-methods.js +39 -0
  141. package/dist/rpc/lifecycle-methods.js.map +1 -0
  142. package/dist/rpc/paint-down.d.ts +17 -0
  143. package/dist/rpc/paint-down.js +96 -0
  144. package/dist/rpc/paint-down.js.map +1 -0
  145. package/dist/rpc/promote-attempt.d.ts +21 -0
  146. package/dist/rpc/promote-attempt.js +55 -0
  147. package/dist/rpc/promote-attempt.js.map +1 -0
  148. package/dist/rpc/push-ref.d.ts +21 -0
  149. package/dist/rpc/push-ref.js +47 -0
  150. package/dist/rpc/push-ref.js.map +1 -0
  151. package/dist/rpc/read-methods.d.ts +17 -0
  152. package/dist/rpc/read-methods.js +94 -0
  153. package/dist/rpc/read-methods.js.map +1 -0
  154. package/dist/rpc/read-token.d.ts +39 -0
  155. package/dist/rpc/read-token.js +107 -0
  156. package/dist/rpc/read-token.js.map +1 -0
  157. package/dist/rpc/repo-access.d.ts +36 -0
  158. package/dist/rpc/repo-access.js +75 -0
  159. package/dist/rpc/repo-access.js.map +1 -0
  160. package/dist/rpc/sync-attempt.d.ts +23 -0
  161. package/dist/rpc/sync-attempt.js +105 -0
  162. package/dist/rpc/sync-attempt.js.map +1 -0
  163. package/dist/sync-workflow-schemas-DCNmNE5-.d.ts +57 -0
  164. package/dist/upstream-DvqMCj5N.d.ts +15 -0
  165. package/dist/workflow-starter-BqhwX6oA.d.ts +45 -0
  166. package/dist/workflows/commit-workflow-schemas.d.ts +2 -0
  167. package/dist/workflows/commit-workflow-schemas.js +84 -0
  168. package/dist/workflows/commit-workflow-schemas.js.map +1 -0
  169. package/dist/workflows/commit-workflow.d.ts +16 -0
  170. package/dist/workflows/commit-workflow.js +22 -0
  171. package/dist/workflows/commit-workflow.js.map +1 -0
  172. package/dist/workflows/on-push.d.ts +2 -0
  173. package/dist/workflows/on-push.js +90 -0
  174. package/dist/workflows/on-push.js.map +1 -0
  175. package/dist/workflows/push-event.d.ts +2 -0
  176. package/dist/workflows/push-event.js +28 -0
  177. package/dist/workflows/push-event.js.map +1 -0
  178. package/dist/workflows/run-commit-workflow.d.ts +15 -0
  179. package/dist/workflows/run-commit-workflow.js +49 -0
  180. package/dist/workflows/run-commit-workflow.js.map +1 -0
  181. package/dist/workflows/run-sync-workflow.d.ts +14 -0
  182. package/dist/workflows/run-sync-workflow.js +67 -0
  183. package/dist/workflows/run-sync-workflow.js.map +1 -0
  184. package/dist/workflows/step-errors.d.ts +15 -0
  185. package/dist/workflows/step-errors.js +24 -0
  186. package/dist/workflows/step-errors.js.map +1 -0
  187. package/dist/workflows/step-runner.d.ts +31 -0
  188. package/dist/workflows/step-runner.js +6 -0
  189. package/dist/workflows/step-runner.js.map +1 -0
  190. package/dist/workflows/sync-branch-workflow.d.ts +15 -0
  191. package/dist/workflows/sync-branch-workflow.js +21 -0
  192. package/dist/workflows/sync-branch-workflow.js.map +1 -0
  193. package/dist/workflows/sync-workflow-schemas.d.ts +2 -0
  194. package/dist/workflows/sync-workflow-schemas.js +104 -0
  195. package/dist/workflows/sync-workflow-schemas.js.map +1 -0
  196. package/dist/workflows/workflow-instance-id.d.ts +12 -0
  197. package/dist/workflows/workflow-instance-id.js +33 -0
  198. package/dist/workflows/workflow-instance-id.js.map +1 -0
  199. package/dist/workflows/workflow-runtime.d.ts +7 -0
  200. package/dist/workflows/workflow-runtime.js +11 -0
  201. package/dist/workflows/workflow-runtime.js.map +1 -0
  202. package/dist/workflows/workflow-starter.d.ts +2 -0
  203. package/dist/workflows/workflow-starter.js +40 -0
  204. package/dist/workflows/workflow-starter.js.map +1 -0
  205. package/package.json +381 -4
  206. package/src/audit/audit-recorder.ts +74 -0
  207. package/src/audit/push-report.ts +60 -0
  208. package/src/auth/authenticate.ts +68 -0
  209. package/src/auth/authorize.ts +57 -0
  210. package/src/auth/read-token-auth.ts +119 -0
  211. package/src/cache/decision-cache.ts +57 -0
  212. package/src/gateway-app.ts +147 -0
  213. package/src/gateway-worker.ts +32 -0
  214. package/src/health.ts +12 -0
  215. package/src/logging/logger.ts +40 -0
  216. package/src/policy/branch-policy.ts +119 -0
  217. package/src/policy/enforce-branch-policy.ts +213 -0
  218. package/src/policy/fast-forward.ts +136 -0
  219. package/src/policy/ref-pattern.ts +24 -0
  220. package/src/policy/rule-branch-policy.ts +76 -0
  221. package/src/proxy/defer.ts +18 -0
  222. package/src/proxy/forward-read.ts +52 -0
  223. package/src/proxy/gateway-deps.ts +43 -0
  224. package/src/proxy/gateway-env.ts +43 -0
  225. package/src/proxy/git-responses.ts +89 -0
  226. package/src/proxy/git-route.ts +49 -0
  227. package/src/proxy/push-events.ts +91 -0
  228. package/src/proxy/push-guard.ts +109 -0
  229. package/src/proxy/push-options.ts +38 -0
  230. package/src/proxy/receive-pack.ts +257 -0
  231. package/src/proxy/request-log.ts +44 -0
  232. package/src/proxy/resolve-route.ts +24 -0
  233. package/src/proxy/upstream-call.ts +71 -0
  234. package/src/proxy/upstream.ts +76 -0
  235. package/src/push-policy/changed-paths.ts +143 -0
  236. package/src/push-policy/pushed-objects.ts +88 -0
  237. package/src/push-policy/run-push-policy.ts +99 -0
  238. package/src/push-policy/tree-diff.ts +107 -0
  239. package/src/push-policy/uncheckable.ts +27 -0
  240. package/src/rpc/branch-methods.ts +57 -0
  241. package/src/rpc/commit-attempt.ts +87 -0
  242. package/src/rpc/commit-graph.ts +44 -0
  243. package/src/rpc/commit-method.ts +36 -0
  244. package/src/rpc/commit-source.ts +15 -0
  245. package/src/rpc/gateway-context.ts +77 -0
  246. package/src/rpc/gateway-rpc.ts +65 -0
  247. package/src/rpc/gateway-service.ts +85 -0
  248. package/src/rpc/history-page.ts +163 -0
  249. package/src/rpc/lifecycle-methods.ts +50 -0
  250. package/src/rpc/paint-down.ts +120 -0
  251. package/src/rpc/promote-attempt.ts +52 -0
  252. package/src/rpc/push-ref.ts +54 -0
  253. package/src/rpc/read-methods.ts +111 -0
  254. package/src/rpc/read-token.ts +135 -0
  255. package/src/rpc/repo-access.ts +112 -0
  256. package/src/rpc/sync-attempt.ts +84 -0
  257. package/src/workflows/commit-workflow-schemas.ts +95 -0
  258. package/src/workflows/commit-workflow.ts +39 -0
  259. package/src/workflows/on-push.ts +128 -0
  260. package/src/workflows/push-event.ts +41 -0
  261. package/src/workflows/run-commit-workflow.ts +45 -0
  262. package/src/workflows/run-sync-workflow.ts +52 -0
  263. package/src/workflows/step-errors.ts +26 -0
  264. package/src/workflows/step-runner.ts +36 -0
  265. package/src/workflows/sync-branch-workflow.ts +40 -0
  266. package/src/workflows/sync-workflow-schemas.ts +122 -0
  267. package/src/workflows/workflow-instance-id.ts +26 -0
  268. package/src/workflows/workflow-runtime.ts +13 -0
  269. package/src/workflows/workflow-starter.ts +69 -0
@@ -0,0 +1,55 @@
1
+ import { CommitGraph } from "./commit-graph.js";
2
+ import { pushRefUpdate } from "./push-ref.js";
3
+ import { branchHead, branchRef, requireBranchHead } from "./repo-access.js";
4
+ import { ZERO_SHA } from "@leed-ai/git-gateway-contract/schemas/sha";
5
+ import { gatewayError } from "@leed-ai/git-gateway-contract/gateway-error";
6
+ import { storageUnavailable } from "@leed-ai/git-gateway-contract/storage/storage-errors";
7
+ // src/rpc/promote-attempt.ts
8
+ /**
9
+ * One attempt at promote(): refuses unless `sha` is the head of `from` (not_head_of_source) and
10
+ * contains the head of `into` (not_fast_forward); otherwise moves `into` to `sha` with an update
11
+ * naming its current head (or creates it). Never merges, never forces.
12
+ */
13
+ async function attemptPromote(context, input) {
14
+ const { repo, from, into, sha } = input;
15
+ const fromHead = await requireBranchHead(context, repo, from);
16
+ if (fromHead !== sha) throw gatewayError("not_head_of_source", `${sha} is not the head of ${from}`, {
17
+ from,
18
+ sha,
19
+ head: fromHead
20
+ });
21
+ const intoHead = await branchHead(context, repo, into);
22
+ if (intoHead === sha) return {
23
+ kind: "done",
24
+ output: {
25
+ status: "up_to_date",
26
+ head: sha
27
+ }
28
+ };
29
+ if (intoHead !== null && !await new CommitGraph(context, repo).contains(sha, intoHead)) throw gatewayError("not_fast_forward", `${sha} does not contain the head of ${into}`, {
30
+ into,
31
+ sha,
32
+ head: intoHead
33
+ });
34
+ const refUpdate = {
35
+ ref: branchRef(into),
36
+ oldSha: intoHead ?? ZERO_SHA,
37
+ newSha: sha
38
+ };
39
+ const pushed = await pushRefUpdate(context, repo, refUpdate, []);
40
+ if (pushed.status === "ok") return {
41
+ kind: "done",
42
+ output: {
43
+ status: "promoted",
44
+ refUpdate
45
+ }
46
+ };
47
+ if (await branchHead(context, repo, into) === intoHead) throw storageUnavailable(`push to ${refUpdate.ref}`, pushed.reason);
48
+ return {
49
+ kind: "stale",
50
+ intoHead
51
+ };
52
+ }
53
+ export { attemptPromote };
54
+
55
+ //# sourceMappingURL=promote-attempt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promote-attempt.js","names":[],"sources":["../../src/rpc/promote-attempt.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { RpcOutput, RpcParsedInput } from '@leed-ai/git-gateway-contract/git-gateway';\nimport { gatewayError } from '@leed-ai/git-gateway-contract/gateway-error';\nimport { ZERO_SHA } from '@leed-ai/git-gateway-contract/schemas/sha';\nimport { storageUnavailable } from '@leed-ai/git-gateway-contract/storage/storage-errors';\n\nimport { CommitGraph } from './commit-graph.ts';\nimport type { GatewayContext } from './gateway-context.ts';\nimport { pushRefUpdate } from './push-ref.ts';\nimport { branchHead, branchRef, requireBranchHead } from './repo-access.ts';\n\n/** promote() input after parsing. */\nexport type PromoteParams = RpcParsedInput<'promote'>;\n\n/** The outcome of one promote attempt. */\nexport type PromoteAttempt =\n | { readonly kind: 'done'; readonly output: RpcOutput<'promote'> }\n /** `into` moved between the checks and the push; `intoHead` is what the push named. */\n | { readonly kind: 'stale'; readonly intoHead: string | null };\n\n/**\n * One attempt at promote(): refuses unless `sha` is the head of `from` (not_head_of_source) and\n * contains the head of `into` (not_fast_forward); otherwise moves `into` to `sha` with an update\n * naming its current head (or creates it). Never merges, never forces.\n */\nexport async function attemptPromote(context: GatewayContext, input: PromoteParams): Promise<PromoteAttempt> {\n const { repo, from, into, sha } = input;\n const fromHead = await requireBranchHead(context, repo, from);\n if (fromHead !== sha) {\n throw gatewayError('not_head_of_source', `${sha} is not the head of ${from}`, {\n from,\n sha,\n head: fromHead,\n });\n }\n const intoHead = await branchHead(context, repo, into);\n if (intoHead === sha) return { kind: 'done', output: { status: 'up_to_date', head: sha } };\n if (intoHead !== null && !(await new CommitGraph(context, repo).contains(sha, intoHead))) {\n throw gatewayError('not_fast_forward', `${sha} does not contain the head of ${into}`, {\n into,\n sha,\n head: intoHead,\n });\n }\n const refUpdate = { ref: branchRef(into), oldSha: intoHead ?? ZERO_SHA, newSha: sha };\n const pushed = await pushRefUpdate(context, repo, refUpdate, []);\n if (pushed.status === 'ok') return { kind: 'done', output: { status: 'promoted', refUpdate } };\n if ((await branchHead(context, repo, into)) === intoHead) {\n throw storageUnavailable(`push to ${refUpdate.ref}`, pushed.reason);\n }\n return { kind: 'stale', intoHead };\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,eAAsB,eAAe,SAAyB,OAA+C;CAC3G,MAAM,EAAE,MAAM,MAAM,MAAM,QAAQ;CAClC,MAAM,WAAW,MAAM,kBAAkB,SAAS,MAAM,IAAI;CAC5D,IAAI,aAAa,KACf,MAAM,aAAa,sBAAsB,GAAG,IAAI,sBAAsB,QAAQ;EAC5E;EACA;EACA,MAAM;CACR,CAAC;CAEH,MAAM,WAAW,MAAM,WAAW,SAAS,MAAM,IAAI;CACrD,IAAI,aAAa,KAAK,OAAO;EAAE,MAAM;EAAQ,QAAQ;GAAE,QAAQ;GAAc,MAAM;EAAI;CAAE;CACzF,IAAI,aAAa,QAAQ,CAAE,MAAM,IAAI,YAAY,SAAS,IAAI,CAAC,CAAC,SAAS,KAAK,QAAQ,GACpF,MAAM,aAAa,oBAAoB,GAAG,IAAI,gCAAgC,QAAQ;EACpF;EACA;EACA,MAAM;CACR,CAAC;CAEH,MAAM,YAAY;EAAE,KAAK,UAAU,IAAI;EAAG,QAAQ,YAAY;EAAU,QAAQ;CAAI;CACpF,MAAM,SAAS,MAAM,cAAc,SAAS,MAAM,WAAW,CAAC,CAAC;CAC/D,IAAI,OAAO,WAAW,MAAM,OAAO;EAAE,MAAM;EAAQ,QAAQ;GAAE,QAAQ;GAAY;EAAU;CAAE;CAC7F,IAAK,MAAM,WAAW,SAAS,MAAM,IAAI,MAAO,UAC9C,MAAM,mBAAmB,WAAW,UAAU,OAAO,OAAO,MAAM;CAEpE,OAAO;EAAE,MAAM;EAAS;CAAS;AACnC"}
@@ -0,0 +1,21 @@
1
+ import { t as GatewayContext } from "../gateway-context-Boh9I0mk.js";
2
+ import { RefUpdate } from "@leed-ai/git-gateway-contract/schemas/ref-update";
3
+ import { GitObject } from "@leed-ai/git-gateway-core/schemas/git-object";
4
+ /** What became of one pushed ref update. */
5
+ export type PushOutcome = {
6
+ readonly status: 'ok';
7
+ } |
8
+ /** The host refused the update: normally because the ref no longer names `oldSha`. */
9
+ {
10
+ readonly status: 'refused';
11
+ readonly reason: string;
12
+ };
13
+ /**
14
+ * Pushes one ref update with the objects it needs, in one git-receive-pack request through a
15
+ * freshly minted write remote. The update names the old id, so the host refuses it when the ref
16
+ * moved in the meantime: nothing is ever overwritten and nothing is forced. Transport failures
17
+ * and a pack the host could not unpack throw storage_unavailable; the credential never leaves
18
+ * this function. An accepted update is passed to the deployment's onPush hook.
19
+ */
20
+ export declare function pushRefUpdate(context: GatewayContext, repo: string, update: RefUpdate, objects: readonly GitObject[]): Promise<PushOutcome>;
21
+ //# sourceMappingURL=push-ref.d.ts.map
@@ -0,0 +1,47 @@
1
+ import { isCoreError } from "@leed-ai/git-gateway-core/core-error";
2
+ import { storageUnavailable } from "@leed-ai/git-gateway-contract/storage/storage-errors";
3
+ import { GitHttpClient } from "@leed-ai/git-gateway-core/smart-http/git-http-client";
4
+ // src/rpc/push-ref.ts
5
+ /**
6
+ * Pushes one ref update with the objects it needs, in one git-receive-pack request through a
7
+ * freshly minted write remote. The update names the old id, so the host refuses it when the ref
8
+ * moved in the meantime: nothing is ever overwritten and nothing is forced. Transport failures
9
+ * and a pack the host could not unpack throw storage_unavailable; the credential never leaves
10
+ * this function. An accepted update is passed to the deployment's onPush hook.
11
+ */
12
+ async function pushRefUpdate(context, repo, update, objects) {
13
+ const remote = await context.backend.gitRemote(repo, "write");
14
+ const client = new GitHttpClient(remote, context.fetch === void 0 ? {} : { fetch: context.fetch });
15
+ let report;
16
+ try {
17
+ report = await client.push([update], objects);
18
+ } catch (thrown) {
19
+ if (isCoreError(thrown)) throw storageUnavailable(`push to ${update.ref}`, thrown);
20
+ throw thrown;
21
+ }
22
+ if (report.unpack !== "ok") throw storageUnavailable(`push to ${update.ref}`, `unpack ${report.unpack}`);
23
+ const status = report.refs.find((entry) => entry.ref === update.ref);
24
+ if (status === void 0) throw storageUnavailable(`push to ${update.ref}`, "no status for the ref");
25
+ if (status.status !== "ok") return {
26
+ status: "refused",
27
+ reason: status.reason
28
+ };
29
+ await notifyPush(context, repo, update);
30
+ return { status: "ok" };
31
+ }
32
+ /** Tells the deployment's onPush hook about an accepted update; a hook failure is reported, not thrown. */
33
+ async function notifyPush(context, repo, update) {
34
+ if (context.onPush === void 0) return;
35
+ try {
36
+ await context.onPush({
37
+ repo,
38
+ updates: [update],
39
+ pushedAt: context.now().toISOString()
40
+ });
41
+ } catch (error) {
42
+ context.onPushError(error);
43
+ }
44
+ }
45
+ export { pushRefUpdate };
46
+
47
+ //# sourceMappingURL=push-ref.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-ref.js","names":[],"sources":["../../src/rpc/push-ref.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { RefUpdate } from '@leed-ai/git-gateway-contract/schemas/ref-update';\nimport { storageUnavailable } from '@leed-ai/git-gateway-contract/storage/storage-errors';\nimport { isCoreError } from '@leed-ai/git-gateway-core/core-error';\nimport type { GitObject } from '@leed-ai/git-gateway-core/schemas/git-object';\nimport { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-client';\n\nimport type { GatewayContext } from './gateway-context.ts';\n\n/** What became of one pushed ref update. */\nexport type PushOutcome =\n | { readonly status: 'ok' }\n /** The host refused the update: normally because the ref no longer names `oldSha`. */\n | { readonly status: 'refused'; readonly reason: string };\n\n/**\n * Pushes one ref update with the objects it needs, in one git-receive-pack request through a\n * freshly minted write remote. The update names the old id, so the host refuses it when the ref\n * moved in the meantime: nothing is ever overwritten and nothing is forced. Transport failures\n * and a pack the host could not unpack throw storage_unavailable; the credential never leaves\n * this function. An accepted update is passed to the deployment's onPush hook.\n */\nexport async function pushRefUpdate(\n context: GatewayContext,\n repo: string,\n update: RefUpdate,\n objects: readonly GitObject[],\n): Promise<PushOutcome> {\n const remote = await context.backend.gitRemote(repo, 'write');\n const client = new GitHttpClient(remote, context.fetch === undefined ? {} : { fetch: context.fetch });\n let report;\n try {\n report = await client.push([update], objects);\n } catch (thrown) {\n if (isCoreError(thrown)) throw storageUnavailable(`push to ${update.ref}`, thrown);\n throw thrown;\n }\n if (report.unpack !== 'ok') throw storageUnavailable(`push to ${update.ref}`, `unpack ${report.unpack}`);\n const status = report.refs.find((entry) => entry.ref === update.ref);\n if (status === undefined) throw storageUnavailable(`push to ${update.ref}`, 'no status for the ref');\n if (status.status !== 'ok') return { status: 'refused', reason: status.reason };\n await notifyPush(context, repo, update);\n return { status: 'ok' };\n}\n\n/** Tells the deployment's onPush hook about an accepted update; a hook failure is reported, not thrown. */\nasync function notifyPush(context: GatewayContext, repo: string, update: RefUpdate): Promise<void> {\n if (context.onPush === undefined) return;\n try {\n await context.onPush({ repo, updates: [update], pushedAt: context.now().toISOString() });\n } catch (error) {\n context.onPushError(error);\n }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,eAAsB,cACpB,SACA,MACA,QACA,SACsB;CACtB,MAAM,SAAS,MAAM,QAAQ,QAAQ,UAAU,MAAM,OAAO;CAC5D,MAAM,SAAS,IAAI,cAAc,QAAQ,QAAQ,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM,CAAC;CACpG,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,OAAO,KAAK,CAAC,MAAM,GAAG,OAAO;CAC9C,SAAS,QAAQ;EACf,IAAI,YAAY,MAAM,GAAG,MAAM,mBAAmB,WAAW,OAAO,OAAO,MAAM;EACjF,MAAM;CACR;CACA,IAAI,OAAO,WAAW,MAAM,MAAM,mBAAmB,WAAW,OAAO,OAAO,UAAU,OAAO,QAAQ;CACvG,MAAM,SAAS,OAAO,KAAK,MAAM,UAAU,MAAM,QAAQ,OAAO,GAAG;CACnE,IAAI,WAAW,KAAA,GAAW,MAAM,mBAAmB,WAAW,OAAO,OAAO,uBAAuB;CACnG,IAAI,OAAO,WAAW,MAAM,OAAO;EAAE,QAAQ;EAAW,QAAQ,OAAO;CAAO;CAC9E,MAAM,WAAW,SAAS,MAAM,MAAM;CACtC,OAAO,EAAE,QAAQ,KAAK;AACxB;;AAGA,eAAe,WAAW,SAAyB,MAAc,QAAkC;CACjG,IAAI,QAAQ,WAAW,KAAA,GAAW;CAClC,IAAI;EACF,MAAM,QAAQ,OAAO;GAAE;GAAM,SAAS,CAAC,MAAM;GAAG,UAAU,QAAQ,IAAI,CAAC,CAAC,YAAY;EAAE,CAAC;CACzF,SAAS,OAAO;EACd,QAAQ,YAAY,KAAK;CAC3B;AACF"}
@@ -0,0 +1,17 @@
1
+ import { t as GatewayContext } from "../gateway-context-Boh9I0mk.js";
2
+ import { RpcOutput, RpcParsedInput } from "@leed-ai/git-gateway-contract/git-gateway";
3
+ /** readFile(): the file at a path, or null when the path is absent or not a file. */
4
+ export declare function gatewayReadFile(context: GatewayContext, { repo, ref, path, encoding }: RpcParsedInput<'readFile'>): Promise<RpcOutput<'readFile'>>;
5
+ /** listTree(): a directory listing, or null when the path is absent or not a directory. */
6
+ export declare function gatewayListTree(context: GatewayContext, { repo, ref, path, recursive }: RpcParsedInput<'listTree'>): Promise<RpcOutput<'listTree'>>;
7
+ /** resolveRef(): the commit a branch or commit id names, or null. */
8
+ export declare function gatewayResolveRef(context: GatewayContext, { repo, ref }: RpcParsedInput<'resolveRef'>): Promise<RpcOutput<'resolveRef'>>;
9
+ /**
10
+ * log(): a page of the history reachable from a revision, in the reference's order (newest
11
+ * committer date first, never a parent before its child), reading only as far back as the page
12
+ * needs (see {@link historyPage}).
13
+ */
14
+ export declare function gatewayLog(context: GatewayContext, { repo, ref, limit, offset, since }: RpcParsedInput<'log'>): Promise<RpcOutput<'log'>>;
15
+ /** commitExists(): whether the commit exists, and is reachable from `branch` when one is named. */
16
+ export declare function gatewayCommitExists(context: GatewayContext, { repo, sha, branch }: RpcParsedInput<'commitExists'>): Promise<RpcOutput<'commitExists'>>;
17
+ //# sourceMappingURL=read-methods.d.ts.map
@@ -0,0 +1,94 @@
1
+ import { CommitGraph } from "./commit-graph.js";
2
+ import { historyPage } from "./history-page.js";
3
+ import { branchHead, entryAt, requireRevision, resolveRevision } from "./repo-access.js";
4
+ import { byteOrder, encodeContent } from "@leed-ai/git-gateway-contract/reference/bytes";
5
+ import { storageUnavailable } from "@leed-ai/git-gateway-contract/storage/storage-errors";
6
+ // src/rpc/read-methods.ts
7
+ const join = (dir, name) => dir === "" ? name : `${dir}/${name}`;
8
+ /** readFile(): the file at a path, or null when the path is absent or not a file. */
9
+ async function gatewayReadFile(context, { repo, ref, path, encoding }) {
10
+ const commit = await requireRevision(context, repo, ref);
11
+ const entry = await entryAt(context, repo, commit.tree, path);
12
+ if (entry === null || entry.type !== "blob") return null;
13
+ const data = await context.backend.readBlob(repo, entry.sha);
14
+ if (data === null) throw storageUnavailable(`read ${path}`, `blob ${entry.sha} is missing`);
15
+ return {
16
+ path,
17
+ commit: commit.sha,
18
+ sha: entry.sha,
19
+ size: data.length,
20
+ executable: entry.mode === "100755",
21
+ ...encodeContent(data, encoding)
22
+ };
23
+ }
24
+ /** Every entry beneath a tree, one level or all levels, with full paths, sorted in byte order. */
25
+ async function listEntries(context, repo, tree, dir, recursive) {
26
+ const listed = [];
27
+ let pending = [{
28
+ sha: tree,
29
+ path: dir
30
+ }];
31
+ while (pending.length > 0) {
32
+ const levels = await Promise.all(pending.map(async (at) => ({
33
+ at,
34
+ entries: await context.backend.readTree(repo, at.sha)
35
+ })));
36
+ pending = [];
37
+ for (const { at, entries } of levels) for (const entry of entries ?? []) {
38
+ const path = join(at.path, entry.name);
39
+ listed.push({
40
+ ...entry,
41
+ path
42
+ });
43
+ if (recursive && entry.type === "tree") pending.push({
44
+ sha: entry.sha,
45
+ path
46
+ });
47
+ }
48
+ }
49
+ return listed.toSorted((a, b) => byteOrder(a.path, b.path));
50
+ }
51
+ /** listTree(): a directory listing, or null when the path is absent or not a directory. */
52
+ async function gatewayListTree(context, { repo, ref, path, recursive }) {
53
+ const commit = await requireRevision(context, repo, ref);
54
+ let tree = commit.tree;
55
+ if (path !== void 0) {
56
+ const entry = await entryAt(context, repo, commit.tree, path);
57
+ if (entry === null || entry.type !== "tree") return null;
58
+ tree = entry.sha;
59
+ }
60
+ return {
61
+ commit: commit.sha,
62
+ path: path ?? null,
63
+ entries: await listEntries(context, repo, tree, path ?? "", recursive)
64
+ };
65
+ }
66
+ /** resolveRef(): the commit a branch or commit id names, or null. */
67
+ async function gatewayResolveRef(context, { repo, ref }) {
68
+ const commit = await resolveRevision(context, repo, ref);
69
+ return commit === null ? null : { sha: commit.sha };
70
+ }
71
+ /**
72
+ * log(): a page of the history reachable from a revision, in the reference's order (newest
73
+ * committer date first, never a parent before its child), reading only as far back as the page
74
+ * needs (see {@link historyPage}).
75
+ */
76
+ async function gatewayLog(context, { repo, ref, limit, offset, since }) {
77
+ const start = await requireRevision(context, repo, ref);
78
+ return historyPage(new CommitGraph(context, repo), start, {
79
+ limit,
80
+ offset,
81
+ since
82
+ });
83
+ }
84
+ /** commitExists(): whether the commit exists, and is reachable from `branch` when one is named. */
85
+ async function gatewayCommitExists(context, { repo, sha, branch }) {
86
+ const graph = new CommitGraph(context, repo);
87
+ if (await graph.commit(sha) === null) return { exists: false };
88
+ if (branch === void 0) return { exists: true };
89
+ const head = await branchHead(context, repo, branch);
90
+ return { exists: head !== null && await graph.contains(head, sha) };
91
+ }
92
+ export { gatewayCommitExists, gatewayListTree, gatewayLog, gatewayReadFile, gatewayResolveRef };
93
+
94
+ //# sourceMappingURL=read-methods.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-methods.js","names":[],"sources":["../../src/rpc/read-methods.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { RpcOutput, RpcParsedInput } from '@leed-ai/git-gateway-contract/git-gateway';\nimport { byteOrder, encodeContent } from '@leed-ai/git-gateway-contract/reference/bytes';\nimport type { TreeEntry } from '@leed-ai/git-gateway-contract/schemas/tree-entry';\nimport { storageUnavailable } from '@leed-ai/git-gateway-contract/storage/storage-errors';\n\nimport { CommitGraph } from './commit-graph.ts';\nimport type { GatewayContext } from './gateway-context.ts';\nimport { historyPage } from './history-page.ts';\nimport { branchHead, entryAt, requireRevision, resolveRevision } from './repo-access.ts';\n\nconst join = (dir: string, name: string): string => (dir === '' ? name : `${dir}/${name}`);\n\n/** readFile(): the file at a path, or null when the path is absent or not a file. */\nexport async function gatewayReadFile(\n context: GatewayContext,\n { repo, ref, path, encoding }: RpcParsedInput<'readFile'>,\n): Promise<RpcOutput<'readFile'>> {\n const commit = await requireRevision(context, repo, ref);\n const entry = await entryAt(context, repo, commit.tree, path);\n if (entry === null || entry.type !== 'blob') return null;\n const data = await context.backend.readBlob(repo, entry.sha);\n if (data === null) throw storageUnavailable(`read ${path}`, `blob ${entry.sha} is missing`);\n return {\n path,\n commit: commit.sha,\n sha: entry.sha,\n size: data.length,\n executable: entry.mode === '100755',\n ...encodeContent(data, encoding),\n };\n}\n\n/** Every entry beneath a tree, one level or all levels, with full paths, sorted in byte order. */\nasync function listEntries(\n context: GatewayContext,\n repo: string,\n tree: string,\n dir: string,\n recursive: boolean,\n): Promise<TreeEntry[]> {\n const listed: TreeEntry[] = [];\n let pending = [{ sha: tree, path: dir }];\n while (pending.length > 0) {\n const levels = await Promise.all(\n pending.map(async (at) => ({ at, entries: await context.backend.readTree(repo, at.sha) })),\n );\n pending = [];\n for (const { at, entries } of levels) {\n for (const entry of entries ?? []) {\n const path = join(at.path, entry.name);\n listed.push({ ...entry, path });\n if (recursive && entry.type === 'tree') pending.push({ sha: entry.sha, path });\n }\n }\n }\n return listed.toSorted((a, b) => byteOrder(a.path, b.path));\n}\n\n/** listTree(): a directory listing, or null when the path is absent or not a directory. */\nexport async function gatewayListTree(\n context: GatewayContext,\n { repo, ref, path, recursive }: RpcParsedInput<'listTree'>,\n): Promise<RpcOutput<'listTree'>> {\n const commit = await requireRevision(context, repo, ref);\n let tree = commit.tree;\n if (path !== undefined) {\n const entry = await entryAt(context, repo, commit.tree, path);\n if (entry === null || entry.type !== 'tree') return null;\n tree = entry.sha;\n }\n return {\n commit: commit.sha,\n path: path ?? null,\n entries: await listEntries(context, repo, tree, path ?? '', recursive),\n };\n}\n\n/** resolveRef(): the commit a branch or commit id names, or null. */\nexport async function gatewayResolveRef(\n context: GatewayContext,\n { repo, ref }: RpcParsedInput<'resolveRef'>,\n): Promise<RpcOutput<'resolveRef'>> {\n const commit = await resolveRevision(context, repo, ref);\n return commit === null ? null : { sha: commit.sha };\n}\n\n/**\n * log(): a page of the history reachable from a revision, in the reference's order (newest\n * committer date first, never a parent before its child), reading only as far back as the page\n * needs (see {@link historyPage}).\n */\nexport async function gatewayLog(\n context: GatewayContext,\n { repo, ref, limit, offset, since }: RpcParsedInput<'log'>,\n): Promise<RpcOutput<'log'>> {\n const start = await requireRevision(context, repo, ref);\n return historyPage(new CommitGraph(context, repo), start, { limit, offset, since });\n}\n\n/** commitExists(): whether the commit exists, and is reachable from `branch` when one is named. */\nexport async function gatewayCommitExists(\n context: GatewayContext,\n { repo, sha, branch }: RpcParsedInput<'commitExists'>,\n): Promise<RpcOutput<'commitExists'>> {\n const graph = new CommitGraph(context, repo);\n if ((await graph.commit(sha)) === null) return { exists: false };\n if (branch === undefined) return { exists: true };\n const head = await branchHead(context, repo, branch);\n return { exists: head !== null && (await graph.contains(head, sha)) };\n}\n"],"mappings":"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"}
@@ -0,0 +1,39 @@
1
+ import { z } from "zod";
2
+ /** Every read token starts with this prefix, so secret scanners and the proxy can recognise one. */
3
+ export declare const READ_TOKEN_PREFIX = "ggr_";
4
+ /** The secret read tokens are signed with. */
5
+ export declare const ReadTokenSecret: z.ZodString;
6
+ /** What a read token asserts. */
7
+ export declare const ReadTokenClaims: z.ZodObject<{
8
+ v: z.ZodLiteral<1>;
9
+ repo: z.ZodString;
10
+ iat: z.ZodInt;
11
+ exp: z.ZodInt;
12
+ jti: z.ZodString;
13
+ }, z.core.$strict>;
14
+ /** Read-token claims, inferred from {@link ReadTokenClaims}. */
15
+ export type ReadTokenClaims = z.infer<typeof ReadTokenClaims>;
16
+ /** Options of {@link mintReadToken}. */
17
+ export interface MintReadTokenOptions {
18
+ readonly repo: string;
19
+ readonly ttlSeconds: number;
20
+ readonly secret: string;
21
+ readonly now: Date;
22
+ }
23
+ /**
24
+ * Issues a read token for one repository: `ggr_<claims>.<signature>`, both base64url, the claims
25
+ * JSON signed with HMAC-SHA256 under `secret`. The token is a credential: return it to the caller
26
+ * and nowhere else (never into a log or a Workflow step result).
27
+ */
28
+ export declare function mintReadToken(options: MintReadTokenOptions): Promise<{
29
+ token: string;
30
+ expiresAt: string;
31
+ }>;
32
+ /**
33
+ * Checks a read token: its signature under `secret` (compared in constant time by WebCrypto),
34
+ * its claims and its expiry against `now`. Returns the claims of a valid token and null for
35
+ * anything else — malformed, forged, signed with another secret or expired. An authenticator
36
+ * grants read access to `claims.repo` and nothing more.
37
+ */
38
+ export declare function verifyReadToken(token: string, secret: string, now?: Date): Promise<ReadTokenClaims | null>;
39
+ //# sourceMappingURL=read-token.d.ts.map
@@ -0,0 +1,107 @@
1
+ import { bytesToHex } from "@leed-ai/git-gateway-core/bytes";
2
+ import { RepoName } from "@leed-ai/git-gateway-contract/schemas/names";
3
+ import { z } from "zod";
4
+ import { utf8 } from "@leed-ai/git-gateway-contract/reference/bytes";
5
+ // src/rpc/read-token.ts
6
+ /** Every read token starts with this prefix, so secret scanners and the proxy can recognise one. */
7
+ const READ_TOKEN_PREFIX = "ggr_";
8
+ /** The secret read tokens are signed with. */
9
+ const ReadTokenSecret = z.string().min(32).max(4096).meta({
10
+ id: "ReadTokenSecret",
11
+ title: "Read-token secret",
12
+ description: "The HMAC-SHA256 key that signs and verifies read tokens: 32–4096 characters of high-entropy secret, set as a Worker secret. Rotating it invalidates every token issued.",
13
+ examples: ["0123456789abcdef0123456789abcdef"]
14
+ });
15
+ /** What a read token asserts. */
16
+ const ReadTokenClaims = z.object({
17
+ v: z.literal(1).describe("Token format version; always 1."),
18
+ repo: RepoName.describe("The one repository the token may clone and fetch."),
19
+ iat: z.int().min(0).describe("When the token was issued, in whole seconds since the Unix epoch."),
20
+ exp: z.int().min(0).describe("When the token stops working, in whole seconds since the Unix epoch; after `iat`."),
21
+ jti: z.string().regex(/^[0-9a-f]{32}$/).describe("Random token id, 32 lowercase hex digits, so two tokens issued together differ.")
22
+ }).strict().refine((claims) => claims.exp > claims.iat, {
23
+ message: "exp must be after iat",
24
+ path: ["exp"]
25
+ }).meta({
26
+ id: "ReadTokenClaims",
27
+ title: "Read-token claims",
28
+ description: "What a read token from mintReadToken() asserts: read access to one repository until `exp`. Signed with HMAC-SHA256; carries no storage-host credential.",
29
+ examples: [{
30
+ v: 1,
31
+ repo: "acme-raw-content",
32
+ iat: 1795e6,
33
+ exp: 1795003600,
34
+ jti: "0".repeat(32)
35
+ }]
36
+ });
37
+ function base64Url(bytes) {
38
+ let binary = "";
39
+ for (const byte of bytes) binary += String.fromCodePoint(byte);
40
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
41
+ }
42
+ function fromBase64Url(text) {
43
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) return null;
44
+ try {
45
+ const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
46
+ return Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ function hmacKey(secret, usage) {
52
+ const key = utf8(ReadTokenSecret.parse(secret));
53
+ return crypto.subtle.importKey("raw", key, {
54
+ name: "HMAC",
55
+ hash: "SHA-256"
56
+ }, false, [usage]);
57
+ }
58
+ /**
59
+ * Issues a read token for one repository: `ggr_<claims>.<signature>`, both base64url, the claims
60
+ * JSON signed with HMAC-SHA256 under `secret`. The token is a credential: return it to the caller
61
+ * and nowhere else (never into a log or a Workflow step result).
62
+ */
63
+ async function mintReadToken(options) {
64
+ const iat = Math.floor(options.now.getTime() / 1e3);
65
+ const claims = ReadTokenClaims.parse({
66
+ v: 1,
67
+ repo: options.repo,
68
+ iat,
69
+ exp: iat + options.ttlSeconds,
70
+ jti: bytesToHex(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)))
71
+ });
72
+ const payload = base64Url(utf8(JSON.stringify(claims)));
73
+ const key = await hmacKey(options.secret, "sign");
74
+ const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, utf8(payload)));
75
+ return {
76
+ token: `${READ_TOKEN_PREFIX}${payload}.${base64Url(signature)}`,
77
+ expiresAt: (/* @__PURE__ */ new Date(claims.exp * 1e3)).toISOString()
78
+ };
79
+ }
80
+ /**
81
+ * Checks a read token: its signature under `secret` (compared in constant time by WebCrypto),
82
+ * its claims and its expiry against `now`. Returns the claims of a valid token and null for
83
+ * anything else — malformed, forged, signed with another secret or expired. An authenticator
84
+ * grants read access to `claims.repo` and nothing more.
85
+ */
86
+ async function verifyReadToken(token, secret, now = /* @__PURE__ */ new Date()) {
87
+ if (!token.startsWith("ggr_") || token.length > 4096) return null;
88
+ const [payload, signature, ...rest] = token.slice(4).split(".");
89
+ if (payload === void 0 || signature === void 0 || rest.length > 0) return null;
90
+ const signatureBytes = fromBase64Url(signature);
91
+ const payloadBytes = fromBase64Url(payload);
92
+ if (signatureBytes === null || payloadBytes === null) return null;
93
+ const key = await hmacKey(secret, "verify");
94
+ if (!await crypto.subtle.verify("HMAC", key, signatureBytes, utf8(payload))) return null;
95
+ let decoded;
96
+ try {
97
+ decoded = JSON.parse(new TextDecoder().decode(payloadBytes));
98
+ } catch {
99
+ return null;
100
+ }
101
+ const claims = ReadTokenClaims.safeParse(decoded);
102
+ if (!claims.success) return null;
103
+ return claims.data.exp * 1e3 > now.getTime() ? claims.data : null;
104
+ }
105
+ export { READ_TOKEN_PREFIX, ReadTokenClaims, ReadTokenSecret, mintReadToken, verifyReadToken };
106
+
107
+ //# sourceMappingURL=read-token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-token.js","names":[],"sources":["../../src/rpc/read-token.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { utf8 } from '@leed-ai/git-gateway-contract/reference/bytes';\nimport { RepoName } from '@leed-ai/git-gateway-contract/schemas/names';\nimport { bytesToHex } from '@leed-ai/git-gateway-core/bytes';\nimport { z } from 'zod';\n\n/** Every read token starts with this prefix, so secret scanners and the proxy can recognise one. */\nexport const READ_TOKEN_PREFIX = 'ggr_';\n\n/** The secret read tokens are signed with. */\nexport const ReadTokenSecret = z\n .string()\n .min(32)\n .max(4096)\n .meta({\n id: 'ReadTokenSecret',\n title: 'Read-token secret',\n description:\n 'The HMAC-SHA256 key that signs and verifies read tokens: 32–4096 characters of high-entropy secret, set as a Worker secret. Rotating it invalidates every token issued.',\n examples: ['0123456789abcdef0123456789abcdef'],\n });\n\n/** What a read token asserts. */\nexport const ReadTokenClaims = z\n .object({\n v: z.literal(1).describe('Token format version; always 1.'),\n repo: RepoName.describe('The one repository the token may clone and fetch.'),\n iat: z.int().min(0).describe('When the token was issued, in whole seconds since the Unix epoch.'),\n exp: z\n .int()\n .min(0)\n .describe('When the token stops working, in whole seconds since the Unix epoch; after `iat`.'),\n jti: z\n .string()\n .regex(/^[0-9a-f]{32}$/)\n .describe('Random token id, 32 lowercase hex digits, so two tokens issued together differ.'),\n })\n .strict()\n .refine((claims) => claims.exp > claims.iat, { message: 'exp must be after iat', path: ['exp'] })\n .meta({\n id: 'ReadTokenClaims',\n title: 'Read-token claims',\n description:\n 'What a read token from mintReadToken() asserts: read access to one repository until `exp`. Signed with HMAC-SHA256; carries no storage-host credential.',\n examples: [\n { v: 1, repo: 'acme-raw-content', iat: 1_795_000_000, exp: 1_795_003_600, jti: '0'.repeat(32) },\n ],\n });\n\n/** Read-token claims, inferred from {@link ReadTokenClaims}. */\nexport type ReadTokenClaims = z.infer<typeof ReadTokenClaims>;\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCodePoint(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array | null {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) return null;\n try {\n const binary = atob(text.replaceAll('-', '+').replaceAll('_', '/'));\n return Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);\n } catch {\n return null;\n }\n}\n\nfunction hmacKey(secret: string, usage: 'sign' | 'verify'): Promise<CryptoKey> {\n const key = utf8(ReadTokenSecret.parse(secret));\n return crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);\n}\n\n/** Options of {@link mintReadToken}. */\nexport interface MintReadTokenOptions {\n readonly repo: string;\n readonly ttlSeconds: number;\n readonly secret: string;\n readonly now: Date;\n}\n\n/**\n * Issues a read token for one repository: `ggr_<claims>.<signature>`, both base64url, the claims\n * JSON signed with HMAC-SHA256 under `secret`. The token is a credential: return it to the caller\n * and nowhere else (never into a log or a Workflow step result).\n */\nexport async function mintReadToken(\n options: MintReadTokenOptions,\n): Promise<{ token: string; expiresAt: string }> {\n const iat = Math.floor(options.now.getTime() / 1000);\n const claims = ReadTokenClaims.parse({\n v: 1,\n repo: options.repo,\n iat,\n exp: iat + options.ttlSeconds,\n jti: bytesToHex(crypto.getRandomValues(new Uint8Array(16))),\n });\n const payload = base64Url(utf8(JSON.stringify(claims)));\n const key = await hmacKey(options.secret, 'sign');\n const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, utf8(payload)));\n return {\n token: `${READ_TOKEN_PREFIX}${payload}.${base64Url(signature)}`,\n expiresAt: new Date(claims.exp * 1000).toISOString(),\n };\n}\n\n/**\n * Checks a read token: its signature under `secret` (compared in constant time by WebCrypto),\n * its claims and its expiry against `now`. Returns the claims of a valid token and null for\n * anything else — malformed, forged, signed with another secret or expired. An authenticator\n * grants read access to `claims.repo` and nothing more.\n */\nexport async function verifyReadToken(\n token: string,\n secret: string,\n now: Date = new Date(),\n): Promise<ReadTokenClaims | null> {\n if (!token.startsWith(READ_TOKEN_PREFIX) || token.length > 4096) return null;\n const [payload, signature, ...rest] = token.slice(READ_TOKEN_PREFIX.length).split('.');\n if (payload === undefined || signature === undefined || rest.length > 0) return null;\n const signatureBytes = fromBase64Url(signature);\n const payloadBytes = fromBase64Url(payload);\n if (signatureBytes === null || payloadBytes === null) return null;\n const key = await hmacKey(secret, 'verify');\n if (!(await crypto.subtle.verify('HMAC', key, signatureBytes, utf8(payload)))) return null;\n let decoded: unknown;\n try {\n decoded = JSON.parse(new TextDecoder().decode(payloadBytes));\n } catch {\n return null;\n }\n const claims = ReadTokenClaims.safeParse(decoded);\n if (!claims.success) return null;\n return claims.data.exp * 1000 > now.getTime() ? claims.data : null;\n}\n"],"mappings":"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"}
@@ -0,0 +1,36 @@
1
+ import { t as GatewayContext } from "../gateway-context-Boh9I0mk.js";
2
+ import { Commit } from "@leed-ai/git-gateway-contract/schemas/commit";
3
+ import { StorageRepoInfo } from "@leed-ai/git-gateway-contract/storage/storage-repo-info";
4
+ import { StorageTreeEntry } from "@leed-ai/git-gateway-contract/storage/storage-tree-entry";
5
+ import { TreeReader } from "@leed-ai/git-gateway-core/tree/tree-reader";
6
+ /** The fully qualified ref of a branch. */
7
+ export declare const branchRef: (branch: string) => string;
8
+ /** The repository's description, or repo_not_found. */
9
+ export declare function requireRepo(context: GatewayContext, repo: string): Promise<StorageRepoInfo>;
10
+ /** The head of a branch, or null when it does not exist. */
11
+ export declare function branchHead(context: GatewayContext, repo: string, branch: string): Promise<string | null>;
12
+ /** The head of a branch, or ref_not_found naming it. */
13
+ export declare function requireBranchHead(context: GatewayContext, repo: string, branch: string): Promise<string>;
14
+ /** A commit the repository must have (it was named by a ref), or storage_unavailable. */
15
+ export declare function requireCommit(context: GatewayContext, repo: string, sha: string): Promise<Commit>;
16
+ /**
17
+ * The commit a revision names: a 40-hex commit id is read as a commit (never a branch), anything
18
+ * else as a branch name. Null when there is no such commit or branch.
19
+ */
20
+ export declare function resolveRevision(context: GatewayContext, repo: string, revision: string): Promise<Commit | null>;
21
+ /** The commit a revision names, or ref_not_found. */
22
+ export declare function requireRevision(context: GatewayContext, repo: string, revision: string): Promise<Commit>;
23
+ /** A {@link TreeReader} over the repository's trees. */
24
+ export declare function treeReader(context: GatewayContext, repo: string): TreeReader;
25
+ /**
26
+ * The entry a path names beneath a root tree, reading one tree per segment, or null when some
27
+ * segment is missing or a parent is not a directory.
28
+ */
29
+ export declare function entryAt(context: GatewayContext, repo: string, rootTree: string, path: string): Promise<StorageTreeEntry | null>;
30
+ /**
31
+ * Whether the repository has any branch at all, read from the ref advertisement of its git
32
+ * remote (the storage contract has no "list refs" call). Only asked when a commit names a branch
33
+ * that does not exist, to decide between a root commit and ref_not_found.
34
+ */
35
+ export declare function hasBranches(context: GatewayContext, repo: string): Promise<boolean>;
36
+ //# sourceMappingURL=repo-access.d.ts.map
@@ -0,0 +1,75 @@
1
+ import { Sha } from "@leed-ai/git-gateway-contract/schemas/sha";
2
+ import { gatewayError } from "@leed-ai/git-gateway-contract/gateway-error";
3
+ import { repoNotFound } from "@leed-ai/git-gateway-contract/storage/storage-errors";
4
+ import { GitHttpClient } from "@leed-ai/git-gateway-core/smart-http/git-http-client";
5
+ // src/rpc/repo-access.ts
6
+ /** The fully qualified ref of a branch. */
7
+ const branchRef = (branch) => `refs/heads/${branch}`;
8
+ /** The repository's description, or repo_not_found. */
9
+ async function requireRepo(context, repo) {
10
+ const info = await context.backend.repoInfo(repo);
11
+ if (info === null) throw repoNotFound(repo);
12
+ return info;
13
+ }
14
+ /** The head of a branch, or null when it does not exist. */
15
+ function branchHead(context, repo, branch) {
16
+ return context.backend.resolveRef(repo, branchRef(branch));
17
+ }
18
+ /** The head of a branch, or ref_not_found naming it. */
19
+ async function requireBranchHead(context, repo, branch) {
20
+ const head = await branchHead(context, repo, branch);
21
+ if (head === null) throw gatewayError("ref_not_found", `Branch not found: ${branch}`, { ref: branch });
22
+ return head;
23
+ }
24
+ /** A commit the repository must have (it was named by a ref), or storage_unavailable. */
25
+ async function requireCommit(context, repo, sha) {
26
+ const commit = await context.backend.readCommit(repo, sha);
27
+ if (commit === null) throw gatewayError("storage_unavailable", `Storage backend failed: commit ${sha} is missing`, { retryable: true });
28
+ return commit;
29
+ }
30
+ /**
31
+ * The commit a revision names: a 40-hex commit id is read as a commit (never a branch), anything
32
+ * else as a branch name. Null when there is no such commit or branch.
33
+ */
34
+ async function resolveRevision(context, repo, revision) {
35
+ if (Sha.safeParse(revision).success) return context.backend.readCommit(repo, revision);
36
+ const head = await branchHead(context, repo, revision);
37
+ return head === null ? null : requireCommit(context, repo, head);
38
+ }
39
+ /** The commit a revision names, or ref_not_found. */
40
+ async function requireRevision(context, repo, revision) {
41
+ const commit = await resolveRevision(context, repo, revision);
42
+ if (commit === null) throw gatewayError("ref_not_found", `Ref not found: ${revision}`, { ref: revision });
43
+ return commit;
44
+ }
45
+ /** A {@link TreeReader} over the repository's trees. */
46
+ function treeReader(context, repo) {
47
+ return { readTree: (sha) => context.backend.readTree(repo, sha) };
48
+ }
49
+ /**
50
+ * The entry a path names beneath a root tree, reading one tree per segment, or null when some
51
+ * segment is missing or a parent is not a directory.
52
+ */
53
+ async function entryAt(context, repo, rootTree, path) {
54
+ let tree = rootTree;
55
+ let found = null;
56
+ for (const segment of path.split("/")) {
57
+ if (found !== null && found.type !== "tree") return null;
58
+ found = (await context.backend.readTree(repo, tree))?.find((entry) => entry.name === segment) ?? null;
59
+ if (found === null) return null;
60
+ tree = found.sha;
61
+ }
62
+ return found;
63
+ }
64
+ /**
65
+ * Whether the repository has any branch at all, read from the ref advertisement of its git
66
+ * remote (the storage contract has no "list refs" call). Only asked when a commit names a branch
67
+ * that does not exist, to decide between a root commit and ref_not_found.
68
+ */
69
+ async function hasBranches(context, repo) {
70
+ const remote = await context.backend.gitRemote(repo, "read");
71
+ return (await new GitHttpClient(remote, context.fetch === void 0 ? {} : { fetch: context.fetch }).advertisement("git-upload-pack")).refs.some((ref) => ref.name.startsWith("refs/heads/"));
72
+ }
73
+ export { branchHead, branchRef, entryAt, hasBranches, requireBranchHead, requireCommit, requireRepo, requireRevision, resolveRevision, treeReader };
74
+
75
+ //# sourceMappingURL=repo-access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repo-access.js","names":[],"sources":["../../src/rpc/repo-access.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { gatewayError } from '@leed-ai/git-gateway-contract/gateway-error';\nimport type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';\nimport { Sha } from '@leed-ai/git-gateway-contract/schemas/sha';\nimport { repoNotFound } from '@leed-ai/git-gateway-contract/storage/storage-errors';\nimport type { StorageRepoInfo } from '@leed-ai/git-gateway-contract/storage/storage-repo-info';\nimport type { StorageTreeEntry } from '@leed-ai/git-gateway-contract/storage/storage-tree-entry';\nimport { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-client';\nimport type { TreeReader } from '@leed-ai/git-gateway-core/tree/tree-reader';\n\nimport type { GatewayContext } from './gateway-context.ts';\n\n/** The fully qualified ref of a branch. */\nexport const branchRef = (branch: string): string => `refs/heads/${branch}`;\n\n/** The repository's description, or repo_not_found. */\nexport async function requireRepo(context: GatewayContext, repo: string): Promise<StorageRepoInfo> {\n const info = await context.backend.repoInfo(repo);\n if (info === null) throw repoNotFound(repo);\n return info;\n}\n\n/** The head of a branch, or null when it does not exist. */\nexport function branchHead(context: GatewayContext, repo: string, branch: string): Promise<string | null> {\n return context.backend.resolveRef(repo, branchRef(branch));\n}\n\n/** The head of a branch, or ref_not_found naming it. */\nexport async function requireBranchHead(\n context: GatewayContext,\n repo: string,\n branch: string,\n): Promise<string> {\n const head = await branchHead(context, repo, branch);\n if (head === null) throw gatewayError('ref_not_found', `Branch not found: ${branch}`, { ref: branch });\n return head;\n}\n\n/** A commit the repository must have (it was named by a ref), or storage_unavailable. */\nexport async function requireCommit(context: GatewayContext, repo: string, sha: string): Promise<Commit> {\n const commit = await context.backend.readCommit(repo, sha);\n if (commit === null) {\n throw gatewayError('storage_unavailable', `Storage backend failed: commit ${sha} is missing`, {\n retryable: true,\n });\n }\n return commit;\n}\n\n/**\n * The commit a revision names: a 40-hex commit id is read as a commit (never a branch), anything\n * else as a branch name. Null when there is no such commit or branch.\n */\nexport async function resolveRevision(\n context: GatewayContext,\n repo: string,\n revision: string,\n): Promise<Commit | null> {\n if (Sha.safeParse(revision).success) return context.backend.readCommit(repo, revision);\n const head = await branchHead(context, repo, revision);\n return head === null ? null : requireCommit(context, repo, head);\n}\n\n/** The commit a revision names, or ref_not_found. */\nexport async function requireRevision(\n context: GatewayContext,\n repo: string,\n revision: string,\n): Promise<Commit> {\n const commit = await resolveRevision(context, repo, revision);\n if (commit === null) throw gatewayError('ref_not_found', `Ref not found: ${revision}`, { ref: revision });\n return commit;\n}\n\n/** A {@link TreeReader} over the repository's trees. */\nexport function treeReader(context: GatewayContext, repo: string): TreeReader {\n return { readTree: (sha) => context.backend.readTree(repo, sha) };\n}\n\n/**\n * The entry a path names beneath a root tree, reading one tree per segment, or null when some\n * segment is missing or a parent is not a directory.\n */\nexport async function entryAt(\n context: GatewayContext,\n repo: string,\n rootTree: string,\n path: string,\n): Promise<StorageTreeEntry | null> {\n let tree = rootTree;\n let found: StorageTreeEntry | null = null;\n for (const segment of path.split('/')) {\n if (found !== null && found.type !== 'tree') return null;\n const entries = await context.backend.readTree(repo, tree);\n found = entries?.find((entry) => entry.name === segment) ?? null;\n if (found === null) return null;\n tree = found.sha;\n }\n return found;\n}\n\n/**\n * Whether the repository has any branch at all, read from the ref advertisement of its git\n * remote (the storage contract has no \"list refs\" call). Only asked when a commit names a branch\n * that does not exist, to decide between a root commit and ref_not_found.\n */\nexport async function hasBranches(context: GatewayContext, repo: string): Promise<boolean> {\n const remote = await context.backend.gitRemote(repo, 'read');\n const client = new GitHttpClient(remote, context.fetch === undefined ? {} : { fetch: context.fetch });\n const advertisement = await client.advertisement('git-upload-pack');\n return advertisement.refs.some((ref) => ref.name.startsWith('refs/heads/'));\n}\n"],"mappings":";;;;;;AAaA,MAAa,aAAa,WAA2B,cAAc;;AAGnE,eAAsB,YAAY,SAAyB,MAAwC;CACjG,MAAM,OAAO,MAAM,QAAQ,QAAQ,SAAS,IAAI;CAChD,IAAI,SAAS,MAAM,MAAM,aAAa,IAAI;CAC1C,OAAO;AACT;;AAGA,SAAgB,WAAW,SAAyB,MAAc,QAAwC;CACxG,OAAO,QAAQ,QAAQ,WAAW,MAAM,UAAU,MAAM,CAAC;AAC3D;;AAGA,eAAsB,kBACpB,SACA,MACA,QACiB;CACjB,MAAM,OAAO,MAAM,WAAW,SAAS,MAAM,MAAM;CACnD,IAAI,SAAS,MAAM,MAAM,aAAa,iBAAiB,qBAAqB,UAAU,EAAE,KAAK,OAAO,CAAC;CACrG,OAAO;AACT;;AAGA,eAAsB,cAAc,SAAyB,MAAc,KAA8B;CACvG,MAAM,SAAS,MAAM,QAAQ,QAAQ,WAAW,MAAM,GAAG;CACzD,IAAI,WAAW,MACb,MAAM,aAAa,uBAAuB,kCAAkC,IAAI,cAAc,EAC5F,WAAW,KACb,CAAC;CAEH,OAAO;AACT;;;;;AAMA,eAAsB,gBACpB,SACA,MACA,UACwB;CACxB,IAAI,IAAI,UAAU,QAAQ,CAAC,CAAC,SAAS,OAAO,QAAQ,QAAQ,WAAW,MAAM,QAAQ;CACrF,MAAM,OAAO,MAAM,WAAW,SAAS,MAAM,QAAQ;CACrD,OAAO,SAAS,OAAO,OAAO,cAAc,SAAS,MAAM,IAAI;AACjE;;AAGA,eAAsB,gBACpB,SACA,MACA,UACiB;CACjB,MAAM,SAAS,MAAM,gBAAgB,SAAS,MAAM,QAAQ;CAC5D,IAAI,WAAW,MAAM,MAAM,aAAa,iBAAiB,kBAAkB,YAAY,EAAE,KAAK,SAAS,CAAC;CACxG,OAAO;AACT;;AAGA,SAAgB,WAAW,SAAyB,MAA0B;CAC5E,OAAO,EAAE,WAAW,QAAQ,QAAQ,QAAQ,SAAS,MAAM,GAAG,EAAE;AAClE;;;;;AAMA,eAAsB,QACpB,SACA,MACA,UACA,MACkC;CAClC,IAAI,OAAO;CACX,IAAI,QAAiC;CACrC,KAAK,MAAM,WAAW,KAAK,MAAM,GAAG,GAAG;EACrC,IAAI,UAAU,QAAQ,MAAM,SAAS,QAAQ,OAAO;EAEpD,SAAQ,MADc,QAAQ,QAAQ,SAAS,MAAM,IAAI,EAAA,EACxC,MAAM,UAAU,MAAM,SAAS,OAAO,KAAK;EAC5D,IAAI,UAAU,MAAM,OAAO;EAC3B,OAAO,MAAM;CACf;CACA,OAAO;AACT;;;;;;AAOA,eAAsB,YAAY,SAAyB,MAAgC;CACzF,MAAM,SAAS,MAAM,QAAQ,QAAQ,UAAU,MAAM,MAAM;CAG3D,QAAO,MADqB,IADT,cAAc,QAAQ,QAAQ,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM,CAClE,CAAC,CAAC,cAAc,iBAAiB,EAAA,CAC7C,KAAK,MAAM,QAAQ,IAAI,KAAK,WAAW,aAAa,CAAC;AAC5E"}
@@ -0,0 +1,23 @@
1
+ import { t as GatewayContext } from "../gateway-context-Boh9I0mk.js";
2
+ import { RpcOutput, RpcParsedInput } from "@leed-ai/git-gateway-contract/git-gateway";
3
+ /** syncBranch() input after parsing. */
4
+ export type SyncParams = RpcParsedInput<'syncBranch'>;
5
+ /** The outcome of one sync attempt. */
6
+ export type SyncAttempt = {
7
+ readonly kind: 'done';
8
+ readonly output: RpcOutput<'syncBranch'>;
9
+ } |
10
+ /** The push was refused because `into` moved; `intoHead` is the head that was built on. */
11
+ {
12
+ readonly kind: 'stale';
13
+ readonly intoHead: string;
14
+ };
15
+ /**
16
+ * One attempt at syncBranch(): `into` already contains `from` → up_to_date; `into` has nothing of
17
+ * its own → fast-forward; otherwise a file-level three-way merge against the merge base (the
18
+ * reference's own merge-base rule, found by a paint-down walk that reads only the history since it), written as a merge commit whose
19
+ * parents are `into` then `from`, or a conflict listing every path, with nothing written. Every
20
+ * push names the head of `into` it was built on, so nothing is overwritten or forced.
21
+ */
22
+ export declare function attemptSync(context: GatewayContext, input: SyncParams): Promise<SyncAttempt>;
23
+ //# sourceMappingURL=sync-attempt.d.ts.map