@b12k/porto 0.9.0 → 0.10.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 {
@@ -79,13 +79,13 @@ function formatEnvironmentValue(entry) {
79
79
  function formatEnvironment(environment) {
80
80
  return Object.entries(environment).map(([name, entry])=>`${name}=${formatEnvironmentValue(entry)}`).join('\n');
81
81
  }
82
- function formatReserveOutput(block, environment, isJson) {
82
+ function formatReserveOutput(slot, environment, isJson) {
83
83
  if (isJson) return JSON.stringify(environment ?? {
84
- end: block.end,
85
- index: block.index,
86
- start: block.start
84
+ firstPort: slot.firstPort,
85
+ index: slot.index,
86
+ lastPort: slot.lastPort
87
87
  });
88
- return environment ? formatEnvironment(environment) : String(block.index);
88
+ return environment ? formatEnvironment(environment) : 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)));
@@ -97,7 +97,7 @@ function formatTable(headers, rows) {
97
97
  function formatStatsTable(reservations) {
98
98
  const now = Date.now();
99
99
  return formatTable([
100
- 'BLOCK',
100
+ 'SLOT',
101
101
  'PORTS',
102
102
  'WORKTREE',
103
103
  'PATH',
@@ -107,9 +107,9 @@ function formatStatsTable(reservations) {
107
107
  'EXPIRED'
108
108
  ], reservations.map((record)=>[
109
109
  String(record.index),
110
- `${record.start}-${record.end}`,
111
- node_path.basename(record.worktree) || record.worktree,
112
- record.worktree,
110
+ `${record.firstPort}-${record.lastPort}`,
111
+ node_path.basename(record.worktreePath) || record.worktreePath,
112
+ record.worktreePath,
113
113
  formatDistance(record.lastUsedAt, now, {
114
114
  addSuffix: true
115
115
  }),
@@ -153,7 +153,13 @@ async function updateEnvironmentFile(filePath, environment, commonDirectory) {
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, environment) {
157
+ const variables = environment ?? {
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
@@ -4,24 +4,29 @@ import proper_lockfile from "proper-lockfile";
4
4
  import { PortoError } from "./error.js";
5
5
  import { checkIsFileMissing, writeFileAtomically } from "./files.js";
6
6
  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) {
7
+ async function fetchRegistry(filePath) {
11
8
  try {
12
9
  return REGISTRY_SCHEMA.parse(JSON.parse(await readFile(filePath, 'utf8')));
13
10
  } catch (error) {
14
- if (checkIsFileMissing(error)) return [];
11
+ if (checkIsFileMissing(error)) return {
12
+ portsPerSlot: 10,
13
+ slots: [],
14
+ startPort: 10000
15
+ };
15
16
  throw new PortoError('registryInvalid', filePath, {
16
17
  cause: error
17
18
  });
18
19
  }
19
20
  }
20
- async function writeReservations(filePath, records, previousContents) {
21
- const contents = JSON.stringify(records);
21
+ function getRegistryPath(commonDirectory) {
22
+ return node_path.join(commonDirectory, 'porto-registry.json');
23
+ }
24
+ async function writeRegistry(filePath, registry, previousContents) {
25
+ while(null === registry.slots.at(-1))registry.slots.pop();
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,89 @@
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: VarsResult<Entries> & {
10
+ PORTO_SLOT: number;
11
+ };
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 issuePorts(record: ReservationRecord, index: number, entries: Vars): {
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
+ PORTO_SLOT: 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 releaseRecord(registry: Registry, index: number, record: ReservationRecord): 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
+ PORTO_SLOT: number;
54
+ };
55
+ worktreeId: string;
56
+ worktreePath: string;
19
57
  } & {
58
+ getPort(offset?: number): number;
59
+ index: number;
60
+ }>;
61
+ declare function removeExpiredRecords(registry: Registry, now: number): 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
- [k: string]: string | number;
75
+ PORTO_SLOT: 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
+ })[]>;
83
+ declare function commitReservation<Result>({ commonDirectory, worktreeId, worktreePath }: Awaited<ReturnType<typeof fetchGitContext>>, { vars, ...options }: Omit<PortoConfig, 'onReleased' | 'onReserved'>, prepare: (slot: ReturnType<typeof issuePorts>) => Promise<Result> | Result): Promise<Result>;
35
84
  declare function reserve<const Entries extends Vars>(options: ReserveOptions & {
36
85
  vars: Entries;
37
- }): Promise<ReservedBlock<Entries>>;
38
- declare function reserve(options?: ReserveOptions): Promise<ReservedBlock>;
39
- export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
86
+ }): Promise<ReservedSlot<Entries>>;
87
+ declare function reserve(options?: ReserveOptions): Promise<ReservedSlot>;
88
+ export { checkIsExpired, commitReservation, releaseRecord, removeExpiredRecords, reserve };
40
89
  export type { ReserveOptions };
package/dist/reserve.js CHANGED
@@ -1,86 +1,117 @@
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
+ if (!slots[index] && !await checkHasBusyPort(firstPort, lastPort, options.host)) {
17
+ const record = {
18
+ ...options,
19
+ firstPort,
20
+ lastPort,
21
+ vars: {
22
+ PORTO_SLOT: index
23
+ }
24
+ };
25
+ slots[index] = record;
26
+ return {
27
+ index,
28
+ record
29
+ };
30
+ }
20
31
  }
21
- throw new PortoError('blockUnavailable');
32
+ throw new PortoError('slotUnavailable');
22
33
  }
23
34
  function checkIsExpired(record, now) {
24
- return !record.keep && now - Date.parse(record.lastUsedAt) > 60000 * record.idleTtlMinutes;
35
+ return null !== record.expiresAt && now > Date.parse(record.expiresAt);
25
36
  }
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
37
+ function issuePorts(record, index, entries) {
38
+ const { firstPort } = record;
39
+ record.vars = {
40
+ ...mapSlotToVars({
41
+ firstPort,
42
+ index
43
+ }, entries),
44
+ PORTO_SLOT: index
45
+ };
46
+ record.ports = union(record.ports, range(firstPort, firstPort + entries.length));
47
+ return buildSlot(record, index);
48
+ }
49
+ async function releaseRecord(registry, index, record) {
50
+ const busyPorts = await listBusyPorts(record.firstPort, record.lastPort, {
51
+ host: record.host
33
52
  });
53
+ if (busyPorts.length > 0) throw new BusyPortsError(busyPorts.map((port)=>({
54
+ port,
55
+ slot: index
56
+ })));
57
+ registry.slots[index] = null;
58
+ return buildSlot(record, index);
34
59
  }
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
- };
60
+ async function removeExpiredRecords(registry, now) {
61
+ const checkedSlots = await Promise.all(registry.slots.flatMap((record, index)=>{
62
+ if (null === record || !checkIsExpired(record, now)) return [];
63
+ return [
64
+ checkHasBusyPort(record.firstPort, record.lastPort, record.host).then((hasBusyPort)=>hasBusyPort ? void 0 : buildSlot(record, index))
65
+ ];
42
66
  }));
43
- const expiredRecords = candidates.filter(({ hasBusyPort })=>!hasBusyPort).map(({ record })=>record);
44
- remove(records, (record)=>expiredRecords.includes(record));
45
- return expiredRecords.map((record)=>buildBlock(record));
67
+ const expiredSlots = checkedSlots.filter((slot)=>void 0 !== slot);
68
+ for (const { index } of expiredSlots)registry.slots[index] = null;
69
+ return expiredSlots;
46
70
  }
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)=>{
71
+ function commitReservation({ commonDirectory, worktreeId, worktreePath }, { vars = [], ...options }, prepare) {
72
+ return updateRegistry(commonDirectory, async (registry)=>{
73
+ const { env, envFile, host, idleTtlMinutes, jsonFile, keep, silent, size, start } = applyReserveDefaults(options, registry);
74
+ assertVarsFit(vars.length, size);
75
+ if ((registry.startPort !== start || registry.portsPerSlot !== size) && registry.slots.some((record)=>null !== record)) throw new PortoError('rangeMismatch');
76
+ registry.startPort = start;
77
+ registry.portsPerSlot = size;
51
78
  const now = Date.now();
52
- const existingRecord = records.find((record)=>record.worktreeId === worktreeId && record.start === start && record.size === size);
79
+ const existingIndex = registry.slots.findIndex((record)=>record?.worktreeId === worktreeId);
80
+ const existingRecord = registry.slots[existingIndex];
53
81
  const lastUsedAt = new Date(now).toISOString();
54
- if (existingRecord) Object.assign(existingRecord, {
55
- host: host ?? existingRecord.host,
82
+ const isKept = keep ?? existingRecord?.keep ?? false;
83
+ const settings = {
84
+ env,
85
+ envFile,
86
+ expiresAt: isKept ? null : new Date(now + 60000 * idleTtlMinutes).toISOString(),
87
+ host: host ?? existingRecord?.host,
56
88
  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,
64
- idleTtlMinutes,
65
- keep: keep ?? false,
89
+ jsonFile,
90
+ keep: isKept,
66
91
  lastUsedAt,
92
+ silent,
93
+ worktreePath
94
+ };
95
+ if (existingRecord) Object.assign(existingRecord, settings);
96
+ await removeExpiredRecords(registry, now);
97
+ const { index, record } = existingRecord ? {
98
+ index: existingIndex,
99
+ record: existingRecord
100
+ } : await allocateRecord(registry, {
101
+ ...settings,
67
102
  ports: [],
68
- size,
69
- start,
70
- worktree,
71
103
  worktreeId
72
104
  });
73
- if (!existingRecord) records.push(record);
74
- return prepare(issuePorts(record, vars));
105
+ return prepare(issuePorts(record, index, vars));
75
106
  });
76
107
  }
77
108
  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,
109
+ const { vars: entries, ...optionsWithoutVars } = options;
110
+ const vars = void 0 === entries ? void 0 : parseVarEntries(entries);
111
+ const git = await fetchGitContext();
112
+ return commitReservation(git, {
113
+ ...parseOptions(optionsWithoutVars),
82
114
  vars
83
- }, (reservedBlock)=>reservedBlock);
84
- return block;
115
+ }, (slot)=>slot);
85
116
  }
86
- export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
117
+ export { checkIsExpired, commitReservation, releaseRecord, removeExpiredRecords, reserve };
package/dist/schemas.d.ts CHANGED
@@ -1,8 +1,14 @@
1
1
  import { z } from 'zod';
2
- import type { PortBlock } from './index.js';
2
+ import type { PortSlot } from './index.js';
3
3
  declare const HOOKS_SCHEMA: z.ZodObject<{
4
- onReleased: z.ZodCustom<(block: PortBlock, ports: Array<number>) => Promise<void> | void, (block: PortBlock, ports: Array<number>) => Promise<void> | void>;
5
- onReserved: z.ZodCustom<(block: PortBlock, ports: Array<number>) => Promise<void> | void, (block: PortBlock, ports: Array<number>) => Promise<void> | void>;
4
+ onReleased: z.ZodCustom<(slot: PortSlot, ports: Array<number>) => Promise<void> | void, (slot: PortSlot, ports: Array<number>) => Promise<void> | void>;
5
+ onReserved: z.ZodCustom<(slot: PortSlot, ports: Array<number>) => Promise<void> | void, (slot: PortSlot, ports: Array<number>) => Promise<void> | void>;
6
+ }, z.core.$strip>;
7
+ declare const OUTPUT_OPTIONS_SCHEMA: z.ZodObject<{
8
+ env: z.ZodBoolean;
9
+ envFile: z.ZodString;
10
+ jsonFile: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>;
11
+ silent: z.ZodBoolean;
6
12
  }, z.core.$strip>;
7
13
  declare const OPTIONS_SCHEMA: z.ZodObject<{
8
14
  host: z.ZodOptional<z.ZodString>;
@@ -11,23 +17,64 @@ declare const OPTIONS_SCHEMA: z.ZodObject<{
11
17
  size: z.ZodInt;
12
18
  start: z.ZodInt;
13
19
  }, z.core.$strip>;
14
- declare const REGISTRY_SCHEMA: z.ZodArray<z.ZodObject<{
20
+ declare const RECORD_SCHEMA: z.ZodObject<{
21
+ env: z.ZodBoolean;
22
+ envFile: z.ZodString;
23
+ jsonFile: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>;
24
+ silent: z.ZodBoolean;
25
+ expiresAt: z.ZodNullable<z.ZodISODateTime>;
26
+ firstPort: z.ZodInt;
15
27
  host: z.ZodOptional<z.ZodString>;
16
28
  idleTtlMinutes: z.ZodNumber;
17
- size: z.ZodInt;
18
- start: z.ZodInt;
19
- index: z.ZodInt;
20
29
  keep: z.ZodBoolean;
30
+ lastPort: z.ZodInt;
21
31
  lastUsedAt: z.ZodISODateTime;
22
32
  ports: z.ZodArray<z.ZodInt>;
23
- worktree: z.ZodString;
33
+ vars: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
34
+ [k: string]: string | number;
35
+ }, [string, string | number][]>>, z.ZodTransform<{
36
+ PORTO_SLOT: number;
37
+ }, {
38
+ [k: string]: string | number;
39
+ }>>;
24
40
  worktreeId: z.ZodString;
25
- }, z.core.$strip>>;
41
+ worktreePath: z.ZodString;
42
+ }, z.core.$strip>;
43
+ type ReservationRecord = z.output<typeof RECORD_SCHEMA>;
44
+ declare const REGISTRY_SCHEMA: z.ZodObject<{
45
+ portsPerSlot: z.ZodInt;
46
+ slots: z.ZodArray<z.ZodNullable<z.ZodObject<{
47
+ env: z.ZodBoolean;
48
+ envFile: z.ZodString;
49
+ jsonFile: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>;
50
+ silent: z.ZodBoolean;
51
+ expiresAt: z.ZodNullable<z.ZodISODateTime>;
52
+ firstPort: z.ZodInt;
53
+ host: z.ZodOptional<z.ZodString>;
54
+ idleTtlMinutes: z.ZodNumber;
55
+ keep: z.ZodBoolean;
56
+ lastPort: z.ZodInt;
57
+ lastUsedAt: z.ZodISODateTime;
58
+ ports: z.ZodArray<z.ZodInt>;
59
+ vars: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
60
+ [k: string]: string | number;
61
+ }, [string, string | number][]>>, z.ZodTransform<{
62
+ PORTO_SLOT: number;
63
+ }, {
64
+ [k: string]: string | number;
65
+ }>>;
66
+ worktreeId: z.ZodString;
67
+ worktreePath: z.ZodString;
68
+ }, z.core.$strip>>>;
69
+ startPort: z.ZodInt;
70
+ }, z.core.$strip>;
71
+ type Registry = z.output<typeof REGISTRY_SCHEMA>;
26
72
  declare function parseOptions(options: unknown): {
27
73
  host?: string | undefined;
28
- idleTtlMinutes: number;
74
+ idleTtlMinutes?: number | undefined;
29
75
  keep?: boolean | undefined;
30
- size: number;
31
- start: number;
76
+ size?: number | undefined;
77
+ start?: number | undefined;
32
78
  };
33
- export { HOOKS_SCHEMA, OPTIONS_SCHEMA, parseOptions, REGISTRY_SCHEMA };
79
+ export { HOOKS_SCHEMA, OPTIONS_SCHEMA, OUTPUT_OPTIONS_SCHEMA, parseOptions, REGISTRY_SCHEMA };
80
+ export type { Registry, ReservationRecord };