@git-stunts/git-cas 6.3.0 → 6.4.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.
@@ -0,0 +1,151 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import CollectionNamespace from './CollectionNamespace.js';
4
+
5
+ export const WORKSPACE_REF_PREFIX = 'refs/cas/workspaces/';
6
+ const WORKSPACE_ID = /^v1-([a-z0-9]+)-([a-f0-9]{32})$/;
7
+ const NONCE_BYTES = 16;
8
+
9
+ /** Immutable ref identifying one scoped staging workspace. */
10
+ export default class WorkspaceRef {
11
+ #createdAt;
12
+ #id;
13
+ #namespace;
14
+ #value;
15
+
16
+ constructor(value) {
17
+ const parsed = WorkspaceRef.#parse(value);
18
+ this.#namespace = parsed.namespace;
19
+ this.#id = parsed.id;
20
+ this.#createdAt = parsed.createdAt;
21
+ this.#value = parsed.value;
22
+ Object.freeze(this);
23
+ }
24
+
25
+ static from(value) {
26
+ return value instanceof WorkspaceRef ? value : new WorkspaceRef(value);
27
+ }
28
+
29
+ static create({ namespace: value, createdAt, nonce }) {
30
+ const namespace = CollectionNamespace.from(value).toString();
31
+ const created = WorkspaceRef.#canonicalTimestamp(createdAt);
32
+ if (!(nonce instanceof Uint8Array) || nonce.length !== NONCE_BYTES) {
33
+ throw WorkspaceRef.#invalid('Workspace nonce must contain exactly 16 bytes', {
34
+ nonceLength: nonce?.length,
35
+ });
36
+ }
37
+ const epoch = String(created.getTime().toString(36));
38
+ const nonceHex = [...nonce]
39
+ .map((byte) => byte.toString(16).padStart(2, '0'))
40
+ .join('');
41
+ const id = `v1-${epoch}-${nonceHex}`;
42
+ return new WorkspaceRef(
43
+ `${WORKSPACE_REF_PREFIX}${WorkspaceRef.#encodeNamespace(namespace)}/${id}`,
44
+ );
45
+ }
46
+
47
+ static prefixForNamespace(value) {
48
+ const namespace = CollectionNamespace.from(value).toString();
49
+ return `${WORKSPACE_REF_PREFIX}${WorkspaceRef.#encodeNamespace(namespace)}/`;
50
+ }
51
+
52
+ get namespace() {
53
+ return this.#namespace;
54
+ }
55
+
56
+ get id() {
57
+ return this.#id;
58
+ }
59
+
60
+ get createdAt() {
61
+ return this.#createdAt;
62
+ }
63
+
64
+ toString() {
65
+ return this.#value;
66
+ }
67
+
68
+ static #parse(value) {
69
+ const [encodedNamespace, id] = WorkspaceRef.#split(value);
70
+ const namespace = WorkspaceRef.#decodeNamespace(encodedNamespace, value);
71
+ const createdAt = WorkspaceRef.#createdAtFromId(id, value);
72
+ return { namespace, id, createdAt, value };
73
+ }
74
+
75
+ static #split(value) {
76
+ if (typeof value !== 'string' || !value.startsWith(WORKSPACE_REF_PREFIX)) {
77
+ throw WorkspaceRef.#invalid(`Workspace ref must be below ${WORKSPACE_REF_PREFIX}`, {
78
+ ref: value,
79
+ });
80
+ }
81
+ const fields = value.slice(WORKSPACE_REF_PREFIX.length).split('/');
82
+ if (fields.length !== 2 || fields.some((field) => field.length === 0)) {
83
+ throw WorkspaceRef.#invalid('Workspace ref must contain one encoded namespace and ID', {
84
+ ref: value,
85
+ });
86
+ }
87
+ return fields;
88
+ }
89
+
90
+ static #decodeNamespace(encodedNamespace, value) {
91
+ if (encodedNamespace.includes('++')) {
92
+ throw WorkspaceRef.#invalid('Workspace ref contains a malformed encoded namespace', {
93
+ ref: value,
94
+ });
95
+ }
96
+ let namespace;
97
+ try {
98
+ namespace = CollectionNamespace.from(encodedNamespace.replaceAll('+', '/')).toString();
99
+ } catch (error) {
100
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid encoded namespace', {
101
+ ref: value,
102
+ originalError: error,
103
+ });
104
+ }
105
+ if (WorkspaceRef.#encodeNamespace(namespace) !== encodedNamespace) {
106
+ throw WorkspaceRef.#invalid('Workspace ref namespace is not canonical', { ref: value });
107
+ }
108
+ return namespace;
109
+ }
110
+
111
+ static #createdAtFromId(id, value) {
112
+ const idMatch = WORKSPACE_ID.exec(id);
113
+ if (!idMatch) {
114
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid workspace ID', { ref: value });
115
+ }
116
+ const epoch = Number.parseInt(idMatch[1], 36);
117
+ if (!Number.isSafeInteger(epoch) || epoch < 0 || epoch.toString(36) !== idMatch[1]) {
118
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid creation epoch', { ref: value });
119
+ }
120
+ const createdAt = new Date(epoch);
121
+ if (Number.isNaN(createdAt.getTime())) {
122
+ throw WorkspaceRef.#invalid('Workspace ref creation epoch is outside the Date range', {
123
+ ref: value,
124
+ });
125
+ }
126
+ return createdAt.toISOString();
127
+ }
128
+
129
+ static #canonicalTimestamp(value) {
130
+ if (typeof value !== 'string') {
131
+ throw WorkspaceRef.#invalid('Workspace creation time must be a canonical timestamp', {
132
+ createdAt: value,
133
+ });
134
+ }
135
+ const date = new Date(value);
136
+ if (Number.isNaN(date.getTime()) || date.toISOString() !== value) {
137
+ throw WorkspaceRef.#invalid('Workspace creation time must be a canonical timestamp', {
138
+ createdAt: value,
139
+ });
140
+ }
141
+ return date;
142
+ }
143
+
144
+ static #encodeNamespace(namespace) {
145
+ return namespace.replaceAll('/', '+');
146
+ }
147
+
148
+ static #invalid(message, meta) {
149
+ return createCasError(message, ErrorCodes.WORKSPACE_REF_INVALID, meta);
150
+ }
151
+ }
@@ -15,6 +15,7 @@ import Oid from '../../domain/value-objects/Oid.js';
15
15
  const DEFAULT_POLICY = Policy.timeout(30_000);
16
16
  const FORBIDDEN_REF_CHARACTERS = new Set(['~', '^', ':', '?', '*', '[', '\\']);
17
17
  const MAX_REF_ITERATION_LIMIT = 1001;
18
+ const REF_NAME_ENCODER = new globalThis.TextEncoder();
18
19
 
19
20
  /**
20
21
  * {@link GitRefPort} implementation backed by `@git-stunts/plumbing`.
@@ -216,8 +217,9 @@ export default class GitRefAdapter extends GitRefPort {
216
217
  }
217
218
 
218
219
  /** @override */
219
- async *iterateRefs({ prefix = 'refs/', limit } = {}) {
220
+ async *iterateRefs({ prefix = 'refs/', after = null, limit } = {}) {
220
221
  assertRefPrefix(prefix);
222
+ assertRefCursor(prefix, after);
221
223
  assertRefIterationLimit(limit);
222
224
  if (typeof this.plumbing?.executeStream !== 'function') {
223
225
  throw new CasError(
@@ -226,19 +228,9 @@ export default class GitRefAdapter extends GitRefPort {
226
228
  { prefix },
227
229
  );
228
230
  }
229
- const stream = await this.policy.execute(() =>
230
- this.plumbing.executeStream({
231
- args: [
232
- 'for-each-ref',
233
- '--format=%(refname)%09%(objectname)%09%(symref)',
234
- `--count=${limit}`,
235
- prefix,
236
- ],
237
- }),
238
- );
239
- for await (const line of consumeRefLines(stream)) {
240
- yield parseIteratedRef(prefix, line);
241
- }
231
+ const args = refInventoryArgs({ prefix, after, limit });
232
+ const stream = await this.policy.execute(() => this.plumbing.executeStream({ args }));
233
+ yield* paginatedRefRecords({ stream, prefix, after, limit });
242
234
  }
243
235
 
244
236
  async #inspectDirectRef(ref) {
@@ -296,6 +288,16 @@ function assertRefName(ref) {
296
288
  assertRefSyntax(ref, { allowTrailingSlash: false });
297
289
  }
298
290
 
291
+ function assertRefCursor(prefix, after) {
292
+ if (after === null) {
293
+ return;
294
+ }
295
+ assertRefName(after);
296
+ if (!after.startsWith(prefix)) {
297
+ throw invalidRefName(after);
298
+ }
299
+ }
300
+
299
301
  function assertRefIterationLimit(limit) {
300
302
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_REF_ITERATION_LIMIT) {
301
303
  throw new CasError(
@@ -330,6 +332,46 @@ function isInvalidRefSegment(part) {
330
332
  return part.length === 0 || part.startsWith('.') || part.endsWith('.lock');
331
333
  }
332
334
 
335
+ function compareRefNames(left, right) {
336
+ const leftBytes = REF_NAME_ENCODER.encode(left);
337
+ const rightBytes = REF_NAME_ENCODER.encode(right);
338
+ const sharedLength = Math.min(leftBytes.length, rightBytes.length);
339
+ for (let index = 0; index < sharedLength; index += 1) {
340
+ if (leftBytes[index] !== rightBytes[index]) {
341
+ return leftBytes[index] - rightBytes[index];
342
+ }
343
+ }
344
+ return leftBytes.length - rightBytes.length;
345
+ }
346
+
347
+ function refInventoryArgs({ prefix, after, limit }) {
348
+ const args = [
349
+ 'for-each-ref',
350
+ '--format=%(refname)%09%(objectname)%09%(symref)',
351
+ '--sort=refname',
352
+ ];
353
+ if (after === null) {
354
+ args.push(`--count=${limit}`);
355
+ }
356
+ args.push(prefix);
357
+ return args;
358
+ }
359
+
360
+ async function* paginatedRefRecords({ stream, prefix, after, limit }) {
361
+ let returned = 0;
362
+ for await (const line of consumeRefLines(stream)) {
363
+ const record = parseIteratedRef(prefix, line);
364
+ if (after !== null && compareRefNames(record.ref, after) <= 0) {
365
+ continue;
366
+ }
367
+ yield record;
368
+ returned += 1;
369
+ if (after !== null && returned >= limit) {
370
+ return;
371
+ }
372
+ }
373
+ }
374
+
333
375
  function hasForbiddenRefCharacter(value) {
334
376
  return typeof value === 'string' && [...value].some((character) => {
335
377
  const code = character.codePointAt(0);
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.3.0';
1
+ export const PACKAGE_VERSION = '6.4.0';
@@ -86,6 +86,7 @@ export default class GitRefPort {
86
86
  * Streams refs below a canonical Git ref prefix.
87
87
  * @param {Object} _options
88
88
  * @param {string} [_options.prefix]
89
+ * @param {string|null} [_options.after] Exclusive ref-name continuation cursor.
89
90
  * @param {number} _options.limit Maximum records to request from Git.
90
91
  * @returns {AsyncIterable<{ref: string, oid: string, symref: string|null}>}
91
92
  */