@leed-ai/git-gateway-testkit 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 (91) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -2
  3. package/dist/contract-suite/ancestry-cases.d.ts +4 -0
  4. package/dist/contract-suite/ancestry-cases.js +49 -0
  5. package/dist/contract-suite/ancestry-cases.js.map +1 -0
  6. package/dist/contract-suite/backend-case.d.ts +35 -0
  7. package/dist/contract-suite/backend-case.js +17 -0
  8. package/dist/contract-suite/backend-case.js.map +1 -0
  9. package/dist/contract-suite/backend-contract-suite.d.ts +44 -0
  10. package/dist/contract-suite/backend-contract-suite.js +59 -0
  11. package/dist/contract-suite/backend-contract-suite.js.map +1 -0
  12. package/dist/contract-suite/backend-fixtures.d.ts +25 -0
  13. package/dist/contract-suite/backend-fixtures.js +79 -0
  14. package/dist/contract-suite/backend-fixtures.js.map +1 -0
  15. package/dist/contract-suite/content-cases.d.ts +4 -0
  16. package/dist/contract-suite/content-cases.js +31 -0
  17. package/dist/contract-suite/content-cases.js.map +1 -0
  18. package/dist/contract-suite/lifecycle-cases.d.ts +4 -0
  19. package/dist/contract-suite/lifecycle-cases.js +86 -0
  20. package/dist/contract-suite/lifecycle-cases.js.map +1 -0
  21. package/dist/contract-suite/push-cases.d.ts +4 -0
  22. package/dist/contract-suite/push-cases.js +92 -0
  23. package/dist/contract-suite/push-cases.js.map +1 -0
  24. package/dist/contract-suite/push-helpers.d.ts +17 -0
  25. package/dist/contract-suite/push-helpers.js +47 -0
  26. package/dist/contract-suite/push-helpers.js.map +1 -0
  27. package/dist/contract-suite/read-cases.d.ts +4 -0
  28. package/dist/contract-suite/read-cases.js +186 -0
  29. package/dist/contract-suite/read-cases.js.map +1 -0
  30. package/dist/contract-suite/transport-cases.d.ts +4 -0
  31. package/dist/contract-suite/transport-cases.js +105 -0
  32. package/dist/contract-suite/transport-cases.js.map +1 -0
  33. package/dist/git-binary.d.ts +19 -0
  34. package/dist/git-binary.js +54 -0
  35. package/dist/git-binary.js.map +1 -0
  36. package/dist/git-sandbox.d.ts +33 -0
  37. package/dist/git-sandbox.js +76 -0
  38. package/dist/git-sandbox.js.map +1 -0
  39. package/dist/memory/memory-backend.d.ts +45 -0
  40. package/dist/memory/memory-backend.js +154 -0
  41. package/dist/memory/memory-backend.js.map +1 -0
  42. package/dist/memory/memory-reads.d.ts +9 -0
  43. package/dist/memory/memory-reads.js +39 -0
  44. package/dist/memory/memory-reads.js.map +1 -0
  45. package/dist/memory/memory-repository.d.ts +38 -0
  46. package/dist/memory/memory-repository.js +97 -0
  47. package/dist/memory/memory-repository.js.map +1 -0
  48. package/dist/memory/memory-tokens.d.ts +28 -0
  49. package/dist/memory/memory-tokens.js +59 -0
  50. package/dist/memory/memory-tokens.js.map +1 -0
  51. package/dist/memory/pack-selection.d.ts +30 -0
  52. package/dist/memory/pack-selection.js +104 -0
  53. package/dist/memory/pack-selection.js.map +1 -0
  54. package/dist/memory/receive-pack-service.d.ts +15 -0
  55. package/dist/memory/receive-pack-service.js +126 -0
  56. package/dist/memory/receive-pack-service.js.map +1 -0
  57. package/dist/memory/smart-http-server.d.ts +15 -0
  58. package/dist/memory/smart-http-server.js +65 -0
  59. package/dist/memory/smart-http-server.js.map +1 -0
  60. package/dist/memory/upload-pack-service.d.ts +15 -0
  61. package/dist/memory/upload-pack-service.js +123 -0
  62. package/dist/memory/upload-pack-service.js.map +1 -0
  63. package/dist/node/serve-fetch-handler.d.ts +16 -0
  64. package/dist/node/serve-fetch-handler.js +52 -0
  65. package/dist/node/serve-fetch-handler.js.map +1 -0
  66. package/dist/node/serve-streaming.d.ts +16 -0
  67. package/dist/node/serve-streaming.js +87 -0
  68. package/dist/node/serve-streaming.js.map +1 -0
  69. package/package.json +175 -4
  70. package/src/contract-suite/ancestry-cases.ts +56 -0
  71. package/src/contract-suite/backend-case.ts +53 -0
  72. package/src/contract-suite/backend-contract-suite.ts +89 -0
  73. package/src/contract-suite/backend-fixtures.ts +89 -0
  74. package/src/contract-suite/content-cases.ts +55 -0
  75. package/src/contract-suite/lifecycle-cases.ts +121 -0
  76. package/src/contract-suite/push-cases.ts +123 -0
  77. package/src/contract-suite/push-helpers.ts +63 -0
  78. package/src/contract-suite/read-cases.ts +213 -0
  79. package/src/contract-suite/transport-cases.ts +134 -0
  80. package/src/git-binary.ts +65 -0
  81. package/src/git-sandbox.ts +87 -0
  82. package/src/memory/memory-backend.ts +188 -0
  83. package/src/memory/memory-reads.ts +52 -0
  84. package/src/memory/memory-repository.ts +115 -0
  85. package/src/memory/memory-tokens.ts +64 -0
  86. package/src/memory/pack-selection.ts +127 -0
  87. package/src/memory/receive-pack-service.ts +141 -0
  88. package/src/memory/smart-http-server.ts +78 -0
  89. package/src/memory/upload-pack-service.ts +132 -0
  90. package/src/node/serve-fetch-handler.ts +71 -0
  91. package/src/node/serve-streaming.ts +107 -0
@@ -0,0 +1,65 @@
1
+ import { credentialOf } from "./memory-tokens.js";
2
+ import { answerReceivePack, receivePackAdvertisement } from "./receive-pack-service.js";
3
+ import { answerUploadPack, uploadPackAdvertisement } from "./upload-pack-service.js";
4
+ import { readAllBytes } from "@leed-ai/git-gateway-core/bytes";
5
+ // src/memory/smart-http-server.ts
6
+ const ROUTE = /^\/(?<repo>[^/]+)\.git\/(?<rest>info\/refs|git-upload-pack|git-receive-pack)$/;
7
+ const NO_CACHE = { "Cache-Control": "no-cache, max-age=0, must-revalidate" };
8
+ const text = (status, body, headers = {}) => new Response(body, {
9
+ status,
10
+ headers: {
11
+ "Content-Type": "text/plain; charset=utf-8",
12
+ ...headers
13
+ }
14
+ });
15
+ function gitResponse(body, type) {
16
+ return new Response(body, {
17
+ status: 200,
18
+ headers: {
19
+ "Content-Type": type,
20
+ ...NO_CACHE
21
+ }
22
+ });
23
+ }
24
+ async function requestBody(request) {
25
+ if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
26
+ const stream = request.headers.get("Content-Encoding") === "gzip" ? request.body.pipeThrough(new DecompressionStream("gzip")) : request.body;
27
+ return readAllBytes(stream);
28
+ }
29
+ /** Checks the request's credential opens `repo` for `access`; returns an error response when not. */
30
+ function authorize(host, request, repo, access) {
31
+ const credential = credentialOf(request);
32
+ const grant = credential === null ? null : host.tokens.check(credential);
33
+ if (grant?.repo !== repo) return text(401, "authentication required\n", { "WWW-Authenticate": "Basic realm=\"git-gateway-testkit\"" });
34
+ if (access === "write" && grant.access !== "write") return text(403, "read-only credential\n");
35
+ return null;
36
+ }
37
+ /**
38
+ * Serves git smart HTTP (protocol v0/v1) for the in-memory repositories: GET
39
+ * /<repo>.git/info/refs?service=…, POST /<repo>.git/git-upload-pack and
40
+ * /git-receive-pack. Every request needs a token minted by gitRemote() for that repository —
41
+ * as a Bearer header or the password of HTTP Basic — and a read token cannot push.
42
+ */
43
+ async function serveSmartHttp(host, request) {
44
+ const url = new URL(request.url);
45
+ const match = ROUTE.exec(url.pathname);
46
+ const name = match?.groups?.["repo"];
47
+ const rest = match?.groups?.["rest"];
48
+ if (name === void 0 || rest === void 0) return text(404, "not found\n");
49
+ const service = rest === "info/refs" ? url.searchParams.get("service") : rest;
50
+ if (service !== "git-upload-pack" && service !== "git-receive-pack") return text(403, "dumb HTTP is not supported\n");
51
+ const denied = authorize(host, request, name, service === "git-receive-pack" ? "write" : "read");
52
+ if (denied !== null) return denied;
53
+ const repo = host.repository(name);
54
+ if (repo === void 0) return text(404, "repository not found\n");
55
+ if (rest === "info/refs") {
56
+ if (request.method !== "GET") return text(405, "method not allowed\n");
57
+ return gitResponse(service === "git-upload-pack" ? uploadPackAdvertisement(repo) : receivePackAdvertisement(repo), `application/x-${service}-advertisement`);
58
+ }
59
+ if (request.method !== "POST") return text(405, "method not allowed\n");
60
+ const body = await requestBody(request);
61
+ return gitResponse(service === "git-upload-pack" ? await answerUploadPack(repo, body) : await answerReceivePack(repo, body), `application/x-${service}-result`);
62
+ }
63
+ export { serveSmartHttp };
64
+
65
+ //# sourceMappingURL=smart-http-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smart-http-server.js","names":[],"sources":["../../src/memory/smart-http-server.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { GitAccess } from '@leed-ai/git-gateway-contract/storage/git-remote';\nimport { readAllBytes } from '@leed-ai/git-gateway-core/bytes';\n\nimport type { MemoryRepository } from './memory-repository.ts';\nimport { credentialOf, type MemoryTokens } from './memory-tokens.ts';\nimport { answerReceivePack, receivePackAdvertisement } from './receive-pack-service.ts';\nimport { answerUploadPack, uploadPackAdvertisement } from './upload-pack-service.ts';\n\nconst ROUTE = /^\\/(?<repo>[^/]+)\\.git\\/(?<rest>info\\/refs|git-upload-pack|git-receive-pack)$/;\nconst NO_CACHE = { 'Cache-Control': 'no-cache, max-age=0, must-revalidate' };\n\n/** What the smart-HTTP server needs from the backend. */\nexport interface SmartHttpHost {\n readonly tokens: MemoryTokens;\n repository(name: string): MemoryRepository | undefined;\n}\n\nconst text = (status: number, body: string, headers: Record<string, string> = {}): Response =>\n new Response(body, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', ...headers } });\n\nfunction gitResponse(body: Uint8Array, type: string): Response {\n return new Response(body, { status: 200, headers: { 'Content-Type': type, ...NO_CACHE } });\n}\n\nasync function requestBody(request: Request): Promise<Uint8Array> {\n if (request.body === null) return new Uint8Array(0);\n const encoding = request.headers.get('Content-Encoding');\n const stream =\n encoding === 'gzip' ? request.body.pipeThrough(new DecompressionStream('gzip')) : request.body;\n return readAllBytes(stream);\n}\n\n/** Checks the request's credential opens `repo` for `access`; returns an error response when not. */\nfunction authorize(host: SmartHttpHost, request: Request, repo: string, access: GitAccess): Response | null {\n const credential = credentialOf(request);\n const grant = credential === null ? null : host.tokens.check(credential);\n if (grant?.repo !== repo) {\n return text(401, 'authentication required\\n', {\n 'WWW-Authenticate': 'Basic realm=\"git-gateway-testkit\"',\n });\n }\n if (access === 'write' && grant.access !== 'write') return text(403, 'read-only credential\\n');\n return null;\n}\n\n/**\n * Serves git smart HTTP (protocol v0/v1) for the in-memory repositories: GET\n * /<repo>.git/info/refs?service=…, POST /<repo>.git/git-upload-pack and\n * /git-receive-pack. Every request needs a token minted by gitRemote() for that repository —\n * as a Bearer header or the password of HTTP Basic — and a read token cannot push.\n */\nexport async function serveSmartHttp(host: SmartHttpHost, request: Request): Promise<Response> {\n const url = new URL(request.url);\n const match = ROUTE.exec(url.pathname);\n const name = match?.groups?.['repo'];\n const rest = match?.groups?.['rest'];\n if (name === undefined || rest === undefined) return text(404, 'not found\\n');\n const service = rest === 'info/refs' ? url.searchParams.get('service') : rest;\n if (service !== 'git-upload-pack' && service !== 'git-receive-pack') {\n return text(403, 'dumb HTTP is not supported\\n');\n }\n const denied = authorize(host, request, name, service === 'git-receive-pack' ? 'write' : 'read');\n if (denied !== null) return denied;\n const repo = host.repository(name);\n if (repo === undefined) return text(404, 'repository not found\\n');\n if (rest === 'info/refs') {\n if (request.method !== 'GET') return text(405, 'method not allowed\\n');\n const body =\n service === 'git-upload-pack' ? uploadPackAdvertisement(repo) : receivePackAdvertisement(repo);\n return gitResponse(body, `application/x-${service}-advertisement`);\n }\n if (request.method !== 'POST') return text(405, 'method not allowed\\n');\n const body = await requestBody(request);\n const answer =\n service === 'git-upload-pack' ? await answerUploadPack(repo, body) : await answerReceivePack(repo, body);\n return gitResponse(answer, `application/x-${service}-result`);\n}\n"],"mappings":";;;;;AASA,MAAM,QAAQ;AACd,MAAM,WAAW,EAAE,iBAAiB,uCAAuC;AAQ3E,MAAM,QAAQ,QAAgB,MAAc,UAAkC,CAAC,MAC7E,IAAI,SAAS,MAAM;CAAE;CAAQ,SAAS;EAAE,gBAAgB;EAA6B,GAAG;CAAQ;AAAE,CAAC;AAErG,SAAS,YAAY,MAAkB,MAAwB;CAC7D,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ;EAAK,SAAS;GAAE,gBAAgB;GAAM,GAAG;EAAS;CAAE,CAAC;AAC3F;AAEA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,oBAAoB,wBAAwB,IAAI,IAAI,yBAAyB,IAAI,GACtE,iBAAiB,QAAQ,eAAe;CACnE;CACA,IAAI,QAAQ,WAAW,QAAQ,OAAO,KAAK,KAAK,sBAAsB;CACtE,MAAM,OAAO,MAAM,YAAY,OAAO;CAGtC,OAAO,YADL,YAAY,oBAAoB,MAAM,iBAAiB,MAAM,IAAI,IAAI,MAAM,kBAAkB,MAAM,IAAI,GAC9E,iBAAiB,QAAQ,QAAQ;AAC9D"}
@@ -0,0 +1,15 @@
1
+ import { MemoryRepository } from "./memory-repository.js";
2
+ /** The capabilities the in-memory upload-pack offers: whole-object packs, shallow (deepen) and filter. */
3
+ export declare const UPLOAD_PACK_CAPABILITIES: readonly string[];
4
+ /** The upload-pack ref advertisement: HEAD (when the default branch exists), then every ref in name order. */
5
+ export declare function uploadPackAdvertisement(repo: MemoryRepository): Uint8Array;
6
+ /**
7
+ * Answers one stateless upload-pack request. A deepen first gets its shallow lines and a flush;
8
+ * a request that ends right after its wants gets nothing more. Otherwise, without "done" the
9
+ * answer acknowledges the first common have ("ACK <id>") or sends "NAK", and the client goes on; with "done" it sends that acknowledgement and a pack of every object
10
+ * reachable from the wants but not from the common haves — cut at the deepen, filtered — on
11
+ * side-band channel 1 when the client asked for side-band. Any object reachable from a ref may be
12
+ * wanted (allow-reachable-sha1-in-want).
13
+ */
14
+ export declare function answerUploadPack(repo: MemoryRepository, body: Uint8Array): Promise<Uint8Array>;
15
+ //# sourceMappingURL=upload-pack-service.d.ts.map
@@ -0,0 +1,123 @@
1
+ import { selectPack } from "./pack-selection.js";
2
+ import { concatBytes } from "@leed-ai/git-gateway-core/bytes";
3
+ import { encodeErrPacket } from "@leed-ai/git-gateway-core/receive-pack/report-status";
4
+ import { encodeRefAdvertisement } from "@leed-ai/git-gateway-core/smart-http/ref-advertisement";
5
+ import { decodePktLines, packetText } from "@leed-ai/git-gateway-core/pkt-line/decode";
6
+ import { FLUSH_PKT, encodePktLine } from "@leed-ai/git-gateway-core/pkt-line/encode";
7
+ import { writePack } from "@leed-ai/git-gateway-core/pack/write-pack";
8
+ import { BAND_DATA, SIDE_BAND_64K_MAX_PAYLOAD, SIDE_BAND_MAX_PAYLOAD, encodeSideBand } from "@leed-ai/git-gateway-core/receive-pack/side-band";
9
+ // src/memory/upload-pack-service.ts
10
+ /** The capabilities the in-memory upload-pack offers: whole-object packs, shallow (deepen) and filter. */
11
+ const UPLOAD_PACK_CAPABILITIES = [
12
+ "side-band",
13
+ "side-band-64k",
14
+ "no-progress",
15
+ "shallow",
16
+ "filter",
17
+ "allow-reachable-sha1-in-want",
18
+ "object-format=sha1",
19
+ "agent=git-gateway-testkit"
20
+ ];
21
+ /** The upload-pack ref advertisement: HEAD (when the default branch exists), then every ref in name order. */
22
+ function uploadPackAdvertisement(repo) {
23
+ const names = [...repo.refs.keys()].toSorted();
24
+ const head = repo.refs.get(repo.headRef);
25
+ const refs = names.map((name) => ({
26
+ name,
27
+ sha: repo.refs.get(name) ?? "",
28
+ peeled: null
29
+ }));
30
+ return encodeRefAdvertisement({
31
+ service: "git-upload-pack",
32
+ refs: head === void 0 ? refs : [{
33
+ name: "HEAD",
34
+ sha: head,
35
+ peeled: null
36
+ }, ...refs],
37
+ capabilities: [...UPLOAD_PACK_CAPABILITIES],
38
+ symrefs: head === void 0 ? {} : { HEAD: repo.headRef }
39
+ });
40
+ }
41
+ /**
42
+ * Reads a stateless upload-pack request: the wants (with capabilities, shallow, deepen and filter
43
+ * lines) up to a flush, then have lines up to a flush or "done". A request that stops right after
44
+ * the wants' flush only asks for the shallow list.
45
+ */
46
+ function readNegotiation(body) {
47
+ const wants = [];
48
+ const haves = [];
49
+ const capabilities = [];
50
+ const clientShallow = [];
51
+ let depth;
52
+ let filter;
53
+ let section = "needs";
54
+ let end = "none";
55
+ for (const packet of decodePktLines(body)) {
56
+ const line = packetText(packet);
57
+ if (line === null) {
58
+ if (section === "needs") section = "haves";
59
+ else end = "flush";
60
+ continue;
61
+ }
62
+ const [verb, argument = "", ...rest] = line.split(" ");
63
+ if (section === "needs" && verb === "want") {
64
+ if (wants.length === 0) capabilities.push(...rest);
65
+ wants.push(argument);
66
+ } else if (section === "needs" && verb === "shallow") clientShallow.push(argument);
67
+ else if (section === "needs" && verb === "deepen" && /^[1-9]\d*$/.test(argument)) depth = Number(argument);
68
+ else if (section === "needs" && verb === "filter") filter = argument;
69
+ else if (section === "haves" && verb === "have") haves.push(argument);
70
+ else if (section === "haves" && line === "done") end = "done";
71
+ else return `unsupported upload-pack line: ${line.slice(0, 60)}`;
72
+ }
73
+ return {
74
+ wants,
75
+ haves,
76
+ capabilities,
77
+ clientShallow,
78
+ depth,
79
+ filter,
80
+ end
81
+ };
82
+ }
83
+ function frame(capabilities, pack) {
84
+ if (capabilities.includes("side-band-64k")) return concatBytes([encodeSideBand(BAND_DATA, pack, SIDE_BAND_64K_MAX_PAYLOAD), FLUSH_PKT]);
85
+ if (capabilities.includes("side-band")) return concatBytes([encodeSideBand(BAND_DATA, pack, SIDE_BAND_MAX_PAYLOAD), FLUSH_PKT]);
86
+ return pack;
87
+ }
88
+ /**
89
+ * Answers one stateless upload-pack request. A deepen first gets its shallow lines and a flush;
90
+ * a request that ends right after its wants gets nothing more. Otherwise, without "done" the
91
+ * answer acknowledges the first common have ("ACK <id>") or sends "NAK", and the client goes on; with "done" it sends that acknowledgement and a pack of every object
92
+ * reachable from the wants but not from the common haves — cut at the deepen, filtered — on
93
+ * side-band channel 1 when the client asked for side-band. Any object reachable from a ref may be
94
+ * wanted (allow-reachable-sha1-in-want).
95
+ */
96
+ async function answerUploadPack(repo, body) {
97
+ const negotiation = readNegotiation(body);
98
+ if (typeof negotiation === "string") return encodeErrPacket(negotiation);
99
+ const reachableFromRefs = new Set(repo.reachable([...repo.refs.values()], []).map((object) => object.sha));
100
+ const unknown = negotiation.wants.find((want) => !reachableFromRefs.has(want));
101
+ if (unknown !== void 0) return encodeErrPacket(`upload-pack: not our ref ${unknown}`);
102
+ const common = negotiation.haves.filter((have) => repo.objects.has(have));
103
+ const selected = selectPack(repo, {
104
+ wants: negotiation.wants,
105
+ haves: common,
106
+ clientShallow: negotiation.clientShallow,
107
+ ...negotiation.depth === void 0 ? {} : { depth: negotiation.depth },
108
+ ...negotiation.filter === void 0 ? {} : { filter: negotiation.filter }
109
+ });
110
+ const parts = [];
111
+ if (negotiation.depth !== void 0) {
112
+ for (const sha of selected.shallow) parts.push(encodePktLine(`shallow ${sha}\n`));
113
+ for (const sha of selected.unshallow) parts.push(encodePktLine(`unshallow ${sha}\n`));
114
+ parts.push(FLUSH_PKT);
115
+ }
116
+ if (negotiation.end === "none") return concatBytes(parts);
117
+ parts.push(common[0] === void 0 ? encodePktLine("NAK\n") : encodePktLine(`ACK ${common[0]}\n`));
118
+ if (negotiation.end === "done") parts.push(frame(negotiation.capabilities, await writePack(selected.objects)));
119
+ return concatBytes(parts);
120
+ }
121
+ export { UPLOAD_PACK_CAPABILITIES, answerUploadPack, uploadPackAdvertisement };
122
+
123
+ //# sourceMappingURL=upload-pack-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-pack-service.js","names":[],"sources":["../../src/memory/upload-pack-service.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { concatBytes } from '@leed-ai/git-gateway-core/bytes';\nimport { decodePktLines, packetText } from '@leed-ai/git-gateway-core/pkt-line/decode';\nimport { encodePktLine, FLUSH_PKT } from '@leed-ai/git-gateway-core/pkt-line/encode';\nimport { writePack } from '@leed-ai/git-gateway-core/pack/write-pack';\nimport { encodeErrPacket } from '@leed-ai/git-gateway-core/receive-pack/report-status';\nimport {\n BAND_DATA,\n encodeSideBand,\n SIDE_BAND_64K_MAX_PAYLOAD,\n SIDE_BAND_MAX_PAYLOAD,\n} from '@leed-ai/git-gateway-core/receive-pack/side-band';\nimport { encodeRefAdvertisement } from '@leed-ai/git-gateway-core/smart-http/ref-advertisement';\n\nimport type { MemoryRepository } from './memory-repository.ts';\nimport { selectPack } from './pack-selection.ts';\n\n/** The capabilities the in-memory upload-pack offers: whole-object packs, shallow (deepen) and filter. */\nexport const UPLOAD_PACK_CAPABILITIES: readonly string[] = [\n 'side-band',\n 'side-band-64k',\n 'no-progress',\n 'shallow',\n 'filter',\n 'allow-reachable-sha1-in-want',\n 'object-format=sha1',\n 'agent=git-gateway-testkit',\n];\n\n/** The upload-pack ref advertisement: HEAD (when the default branch exists), then every ref in name order. */\nexport function uploadPackAdvertisement(repo: MemoryRepository): Uint8Array {\n const names = [...repo.refs.keys()].toSorted();\n const head = repo.refs.get(repo.headRef);\n const refs = names.map((name) => ({ name, sha: repo.refs.get(name) ?? '', peeled: null }));\n return encodeRefAdvertisement({\n service: 'git-upload-pack',\n refs: head === undefined ? refs : [{ name: 'HEAD', sha: head, peeled: null }, ...refs],\n capabilities: [...UPLOAD_PACK_CAPABILITIES],\n symrefs: head === undefined ? {} : { HEAD: repo.headRef },\n });\n}\n\ninterface Negotiation {\n readonly wants: string[];\n readonly haves: string[];\n readonly capabilities: string[];\n readonly clientShallow: string[];\n readonly depth: number | undefined;\n readonly filter: string | undefined;\n /** How the request ended after the wants: \"done\", a flush closing a round of haves, or nothing. */\n readonly end: 'done' | 'flush' | 'none';\n}\n\n/**\n * Reads a stateless upload-pack request: the wants (with capabilities, shallow, deepen and filter\n * lines) up to a flush, then have lines up to a flush or \"done\". A request that stops right after\n * the wants' flush only asks for the shallow list.\n */\nfunction readNegotiation(body: Uint8Array): Negotiation | string {\n const wants: string[] = [];\n const haves: string[] = [];\n const capabilities: string[] = [];\n const clientShallow: string[] = [];\n let depth: number | undefined;\n let filter: string | undefined;\n let section: 'needs' | 'haves' = 'needs';\n let end: Negotiation['end'] = 'none';\n for (const packet of decodePktLines(body)) {\n const line = packetText(packet);\n if (line === null) {\n if (section === 'needs') section = 'haves';\n else end = 'flush';\n continue;\n }\n const [verb, argument = '', ...rest] = line.split(' ');\n if (section === 'needs' && verb === 'want') {\n if (wants.length === 0) capabilities.push(...rest);\n wants.push(argument);\n } else if (section === 'needs' && verb === 'shallow') clientShallow.push(argument);\n else if (section === 'needs' && verb === 'deepen' && /^[1-9]\\d*$/.test(argument))\n depth = Number(argument);\n else if (section === 'needs' && verb === 'filter') filter = argument;\n else if (section === 'haves' && verb === 'have') haves.push(argument);\n else if (section === 'haves' && line === 'done') end = 'done';\n else return `unsupported upload-pack line: ${line.slice(0, 60)}`;\n }\n return { wants, haves, capabilities, clientShallow, depth, filter, end };\n}\n\nfunction frame(capabilities: readonly string[], pack: Uint8Array): Uint8Array {\n if (capabilities.includes('side-band-64k')) {\n return concatBytes([encodeSideBand(BAND_DATA, pack, SIDE_BAND_64K_MAX_PAYLOAD), FLUSH_PKT]);\n }\n if (capabilities.includes('side-band'))\n return concatBytes([encodeSideBand(BAND_DATA, pack, SIDE_BAND_MAX_PAYLOAD), FLUSH_PKT]);\n return pack;\n}\n\n/**\n * Answers one stateless upload-pack request. A deepen first gets its shallow lines and a flush;\n * a request that ends right after its wants gets nothing more. Otherwise, without \"done\" the\n * answer acknowledges the first common have (\"ACK <id>\") or sends \"NAK\", and the client goes on; with \"done\" it sends that acknowledgement and a pack of every object\n * reachable from the wants but not from the common haves — cut at the deepen, filtered — on\n * side-band channel 1 when the client asked for side-band. Any object reachable from a ref may be\n * wanted (allow-reachable-sha1-in-want).\n */\nexport async function answerUploadPack(repo: MemoryRepository, body: Uint8Array): Promise<Uint8Array> {\n const negotiation = readNegotiation(body);\n if (typeof negotiation === 'string') return encodeErrPacket(negotiation);\n const reachableFromRefs = new Set(repo.reachable([...repo.refs.values()], []).map((object) => object.sha));\n const unknown = negotiation.wants.find((want) => !reachableFromRefs.has(want));\n if (unknown !== undefined) return encodeErrPacket(`upload-pack: not our ref ${unknown}`);\n const common = negotiation.haves.filter((have) => repo.objects.has(have));\n const selected = selectPack(repo, {\n wants: negotiation.wants,\n haves: common,\n clientShallow: negotiation.clientShallow,\n ...(negotiation.depth === undefined ? {} : { depth: negotiation.depth }),\n ...(negotiation.filter === undefined ? {} : { filter: negotiation.filter }),\n });\n const parts: Uint8Array[] = [];\n if (negotiation.depth !== undefined) {\n for (const sha of selected.shallow) parts.push(encodePktLine(`shallow ${sha}\\n`));\n for (const sha of selected.unshallow) parts.push(encodePktLine(`unshallow ${sha}\\n`));\n parts.push(FLUSH_PKT);\n }\n if (negotiation.end === 'none') return concatBytes(parts);\n parts.push(common[0] === undefined ? encodePktLine('NAK\\n') : encodePktLine(`ACK ${common[0]}\\n`));\n if (negotiation.end === 'done')\n parts.push(frame(negotiation.capabilities, await writePack(selected.objects)));\n return concatBytes(parts);\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAa,2BAA8C;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,wBAAwB,MAAoC;CAC1E,MAAM,QAAQ,CAAC,GAAG,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,SAAS;CAC7C,MAAM,OAAO,KAAK,KAAK,IAAI,KAAK,OAAO;CACvC,MAAM,OAAO,MAAM,KAAK,UAAU;EAAE;EAAM,KAAK,KAAK,KAAK,IAAI,IAAI,KAAK;EAAI,QAAQ;CAAK,EAAE;CACzF,OAAO,uBAAuB;EAC5B,SAAS;EACT,MAAM,SAAS,KAAA,IAAY,OAAO,CAAC;GAAE,MAAM;GAAQ,KAAK;GAAM,QAAQ;EAAK,GAAG,GAAG,IAAI;EACrF,cAAc,CAAC,GAAG,wBAAwB;EAC1C,SAAS,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK,QAAQ;CAC1D,CAAC;AACH;;;;;;AAkBA,SAAS,gBAAgB,MAAwC;CAC/D,MAAM,QAAkB,CAAC;CACzB,MAAM,QAAkB,CAAC;CACzB,MAAM,eAAyB,CAAC;CAChC,MAAM,gBAA0B,CAAC;CACjC,IAAI;CACJ,IAAI;CACJ,IAAI,UAA6B;CACjC,IAAI,MAA0B;CAC9B,KAAK,MAAM,UAAU,eAAe,IAAI,GAAG;EACzC,MAAM,OAAO,WAAW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,SAAS,CAAC,kBAAkB,IAAI,IAAI,CAAC;CAC7E,IAAI,YAAY,KAAA,GAAW,OAAO,gBAAgB,4BAA4B,SAAS;CACvF,MAAM,SAAS,YAAY,MAAM,QAAQ,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC;CACxE,MAAM,WAAW,WAAW,MAAM;EAChC,OAAO,YAAY;EACnB,OAAO;EACP,eAAe,YAAY;EAC3B,GAAI,YAAY,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,YAAY,MAAM;EACtE,GAAI,YAAY,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,YAAY,OAAO;CAC3E,CAAC;CACD,MAAM,QAAsB,CAAC;CAC7B,IAAI,YAAY,UAAU,KAAA,GAAW;EACnC,KAAK,MAAM,OAAO,SAAS,SAAS,MAAM,KAAK,cAAc,WAAW,IAAI,GAAG,CAAC;EAChF,KAAK,MAAM,OAAO,SAAS,WAAW,MAAM,KAAK,cAAc,aAAa,IAAI,GAAG,CAAC;EACpF,MAAM,KAAK,SAAS;CACtB;CACA,IAAI,YAAY,QAAQ,QAAQ,OAAO,YAAY,KAAK;CACxD,MAAM,KAAK,OAAO,OAAO,KAAA,IAAY,cAAc,OAAO,IAAI,cAAc,OAAO,OAAO,GAAG,GAAG,CAAC;CACjG,IAAI,YAAY,QAAQ,QACtB,MAAM,KAAK,MAAM,YAAY,cAAc,MAAM,UAAU,SAAS,OAAO,CAAC,CAAC;CAC/E,OAAO,YAAY,KAAK;AAC1B"}
@@ -0,0 +1,16 @@
1
+ /** A fetch-style request handler, such as `MemoryBackend.handle` or a Worker's `fetch`. */
2
+ export type FetchHandler = (request: Request) => Promise<Response>;
3
+ /** A running local HTTP server. */
4
+ export interface LocalServer {
5
+ /** Base URL, e.g. "http://127.0.0.1:43210". */
6
+ readonly url: string;
7
+ /** Stops accepting connections and resolves once the server has closed. */
8
+ close(): Promise<void>;
9
+ }
10
+ /**
11
+ * Serves a fetch-style handler over plain HTTP on 127.0.0.1 (a random free port unless one is
12
+ * given), so a real git client can talk to an in-process server such as the in-memory backend.
13
+ * Request bodies are buffered before the handler runs; a thrown handler answers 500.
14
+ */
15
+ export declare function serveFetchHandler(handler: FetchHandler, port?: number): Promise<LocalServer>;
16
+ //# sourceMappingURL=serve-fetch-handler.d.ts.map
@@ -0,0 +1,52 @@
1
+ import { createServer } from "node:http";
2
+ // src/node/serve-fetch-handler.ts
3
+ async function readBody(message) {
4
+ if (message.method === "GET" || message.method === "HEAD") return null;
5
+ const chunks = [];
6
+ for await (const chunk of message) chunks.push(chunk instanceof Uint8Array ? chunk : new TextEncoder().encode(String(chunk)));
7
+ return new Uint8Array(Buffer.concat(chunks));
8
+ }
9
+ async function toRequest(message, base) {
10
+ const headers = new Headers();
11
+ for (const [name, value] of Object.entries(message.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
12
+ else if (value !== void 0) headers.set(name, value);
13
+ const body = await readBody(message);
14
+ return new Request(new URL(message.url ?? "/", base), {
15
+ method: message.method ?? "GET",
16
+ headers,
17
+ ...body === null ? {} : { body }
18
+ });
19
+ }
20
+ async function send(response, out) {
21
+ const headers = {};
22
+ response.headers.forEach((value, name) => {
23
+ headers[name] = value;
24
+ });
25
+ out.writeHead(response.status, headers);
26
+ out.end(Buffer.from(await response.arrayBuffer()));
27
+ }
28
+ /**
29
+ * Serves a fetch-style handler over plain HTTP on 127.0.0.1 (a random free port unless one is
30
+ * given), so a real git client can talk to an in-process server such as the in-memory backend.
31
+ * Request bodies are buffered before the handler runs; a thrown handler answers 500.
32
+ */
33
+ async function serveFetchHandler(handler, port = 0) {
34
+ let base = "http://127.0.0.1";
35
+ const server = createServer((message, out) => {
36
+ toRequest(message, base).then(handler).then(async (response) => send(response, out)).catch((error) => {
37
+ out.writeHead(500, { "Content-Type": "text/plain" });
38
+ out.end(error instanceof Error ? error.message : "internal error");
39
+ });
40
+ });
41
+ await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve));
42
+ const address = server.address();
43
+ if (address === null || typeof address === "string") throw new Error("the server has no TCP address");
44
+ base = `http://127.0.0.1:${address.port}`;
45
+ return {
46
+ url: base,
47
+ close: async () => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
48
+ };
49
+ }
50
+ export { serveFetchHandler };
51
+
52
+ //# sourceMappingURL=serve-fetch-handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-fetch-handler.js","names":[],"sources":["../../src/node/serve-fetch-handler.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\n\n/** A fetch-style request handler, such as `MemoryBackend.handle` or a Worker's `fetch`. */\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/** A running local HTTP server. */\nexport interface LocalServer {\n /** Base URL, e.g. \"http://127.0.0.1:43210\". */\n readonly url: string;\n /** Stops accepting connections and resolves once the server has closed. */\n close(): Promise<void>;\n}\n\nasync function readBody(message: IncomingMessage): Promise<Uint8Array | null> {\n if (message.method === 'GET' || message.method === 'HEAD') return null;\n const chunks: Uint8Array[] = [];\n for await (const chunk of message)\n chunks.push(chunk instanceof Uint8Array ? chunk : new TextEncoder().encode(String(chunk)));\n return new Uint8Array(Buffer.concat(chunks));\n}\n\nasync function toRequest(message: IncomingMessage, base: string): Promise<Request> {\n const headers = new Headers();\n for (const [name, value] of Object.entries(message.headers)) {\n if (Array.isArray(value)) for (const item of value) headers.append(name, item);\n else if (value !== undefined) headers.set(name, value);\n }\n const body = await readBody(message);\n return new Request(new URL(message.url ?? '/', base), {\n method: message.method ?? 'GET',\n headers,\n ...(body === null ? {} : { body }),\n });\n}\n\nasync function send(response: Response, out: ServerResponse): Promise<void> {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n headers[name] = value;\n });\n out.writeHead(response.status, headers);\n out.end(Buffer.from(await response.arrayBuffer()));\n}\n\n/**\n * Serves a fetch-style handler over plain HTTP on 127.0.0.1 (a random free port unless one is\n * given), so a real git client can talk to an in-process server such as the in-memory backend.\n * Request bodies are buffered before the handler runs; a thrown handler answers 500.\n */\nexport async function serveFetchHandler(handler: FetchHandler, port = 0): Promise<LocalServer> {\n let base = 'http://127.0.0.1';\n const server = createServer((message, out) => {\n toRequest(message, base)\n .then(handler)\n .then(async (response) => send(response, out))\n .catch((error: unknown) => {\n out.writeHead(500, { 'Content-Type': 'text/plain' });\n out.end(error instanceof Error ? error.message : 'internal error');\n });\n });\n await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));\n const address = server.address();\n if (address === null || typeof address === 'string') throw new Error('the server has no TCP address');\n base = `http://127.0.0.1:${address.port}`;\n return {\n url: base,\n close: async () =>\n new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))),\n };\n}\n"],"mappings":";;AAcA,eAAe,SAAS,SAAsD;CAC5E,IAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ,OAAO;CAClE,MAAM,SAAuB,CAAC;CAC9B,WAAW,MAAM,SAAS,SACxB,OAAO,KAAK,iBAAiB,aAAa,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,KAAK,CAAC,CAAC;CAC3F,OAAO,IAAI,WAAW,OAAO,OAAO,MAAM,CAAC;AAC7C;AAEA,eAAe,UAAU,SAA0B,MAAgC;CACjF,MAAM,UAAU,IAAI,QAAQ;CAC5B,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,OAAO,GACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,KAAK,MAAM,QAAQ,OAAO,QAAQ,OAAO,MAAM,IAAI;MACxE,IAAI,UAAU,KAAA,GAAW,QAAQ,IAAI,MAAM,KAAK;CAEvD,MAAM,OAAO,MAAM,SAAS,OAAO;CACnC,OAAO,IAAI,QAAQ,IAAI,IAAI,QAAQ,OAAO,KAAK,IAAI,GAAG;EACpD,QAAQ,QAAQ,UAAU;EAC1B;EACA,GAAI,SAAS,OAAO,CAAC,IAAI,EAAE,KAAK;CAClC,CAAC;AACH;AAEA,eAAe,KAAK,UAAoB,KAAoC;CAC1E,MAAM,UAAkC,CAAC;CACzC,SAAS,QAAQ,SAAS,OAAO,SAAS;EACxC,QAAQ,QAAQ;CAClB,CAAC;CACD,IAAI,UAAU,SAAS,QAAQ,OAAO;CACtC,IAAI,IAAI,OAAO,KAAK,MAAM,SAAS,YAAY,CAAC,CAAC;AACnD;;;;;;AAOA,eAAsB,kBAAkB,SAAuB,OAAO,GAAyB;CAC7F,IAAI,OAAO;CACX,MAAM,SAAS,cAAc,SAAS,QAAQ;EAC5C,UAAU,SAAS,IAAI,CAAC,CACrB,KAAK,OAAO,CAAC,CACb,KAAK,OAAO,aAAa,KAAK,UAAU,GAAG,CAAC,CAAC,CAC7C,OAAO,UAAmB;GACzB,IAAI,UAAU,KAAK,EAAE,gBAAgB,aAAa,CAAC;GACnD,IAAI,IAAI,iBAAiB,QAAQ,MAAM,UAAU,gBAAgB;EACnE,CAAC;CACL,CAAC;CACD,MAAM,IAAI,SAAe,YAAY,OAAO,OAAO,MAAM,aAAa,OAAO,CAAC;CAC9E,MAAM,UAAU,OAAO,QAAQ;CAC/B,IAAI,YAAY,QAAQ,OAAO,YAAY,UAAU,MAAM,IAAI,MAAM,+BAA+B;CACpG,OAAO,oBAAoB,QAAQ;CACnC,OAAO;EACL,KAAK;EACL,OAAO,YACL,IAAI,SAAe,SAAS,WAAW,OAAO,OAAO,UAAW,QAAQ,OAAO,KAAK,IAAI,QAAQ,CAAE,CAAC;CACvG;AACF"}
@@ -0,0 +1,16 @@
1
+ import { FetchHandler, LocalServer } from "./serve-fetch-handler.js";
2
+ /** Byte counts a {@link serveStreaming} server reports as traffic flows. */
3
+ export interface StreamingTraffic {
4
+ /** Called with each chunk of a request body as it is handed to the handler. */
5
+ readonly onRequestChunk?: (bytes: number) => void;
6
+ /** Called with each chunk of a response body once the socket has accepted it. */
7
+ readonly onResponseChunk?: (bytes: number) => void;
8
+ }
9
+ /**
10
+ * Serves a fetch-style handler (a Worker's `fetch`, a Hono app) over plain HTTP on 127.0.0.1 with
11
+ * request and response bodies streamed in both directions under backpressure — as the Workers
12
+ * runtime streams them — so a real git client can drive the gateway and tests can observe how much
13
+ * it holds at once. A thrown handler answers 500.
14
+ */
15
+ export declare function serveStreaming(handler: FetchHandler, traffic?: StreamingTraffic, port?: number): Promise<LocalServer>;
16
+ //# sourceMappingURL=serve-streaming.d.ts.map
@@ -0,0 +1,87 @@
1
+ import { createServer } from "node:http";
2
+ import { once } from "node:events";
3
+ // src/node/serve-streaming.ts
4
+ /**
5
+ * The request body as a stream that pulls from the socket only as the handler reads: the socket
6
+ * is paused whenever a chunk is waiting, so nothing piles up in memory.
7
+ */
8
+ function requestBody(message, traffic) {
9
+ return new ReadableStream({
10
+ start(controller) {
11
+ message.pause();
12
+ message.on("data", (chunk) => {
13
+ message.pause();
14
+ traffic.onRequestChunk?.(chunk.length);
15
+ controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.length));
16
+ });
17
+ message.on("end", () => controller.close());
18
+ message.on("error", (error) => controller.error(error));
19
+ },
20
+ pull() {
21
+ message.resume();
22
+ },
23
+ cancel() {
24
+ message.destroy();
25
+ }
26
+ }, { highWaterMark: 0 });
27
+ }
28
+ function toRequest(message, base, traffic) {
29
+ const headers = new Headers();
30
+ for (const [name, value] of Object.entries(message.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
31
+ else if (value !== void 0) headers.set(name, value);
32
+ const method = message.method ?? "GET";
33
+ const init = {
34
+ method,
35
+ headers
36
+ };
37
+ if (method !== "GET" && method !== "HEAD") {
38
+ init.body = requestBody(message, traffic);
39
+ init.duplex = "half";
40
+ }
41
+ return new Request(new URL(message.url ?? "/", base), init);
42
+ }
43
+ /** Writes a response chunk by chunk, waiting for the socket to drain, so it is never buffered whole. */
44
+ async function send(response, out, traffic) {
45
+ const headers = {};
46
+ response.headers.forEach((value, name) => {
47
+ headers[name] = value;
48
+ });
49
+ out.writeHead(response.status, headers);
50
+ if (response.body !== null) {
51
+ const reader = response.body.getReader();
52
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
53
+ if (!out.write(next.value)) await once(out, "drain");
54
+ traffic.onResponseChunk?.(next.value.length);
55
+ }
56
+ }
57
+ out.end();
58
+ }
59
+ /**
60
+ * Serves a fetch-style handler (a Worker's `fetch`, a Hono app) over plain HTTP on 127.0.0.1 with
61
+ * request and response bodies streamed in both directions under backpressure — as the Workers
62
+ * runtime streams them — so a real git client can drive the gateway and tests can observe how much
63
+ * it holds at once. A thrown handler answers 500.
64
+ */
65
+ async function serveStreaming(handler, traffic = {}, port = 0) {
66
+ let base = "http://127.0.0.1";
67
+ const server = createServer((message, out) => {
68
+ handler(toRequest(message, base, traffic)).then(async (response) => send(response, out, traffic)).catch((error) => {
69
+ if (!out.headersSent) out.writeHead(500, { "Content-Type": "text/plain" });
70
+ out.end(error instanceof Error ? error.message : "internal error");
71
+ });
72
+ });
73
+ await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve));
74
+ const address = server.address();
75
+ if (address === null || typeof address === "string") throw new Error("the server has no TCP address");
76
+ base = `http://127.0.0.1:${address.port}`;
77
+ return {
78
+ url: base,
79
+ close: async () => new Promise((resolve, reject) => {
80
+ server.closeAllConnections();
81
+ server.close((error) => error ? reject(error) : resolve());
82
+ })
83
+ };
84
+ }
85
+ export { serveStreaming };
86
+
87
+ //# sourceMappingURL=serve-streaming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-streaming.js","names":[],"sources":["../../src/node/serve-streaming.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { once } from 'node:events';\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\n\nimport type { FetchHandler, LocalServer } from './serve-fetch-handler.ts';\n\n/** Byte counts a {@link serveStreaming} server reports as traffic flows. */\nexport interface StreamingTraffic {\n /** Called with each chunk of a request body as it is handed to the handler. */\n readonly onRequestChunk?: (bytes: number) => void;\n /** Called with each chunk of a response body once the socket has accepted it. */\n readonly onResponseChunk?: (bytes: number) => void;\n}\n\n/**\n * The request body as a stream that pulls from the socket only as the handler reads: the socket\n * is paused whenever a chunk is waiting, so nothing piles up in memory.\n */\nfunction requestBody(message: IncomingMessage, traffic: StreamingTraffic): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>(\n {\n start(controller) {\n message.pause();\n message.on('data', (chunk: Buffer) => {\n message.pause();\n traffic.onRequestChunk?.(chunk.length);\n controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.length));\n });\n message.on('end', () => controller.close());\n message.on('error', (error) => controller.error(error));\n },\n pull() {\n message.resume();\n },\n cancel() {\n message.destroy();\n },\n },\n { highWaterMark: 0 },\n );\n}\n\nfunction toRequest(message: IncomingMessage, base: string, traffic: StreamingTraffic): Request {\n const headers = new Headers();\n for (const [name, value] of Object.entries(message.headers)) {\n if (Array.isArray(value)) for (const item of value) headers.append(name, item);\n else if (value !== undefined) headers.set(name, value);\n }\n const method = message.method ?? 'GET';\n const init: RequestInit & { duplex?: 'half' } = { method, headers };\n if (method !== 'GET' && method !== 'HEAD') {\n init.body = requestBody(message, traffic);\n init.duplex = 'half';\n }\n return new Request(new URL(message.url ?? '/', base), init);\n}\n\n/** Writes a response chunk by chunk, waiting for the socket to drain, so it is never buffered whole. */\nasync function send(response: Response, out: ServerResponse, traffic: StreamingTraffic): Promise<void> {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n headers[name] = value;\n });\n out.writeHead(response.status, headers);\n if (response.body !== null) {\n const reader = response.body.getReader();\n for (let next = await reader.read(); !next.done; next = await reader.read()) {\n if (!out.write(next.value)) await once(out, 'drain');\n traffic.onResponseChunk?.(next.value.length);\n }\n }\n out.end();\n}\n\n/**\n * Serves a fetch-style handler (a Worker's `fetch`, a Hono app) over plain HTTP on 127.0.0.1 with\n * request and response bodies streamed in both directions under backpressure — as the Workers\n * runtime streams them — so a real git client can drive the gateway and tests can observe how much\n * it holds at once. A thrown handler answers 500.\n */\nexport async function serveStreaming(\n handler: FetchHandler,\n traffic: StreamingTraffic = {},\n port = 0,\n): Promise<LocalServer> {\n let base = 'http://127.0.0.1';\n const server = createServer((message, out) => {\n handler(toRequest(message, base, traffic))\n .then(async (response) => send(response, out, traffic))\n .catch((error: unknown) => {\n if (!out.headersSent) out.writeHead(500, { 'Content-Type': 'text/plain' });\n out.end(error instanceof Error ? error.message : 'internal error');\n });\n });\n await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));\n const address = server.address();\n if (address === null || typeof address === 'string') throw new Error('the server has no TCP address');\n base = `http://127.0.0.1:${address.port}`;\n return {\n url: base,\n close: async () =>\n new Promise<void>((resolve, reject) => {\n server.closeAllConnections();\n server.close((error) => (error ? reject(error) : resolve()));\n }),\n };\n}\n"],"mappings":";;;;;;;AAkBA,SAAS,YAAY,SAA0B,SAAuD;CACpG,OAAO,IAAI,eACT;EACE,MAAM,YAAY;GAChB,QAAQ,MAAM;GACd,QAAQ,GAAG,SAAS,UAAkB;IACpC,QAAQ,MAAM;IACd,QAAQ,iBAAiB,MAAM,MAAM;IACrC,WAAW,QAAQ,IAAI,WAAW,MAAM,QAAQ,MAAM,YAAY,MAAM,MAAM,CAAC;GACjF,CAAC;GACD,QAAQ,GAAG,aAAa,WAAW,MAAM,CAAC;GAC1C,QAAQ,GAAG,UAAU,UAAU,WAAW,MAAM,KAAK,CAAC;EACxD;EACA,OAAO;GACL,QAAQ,OAAO;EACjB;EACA,SAAS;GACP,QAAQ,QAAQ;EAClB;CACF,GACA,EAAE,eAAe,EAAE,CACrB;AACF;AAEA,SAAS,UAAU,SAA0B,MAAc,SAAoC;CAC7F,MAAM,UAAU,IAAI,QAAQ;CAC5B,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,OAAO,GACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,KAAK,MAAM,QAAQ,OAAO,QAAQ,OAAO,MAAM,IAAI;MACxE,IAAI,UAAU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C;CAC9E,MAAM,UAAU,OAAO,QAAQ;CAC/B,IAAI,YAAY,QAAQ,OAAO,YAAY,UAAU,MAAM,IAAI,MAAM,+BAA+B;CACpG,OAAO,oBAAoB,QAAQ;CACnC,OAAO;EACL,KAAK;EACL,OAAO,YACL,IAAI,SAAe,SAAS,WAAW;GACrC,OAAO,oBAAoB;GAC3B,OAAO,OAAO,UAAW,QAAQ,OAAO,KAAK,IAAI,QAAQ,CAAE;EAC7D,CAAC;CACL;AACF"}
package/package.json CHANGED
@@ -1,6 +1,177 @@
1
1
  {
2
2
  "name": "@leed-ai/git-gateway-testkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Test kit for git-gateway: in-memory backend, repository fixtures, a real-git conformance harness and the backend contract suite.",
5
+ "keywords": [
6
+ "cloudflare-workers",
7
+ "conformance",
8
+ "git",
9
+ "git-gateway",
10
+ "testing"
11
+ ],
12
+ "homepage": "https://github.com/leed-ai/git-gateway/tree/main/packages/testkit#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/leed-ai/git-gateway/issues"
15
+ },
16
+ "license": "Apache-2.0",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/leed-ai/git-gateway.git",
20
+ "directory": "packages/testkit"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "src"
25
+ ],
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "exports": {
29
+ "./contract-suite/ancestry-cases": {
30
+ "source": "./src/contract-suite/ancestry-cases.ts",
31
+ "types": "./dist/contract-suite/ancestry-cases.d.ts",
32
+ "default": "./dist/contract-suite/ancestry-cases.js"
33
+ },
34
+ "./contract-suite/backend-case": {
35
+ "source": "./src/contract-suite/backend-case.ts",
36
+ "types": "./dist/contract-suite/backend-case.d.ts",
37
+ "default": "./dist/contract-suite/backend-case.js"
38
+ },
39
+ "./contract-suite/backend-contract-suite": {
40
+ "source": "./src/contract-suite/backend-contract-suite.ts",
41
+ "types": "./dist/contract-suite/backend-contract-suite.d.ts",
42
+ "default": "./dist/contract-suite/backend-contract-suite.js"
43
+ },
44
+ "./contract-suite/backend-fixtures": {
45
+ "source": "./src/contract-suite/backend-fixtures.ts",
46
+ "types": "./dist/contract-suite/backend-fixtures.d.ts",
47
+ "default": "./dist/contract-suite/backend-fixtures.js"
48
+ },
49
+ "./contract-suite/content-cases": {
50
+ "source": "./src/contract-suite/content-cases.ts",
51
+ "types": "./dist/contract-suite/content-cases.d.ts",
52
+ "default": "./dist/contract-suite/content-cases.js"
53
+ },
54
+ "./contract-suite/lifecycle-cases": {
55
+ "source": "./src/contract-suite/lifecycle-cases.ts",
56
+ "types": "./dist/contract-suite/lifecycle-cases.d.ts",
57
+ "default": "./dist/contract-suite/lifecycle-cases.js"
58
+ },
59
+ "./contract-suite/push-cases": {
60
+ "source": "./src/contract-suite/push-cases.ts",
61
+ "types": "./dist/contract-suite/push-cases.d.ts",
62
+ "default": "./dist/contract-suite/push-cases.js"
63
+ },
64
+ "./contract-suite/push-helpers": {
65
+ "source": "./src/contract-suite/push-helpers.ts",
66
+ "types": "./dist/contract-suite/push-helpers.d.ts",
67
+ "default": "./dist/contract-suite/push-helpers.js"
68
+ },
69
+ "./contract-suite/read-cases": {
70
+ "source": "./src/contract-suite/read-cases.ts",
71
+ "types": "./dist/contract-suite/read-cases.d.ts",
72
+ "default": "./dist/contract-suite/read-cases.js"
73
+ },
74
+ "./contract-suite/transport-cases": {
75
+ "source": "./src/contract-suite/transport-cases.ts",
76
+ "types": "./dist/contract-suite/transport-cases.d.ts",
77
+ "default": "./dist/contract-suite/transport-cases.js"
78
+ },
79
+ "./git-binary": {
80
+ "source": "./src/git-binary.ts",
81
+ "types": "./dist/git-binary.d.ts",
82
+ "default": "./dist/git-binary.js"
83
+ },
84
+ "./git-sandbox": {
85
+ "source": "./src/git-sandbox.ts",
86
+ "types": "./dist/git-sandbox.d.ts",
87
+ "default": "./dist/git-sandbox.js"
88
+ },
89
+ "./memory/memory-backend": {
90
+ "source": "./src/memory/memory-backend.ts",
91
+ "types": "./dist/memory/memory-backend.d.ts",
92
+ "default": "./dist/memory/memory-backend.js"
93
+ },
94
+ "./memory/memory-reads": {
95
+ "source": "./src/memory/memory-reads.ts",
96
+ "types": "./dist/memory/memory-reads.d.ts",
97
+ "default": "./dist/memory/memory-reads.js"
98
+ },
99
+ "./memory/memory-repository": {
100
+ "source": "./src/memory/memory-repository.ts",
101
+ "types": "./dist/memory/memory-repository.d.ts",
102
+ "default": "./dist/memory/memory-repository.js"
103
+ },
104
+ "./memory/memory-tokens": {
105
+ "source": "./src/memory/memory-tokens.ts",
106
+ "types": "./dist/memory/memory-tokens.d.ts",
107
+ "default": "./dist/memory/memory-tokens.js"
108
+ },
109
+ "./memory/pack-selection": {
110
+ "source": "./src/memory/pack-selection.ts",
111
+ "types": "./dist/memory/pack-selection.d.ts",
112
+ "default": "./dist/memory/pack-selection.js"
113
+ },
114
+ "./memory/receive-pack-service": {
115
+ "source": "./src/memory/receive-pack-service.ts",
116
+ "types": "./dist/memory/receive-pack-service.d.ts",
117
+ "default": "./dist/memory/receive-pack-service.js"
118
+ },
119
+ "./memory/smart-http-server": {
120
+ "source": "./src/memory/smart-http-server.ts",
121
+ "types": "./dist/memory/smart-http-server.d.ts",
122
+ "default": "./dist/memory/smart-http-server.js"
123
+ },
124
+ "./memory/upload-pack-service": {
125
+ "source": "./src/memory/upload-pack-service.ts",
126
+ "types": "./dist/memory/upload-pack-service.d.ts",
127
+ "default": "./dist/memory/upload-pack-service.js"
128
+ },
129
+ "./node/serve-fetch-handler": {
130
+ "source": "./src/node/serve-fetch-handler.ts",
131
+ "types": "./dist/node/serve-fetch-handler.d.ts",
132
+ "default": "./dist/node/serve-fetch-handler.js"
133
+ },
134
+ "./node/serve-streaming": {
135
+ "source": "./src/node/serve-streaming.ts",
136
+ "types": "./dist/node/serve-streaming.d.ts",
137
+ "default": "./dist/node/serve-streaming.js"
138
+ },
139
+ "./package.json": "./package.json"
140
+ },
141
+ "publishConfig": {
142
+ "access": "public",
143
+ "provenance": true
144
+ },
145
+ "scripts": {
146
+ "build": "vp pack",
147
+ "check": "vp check",
148
+ "test": "vp test --exclude 'test/**/*.conformance.test.ts'",
149
+ "test:conformance": "vp test conformance",
150
+ "test:contract": "vp test test/contract/"
151
+ },
152
+ "dependencies": {
153
+ "@leed-ai/git-gateway-contract": "0.1.0",
154
+ "@leed-ai/git-gateway-core": "0.1.0"
155
+ },
156
+ "devDependencies": {
157
+ "@leed-ai/git-gateway-repo-tools": "0.0.0",
158
+ "@leed-ai/git-gateway-schema-docs": "0.0.0",
159
+ "@types/node": "^24.19.2",
160
+ "cloudflare": "^5.2.0",
161
+ "typescript": "^7.0.2",
162
+ "vite-plus": "^1.7.0",
163
+ "zod": "^4.6.7"
164
+ },
165
+ "peerDependencies": {
166
+ "cloudflare": "^5",
167
+ "zod": "^4"
168
+ },
169
+ "peerDependenciesMeta": {
170
+ "cloudflare": {
171
+ "optional": true
172
+ }
173
+ },
174
+ "engines": {
175
+ "node": ">=22.18.0"
176
+ }
177
+ }