@leed-ai/git-gateway-backend-gitlab 0.0.0-stage → 0.1.1-next.20261122193358

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @leed-ai/git-gateway-backend-gitlab
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ git-gateway storage backend over a GitLab instance.
4
+
5
+ Part of [git-gateway](https://github.com/leed-ai/git-gateway). Status: in development; see the [design](https://github.com/leed-ai/git-gateway/blob/main/docs/design.md).
6
+
7
+ Peer dependencies: `zod` (`^4`). Install them alongside this package.
8
+
9
+ ## Usage
10
+
11
+ ```ts
12
+ import { GitLabBackend } from '@leed-ai/git-gateway-backend-gitlab/gitlab-backend';
13
+
14
+ const backend = new GitLabBackend({
15
+ baseUrl: 'https://gitlab.com',
16
+ token: env.GITLAB_TOKEN, // api, read_repository and write_repository on the group
17
+ namespace: 'acme/sites', // repository <repo> is the project acme/sites/<repo>
18
+ });
19
+ ```
20
+
21
+ ### Fronting existing projects
22
+
23
+ Projects that predate the gateway can be served without moving them. With `frontedProjects`, the reserved name `<prefix><projectId>` (default prefix `gl-`) addresses an existing project by id, provided it lives under `frontedProjects.namespace` at any depth:
24
+
25
+ ```ts
26
+ const backend = new GitLabBackend({
27
+ token: env.GITLAB_TOKEN,
28
+ namespace: 'acme/sites', // where createRepo puts new repositories
29
+ frontedProjects: { namespace: 'acme/customers' }, // gl-1234 is project 1234, if it is under acme/customers
30
+ });
31
+ ```
32
+
33
+ A project id outside that namespace answers `repo_not_found`, so the token's other projects stay out of reach. Reserved names can be read and pushed, but `createRepo` and `deleteRepo` refuse them with `invalid_input`.
34
+
35
+ Lifecycle, refs, blobs, files and history use the REST API (v4); commits and trees are read as git objects over smart HTTP; writes are git pushes to `gitRemote()`.
36
+
37
+ ## Tests
38
+
39
+ `bun run test` runs the unit tests and the backend contract suite against a fake GitLab (REST and git over the in-memory backend). With `GITLAB_CONTRACT_TOKEN` and `GITLAB_CONTRACT_NAMESPACE` set (and optionally `GITLAB_CONTRACT_URL`), `bun run test:contract` also runs the suite against that real group, creating and deleting one disposable project per case.
40
+
41
+ ## License
42
+
43
+ Apache-2.0
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+ import { FetchLike } from "@leed-ai/git-gateway-core/smart-http/git-http-client";
3
+ /** A GitLab API call that answered with an error status. */
4
+ export declare class GitLabHttpError extends Error {
5
+ readonly name = "GitLabHttpError";
6
+ readonly status: number;
7
+ /** GitLab's message, flattened to text ("404 Project Not Found", "path has already been taken"). */
8
+ readonly detail: string;
9
+ constructor(status: number, detail: string, what: string);
10
+ /** A 404 about the project itself, as opposed to a missing branch, commit, file or blob in it. */
11
+ get projectMissing(): boolean;
12
+ }
13
+ /** Options of one API request. */
14
+ export interface GitLabRequest {
15
+ readonly method?: 'GET' | 'POST' | 'DELETE';
16
+ readonly query?: Readonly<Record<string, string | number | boolean>>;
17
+ readonly body?: unknown;
18
+ }
19
+ /**
20
+ * The GitLab REST API (v4) over `fetch`, authenticated with a PRIVATE-TOKEN header. Error
21
+ * statuses throw {@link GitLabHttpError}; successful JSON is parsed with a Zod schema.
22
+ */
23
+ export declare class GitLabApi {
24
+ #private;
25
+ constructor(baseUrl: string, token: string, fetch: FetchLike);
26
+ /** Sends a request and returns the successful response. */
27
+ request(path: string, options?: GitLabRequest): Promise<Response>;
28
+ /** Sends a request and parses the JSON body with `schema`. */
29
+ json<S extends z.ZodType>(schema: S, path: string, options?: GitLabRequest): Promise<z.output<S>>;
30
+ /** Sends a GET and returns the body bytes, or null on a 404 that is not about the project. */
31
+ bytesOrNull(path: string, query?: GitLabRequest['query']): Promise<Uint8Array | null>;
32
+ }
33
+ //# sourceMappingURL=gitlab-api.d.ts.map
@@ -0,0 +1,77 @@
1
+ import { GitLabErrorBody } from "./schemas/gitlab-responses.js";
2
+ // src/gitlab-api.ts
3
+ /** A GitLab API call that answered with an error status. */
4
+ var GitLabHttpError = class extends Error {
5
+ name = "GitLabHttpError";
6
+ status;
7
+ /** GitLab's message, flattened to text ("404 Project Not Found", "path has already been taken"). */
8
+ detail;
9
+ constructor(status, detail, what) {
10
+ super(`GitLab ${what} answered ${status}: ${detail}`);
11
+ this.status = status;
12
+ this.detail = detail;
13
+ }
14
+ /** A 404 about the project itself, as opposed to a missing branch, commit, file or blob in it. */
15
+ get projectMissing() {
16
+ return this.status === 404 && /project not found/i.test(this.detail);
17
+ }
18
+ };
19
+ function flatten(body) {
20
+ if (typeof body.message === "string") return body.message;
21
+ if (body.message !== void 0) return Object.entries(body.message).map(([field, problems]) => `${field} ${problems.join(", ")}`).join("; ");
22
+ return body.error ?? "no message";
23
+ }
24
+ /**
25
+ * The GitLab REST API (v4) over `fetch`, authenticated with a PRIVATE-TOKEN header. Error
26
+ * statuses throw {@link GitLabHttpError}; successful JSON is parsed with a Zod schema.
27
+ */
28
+ var GitLabApi = class {
29
+ #base;
30
+ #token;
31
+ #fetch;
32
+ constructor(baseUrl, token, fetch) {
33
+ this.#base = `${baseUrl.replace(/\/$/, "")}/api/v4`;
34
+ this.#token = token;
35
+ this.#fetch = fetch;
36
+ }
37
+ /** Sends a request and returns the successful response. */
38
+ async request(path, options = {}) {
39
+ const url = new URL(`${this.#base}${path}`);
40
+ for (const [key, value] of Object.entries(options.query ?? {})) url.searchParams.set(key, String(value));
41
+ const headers = new Headers({
42
+ "PRIVATE-TOKEN": this.#token,
43
+ Accept: "application/json"
44
+ });
45
+ if (options.body !== void 0) headers.set("Content-Type", "application/json");
46
+ const response = await this.#fetch(new Request(url, {
47
+ method: options.method ?? "GET",
48
+ headers,
49
+ ...options.body === void 0 ? {} : { body: JSON.stringify(options.body) }
50
+ }));
51
+ if (response.ok) return response;
52
+ const text = await response.text();
53
+ let detail = text.slice(0, 200) || response.statusText;
54
+ try {
55
+ const parsed = GitLabErrorBody.safeParse(JSON.parse(text));
56
+ if (parsed.success) detail = flatten(parsed.data);
57
+ } catch {}
58
+ throw new GitLabHttpError(response.status, detail, `${options.method ?? "GET"} ${path.split("?")[0] ?? path}`);
59
+ }
60
+ /** Sends a request and parses the JSON body with `schema`. */
61
+ async json(schema, path, options = {}) {
62
+ const response = await this.request(path, options);
63
+ return schema.parse(await response.json());
64
+ }
65
+ /** Sends a GET and returns the body bytes, or null on a 404 that is not about the project. */
66
+ async bytesOrNull(path, query = {}) {
67
+ try {
68
+ return new Uint8Array(await (await this.request(path, { query })).arrayBuffer());
69
+ } catch (error) {
70
+ if (error instanceof GitLabHttpError && error.status === 404 && !error.projectMissing) return null;
71
+ throw error;
72
+ }
73
+ }
74
+ };
75
+ export { GitLabApi, GitLabHttpError };
76
+
77
+ //# sourceMappingURL=gitlab-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gitlab-api.js","names":[],"sources":["../src/gitlab-api.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { FetchLike } from '@leed-ai/git-gateway-core/smart-http/git-http-client';\nimport type { z } from 'zod';\n\nimport { GitLabErrorBody } from './schemas/gitlab-responses.ts';\n\n/** A GitLab API call that answered with an error status. */\nexport class GitLabHttpError extends Error {\n override readonly name = 'GitLabHttpError';\n readonly status: number;\n /** GitLab's message, flattened to text (\"404 Project Not Found\", \"path has already been taken\"). */\n readonly detail: string;\n\n constructor(status: number, detail: string, what: string) {\n super(`GitLab ${what} answered ${status}: ${detail}`);\n this.status = status;\n this.detail = detail;\n }\n\n /** A 404 about the project itself, as opposed to a missing branch, commit, file or blob in it. */\n get projectMissing(): boolean {\n return this.status === 404 && /project not found/i.test(this.detail);\n }\n}\n\nfunction flatten(body: GitLabErrorBody): string {\n if (typeof body.message === 'string') return body.message;\n if (body.message !== undefined) {\n return Object.entries(body.message)\n .map(([field, problems]) => `${field} ${problems.join(', ')}`)\n .join('; ');\n }\n return body.error ?? 'no message';\n}\n\n/** Options of one API request. */\nexport interface GitLabRequest {\n readonly method?: 'GET' | 'POST' | 'DELETE';\n readonly query?: Readonly<Record<string, string | number | boolean>>;\n readonly body?: unknown;\n}\n\n/**\n * The GitLab REST API (v4) over `fetch`, authenticated with a PRIVATE-TOKEN header. Error\n * statuses throw {@link GitLabHttpError}; successful JSON is parsed with a Zod schema.\n */\nexport class GitLabApi {\n readonly #base: string;\n readonly #token: string;\n readonly #fetch: FetchLike;\n\n constructor(baseUrl: string, token: string, fetch: FetchLike) {\n this.#base = `${baseUrl.replace(/\\/$/, '')}/api/v4`;\n this.#token = token;\n this.#fetch = fetch;\n }\n\n /** Sends a request and returns the successful response. */\n async request(path: string, options: GitLabRequest = {}): Promise<Response> {\n const url = new URL(`${this.#base}${path}`);\n for (const [key, value] of Object.entries(options.query ?? {})) url.searchParams.set(key, String(value));\n const headers = new Headers({ 'PRIVATE-TOKEN': this.#token, Accept: 'application/json' });\n if (options.body !== undefined) headers.set('Content-Type', 'application/json');\n const response = await this.#fetch(\n new Request(url, {\n method: options.method ?? 'GET',\n headers,\n ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),\n }),\n );\n if (response.ok) return response;\n const text = await response.text();\n let detail = text.slice(0, 200) || response.statusText;\n try {\n const parsed = GitLabErrorBody.safeParse(JSON.parse(text));\n if (parsed.success) detail = flatten(parsed.data);\n } catch {\n // Not JSON: keep the text.\n }\n throw new GitLabHttpError(\n response.status,\n detail,\n `${options.method ?? 'GET'} ${path.split('?')[0] ?? path}`,\n );\n }\n\n /** Sends a request and parses the JSON body with `schema`. */\n async json<S extends z.ZodType>(\n schema: S,\n path: string,\n options: GitLabRequest = {},\n ): Promise<z.output<S>> {\n const response = await this.request(path, options);\n return schema.parse(await response.json());\n }\n\n /** Sends a GET and returns the body bytes, or null on a 404 that is not about the project. */\n async bytesOrNull(path: string, query: GitLabRequest['query'] = {}): Promise<Uint8Array | null> {\n try {\n return new Uint8Array(await (await this.request(path, { query })).arrayBuffer());\n } catch (error) {\n if (error instanceof GitLabHttpError && error.status === 404 && !error.projectMissing) return null;\n throw error;\n }\n }\n}\n"],"mappings":";;;AAOA,IAAa,kBAAb,cAAqC,MAAM;CACzC,OAAyB;CACzB;;CAEA;CAEA,YAAY,QAAgB,QAAgB,MAAc;EACxD,MAAM,UAAU,KAAK,YAAY,OAAO,IAAI,QAAQ;EACpD,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;;CAGA,IAAI,iBAA0B;EAC5B,OAAO,KAAK,WAAW,OAAO,qBAAqB,KAAK,KAAK,MAAM;CACrE;AACF;AAEA,SAAS,QAAQ,MAA+B;CAC9C,IAAI,OAAO,KAAK,YAAY,UAAU,OAAO,KAAK;CAClD,IAAI,KAAK,YAAY,KAAA,GACnB,OAAO,OAAO,QAAQ,KAAK,OAAO,CAAC,CAChC,KAAK,CAAC,OAAO,cAAc,GAAG,MAAM,GAAG,SAAS,KAAK,IAAI,GAAG,CAAC,CAC7D,KAAK,IAAI;CAEd,OAAO,KAAK,SAAS;AACvB;;;;;AAaA,IAAa,YAAb,MAAuB;CACrB;CACA;CACA;CAEA,YAAY,SAAiB,OAAe,OAAkB;EAC5D,KAAK,QAAQ,GAAG,QAAQ,QAAQ,OAAO,EAAE,EAAE;EAC3C,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;;CAGA,MAAM,QAAQ,MAAc,UAAyB,CAAC,GAAsB;EAC1E,MAAM,MAAM,IAAI,IAAI,GAAG,KAAK,QAAQ,MAAM;EAC1C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,SAAS,CAAC,CAAC,GAAG,IAAI,aAAa,IAAI,KAAK,OAAO,KAAK,CAAC;EACvG,MAAM,UAAU,IAAI,QAAQ;GAAE,iBAAiB,KAAK;GAAQ,QAAQ;EAAmB,CAAC;EACxF,IAAI,QAAQ,SAAS,KAAA,GAAW,QAAQ,IAAI,gBAAgB,kBAAkB;EAC9E,MAAM,WAAW,MAAM,KAAK,OAC1B,IAAI,QAAQ,KAAK;GACf,QAAQ,QAAQ,UAAU;GAC1B;GACA,GAAI,QAAQ,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,QAAQ,IAAI,EAAE;EAC7E,CAAC,CACH;EACA,IAAI,SAAS,IAAI,OAAO;EACxB,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,IAAI,SAAS,KAAK,MAAM,GAAG,GAAG,KAAK,SAAS;EAC5C,IAAI;GACF,MAAM,SAAS,gBAAgB,UAAU,KAAK,MAAM,IAAI,CAAC;GACzD,IAAI,OAAO,SAAS,SAAS,QAAQ,OAAO,IAAI;EAClD,QAAQ,CAER;EACA,MAAM,IAAI,gBACR,SAAS,QACT,QACA,GAAG,QAAQ,UAAU,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,MACtD;CACF;;CAGA,MAAM,KACJ,QACA,MACA,UAAyB,CAAC,GACJ;EACtB,MAAM,WAAW,MAAM,KAAK,QAAQ,MAAM,OAAO;EACjD,OAAO,OAAO,MAAM,MAAM,SAAS,KAAK,CAAC;CAC3C;;CAGA,MAAM,YAAY,MAAc,QAAgC,CAAC,GAA+B;EAC9F,IAAI;GACF,OAAO,IAAI,WAAW,OAAO,MAAM,KAAK,QAAQ,MAAM,EAAE,MAAM,CAAC,EAAA,CAAG,YAAY,CAAC;EACjF,SAAS,OAAO;GACd,IAAI,iBAAiB,mBAAmB,MAAM,WAAW,OAAO,CAAC,MAAM,gBAAgB,OAAO;GAC9F,MAAM;EACR;CACF;AACF"}
@@ -0,0 +1,43 @@
1
+ import { GitLabBackendConfig } from "./schemas/gitlab-config.js";
2
+ import { GitRemote } from "@leed-ai/git-gateway-contract/storage/git-remote";
3
+ import { StorageLogOptions } from "@leed-ai/git-gateway-contract/storage/storage-read";
4
+ import { CreateStorageRepoOptions, StorageRepoInfo } from "@leed-ai/git-gateway-contract/storage/storage-repo-info";
5
+ import { FetchLike } from "@leed-ai/git-gateway-core/smart-http/git-http-client";
6
+ import { StorageTreeEntry } from "@leed-ai/git-gateway-contract/storage/storage-tree-entry";
7
+ import { Commit } from "@leed-ai/git-gateway-contract/schemas/commit";
8
+ import { StorageBackend } from "@leed-ai/git-gateway-contract/storage/storage-backend";
9
+ /** Options of a {@link GitLabBackend}: its configuration and, optionally, how requests are sent. */
10
+ export type GitLabBackendOptions = GitLabBackendConfig & {
11
+ /** Sends API and git requests; default the global fetch. */
12
+ readonly fetch?: FetchLike;
13
+ };
14
+ /**
15
+ * A {@link StorageBackend} over a GitLab instance, so the gateway can front repositories that
16
+ * still live on GitLab. Each repository is a private project in one group. Lifecycle, refs,
17
+ * blobs, files and history use the REST API (v4); commits and trees are read as git objects over
18
+ * the smart-HTTP transport (GitLab's API reports neither tree ids nor raw messages), and writes
19
+ * are git pushes to {@link gitRemote}. It offers the optional `isAncestor` capability through
20
+ * GitLab's merge-base API, so the gateway proves fast-forwards in one call. Every API response is parsed with Zod.
21
+ *
22
+ * With `frontedProjects`, a reserved name `<prefix><projectId>` addresses an existing project by
23
+ * id, wherever it lives under `frontedProjects.namespace`, so the gateway can front repositories
24
+ * that predate it without moving them. Those names can be read and pushed but never created or
25
+ * deleted.
26
+ */
27
+ export declare class GitLabBackend implements StorageBackend {
28
+ #private;
29
+ constructor(options: GitLabBackendOptions);
30
+ createRepo(name: string, options?: CreateStorageRepoOptions): Promise<StorageRepoInfo>;
31
+ deleteRepo(name: string): Promise<void>;
32
+ repoInfo(name: string): Promise<StorageRepoInfo | null>;
33
+ resolveRef(name: string, ref: string): Promise<string | null>;
34
+ readCommit(name: string, sha: string): Promise<Commit | null>;
35
+ readTree(name: string, sha: string): Promise<StorageTreeEntry[] | null>;
36
+ readBlob(name: string, sha: string): Promise<Uint8Array | null>;
37
+ readFile(name: string, ref: string, path: string): Promise<Uint8Array | null>;
38
+ log(name: string, ref: string, options: StorageLogOptions): Promise<Commit[]>;
39
+ /** One merge-base API call: `ancestor` is an ancestor exactly when it is the merge base. */
40
+ isAncestor(name: string, ancestor: string, descendant: string): Promise<boolean | null>;
41
+ gitRemote(name: string, access: string): Promise<GitRemote>;
42
+ }
43
+ //# sourceMappingURL=gitlab-backend.d.ts.map
@@ -0,0 +1,237 @@
1
+ import { GitLabApi, GitLabHttpError } from "./gitlab-api.js";
2
+ import { FrontedProjects, frontedLifecycleRefused } from "./gitlab-fronted.js";
3
+ import { readCommitsOverGit, readTreeOverGit } from "./gitlab-git-reads.js";
4
+ import { isAncestorOnGitLab } from "./gitlab-merge-base.js";
5
+ import { GitLabBackendConfig } from "./schemas/gitlab-config.js";
6
+ import { GitLabCommitSummary, GitLabGroup, GitLabProject, GitLabRef } from "./schemas/gitlab-responses.js";
7
+ import { z } from "zod";
8
+ import { isGatewayError } from "@leed-ai/git-gateway-contract/gateway-error";
9
+ import { FilePath, RepoName, Revision } from "@leed-ai/git-gateway-contract/schemas/names";
10
+ import { Sha } from "@leed-ai/git-gateway-contract/schemas/sha";
11
+ import { GitAccess, GitRemote } from "@leed-ai/git-gateway-contract/storage/git-remote";
12
+ import { repoExists, repoNotFound, storageUnavailable } from "@leed-ai/git-gateway-contract/storage/storage-errors";
13
+ import { parseStorageInput } from "@leed-ai/git-gateway-contract/storage/storage-input";
14
+ import { StorageLogOptions, StorageRef } from "@leed-ai/git-gateway-contract/storage/storage-read";
15
+ import { CreateStorageRepoOptions, StorageRepoInfo } from "@leed-ai/git-gateway-contract/storage/storage-repo-info";
16
+ import { GitHttpClient } from "@leed-ai/git-gateway-core/smart-http/git-http-client";
17
+ // src/gitlab-backend.ts
18
+ const PAGE = 100;
19
+ const enc = encodeURIComponent;
20
+ /**
21
+ * A {@link StorageBackend} over a GitLab instance, so the gateway can front repositories that
22
+ * still live on GitLab. Each repository is a private project in one group. Lifecycle, refs,
23
+ * blobs, files and history use the REST API (v4); commits and trees are read as git objects over
24
+ * the smart-HTTP transport (GitLab's API reports neither tree ids nor raw messages), and writes
25
+ * are git pushes to {@link gitRemote}. It offers the optional `isAncestor` capability through
26
+ * GitLab's merge-base API, so the gateway proves fast-forwards in one call. Every API response is parsed with Zod.
27
+ *
28
+ * With `frontedProjects`, a reserved name `<prefix><projectId>` addresses an existing project by
29
+ * id, wherever it lives under `frontedProjects.namespace`, so the gateway can front repositories
30
+ * that predate it without moving them. Those names can be read and pushed but never created or
31
+ * deleted.
32
+ */
33
+ var GitLabBackend = class {
34
+ #config;
35
+ #api;
36
+ #fetch;
37
+ #namespaceId;
38
+ #fronted;
39
+ constructor(options) {
40
+ const { fetch, ...config } = options;
41
+ this.#config = GitLabBackendConfig.parse(config);
42
+ this.#fetch = fetch ?? (async (request) => globalThis.fetch(request));
43
+ this.#api = new GitLabApi(this.#config.baseUrl, this.#config.token, this.#fetch);
44
+ this.#namespaceId = this.#config.namespaceId;
45
+ this.#fronted = new FrontedProjects(this.#config.frontedProjects);
46
+ }
47
+ async createRepo(name, options = {}) {
48
+ const repo = parseStorageInput(RepoName, name);
49
+ const { defaultBranch } = parseStorageInput(CreateStorageRepoOptions, options);
50
+ if (this.#fronted.idOf(repo) !== null) throw frontedLifecycleRefused(repo, "created");
51
+ return this.#call(repo, "createRepo", async () => {
52
+ const namespaceId = await this.#resolveNamespaceId();
53
+ try {
54
+ const body = {
55
+ name: repo,
56
+ path: repo,
57
+ namespace_id: namespaceId,
58
+ default_branch: defaultBranch,
59
+ visibility: "private",
60
+ initialize_with_readme: false
61
+ };
62
+ return this.#info(await this.#api.json(GitLabProject, "/projects", {
63
+ method: "POST",
64
+ body
65
+ }), defaultBranch);
66
+ } catch (error) {
67
+ if (error instanceof GitLabHttpError && error.status === 400 && /already been taken/i.test(error.detail)) throw repoExists(repo);
68
+ throw error;
69
+ }
70
+ });
71
+ }
72
+ async deleteRepo(name) {
73
+ const repo = parseStorageInput(RepoName, name);
74
+ if (this.#fronted.idOf(repo) !== null) throw frontedLifecycleRefused(repo, "deleted");
75
+ await this.#call(repo, "deleteRepo", async () => {
76
+ const project = await this.#projectOrNull(repo);
77
+ if (project === null) return;
78
+ await this.#api.request(`/projects/${project.id}`, { method: "DELETE" });
79
+ const marked = await this.#api.json(GitLabProject, `/projects/${project.id}`).catch(() => null);
80
+ if (marked !== null) await this.#api.request(`/projects/${project.id}`, {
81
+ method: "DELETE",
82
+ query: {
83
+ permanently_remove: true,
84
+ full_path: marked.path_with_namespace
85
+ }
86
+ });
87
+ });
88
+ }
89
+ async repoInfo(name) {
90
+ const repo = parseStorageInput(RepoName, name);
91
+ return this.#call(repo, "repoInfo", async () => {
92
+ const project = await this.#projectOrNull(repo);
93
+ return project === null ? null : this.#info(project, "main", repo);
94
+ });
95
+ }
96
+ async resolveRef(name, ref) {
97
+ const repo = parseStorageInput(RepoName, name);
98
+ const parsed = parseStorageInput(StorageRef, ref);
99
+ const [kind, short] = parsed.startsWith("refs/tags/") ? ["tags", parsed.slice(10)] : ["branches", parsed.replace(/^refs\/heads\//, "")];
100
+ return this.#call(repo, "resolveRef", async () => {
101
+ try {
102
+ return (await this.#api.json(GitLabRef, `${await this.#projectPath(repo)}/repository/${kind}/${enc(short)}`)).commit.id;
103
+ } catch (error) {
104
+ if (error instanceof GitLabHttpError && error.status === 404 && !error.projectMissing) return null;
105
+ throw error;
106
+ }
107
+ });
108
+ }
109
+ async readCommit(name, sha) {
110
+ const repo = parseStorageInput(RepoName, name);
111
+ const id = parseStorageInput(Sha, sha);
112
+ return this.#call(repo, "readCommit", async () => {
113
+ if (await this.#api.bytesOrNull(`${await this.#projectPath(repo)}/repository/commits/${id}`) === null) return null;
114
+ const [commit] = await readCommitsOverGit(await this.#client(repo), [id]);
115
+ return commit ?? null;
116
+ });
117
+ }
118
+ async readTree(name, sha) {
119
+ const repo = parseStorageInput(RepoName, name);
120
+ const id = parseStorageInput(Sha, sha);
121
+ return this.#call(repo, "readTree", async () => readTreeOverGit(await this.#client(repo), id));
122
+ }
123
+ async readBlob(name, sha) {
124
+ const repo = parseStorageInput(RepoName, name);
125
+ const id = parseStorageInput(Sha, sha);
126
+ return this.#call(repo, "readBlob", async () => this.#api.bytesOrNull(`${await this.#projectPath(repo)}/repository/blobs/${id}/raw`));
127
+ }
128
+ async readFile(name, ref, path) {
129
+ const repo = parseStorageInput(RepoName, name);
130
+ const revision = parseStorageInput(Revision, ref);
131
+ const file = parseStorageInput(FilePath, path);
132
+ return this.#call(repo, "readFile", async () => this.#api.bytesOrNull(`${await this.#projectPath(repo)}/repository/files/${enc(file)}/raw`, { ref: revision }));
133
+ }
134
+ async log(name, ref, options) {
135
+ const repo = parseStorageInput(RepoName, name);
136
+ const revision = parseStorageInput(Revision, ref);
137
+ const { limit, offset } = parseStorageInput(StorageLogOptions, options);
138
+ return this.#call(repo, "log", async () => {
139
+ const shas = await this.#listFirstParents(repo, revision, offset + limit);
140
+ return readCommitsOverGit(await this.#client(repo), shas.slice(offset, offset + limit));
141
+ });
142
+ }
143
+ /** One merge-base API call: `ancestor` is an ancestor exactly when it is the merge base. */
144
+ async isAncestor(name, ancestor, descendant) {
145
+ const repo = parseStorageInput(RepoName, name);
146
+ const older = parseStorageInput(Sha, ancestor);
147
+ const newer = parseStorageInput(Sha, descendant);
148
+ return this.#call(repo, "isAncestor", async () => isAncestorOnGitLab(this.#api, await this.#projectPath(repo), older, newer));
149
+ }
150
+ async gitRemote(name, access) {
151
+ const repo = parseStorageInput(RepoName, name);
152
+ parseStorageInput(GitAccess, access);
153
+ return this.#call(repo, "gitRemote", async () => {
154
+ const project = await this.#projectOrNull(repo);
155
+ if (project === null) throw repoNotFound(repo);
156
+ const basic = btoa(`${this.#config.gitUsername}:${this.#config.token}`);
157
+ return GitRemote.parse({
158
+ url: project.http_url_to_repo,
159
+ headers: { Authorization: `Basic ${basic}` },
160
+ expiresAt: null
161
+ });
162
+ });
163
+ }
164
+ /** The ids along the first-parent chain from `revision`, newest first, at most `count`. */
165
+ async #listFirstParents(repo, revision, count) {
166
+ const shas = [];
167
+ for (let page = 1; shas.length < count; page += 1) {
168
+ let listed;
169
+ try {
170
+ const query = {
171
+ ref_name: revision,
172
+ first_parent: true,
173
+ per_page: PAGE,
174
+ page
175
+ };
176
+ listed = await this.#api.json(z.array(GitLabCommitSummary), `${await this.#projectPath(repo)}/repository/commits`, { query });
177
+ } catch (error) {
178
+ if (error instanceof GitLabHttpError && error.status === 404 && !error.projectMissing) return [];
179
+ throw error;
180
+ }
181
+ shas.push(...listed.map((commit) => commit.id));
182
+ if (listed.length < PAGE) break;
183
+ }
184
+ return shas.slice(0, count);
185
+ }
186
+ async #client(repo) {
187
+ return new GitHttpClient(await this.gitRemote(repo, "read"), { fetch: this.#fetch });
188
+ }
189
+ /**
190
+ * The API path of `repo`'s project. A fronted name is checked to lie under the fronted namespace
191
+ * first (once per id), so a project elsewhere is repo_not_found rather than reachable by id.
192
+ */
193
+ async #projectPath(repo) {
194
+ const id = this.#fronted.idOf(repo);
195
+ if (id === null) return `/projects/${enc(`${this.#config.namespace}/${repo}`)}`;
196
+ if (!this.#fronted.verified(id) && await this.#projectOrNull(repo) === null) throw repoNotFound(repo);
197
+ return `/projects/${id}`;
198
+ }
199
+ async #projectOrNull(repo) {
200
+ const id = this.#fronted.idOf(repo);
201
+ const path = id === null ? `/projects/${enc(`${this.#config.namespace}/${repo}`)}` : `/projects/${id}`;
202
+ try {
203
+ const project = await this.#api.json(GitLabProject, path);
204
+ if (project.marked_for_deletion_on !== null && project.marked_for_deletion_on !== void 0) return null;
205
+ if (id === null) return project;
206
+ return this.#fronted.admits(id, project) ? project : null;
207
+ } catch (error) {
208
+ if (error instanceof GitLabHttpError && error.status === 404) return null;
209
+ throw error;
210
+ }
211
+ }
212
+ async #resolveNamespaceId() {
213
+ this.#namespaceId ??= (await this.#api.json(GitLabGroup, `/groups/${enc(this.#config.namespace)}`)).id;
214
+ return this.#namespaceId;
215
+ }
216
+ /** The StorageRepoInfo of `project`; a fronted project is named by the reserved `name` it was opened by. */
217
+ #info(project, fallbackBranch, name) {
218
+ return StorageRepoInfo.parse({
219
+ name: name !== void 0 && this.#fronted.idOf(name) !== null ? name : project.path,
220
+ defaultBranch: project.default_branch ?? fallbackBranch,
221
+ createdAt: new Date(project.created_at).toISOString()
222
+ });
223
+ }
224
+ /** Runs one call: GatewayErrors pass through, a 404 for the project is repo_not_found, anything else storage_unavailable. */
225
+ async #call(repo, what, work) {
226
+ try {
227
+ return await work();
228
+ } catch (error) {
229
+ if (isGatewayError(error)) throw error;
230
+ if (error instanceof GitLabHttpError && error.projectMissing) throw repoNotFound(repo);
231
+ throw storageUnavailable(`GitLab ${what}`, error);
232
+ }
233
+ }
234
+ };
235
+ export { GitLabBackend };
236
+
237
+ //# sourceMappingURL=gitlab-backend.js.map