@b12k/porto 0.9.0 → 0.11.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/dist/output.js CHANGED
@@ -36,16 +36,16 @@ async function assertExportPaths(exportPaths, registryPath) {
36
36
  lockPath,
37
37
  lockTarget
38
38
  ].map((filePath)=>normalizePathForComparison(filePath));
39
- const protectedIdentities = new Set(await Promise.all([
40
- fetchFileIdentity(registryTarget),
41
- fetchFileIdentity(lockTarget)
42
- ]));
43
- protectedIdentities.delete(false);
44
- const exportIdentities = await Promise.all(exportPaths.map((filePath)=>fetchFileIdentity(filePath)));
45
- if (exportPaths.some((filePath)=>{
39
+ const [registryIdentity, lockIdentity, ...exportIdentities] = await Promise.all([
40
+ registryTarget,
41
+ lockTarget,
42
+ ...exportPaths
43
+ ].map((filePath)=>fetchFileIdentity(filePath)));
44
+ const hasProtectedPath = exportPaths.some((filePath)=>{
46
45
  const normalizedPath = normalizePathForComparison(filePath);
47
46
  return registryPaths.has(normalizedPath) || lockPaths.some((targetPath)=>normalizedPath === targetPath || normalizedPath.startsWith(`${targetPath}${node_path.sep}`));
48
- }) || exportIdentities.some((identity)=>protectedIdentities.has(identity))) throw new PortoError('exportInvalid', 'The Porto registry and its lock are reserved.');
47
+ });
48
+ if (hasProtectedPath || exportIdentities.some((identity)=>identity && (identity === registryIdentity || identity === lockIdentity))) throw new PortoError('exportInvalid', 'The Porto registry and its lock are reserved.');
49
49
  }
50
50
  async function fetchEnvironmentContents(filePath) {
51
51
  try {
@@ -57,35 +57,35 @@ async function fetchEnvironmentContents(filePath) {
57
57
  }
58
58
  async function fetchExportPaths(settings, commonDirectory) {
59
59
  const jsonPath = settings.jsonFile ? await fetchCanonicalPath(node_path.resolve(settings.jsonFile)) : void 0;
60
- const environmentPath = settings.env ? await fetchCanonicalPath(node_path.resolve(settings.envFile)) : void 0;
61
- const arePathsEqual = void 0 !== jsonPath && void 0 !== environmentPath && normalizePathForComparison(jsonPath) === normalizePathForComparison(environmentPath);
60
+ const envPath = settings.env ? await fetchCanonicalPath(node_path.resolve(settings.envFile)) : void 0;
61
+ const arePathsEqual = void 0 !== jsonPath && void 0 !== envPath && normalizePathForComparison(jsonPath) === normalizePathForComparison(envPath);
62
62
  if (arePathsEqual) throw new PortoError('exportInvalid', '--json-file and --env-file must use different files.');
63
63
  await assertExportPaths([
64
64
  jsonPath,
65
- environmentPath
65
+ envPath
66
66
  ].filter((filePath)=>void 0 !== filePath), getRegistryPath(commonDirectory));
67
67
  return {
68
- environmentPath,
68
+ envPath,
69
69
  jsonPath
70
70
  };
71
71
  }
72
- function formatEnvironmentValue(entry) {
73
- const text = String(entry);
72
+ function formatEnvironmentValue(value) {
73
+ const text = String(value);
74
74
  if (/^[A-Za-z0-9_./:@%+,-]*$/u.test(text)) return text;
75
75
  if (!text.includes("'")) return `'${text}'`;
76
76
  if (!text.includes('"') && !text.includes('\\')) return `"${text}"`;
77
77
  throw new PortoError('mappingInvalid', 'Value cannot be represented safely on a single env line.');
78
78
  }
79
- function formatEnvironment(environment) {
80
- return Object.entries(environment).map(([name, entry])=>`${name}=${formatEnvironmentValue(entry)}`).join('\n');
79
+ function formatEnvironment(vars) {
80
+ return Object.entries(vars).map(([name, value])=>`${name}=${formatEnvironmentValue(value)}`).join('\n');
81
81
  }
82
- function formatReserveOutput(block, environment, isJson) {
83
- if (isJson) return JSON.stringify(environment ?? {
84
- end: block.end,
85
- index: block.index,
86
- start: block.start
82
+ function formatReserveOutput(slot, vars, isJson) {
83
+ if (isJson) return JSON.stringify(vars ?? {
84
+ firstPort: slot.firstPort,
85
+ index: slot.index,
86
+ lastPort: slot.lastPort
87
87
  });
88
- return environment ? formatEnvironment(environment) : String(block.index);
88
+ return vars ? formatEnvironment(vars) : String(slot.index);
89
89
  }
90
90
  function formatTable(headers, rows) {
91
91
  const widths = headers.map((header, index)=>Math.max(header.length, ...rows.map((row)=>row[index]?.length ?? 0)));
@@ -94,10 +94,10 @@ function formatTable(headers, rows) {
94
94
  ...rows
95
95
  ].map((row)=>row.map((cell, index)=>cell.padEnd(widths[index] ?? 0)).join(' ').trimEnd()).join('\n');
96
96
  }
97
- function formatStatsTable(reservations) {
97
+ function formatStatsTable(slots) {
98
98
  const now = Date.now();
99
99
  return formatTable([
100
- 'BLOCK',
100
+ 'SLOT',
101
101
  'PORTS',
102
102
  'WORKTREE',
103
103
  'PATH',
@@ -105,35 +105,35 @@ function formatStatsTable(reservations) {
105
105
  'IDLE (MIN)',
106
106
  'KEEP',
107
107
  'EXPIRED'
108
- ], reservations.map((record)=>[
109
- String(record.index),
110
- `${record.start}-${record.end}`,
111
- node_path.basename(record.worktree) || record.worktree,
112
- record.worktree,
113
- formatDistance(record.lastUsedAt, now, {
108
+ ], slots.map((slot)=>[
109
+ String(slot.index),
110
+ `${slot.firstPort}-${slot.lastPort}`,
111
+ node_path.basename(slot.worktreePath) || slot.worktreePath,
112
+ slot.worktreePath,
113
+ formatDistance(slot.lastUsedAt, now, {
114
114
  addSuffix: true
115
115
  }),
116
- String(record.idleTtlMinutes),
117
- record.keep ? 'yes' : 'no',
118
- record.isExpired ? 'yes' : 'no'
116
+ String(slot.idleTtlMinutes),
117
+ slot.keep ? 'yes' : 'no',
118
+ slot.isExpired ? 'yes' : 'no'
119
119
  ]));
120
120
  }
121
- async function saveEnvironmentFile(filePath, environment) {
121
+ async function saveEnvironmentFile(filePath, vars) {
122
122
  const contents = await fetchEnvironmentContents(filePath);
123
123
  const lineEnding = contents.includes('\r\n') ? '\r\n' : '\n';
124
- const pendingEntries = new Map(Object.entries(environment));
124
+ const pendingVars = new Map(Object.entries(vars));
125
125
  const updated = contents.replaceAll(ENV_ASSIGNMENT_PATTERN, (line, ...captures)=>{
126
126
  const [prefix, name, separator, suffix] = captures;
127
- const entry = Object.hasOwn(environment, name) ? environment[name] : void 0;
127
+ const entry = Object.hasOwn(vars, name) ? vars[name] : void 0;
128
128
  if (void 0 === entry) return line;
129
- pendingEntries.delete(name);
129
+ pendingVars.delete(name);
130
130
  return `${prefix}${name}${separator}${formatEnvironmentValue(entry)}${suffix}`;
131
131
  });
132
- const appended = formatEnvironment(Object.fromEntries(pendingEntries)).replaceAll('\n', lineEnding);
132
+ const appended = formatEnvironment(Object.fromEntries(pendingVars)).replaceAll('\n', lineEnding);
133
133
  const separator = updated.length > 0 && !updated.endsWith('\n') ? lineEnding : '';
134
134
  await writeFileAtomically(filePath, `${updated}${appended ? `${separator}${appended}${lineEnding}` : ''}`);
135
135
  }
136
- async function updateEnvironmentFile(filePath, environment, commonDirectory) {
136
+ async function updateEnvironmentFile(filePath, vars, commonDirectory) {
137
137
  const targetPath = await fetchCanonicalPath(filePath);
138
138
  if (void 0 !== commonDirectory) await assertExportPaths([
139
139
  targetPath
@@ -148,12 +148,18 @@ async function updateEnvironmentFile(filePath, environment, commonDirectory) {
148
148
  }
149
149
  });
150
150
  try {
151
- await saveEnvironmentFile(targetPath, environment);
151
+ await saveEnvironmentFile(targetPath, vars);
152
152
  } finally{
153
153
  await unlock();
154
154
  }
155
155
  }
156
- async function writeReserveJsonFile(filePath, block, environment) {
157
- await writeFileAtomically(filePath, `${formatReserveOutput(block, environment, true)}\n`);
156
+ async function writeReserveJsonFile(filePath, slot, vars) {
157
+ const variables = vars ?? {
158
+ firstPort: slot.firstPort,
159
+ index: slot.index,
160
+ lastPort: slot.lastPort,
161
+ ...slot.vars
162
+ };
163
+ await writeFileAtomically(filePath, `${JSON.stringify(variables)}\n`);
158
164
  }
159
165
  export { fetchExportPaths, formatEnvironment, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile };
package/dist/ports.d.ts CHANGED
@@ -1,16 +1,13 @@
1
- declare function buildBlock(record: {
2
- index: number;
3
- size: number;
4
- start: number;
5
- }): {
6
- end: number;
1
+ declare function buildSlot<Slot extends {
2
+ firstPort: number;
3
+ lastPort: number;
4
+ }>(record: Slot, index: number): Slot & {
7
5
  getPort(offset?: number): number;
8
6
  index: number;
9
- start: number;
10
7
  };
11
- declare function listBusyPorts(start: number, end: number, { host, limit }?: {
8
+ declare function listBusyPorts(start: number, end: number, { host, stopAtFirst }?: {
12
9
  host?: string | undefined;
13
- limit?: number;
10
+ stopAtFirst?: boolean;
14
11
  }): Promise<number[]>;
15
12
  declare function checkHasBusyPort(start: number, end: number, host?: string): Promise<boolean>;
16
- export { buildBlock, checkHasBusyPort, listBusyPorts };
13
+ export { buildSlot, checkHasBusyPort, listBusyPorts };
package/dist/ports.js CHANGED
@@ -1,16 +1,14 @@
1
1
  import { createServer } from "node:net";
2
2
  import { networkInterfaces } from "node:os";
3
3
  import { PortoError } from "./error.js";
4
- function buildBlock(record) {
5
- const start = record.start + record.index * record.size;
4
+ function buildSlot(record, index) {
6
5
  return {
7
- end: start + record.size - 1,
6
+ ...record,
8
7
  getPort (offset = 0) {
9
- if (!Number.isInteger(offset) || offset < 0 || offset >= record.size) throw new PortoError('offsetInvalid', `offset must be an integer between 0 and ${record.size - 1}.`);
10
- return start + offset;
8
+ if (!Number.isInteger(offset) || offset < 0 || record.firstPort + offset > record.lastPort) throw new PortoError('offsetInvalid', `offset must be an integer between 0 and ${record.lastPort - record.firstPort}.`);
9
+ return record.firstPort + offset;
11
10
  },
12
- index: record.index,
13
- start
11
+ index
14
12
  };
15
13
  }
16
14
  function checkIsAddressAvailable(port, host, isAutomatic) {
@@ -27,10 +25,7 @@ function checkIsAddressAvailable(port, host, isAutomatic) {
27
25
  ipv6Only: true,
28
26
  port
29
27
  }, ()=>{
30
- server.close((error)=>{
31
- if (error) reject(error);
32
- else resolve(true);
33
- });
28
+ server.close(()=>resolve(true));
34
29
  });
35
30
  });
36
31
  }
@@ -48,14 +43,14 @@ function getProbeHosts() {
48
43
  ...interfaceHosts
49
44
  ]);
50
45
  }
51
- async function listBusyPorts(start, end, { host, limit = 1 / 0 } = {}) {
46
+ async function listBusyPorts(start, end, { host, stopAtFirst = false } = {}) {
52
47
  const busyPorts = [];
53
48
  const hosts = void 0 === host ? getProbeHosts() : [
54
49
  host
55
50
  ];
56
51
  for(let port = start; port <= end; port += 1)for (const probeHost of hosts)if (!await checkIsAddressAvailable(port, probeHost, void 0 === host)) {
57
52
  busyPorts.push(port);
58
- if (busyPorts.length === limit) return busyPorts;
53
+ if (stopAtFirst) return busyPorts;
59
54
  break;
60
55
  }
61
56
  return busyPorts;
@@ -63,8 +58,8 @@ async function listBusyPorts(start, end, { host, limit = 1 / 0 } = {}) {
63
58
  async function checkHasBusyPort(start, end, host) {
64
59
  const busyPorts = await listBusyPorts(start, end, {
65
60
  host,
66
- limit: 1
61
+ stopAtFirst: true
67
62
  });
68
63
  return busyPorts.length > 0;
69
64
  }
70
- export { buildBlock, checkHasBusyPort, listBusyPorts };
65
+ export { buildSlot, checkHasBusyPort, listBusyPorts };
@@ -1,14 +1,5 @@
1
- import type { SetRequired } from 'type-fest';
2
- import type { ReserveOptions } from './index.js';
3
- type ReservationRecord = SetRequired<Omit<ReserveOptions, 'vars'>, 'idleTtlMinutes' | 'size' | 'start'> & {
4
- index: number;
5
- keep: boolean;
6
- lastUsedAt: string;
7
- ports: Array<number>;
8
- worktree: string;
9
- worktreeId: string;
10
- };
1
+ import type { Registry } from './schemas.js';
11
2
  declare function getRegistryPath(commonDirectory: string): string;
12
- declare function updateRegistry<Result>(commonDirectory: string, handleRecords: (records: Array<ReservationRecord>) => Promise<Result> | Result): Promise<Result>;
3
+ declare function updateRegistry<Result>(commonDirectory: string, handleRegistry: (registry: Registry) => Promise<Result> | Result): Promise<Result>;
13
4
  export { getRegistryPath, updateRegistry };
14
- export type { ReservationRecord };
5
+ export type { Registry, ReservationRecord } from './schemas.js';
package/dist/registry.js CHANGED
@@ -1,27 +1,32 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import node_path from "node:path";
3
3
  import proper_lockfile from "proper-lockfile";
4
+ import { DEFAULT_CONFIG } from "./config.js";
4
5
  import { PortoError } from "./error.js";
5
6
  import { checkIsFileMissing, writeFileAtomically } from "./files.js";
6
7
  import { REGISTRY_SCHEMA } from "./schemas.js";
7
- function getRegistryPath(commonDirectory) {
8
- return node_path.join(commonDirectory, 'porto-registry.json');
9
- }
10
- async function listReservations(filePath) {
8
+ async function fetchRegistry(filePath) {
11
9
  try {
12
10
  return REGISTRY_SCHEMA.parse(JSON.parse(await readFile(filePath, 'utf8')));
13
11
  } catch (error) {
14
- if (checkIsFileMissing(error)) return [];
12
+ if (checkIsFileMissing(error)) return {
13
+ portsPerSlot: DEFAULT_CONFIG.size,
14
+ slots: {},
15
+ startPort: DEFAULT_CONFIG.start
16
+ };
15
17
  throw new PortoError('registryInvalid', filePath, {
16
18
  cause: error
17
19
  });
18
20
  }
19
21
  }
20
- async function writeReservations(filePath, records, previousContents) {
21
- const contents = JSON.stringify(records);
22
+ function getRegistryPath(commonDirectory) {
23
+ return node_path.join(commonDirectory, 'porto-registry.json');
24
+ }
25
+ async function writeRegistry(filePath, registry, previousContents) {
26
+ const contents = JSON.stringify(registry);
22
27
  if (contents !== previousContents) await writeFileAtomically(filePath, `${contents}\n`);
23
28
  }
24
- async function updateRegistry(commonDirectory, handleRecords) {
29
+ async function updateRegistry(commonDirectory, handleRegistry) {
25
30
  const filePath = getRegistryPath(commonDirectory);
26
31
  const unlock = await proper_lockfile.lock(filePath, {
27
32
  realpath: false,
@@ -33,10 +38,10 @@ async function updateRegistry(commonDirectory, handleRecords) {
33
38
  }
34
39
  });
35
40
  try {
36
- const records = await listReservations(filePath);
37
- const previousContents = JSON.stringify(records);
38
- const result = await handleRecords(records);
39
- await writeReservations(filePath, records, previousContents);
41
+ const registry = await fetchRegistry(filePath);
42
+ const previousContents = JSON.stringify(registry);
43
+ const result = await handleRegistry(registry);
44
+ await writeRegistry(filePath, registry, previousContents);
40
45
  return result;
41
46
  } finally{
42
47
  await unlock();
package/dist/reserve.d.ts CHANGED
@@ -1,40 +1,88 @@
1
- import type { ReservationRecord } from './registry.js';
1
+ import type { z } from 'zod';
2
+ import type { PortoConfig } from './config.js';
3
+ import type { Registry, ReservationRecord } from './registry.js';
4
+ import type { OPTIONS_SCHEMA } from './schemas.js';
2
5
  import type { Vars, VarsResult } from './vars.js';
3
6
  import { fetchGitContext } from './git.js';
4
- import { buildBlock } from './ports.js';
5
- import { parseOptions } from './schemas.js';
6
- type ReservedBlock<Entries extends Vars = Vars> = ReturnType<typeof buildBlock> & {
7
- ports: Array<number>;
8
- vars: VarsResult<Entries>;
7
+ import { buildSlot } from './ports.js';
8
+ type ReservedSlot<Entries extends Vars = Vars> = Omit<ReturnType<typeof buildSlot<ReservationRecord>>, 'vars'> & {
9
+ vars: Entries extends readonly [] ? {
10
+ SLOT: number;
11
+ } : VarsResult<Entries>;
9
12
  };
10
- type ReserveOptions = Partial<ReturnType<typeof parseOptions>> & {
13
+ type ReserveOptions = Partial<z.output<typeof OPTIONS_SCHEMA>> & {
11
14
  vars?: undefined | Vars;
12
15
  };
13
- declare function checkIsExpired(record: Pick<ReservationRecord, 'idleTtlMinutes' | 'keep' | 'lastUsedAt'>, now: number): boolean;
14
- declare function issuePorts(record: ReservationRecord, entries: Vars): {
15
- end: number;
16
+ declare function checkIsExpired(record: Pick<ReservationRecord, 'expiresAt'>, now: number): boolean;
17
+ declare function releaseRecord(registry: Registry, index: number, record: ReservationRecord, force?: boolean): Promise<{
18
+ env: boolean;
19
+ envFile: string;
20
+ jsonFile: string | false;
21
+ silent: boolean;
22
+ expiresAt: string | null;
23
+ firstPort: number;
24
+ host?: string | undefined;
25
+ idleTtlMinutes: number;
26
+ keep: boolean;
27
+ lastPort: number;
28
+ lastUsedAt: string;
29
+ ports: number[];
30
+ vars: {
31
+ [k: string]: string | number;
32
+ };
33
+ worktreeId: string;
34
+ worktreePath: string;
35
+ } & {
16
36
  getPort(offset?: number): number;
17
37
  index: number;
18
- start: number;
38
+ }>;
39
+ declare function removeExpiredRecords(registry: Registry, now: number): Promise<({
40
+ env: boolean;
41
+ envFile: string;
42
+ jsonFile: string | false;
43
+ silent: boolean;
44
+ expiresAt: string | null;
45
+ firstPort: number;
46
+ host?: string | undefined;
47
+ idleTtlMinutes: number;
48
+ keep: boolean;
49
+ lastPort: number;
50
+ lastUsedAt: string;
51
+ ports: number[];
52
+ vars: {
53
+ [k: string]: string | number;
54
+ };
55
+ worktreeId: string;
56
+ worktreePath: string;
19
57
  } & {
58
+ getPort(offset?: number): number;
59
+ index: number;
60
+ })[]>;
61
+ declare function commitReservation({ commonDirectory, worktreeId, worktreePath }: Awaited<ReturnType<typeof fetchGitContext>>, { vars, ...options }: Omit<PortoConfig, 'onReleased' | 'onReserved'>): Promise<{
62
+ env: boolean;
63
+ envFile: string;
64
+ jsonFile: string | false;
65
+ silent: boolean;
66
+ expiresAt: string | null;
67
+ firstPort: number;
68
+ host?: string | undefined;
69
+ idleTtlMinutes: number;
70
+ keep: boolean;
71
+ lastPort: number;
72
+ lastUsedAt: string;
20
73
  ports: number[];
21
74
  vars: {
22
75
  [k: string]: string | number;
23
76
  };
24
- };
25
- declare function removeExpiredRecords(records: Array<ReservationRecord>, now: number): Promise<{
26
- end: number;
77
+ worktreeId: string;
78
+ worktreePath: string;
79
+ } & {
27
80
  getPort(offset?: number): number;
28
81
  index: number;
29
- start: number;
30
- }[]>;
31
- declare function commitReservation<Result>({ git, host, idleTtlMinutes, keep, size, start, vars, }: ReturnType<typeof parseOptions> & {
32
- git?: Awaited<ReturnType<typeof fetchGitContext>>;
33
- vars?: undefined | Vars;
34
- }, prepare: (block: ReturnType<typeof issuePorts>) => Result): Promise<Result>;
82
+ }>;
35
83
  declare function reserve<const Entries extends Vars>(options: ReserveOptions & {
36
84
  vars: Entries;
37
- }): Promise<ReservedBlock<Entries>>;
38
- declare function reserve(options?: ReserveOptions): Promise<ReservedBlock>;
39
- export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
85
+ }): Promise<ReservedSlot<Entries>>;
86
+ declare function reserve(options?: ReserveOptions): Promise<ReservedSlot>;
87
+ export { checkIsExpired, commitReservation, releaseRecord, removeExpiredRecords, reserve };
40
88
  export type { ReserveOptions };
package/dist/reserve.js CHANGED
@@ -1,86 +1,119 @@
1
- import { range, remove, union } from "es-toolkit";
1
+ import { range, union } from "es-toolkit";
2
+ import { BusyPortsError } from "./busy-ports-error.js";
3
+ import { applyReserveDefaults } from "./config.js";
2
4
  import { PortoError } from "./error.js";
3
5
  import { fetchGitContext } from "./git.js";
4
- import { buildBlock, checkHasBusyPort } from "./ports.js";
6
+ import { buildSlot, checkHasBusyPort, listBusyPorts } from "./ports.js";
5
7
  import { updateRegistry } from "./registry.js";
6
8
  import { parseOptions } from "./schemas.js";
7
- import { assertVarsFit, mapBlockToVars, parseVarEntries } from "./vars.js";
8
- async function allocateRecord(records, options) {
9
- for(let index = 0; options.start + (index + 1) * options.size - 1 <= 65535; index += 1){
10
- const record = {
11
- ...options,
12
- index
13
- };
14
- const block = buildBlock(record);
15
- const hasOverlap = records.some((reserved)=>{
16
- const reservedBlock = buildBlock(reserved);
17
- return block.start <= reservedBlock.end && block.end >= reservedBlock.start;
18
- });
19
- if (!hasOverlap && !await checkHasBusyPort(block.start, block.end, options.host)) return record;
9
+ import { assertVarsFit, mapSlotToVars, parseVarEntries } from "./vars.js";
10
+ async function allocateRecord(registry, options) {
11
+ const { portsPerSlot, slots, startPort } = registry;
12
+ const slotsCount = Math.floor((65536 - startPort) / portsPerSlot);
13
+ for(let index = 0; index < slotsCount; index += 1){
14
+ const firstPort = startPort + index * portsPerSlot;
15
+ const lastPort = firstPort + portsPerSlot - 1;
16
+ const isOccupied = void 0 !== slots[index];
17
+ if (!isOccupied && !await checkHasBusyPort(firstPort, lastPort, options.host)) {
18
+ const record = {
19
+ ...options,
20
+ firstPort,
21
+ lastPort,
22
+ vars: {}
23
+ };
24
+ slots[index] = record;
25
+ return {
26
+ index,
27
+ record
28
+ };
29
+ }
20
30
  }
21
- throw new PortoError('blockUnavailable');
31
+ throw new PortoError('slotUnavailable');
22
32
  }
23
33
  function checkIsExpired(record, now) {
24
- return !record.keep && now - Date.parse(record.lastUsedAt) > 60000 * record.idleTtlMinutes;
34
+ return null !== record.expiresAt && now > Date.parse(record.expiresAt);
25
35
  }
26
- function issuePorts(record, entries) {
27
- const block = buildBlock(record);
28
- const vars = mapBlockToVars(block, entries);
29
- record.ports = union(record.ports, range(block.start, block.start + entries.length));
30
- return Object.assign(block, {
31
- ports: record.ports,
32
- vars
33
- });
36
+ function issuePorts(record, index, entries) {
37
+ const { firstPort } = record;
38
+ record.vars = 0 === entries.length ? {
39
+ SLOT: index
40
+ } : mapSlotToVars({
41
+ firstPort,
42
+ index
43
+ }, entries);
44
+ record.ports = union(record.ports, range(firstPort, firstPort + entries.length));
45
+ return buildSlot(record, index);
34
46
  }
35
- async function removeExpiredRecords(records, now) {
36
- const candidates = await Promise.all(records.filter((record)=>checkIsExpired(record, now)).map(async (record)=>{
37
- const { end, start } = buildBlock(record);
38
- return {
39
- hasBusyPort: await checkHasBusyPort(start, end, record.host),
40
- record
41
- };
47
+ async function releaseRecord(registry, index, record, force = false) {
48
+ if (!force) {
49
+ const busyPorts = await listBusyPorts(record.firstPort, record.lastPort, {
50
+ host: record.host
51
+ });
52
+ if (busyPorts.length > 0) throw new BusyPortsError(busyPorts.map((port)=>({
53
+ port,
54
+ slot: index
55
+ })));
56
+ }
57
+ delete registry.slots[index];
58
+ return buildSlot(record, index);
59
+ }
60
+ async function removeExpiredRecords(registry, now) {
61
+ const checkedSlots = await Promise.all(Object.entries(registry.slots).flatMap(([key, record])=>{
62
+ const index = Number(key);
63
+ if (!checkIsExpired(record, now)) return [];
64
+ return [
65
+ checkHasBusyPort(record.firstPort, record.lastPort, record.host).then((hasBusyPort)=>hasBusyPort ? void 0 : buildSlot(record, index))
66
+ ];
42
67
  }));
43
- const expiredRecords = candidates.filter(({ hasBusyPort })=>!hasBusyPort).map(({ record })=>record);
44
- remove(records, (record)=>expiredRecords.includes(record));
45
- return expiredRecords.map((record)=>buildBlock(record));
68
+ const expiredSlots = checkedSlots.filter((slot)=>void 0 !== slot);
69
+ for (const { index } of expiredSlots)delete registry.slots[index];
70
+ return expiredSlots;
46
71
  }
47
- async function commitReservation({ git, host, idleTtlMinutes, keep, size, start, vars = [] }, prepare) {
48
- assertVarsFit(vars.length, size);
49
- const { commonDirectory, worktree, worktreeId } = git ?? await fetchGitContext();
50
- return updateRegistry(commonDirectory, async (records)=>{
72
+ function commitReservation({ commonDirectory, worktreeId, worktreePath }, { vars = [], ...options }) {
73
+ return updateRegistry(commonDirectory, async (registry)=>{
74
+ const { env, envFile, host, idleTtlMinutes, jsonFile, keep, silent, size, start } = applyReserveDefaults(options, registry);
75
+ assertVarsFit(vars.length, size);
76
+ if ((registry.startPort !== start || registry.portsPerSlot !== size) && Object.keys(registry.slots).length > 0) throw new PortoError('rangeMismatch');
77
+ registry.startPort = start;
78
+ registry.portsPerSlot = size;
51
79
  const now = Date.now();
52
- const existingRecord = records.find((record)=>record.worktreeId === worktreeId && record.start === start && record.size === size);
80
+ const existingEntry = Object.entries(registry.slots).find(([, record])=>record.worktreeId === worktreeId);
81
+ const existingIndex = void 0 === existingEntry ? -1 : Number(existingEntry[0]);
82
+ const existingRecord = existingEntry?.[1];
53
83
  const lastUsedAt = new Date(now).toISOString();
54
- if (existingRecord) Object.assign(existingRecord, {
55
- host: host ?? existingRecord.host,
56
- idleTtlMinutes,
57
- keep: keep ?? existingRecord.keep,
58
- lastUsedAt,
59
- worktree
60
- });
61
- await removeExpiredRecords(records, now);
62
- const record = existingRecord ?? await allocateRecord(records, {
63
- host,
84
+ const isKept = keep ?? existingRecord?.keep ?? false;
85
+ const settings = {
86
+ env,
87
+ envFile,
88
+ expiresAt: isKept ? null : new Date(now + 60000 * idleTtlMinutes).toISOString(),
89
+ host: host ?? existingRecord?.host,
64
90
  idleTtlMinutes,
65
- keep: keep ?? false,
91
+ jsonFile,
92
+ keep: isKept,
66
93
  lastUsedAt,
94
+ silent,
95
+ worktreePath
96
+ };
97
+ if (existingRecord) Object.assign(existingRecord, settings);
98
+ await removeExpiredRecords(registry, now);
99
+ const { index, record } = existingRecord ? {
100
+ index: existingIndex,
101
+ record: existingRecord
102
+ } : await allocateRecord(registry, {
103
+ ...settings,
67
104
  ports: [],
68
- size,
69
- start,
70
- worktree,
71
105
  worktreeId
72
106
  });
73
- if (!existingRecord) records.push(record);
74
- return prepare(issuePorts(record, vars));
107
+ return issuePorts(record, index, vars);
75
108
  });
76
109
  }
77
110
  async function reserve(options = {}) {
78
- const settings = parseOptions(options);
79
- const vars = void 0 === options.vars ? void 0 : parseVarEntries(options.vars);
80
- const block = await commitReservation({
81
- ...settings,
111
+ const { vars: entries, ...optionsWithoutVars } = options;
112
+ const vars = void 0 === entries ? void 0 : parseVarEntries(entries);
113
+ const git = await fetchGitContext();
114
+ return commitReservation(git, {
115
+ ...parseOptions(optionsWithoutVars),
82
116
  vars
83
- }, (reservedBlock)=>reservedBlock);
84
- return block;
117
+ });
85
118
  }
86
- export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
119
+ export { checkIsExpired, commitReservation, releaseRecord, removeExpiredRecords, reserve };