@foss.global/codefeed 5.1.0 → 5.3.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.
- package/changelog.md +45 -0
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/classes.giteasourceinventory.d.ts +35 -9
- package/dist_ts/classes.giteasourceinventory.js +284 -26
- package/dist_ts/classes.giteasourcetransfer.d.ts +151 -6
- package/dist_ts/classes.giteasourcetransfer.js +411 -9
- package/dist_ts/forgeinventory.client.d.ts +43 -5
- package/dist_ts/forgeinventory.client.js +57 -13
- package/dist_ts/forgeinventory.transport.d.ts +21 -7
- package/dist_ts/forgeinventory.transport.js +15 -10
- package/dist_ts/giteasourceinventory.packages.d.ts +46 -0
- package/dist_ts/giteasourceinventory.packages.js +139 -0
- package/dist_ts/giteasourcetransfer.documents.d.ts +35 -0
- package/dist_ts/giteasourcetransfer.documents.js +86 -0
- package/dist_ts/index.d.ts +3 -0
- package/dist_ts/index.js +3 -1
- package/dist_ts/plugins.d.ts +2 -2
- package/dist_ts/plugins.js +3 -1
- package/package.json +3 -3
- package/readme.md +37 -2
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/classes.giteasourceinventory.ts +293 -24
- package/ts/classes.giteasourcetransfer.ts +532 -8
- package/ts/forgeinventory.client.ts +106 -13
- package/ts/forgeinventory.transport.ts +33 -13
- package/ts/giteasourceinventory.packages.ts +160 -0
- package/ts/giteasourcetransfer.documents.ts +97 -0
- package/ts/index.ts +3 -0
- package/ts/plugins.ts +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as transport from './forgeinventory.transport.js';
|
|
2
2
|
import * as validation from './forgeinventory.validation.js';
|
|
3
3
|
|
|
4
4
|
export interface IForgeRequestMetrics {
|
|
@@ -32,11 +32,56 @@ export interface IForgeJsonResponse {
|
|
|
32
32
|
headers: transport.IForgeTransportResponse['headers'];
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
export interface IForgeBytesRequestOptions {
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
/** Optional lower response-body budget for this request. */
|
|
38
|
+
maxResponseBytes?: number;
|
|
39
|
+
/** Additional request headers. */
|
|
40
|
+
headers?: Record<string, string>;
|
|
41
|
+
/** Sent as `accept`; the response may carry any content type, which the caller checks. */
|
|
42
|
+
accept: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface IForgeBytesResponse {
|
|
46
|
+
/** The response body exactly as it arrived. */
|
|
47
|
+
bytes: Buffer;
|
|
48
|
+
/** The response's media type without parameters, lowercased; null when it sent none. */
|
|
49
|
+
mediaType: string | null;
|
|
50
|
+
headers: transport.IForgeTransportResponse['headers'];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A redirect a read returned instead of refusing: never followed, its body discarded. */
|
|
54
|
+
export interface IForgeRedirectResponse {
|
|
55
|
+
/** One of 301, 302, 303, 307 and 308. */
|
|
56
|
+
status: number;
|
|
57
|
+
/** The `Location` header verbatim; null when the response sent none. */
|
|
58
|
+
location: string | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The answer of `requestBytesOrRedirect`: the body of a 200, or the redirect. */
|
|
62
|
+
export type TForgeBytesOrRedirect = ({ kind: 'bytes' } & IForgeBytesResponse) | ({ kind: 'redirect' } & IForgeRedirectResponse);
|
|
63
|
+
|
|
64
|
+
interface IReadOptions {
|
|
65
|
+
signal?: AbortSignal;
|
|
66
|
+
maxResponseBytes?: number;
|
|
67
|
+
headers?: Record<string, string>;
|
|
68
|
+
accept: string;
|
|
69
|
+
/** The media type the response must carry, checked before its body is read; any when absent. */
|
|
70
|
+
requiredMediaType?: string;
|
|
71
|
+
body?: { mediaType: string; bytes: Uint8Array<ArrayBuffer> };
|
|
72
|
+
/** `return` resolves a redirect status as `redirect` instead of rejecting; defaults to `refuse`. */
|
|
73
|
+
redirect?: transport.TForgeRedirectMode;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type TReadResult =
|
|
77
|
+
| { kind: 'bytes'; bytes: Buffer; headers: transport.IForgeTransportResponse['headers'] }
|
|
78
|
+
| ({ kind: 'redirect' } & IForgeRedirectResponse);
|
|
79
|
+
|
|
35
80
|
/**
|
|
36
|
-
* One bounded, credential-scoped
|
|
37
|
-
*
|
|
38
|
-
* content type. Failures surface as
|
|
39
|
-
*
|
|
81
|
+
* One bounded, credential-scoped read at a time, a GET or a POST with a JSON
|
|
82
|
+
* body: a per-request deadline, a response-size budget and, for JSON, a
|
|
83
|
+
* strict content type. Failures surface as `ForgeInventoryError` codes that
|
|
84
|
+
* never contain bodies, URLs or credentials.
|
|
40
85
|
*/
|
|
41
86
|
export class ForgeRequestClient {
|
|
42
87
|
readonly #options: IForgeRequestClientOptions;
|
|
@@ -49,6 +94,46 @@ export class ForgeRequestClient {
|
|
|
49
94
|
public get metrics(): IForgeRequestMetrics { return { ...this.#metrics }; }
|
|
50
95
|
|
|
51
96
|
public async request(url: URL, requestArg: IForgeRequestOptions = {}): Promise<IForgeJsonResponse> {
|
|
97
|
+
const mediaType = requestArg.mediaType ?? 'application/json';
|
|
98
|
+
const response = await this.#body(url, {
|
|
99
|
+
signal: requestArg.signal, maxResponseBytes: requestArg.maxResponseBytes, headers: requestArg.headers, accept: mediaType, requiredMediaType: mediaType,
|
|
100
|
+
...(requestArg.json === undefined ? {} : { body: { mediaType, bytes: new TextEncoder().encode(JSON.stringify(requestArg.json)) } }),
|
|
101
|
+
});
|
|
102
|
+
try {
|
|
103
|
+
return { body: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(response.bytes)) as unknown, headers: response.headers };
|
|
104
|
+
} catch {
|
|
105
|
+
throw new validation.ForgeInventoryError('request-or-json-failed');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** A GET whose body is returned as the bytes that arrived, with the media type the response declared. */
|
|
110
|
+
public async requestBytes(url: URL, requestArg: IForgeBytesRequestOptions): Promise<IForgeBytesResponse> {
|
|
111
|
+
const response = await this.#body(url, requestArg);
|
|
112
|
+
return { bytes: response.bytes, mediaType: mediaTypeOf(response.headers), headers: response.headers };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A GET like `requestBytes`, except that a redirect status resolves as
|
|
117
|
+
* `{ kind: 'redirect', status, location }` instead of rejecting. The
|
|
118
|
+
* redirect is never followed and its body is discarded unread; any status
|
|
119
|
+
* other than 200 and a redirect still rejects with `http-<status>`.
|
|
120
|
+
*/
|
|
121
|
+
public async requestBytesOrRedirect(url: URL, requestArg: IForgeBytesRequestOptions): Promise<TForgeBytesOrRedirect> {
|
|
122
|
+
const response = await this.#read(url, { ...requestArg, redirect: 'return' });
|
|
123
|
+
return response.kind === 'redirect'
|
|
124
|
+
? response
|
|
125
|
+
: { kind: 'bytes', bytes: response.bytes, mediaType: mediaTypeOf(response.headers), headers: response.headers };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** A read that refuses redirects, so it always answers a body. */
|
|
129
|
+
async #body(url: URL, requestArg: Omit<IReadOptions, 'redirect'>): Promise<{ bytes: Buffer; headers: transport.IForgeTransportResponse['headers'] }> {
|
|
130
|
+
const response = await this.#read(url, requestArg);
|
|
131
|
+
// The transport refuses every redirect status in this mode, so a redirect never arrives here.
|
|
132
|
+
if (response.kind === 'redirect') throw new validation.ForgeInventoryError('request-or-json-failed');
|
|
133
|
+
return response;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async #read(url: URL, requestArg: IReadOptions): Promise<TReadResult> {
|
|
52
137
|
const { signal } = requestArg;
|
|
53
138
|
const maxBytes = requestArg.maxResponseBytes ?? this.#options.maxResponseBytes;
|
|
54
139
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new validation.ForgeInventoryError('invalid-response-budget');
|
|
@@ -61,14 +146,20 @@ export class ForgeRequestClient {
|
|
|
61
146
|
let bodyChunks: AsyncIterator<Uint8Array> | undefined;
|
|
62
147
|
try {
|
|
63
148
|
this.#metrics.requests++;
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const response = await this.#options.transport(url, headers, controller.signal,
|
|
149
|
+
const headers = {
|
|
150
|
+
accept: requestArg.accept, ...(requestArg.body ? { 'content-type': requestArg.body.mediaType } : {}), ...requestArg.headers, ...this.#options.headers,
|
|
151
|
+
};
|
|
152
|
+
const response = await this.#options.transport(url, headers, controller.signal, requestArg.body?.bytes, { redirect: requestArg.redirect ?? 'refuse' });
|
|
68
153
|
bodyChunks = response.body?.[Symbol.asyncIterator]();
|
|
69
154
|
if (response.status === 429) this.#metrics.rateLimitedRequests++;
|
|
155
|
+
if (requestArg.redirect === 'return' && transport.redirectStatuses.has(response.status)) {
|
|
156
|
+
// The body is discarded unread by the `finally` below.
|
|
157
|
+
return { kind: 'redirect', status: response.status, location: response.headers.get('location') };
|
|
158
|
+
}
|
|
70
159
|
if (response.status !== 200) throw new validation.ForgeInventoryError(`http-${response.status}`);
|
|
71
|
-
if (
|
|
160
|
+
if ((requestArg.requiredMediaType !== undefined && mediaTypeOf(response.headers) !== requestArg.requiredMediaType) || !bodyChunks) {
|
|
161
|
+
throw new validation.ForgeInventoryError('invalid-content-type');
|
|
162
|
+
}
|
|
72
163
|
const chunks: Uint8Array[] = [];
|
|
73
164
|
let bytes = 0;
|
|
74
165
|
while (true) {
|
|
@@ -79,10 +170,8 @@ export class ForgeRequestClient {
|
|
|
79
170
|
if (controller.signal.aborted || Date.now() >= deadline) throw new validation.ForgeInventoryError('request-aborted-or-timed-out');
|
|
80
171
|
chunks.push(result.value);
|
|
81
172
|
}
|
|
82
|
-
const text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
|
|
83
|
-
const body = JSON.parse(text) as unknown;
|
|
84
173
|
if (controller.signal.aborted || Date.now() >= deadline) throw new validation.ForgeInventoryError('request-aborted-or-timed-out');
|
|
85
|
-
return {
|
|
174
|
+
return { kind: 'bytes', bytes: Buffer.concat(chunks), headers: response.headers };
|
|
86
175
|
} catch (error) {
|
|
87
176
|
if (error instanceof validation.ForgeInventoryError) throw error;
|
|
88
177
|
throw new validation.ForgeInventoryError(controller.signal.aborted ? 'request-aborted-or-timed-out' : 'request-or-json-failed');
|
|
@@ -93,3 +182,7 @@ export class ForgeRequestClient {
|
|
|
93
182
|
}
|
|
94
183
|
}
|
|
95
184
|
}
|
|
185
|
+
|
|
186
|
+
/** A response's media type without parameters, lowercased; null when it sent none. */
|
|
187
|
+
const mediaTypeOf = (headersArg: transport.IForgeTransportResponse['headers']): string | null =>
|
|
188
|
+
headersArg.get('content-type')?.split(';')[0].trim().toLowerCase() || null;
|
|
@@ -8,16 +8,29 @@ export interface IForgeTransportResponse {
|
|
|
8
8
|
body: AsyncIterable<Uint8Array> | null;
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* What a transport does with a redirect status: `refuse` rejects it, `return`
|
|
13
|
+
* resolves it as the response it is, `Location` included. Neither follows it.
|
|
14
|
+
*/
|
|
15
|
+
export type TForgeRedirectMode = 'refuse' | 'return';
|
|
16
|
+
|
|
17
|
+
export interface IForgeTransportOptions {
|
|
18
|
+
/** Defaults to `refuse`. */
|
|
19
|
+
redirect?: TForgeRedirectMode;
|
|
20
|
+
}
|
|
21
|
+
|
|
11
22
|
/**
|
|
12
23
|
* Sends one credential-scoped GET, or a POST of `body` when one is given, and
|
|
13
|
-
* resolves once response headers arrive. A redirect status
|
|
14
|
-
*
|
|
15
|
-
* body is still being read.
|
|
24
|
+
* resolves once response headers arrive. A redirect status is never followed:
|
|
25
|
+
* it rejects, unless `options.redirect` is `return`. Aborting `signal`
|
|
26
|
+
* discards the connection, also while the body is still being read.
|
|
16
27
|
*/
|
|
17
|
-
export type TForgeTransport = (
|
|
28
|
+
export type TForgeTransport = (
|
|
29
|
+
url: URL, headers: Record<string, string>, signal: AbortSignal, body?: Uint8Array<ArrayBuffer>, options?: IForgeTransportOptions,
|
|
30
|
+
) => Promise<IForgeTransportResponse>;
|
|
18
31
|
|
|
19
32
|
/** The fetch statuses whose redirect mode `error` turns them into a network error. */
|
|
20
|
-
const redirectStatuses: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);
|
|
33
|
+
export const redirectStatuses: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);
|
|
21
34
|
|
|
22
35
|
/**
|
|
23
36
|
* Idle keep-alive sockets close after this delay, or earlier when the server
|
|
@@ -27,8 +40,10 @@ const redirectStatuses: ReadonlySet<number> = new Set([301, 302, 303, 307, 308])
|
|
|
27
40
|
const idleSocketTimeoutMs = 4_000;
|
|
28
41
|
|
|
29
42
|
/** Node's global `fetch` with the process-wide default trust store. */
|
|
30
|
-
export const globalFetchTransport: TForgeTransport = async (url, headers, signal, body) => {
|
|
31
|
-
|
|
43
|
+
export const globalFetchTransport: TForgeTransport = async (url, headers, signal, body, options) => {
|
|
44
|
+
// Node's fetch answers `manual` with the redirect response itself, status and `Location` included.
|
|
45
|
+
const redirect = options?.redirect === 'return' ? 'manual' : 'error';
|
|
46
|
+
const response = await fetch(url, { method: body ? 'POST' : 'GET', headers, body, redirect, credentials: 'omit', signal });
|
|
32
47
|
return { status: response.status, headers: response.headers, body: response.body };
|
|
33
48
|
};
|
|
34
49
|
|
|
@@ -45,6 +60,8 @@ export interface INodeRequest {
|
|
|
45
60
|
body?: Uint8Array | AsyncIterable<Uint8Array>;
|
|
46
61
|
signal: AbortSignal;
|
|
47
62
|
agents: INodeRequestAgents;
|
|
63
|
+
/** Defaults to `refuse`. */
|
|
64
|
+
redirect?: TForgeRedirectMode;
|
|
48
65
|
}
|
|
49
66
|
|
|
50
67
|
export interface INodeResponse extends IForgeTransportResponse {
|
|
@@ -74,9 +91,10 @@ const drained = (requestArg: InstanceType<typeof plugins.http.ClientRequest>): P
|
|
|
74
91
|
|
|
75
92
|
/**
|
|
76
93
|
* Sends one request through `node:http` or `node:https` and resolves once
|
|
77
|
-
* response headers arrive. A redirect status
|
|
78
|
-
*
|
|
79
|
-
* sent or read. A streamed body that fails
|
|
94
|
+
* response headers arrive. A redirect status is never followed: it rejects,
|
|
95
|
+
* unless `redirect` is `return`. Aborting `signal` discards the connection,
|
|
96
|
+
* also while a body is still being sent or read. A streamed body that fails
|
|
97
|
+
* destroys the request and rejects.
|
|
80
98
|
*/
|
|
81
99
|
export const sendNodeRequest = (url: URL, requestArg: INodeRequest): Promise<INodeResponse> => new Promise<INodeResponse>((resolve, reject) => {
|
|
82
100
|
const { signal } = requestArg;
|
|
@@ -126,7 +144,7 @@ export const sendNodeRequest = (url: URL, requestArg: INodeRequest): Promise<INo
|
|
|
126
144
|
request.on('response', (response) => {
|
|
127
145
|
try {
|
|
128
146
|
const status = response.statusCode ?? 0;
|
|
129
|
-
if (redirectStatuses.has(status)) throw new Error('Refused redirect.');
|
|
147
|
+
if (redirectStatuses.has(status) && requestArg.redirect !== 'return') throw new Error('Refused redirect.');
|
|
130
148
|
// Same combination rules as fetch: repeated fields join with ", ".
|
|
131
149
|
const responseHeaders = new Headers();
|
|
132
150
|
for (let index = 0; index < response.rawHeaders.length; index += 2) {
|
|
@@ -149,8 +167,10 @@ export const sendNodeRequest = (url: URL, requestArg: INodeRequest): Promise<INo
|
|
|
149
167
|
*/
|
|
150
168
|
export const createHttpsTransport = (caCertificates: string[]): TForgeTransport => {
|
|
151
169
|
const agents = createNodeAgents(caCertificates);
|
|
152
|
-
return async (url, headers, signal, body) => {
|
|
153
|
-
const { sent: _sent, ...response } = await sendNodeRequest(url, {
|
|
170
|
+
return async (url, headers, signal, body, options) => {
|
|
171
|
+
const { sent: _sent, ...response } = await sendNodeRequest(url, {
|
|
172
|
+
method: body ? 'POST' : 'GET', headers, body, signal, agents, redirect: options?.redirect,
|
|
173
|
+
});
|
|
154
174
|
return response;
|
|
155
175
|
};
|
|
156
176
|
};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import * as validation from './forgeinventory.validation.js';
|
|
3
|
+
|
|
4
|
+
type TMeasure = plugins.fossInterfaces.data.TForgeSourceMeasure;
|
|
5
|
+
type IPackageRef = plugins.fossInterfaces.data.IForgeSourcePackageRef;
|
|
6
|
+
type IPackageRecord = plugins.fossInterfaces.data.IForgeSourcePackageInventory;
|
|
7
|
+
type IPackageContent = plugins.fossInterfaces.data.IForgeSourcePackageContent;
|
|
8
|
+
type IPackageContentSelection = plugins.fossInterfaces.data.IForgeSourcePackageContentSelection;
|
|
9
|
+
type IPackageContentGroup = plugins.fossInterfaces.data.IForgeSourcePackageContentGroup;
|
|
10
|
+
type IPackageContentTotals = plugins.fossInterfaces.data.IForgeSourcePackageContentTotals;
|
|
11
|
+
|
|
12
|
+
/** Media types Gitea serves an index or a manifest list as; an index candidate must be one of them. */
|
|
13
|
+
export const containerIndexMediaTypes: readonly string[] = Object.freeze([
|
|
14
|
+
'application/vnd.oci.image.index.v1+json',
|
|
15
|
+
'application/vnd.docker.distribution.manifest.list.v2+json',
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
/** Every manifest media type Gitea serves: images, indexes and manifest lists, OCI and Docker. */
|
|
19
|
+
export const containerManifestMediaTypes: readonly string[] = Object.freeze([
|
|
20
|
+
...containerIndexMediaTypes,
|
|
21
|
+
'application/vnd.oci.image.manifest.v1+json',
|
|
22
|
+
'application/vnd.docker.distribution.manifest.v2+json',
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
/** A package type as Gitea names it; it names reason paths, so it must be one of Gitea's plain identifiers. */
|
|
26
|
+
export const packageTypePattern = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
27
|
+
|
|
28
|
+
/** Gitea's npm name rule (`modules/packages/npm/creator.go`): `name` or `@scope/name`, URL-safe as it stands. */
|
|
29
|
+
const npmNamePattern = /^(?:@[a-z0-9-][a-z0-9-._]*\/)?[a-z0-9-][a-z0-9-._]*$/;
|
|
30
|
+
/** Gitea's Cargo crate name rule (`modules/packages/cargo/parser.go`). */
|
|
31
|
+
const cargoNamePattern = /^[A-Za-z][A-Za-z0-9-_]{0,63}$/;
|
|
32
|
+
/** Gitea's Swift scope and name rules (`routers/api/packages/swift/swift.go`); it stores the package as `scope.name`. */
|
|
33
|
+
const swiftPackagePattern = /^([A-Za-z0-9][A-Za-z0-9-]{0,38})\.([A-Za-z0-9][A-Za-z0-9-_]{0,99})$/;
|
|
34
|
+
|
|
35
|
+
const compareText = (aArg: string, bArg: string): number => (aArg < bArg ? -1 : aArg > bArg ? 1 : 0);
|
|
36
|
+
|
|
37
|
+
/** The key of a package within one instance: owner, type and name, which Gitea keeps unique (the name without case). */
|
|
38
|
+
export const packageKey = (refArg: IPackageRef): string => `${refArg.owner}/${refArg.type}/${refArg.name}`;
|
|
39
|
+
|
|
40
|
+
/** Orders packages by owner, type and name in code-unit order. */
|
|
41
|
+
export const comparePackages = (aArg: IPackageRef, bArg: IPackageRef): number =>
|
|
42
|
+
compareText(aArg.owner, bArg.owner) || compareText(aArg.type, bArg.type) || compareText(aArg.name, bArg.name);
|
|
43
|
+
|
|
44
|
+
/** The path segment(s) of an npm package in Gitea's npm registry: the name unencoded, as Gitea's npm routes match it. */
|
|
45
|
+
export const npmPackagePath = (nameArg: string): string => {
|
|
46
|
+
if (!npmNamePattern.test(nameArg) || nameArg.length > 214) throw new validation.ForgeInventoryError('invalid-npm-name');
|
|
47
|
+
return nameArg;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** The path of a crate's entry in the Cargo sparse index, lowercased, per the Cargo registry index layout. */
|
|
51
|
+
export const cargoIndexPath = (nameArg: string): string => {
|
|
52
|
+
if (!cargoNamePattern.test(nameArg)) throw new validation.ForgeInventoryError('invalid-cargo-name');
|
|
53
|
+
const name = nameArg.toLowerCase();
|
|
54
|
+
if (name.length === 1) return `1/${name}`;
|
|
55
|
+
if (name.length === 2) return `2/${name}`;
|
|
56
|
+
if (name.length === 3) return `3/${name[0]}/${name}`;
|
|
57
|
+
return `${name.slice(0, 2)}/${name.slice(2, 4)}/${name}`;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** The scope and name of a Swift package stored as `scope.name`. */
|
|
61
|
+
export const swiftPackageParts = (nameArg: string): { scope: string; name: string } => {
|
|
62
|
+
const match = swiftPackagePattern.exec(nameArg);
|
|
63
|
+
if (!match) throw new validation.ForgeInventoryError('invalid-swift-name');
|
|
64
|
+
return { scope: match[1], name: match[2] };
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The digest of the manifest a container version holds: `sha256:` and the
|
|
69
|
+
* SHA-256 of the blob holding the version's `manifest.json`; null for a
|
|
70
|
+
* version without one.
|
|
71
|
+
*/
|
|
72
|
+
export const containerManifestDigest = (packageArg: IPackageRecord, versionIdArg: string): string | null => {
|
|
73
|
+
const blob = packageArg.blobs.find((blobArg) => blobArg.files.some((fileArg) => fileArg.versionId === versionIdArg && fileArg.name === 'manifest.json'));
|
|
74
|
+
return blob ? `sha256:${blob.sha256}` : null;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The version ids of a package's tagged-and-referenced selection: for a
|
|
79
|
+
* container package the tagged versions and the versions holding a manifest
|
|
80
|
+
* a tagged index references; every version of any other type.
|
|
81
|
+
*/
|
|
82
|
+
export const taggedAndReferencedVersionIds = (packageArg: IPackageRecord): Set<string> => {
|
|
83
|
+
if (packageArg.type !== 'container') return new Set(packageArg.versions.map((versionArg) => versionArg.id));
|
|
84
|
+
const tagged = packageArg.versions.filter((versionArg) => !versionArg.version.startsWith('sha256:'));
|
|
85
|
+
const referenced = new Set(tagged.flatMap((versionArg) => versionArg.references ?? []));
|
|
86
|
+
const selected = new Set(tagged.map((versionArg) => versionArg.id));
|
|
87
|
+
for (const version of packageArg.versions) {
|
|
88
|
+
const digest = containerManifestDigest(packageArg, version.id);
|
|
89
|
+
if (digest !== null && referenced.has(digest)) selected.add(version.id);
|
|
90
|
+
}
|
|
91
|
+
return selected;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
interface IContentSum {
|
|
95
|
+
blobs: Map<string, bigint>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const contentMeasure = (sumArg: IContentSum, missingArg: number): IPackageContent => {
|
|
99
|
+
const blobs = BigInt(sumArg.blobs.size);
|
|
100
|
+
const bytes = [...sumArg.blobs.values()].reduce((totalArg, sizeArg) => totalArg + sizeArg, 0n);
|
|
101
|
+
if (missingArg === 0) return { blobs: { status: 'complete', value: blobs.toString() }, bytes: { status: 'complete', value: bytes.toString() } };
|
|
102
|
+
const reason = `Package units not measured: ${missingArg}.`;
|
|
103
|
+
const partial = (valueArg: bigint): TMeasure => ({ status: 'partial', observedValue: valueArg.toString(), reason });
|
|
104
|
+
return { blobs: partial(blobs), bytes: partial(bytes) };
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/** Distinct content of a set of package records over both selections; `missingArg` packages of the set were not read. */
|
|
108
|
+
const selection = (packagesArg: readonly IPackageRecord[], missingArg: number): IPackageContentSelection => {
|
|
109
|
+
const all: IContentSum = { blobs: new Map() };
|
|
110
|
+
const tagged: IContentSum = { blobs: new Map() };
|
|
111
|
+
for (const record of packagesArg) {
|
|
112
|
+
const selected = taggedAndReferencedVersionIds(record);
|
|
113
|
+
for (const blob of record.blobs) {
|
|
114
|
+
const size = BigInt(blob.size);
|
|
115
|
+
all.blobs.set(blob.sha256, size);
|
|
116
|
+
if (blob.files.some((fileArg) => selected.has(fileArg.versionId))) tagged.blobs.set(blob.sha256, size);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return { allVersions: contentMeasure(all, missingArg), taggedAndReferenced: contentMeasure(tagged, missingArg) };
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/** A group of packages with its content by type; `refsArg` are the group's discovered packages. */
|
|
123
|
+
const group = (refsArg: readonly IPackageRef[], recordsArg: ReadonlyMap<string, IPackageRecord>): IPackageContentGroup => {
|
|
124
|
+
const read = (refs: readonly IPackageRef[]) => refs.flatMap((refArg) => {
|
|
125
|
+
const record = recordsArg.get(packageKey(refArg));
|
|
126
|
+
return record ? [record] : [];
|
|
127
|
+
});
|
|
128
|
+
const missing = (refs: readonly IPackageRef[]) => refs.filter((refArg) => !recordsArg.has(packageKey(refArg))).length;
|
|
129
|
+
const types = [...new Set(refsArg.map((refArg) => refArg.type))].sort(compareText);
|
|
130
|
+
return {
|
|
131
|
+
...selection(read(refsArg), missing(refsArg)),
|
|
132
|
+
types: types.map((typeArg) => {
|
|
133
|
+
const refs = refsArg.filter((refArg) => refArg.type === typeArg);
|
|
134
|
+
return { type: typeArg, ...selection(read(refs), missing(refs)) };
|
|
135
|
+
}),
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The distinct content of an inventory's packages, `totals.packageContent`:
|
|
141
|
+
* a pure function of the discovered packages and the records their units
|
|
142
|
+
* returned. Every SHA-256 counts once per scope, globally and per owner, each
|
|
143
|
+
* by type, over all versions and over the tagged versions with the manifests
|
|
144
|
+
* their indexes reference. A measure is complete only when every discovered
|
|
145
|
+
* package of its scope has a record; otherwise it is partial with the sum of
|
|
146
|
+
* the records read. Records of packages discovery does not list are ignored.
|
|
147
|
+
*/
|
|
148
|
+
export const composeGiteaPackageContent = (
|
|
149
|
+
discoveredArg: readonly IPackageRef[],
|
|
150
|
+
packagesArg: readonly IPackageRecord[],
|
|
151
|
+
): IPackageContentTotals => {
|
|
152
|
+
const discovered = new Set(discoveredArg.map(packageKey));
|
|
153
|
+
const records = new Map(packagesArg.filter((recordArg) => discovered.has(packageKey(recordArg))).map((recordArg) => [packageKey(recordArg), recordArg]));
|
|
154
|
+
const refs = [...new Map(discoveredArg.map((refArg) => [packageKey(refArg), { owner: refArg.owner, type: refArg.type, name: refArg.name }])).values()];
|
|
155
|
+
const owners = [...new Set(refs.map((refArg) => refArg.owner))].sort(compareText);
|
|
156
|
+
return {
|
|
157
|
+
global: group(refs, records),
|
|
158
|
+
owners: owners.map((ownerArg) => ({ owner: ownerArg, ...group(refs.filter((refArg) => refArg.owner === ownerArg), records) })),
|
|
159
|
+
};
|
|
160
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import * as validation from './forgeinventory.validation.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Package metadata documents that are JSON, which `canonicalPackageDocument`
|
|
6
|
+
* brings into one form: an npm version document, Swift release metadata, a
|
|
7
|
+
* crate version's line of the Cargo sparse index, and `{"description":…}`
|
|
8
|
+
* of a crate's latest version as the Cargo search serves it.
|
|
9
|
+
*/
|
|
10
|
+
export type TGiteaCanonicalPackageDocumentKind = 'npm-version' | 'swift-release' | 'cargo-index-entry' | 'cargo-description';
|
|
11
|
+
|
|
12
|
+
export interface IGiteaCanonicalPackageDocument {
|
|
13
|
+
/** The canonical JSON, UTF-8. */
|
|
14
|
+
bytes: Buffer;
|
|
15
|
+
/** Lowercase hex SHA-256 of `bytes`. */
|
|
16
|
+
sha256: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The top-level member each kind removes: state the forge changes without
|
|
21
|
+
* replacing the version, which the source inventory records apart (a Cargo
|
|
22
|
+
* version's `yanked`, an npm version's `deprecated`).
|
|
23
|
+
*/
|
|
24
|
+
const mutableStateMembers: Readonly<Record<TGiteaCanonicalPackageDocumentKind, string | null>> = Object.freeze({
|
|
25
|
+
'npm-version': 'deprecated',
|
|
26
|
+
'swift-release': null,
|
|
27
|
+
'cargo-index-entry': 'yanked',
|
|
28
|
+
'cargo-description': null,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Orders two strings by Unicode code point. UTF-16 code-unit order (the
|
|
33
|
+
* default sort) differs from it where a surrogate pair meets U+E000 to U+FFFF.
|
|
34
|
+
*/
|
|
35
|
+
const compareCodePoints = (leftArg: string, rightArg: string): number => {
|
|
36
|
+
let left = 0;
|
|
37
|
+
let right = 0;
|
|
38
|
+
while (left < leftArg.length && right < rightArg.length) {
|
|
39
|
+
const leftPoint = leftArg.codePointAt(left)!;
|
|
40
|
+
const rightPoint = rightArg.codePointAt(right)!;
|
|
41
|
+
if (leftPoint !== rightPoint) return leftPoint - rightPoint;
|
|
42
|
+
left += leftPoint > 0xffff ? 2 : 1;
|
|
43
|
+
right += rightPoint > 0xffff ? 2 : 1;
|
|
44
|
+
}
|
|
45
|
+
return (leftArg.length - left) - (rightArg.length - right);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** Compact JSON with object keys in code-point order at every depth, arrays in order and only safe integers as numbers. */
|
|
49
|
+
const canonicalJson = (valueArg: unknown): string => {
|
|
50
|
+
if (valueArg === null || typeof valueArg === 'boolean' || typeof valueArg === 'string') return JSON.stringify(valueArg);
|
|
51
|
+
if (typeof valueArg === 'number') {
|
|
52
|
+
if (!Number.isSafeInteger(valueArg)) throw new validation.ForgeInventoryError('document-not-canonical');
|
|
53
|
+
return JSON.stringify(valueArg);
|
|
54
|
+
}
|
|
55
|
+
if (Array.isArray(valueArg)) return `[${valueArg.map(canonicalJson).join(',')}]`;
|
|
56
|
+
const record = valueArg as Record<string, unknown>;
|
|
57
|
+
return `{${Object.keys(record).sort(compareCodePoints).map((keyArg) => `${JSON.stringify(keyArg)}:${canonicalJson(record[keyArg])}`).join(',')}}`;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The canonical form of a package metadata document and its SHA-256, which a
|
|
62
|
+
* consumer records and compares instead of the bytes Gitea served: Gitea 28
|
|
63
|
+
* writes JSON objects held in maps (a crate's `features`, npm's maps) in a
|
|
64
|
+
* different key order on every read, and documents carry state that changes
|
|
65
|
+
* without a new version. In this order: decode as UTF-8 (fatal), parse as a
|
|
66
|
+
* JSON object, remove the kind's top-level mutable-state member (`yanked`
|
|
67
|
+
* for `cargo-index-entry`, `deprecated` for `npm-version`), and write it
|
|
68
|
+
* compact, object keys sorted by code point at every depth, arrays in their
|
|
69
|
+
* order, strings and safe integers as `JSON.stringify` writes them. Anything
|
|
70
|
+
* else, a number that is not a safe integer included, rejects with
|
|
71
|
+
* `document-not-canonical`; an unknown kind with
|
|
72
|
+
* `package-document-kind-invalid`. The same document gives the same bytes
|
|
73
|
+
* whatever order its keys arrived in.
|
|
74
|
+
*/
|
|
75
|
+
export const canonicalPackageDocument = (kindArg: TGiteaCanonicalPackageDocumentKind, bytesArg: Uint8Array): IGiteaCanonicalPackageDocument => {
|
|
76
|
+
if (!Object.hasOwn(mutableStateMembers, kindArg)) throw new validation.ForgeInventoryError('package-document-kind-invalid');
|
|
77
|
+
let canonical: string;
|
|
78
|
+
try {
|
|
79
|
+
const parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytesArg)) as unknown;
|
|
80
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new validation.ForgeInventoryError('document-not-canonical');
|
|
81
|
+
const member = mutableStateMembers[kindArg];
|
|
82
|
+
if (member !== null) delete (parsed as Record<string, unknown>)[member];
|
|
83
|
+
canonical = canonicalJson(parsed);
|
|
84
|
+
} catch {
|
|
85
|
+
// Invalid UTF-8 or JSON, a non-object, an unsafe number, or nesting deeper than the stack.
|
|
86
|
+
throw new validation.ForgeInventoryError('document-not-canonical');
|
|
87
|
+
}
|
|
88
|
+
const bytes = Buffer.from(canonical, 'utf8');
|
|
89
|
+
return { bytes, sha256: plugins.crypto.createHash('sha256').update(bytes).digest('hex') };
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A Swift version as Gitea keys an alternate manifest (`Package@swift-<v>.swift`),
|
|
94
|
+
* trimmed by its `TrimmedVersionString`: major and minor, and the patch only
|
|
95
|
+
* when it is not zero.
|
|
96
|
+
*/
|
|
97
|
+
export const swiftManifestVersionPattern = /^(?:0|[1-9]\d{0,17})\.(?:0|[1-9]\d{0,17})(?:\.[1-9]\d{0,17})?$/;
|
package/ts/index.ts
CHANGED
|
@@ -491,3 +491,6 @@ export * from './classes.giteasourceinventory.js';
|
|
|
491
491
|
export * from './classes.giteasourcetransfer.js';
|
|
492
492
|
export * from './classes.lfsbatchclient.js';
|
|
493
493
|
export { GitScratchBudget, mirrorScratchBytes } from './giteasourceinventory.git.js';
|
|
494
|
+
export { composeGiteaPackageContent } from './giteasourceinventory.packages.js';
|
|
495
|
+
export { canonicalPackageDocument } from './giteasourcetransfer.documents.js';
|
|
496
|
+
export type { IGiteaCanonicalPackageDocument, TGiteaCanonicalPackageDocumentKind } from './giteasourcetransfer.documents.js';
|
package/ts/plugins.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as fossInterfaces from '@foss.global/interfaces';
|
|
2
2
|
|
|
3
3
|
import * as crypto from 'node:crypto';
|
|
4
4
|
import * as fs from 'node:fs/promises';
|
|
@@ -20,7 +20,7 @@ export {
|
|
|
20
20
|
import * as lik from '@push.rocks/lik';
|
|
21
21
|
import * as smarttime from '@push.rocks/smarttime';
|
|
22
22
|
|
|
23
|
-
export
|
|
23
|
+
export { fossInterfaces };
|
|
24
24
|
export type TNpmRegistry = import('@push.rocks/smartnpm').NpmRegistry;
|
|
25
25
|
export type TGitManager = import('@foss.global/gitmanager').GitManager;
|
|
26
26
|
export type TGitManagerCommitSummary = import('@foss.global/gitmanager').IGitManagerCommitSummary;
|