@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/config.js CHANGED
@@ -1,15 +1,13 @@
1
- import { access, realpath } from "node:fs/promises";
1
+ import { cosmiconfig } from "cosmiconfig";
2
+ import { realpath } from "node:fs/promises";
2
3
  import node_path from "node:path";
3
4
  import { z } from "zod";
4
5
  import package_0 from "../package.json" with {
5
6
  type: "json"
6
7
  };
7
8
  import { PortoError } from "./error.js";
8
- import { checkIsFileMissing } from "./files.js";
9
- import { loadConfigFile } from "./load-config.js";
10
- import { HOOKS_SCHEMA, OPTIONS_SCHEMA, parseOptions } from "./schemas.js";
9
+ import { HOOKS_SCHEMA, OPTIONS_SCHEMA, OUTPUT_OPTIONS_SCHEMA } from "./schemas.js";
11
10
  import { VARS_SCHEMA } from "./vars.js";
12
- const DEFAULT_ENV_FILE = '.env';
13
11
  const CONFIG_FILES = [
14
12
  'porto.config.ts',
15
13
  'porto.config.js'
@@ -17,38 +15,42 @@ const CONFIG_FILES = [
17
15
  const CONFIG_SCHEMA = z.strictObject({
18
16
  ...OPTIONS_SCHEMA.shape,
19
17
  ...HOOKS_SCHEMA.shape,
20
- env: z.boolean(),
21
- envFile: z.string().min(1),
22
- jsonFile: z.union([
23
- z.literal(false),
24
- z.string().min(1)
25
- ]),
26
- silent: z.boolean(),
18
+ ...OUTPUT_OPTIONS_SCHEMA.shape,
27
19
  vars: VARS_SCHEMA
28
20
  }).partial();
29
21
  const libraryName = 'porto';
30
22
  const { name: config_name, version } = package_0;
31
- function defineConfig(config) {
32
- return config;
23
+ const DEFAULT_CONFIG = {
24
+ env: false,
25
+ envFile: '.env',
26
+ idleTtlMinutes: 60,
27
+ jsonFile: false,
28
+ silent: false,
29
+ size: 10,
30
+ start: 10000
31
+ };
32
+ function resolveOutputSettings(settings) {
33
+ return {
34
+ env: settings.env ?? DEFAULT_CONFIG.env,
35
+ envFile: settings.envFile ?? DEFAULT_CONFIG.envFile,
36
+ jsonFile: settings.jsonFile ?? DEFAULT_CONFIG.jsonFile
37
+ };
33
38
  }
34
- async function fetchConfigPath(candidates) {
35
- let configPath;
36
- for (const filePath of candidates)try {
37
- await access(filePath);
38
- configPath = filePath;
39
- break;
40
- } catch (error) {
41
- if (!checkIsFileMissing(error)) throw error;
42
- }
43
- return configPath;
39
+ function applyReserveDefaults(settings, storedRange) {
40
+ const size = settings.size ?? storedRange.portsPerSlot;
41
+ const start = settings.start ?? storedRange.startPort;
42
+ if (start + size - 1 > 65535) throw new PortoError('optionsInvalid', 'size: size must fit in the TCP port range.');
43
+ return {
44
+ ...settings,
45
+ ...resolveOutputSettings(settings),
46
+ idleTtlMinutes: settings.idleTtlMinutes ?? DEFAULT_CONFIG.idleTtlMinutes,
47
+ silent: settings.silent ?? DEFAULT_CONFIG.silent,
48
+ size,
49
+ start
50
+ };
44
51
  }
45
- function getConfigPaths(directoryPath, worktreePath) {
46
- const filePaths = [];
47
- for(let currentPath = directoryPath;; currentPath = node_path.dirname(currentPath)){
48
- filePaths.push(...CONFIG_FILES.map((fileName)=>node_path.join(currentPath, fileName)));
49
- if (currentPath === worktreePath) return filePaths;
50
- if (node_path.dirname(currentPath) === currentPath) throw new PortoError('configInvalid', 'Cannot find the checkout root.');
51
- }
52
+ function defineConfig(config) {
53
+ return config;
52
54
  }
53
55
  function parseConfig(config) {
54
56
  const result = CONFIG_SCHEMA.safeParse(config);
@@ -59,45 +61,32 @@ function parseConfig(config) {
59
61
  });
60
62
  }
61
63
  const settings = result.data;
62
- return {
63
- ...settings,
64
- ...void 0 !== settings.envFile && void 0 === settings.env ? {
65
- env: true
66
- } : {}
67
- };
64
+ if (void 0 !== settings.envFile) settings.env ??= true;
65
+ return settings;
68
66
  }
69
- function applyReserveDefaults(settings) {
70
- return {
71
- ...settings,
72
- ...parseOptions(settings),
73
- env: settings.env ?? false,
74
- envFile: settings.envFile ?? DEFAULT_ENV_FILE,
75
- jsonFile: settings.jsonFile ?? false,
76
- silent: settings.silent ?? false
77
- };
78
- }
79
- function resolveConfigPaths(config, filePath) {
80
- const directoryPath = node_path.dirname(filePath);
81
- for (const key of [
82
- 'envFile',
83
- 'jsonFile'
84
- ]){
85
- const configuredPath = config[key];
86
- if ('string' == typeof configuredPath) config[key] = node_path.resolve(directoryPath, configuredPath);
87
- }
88
- return config;
89
- }
90
- async function fetchConfig(worktree) {
91
- const candidates = getConfigPaths(await realpath(process.cwd()), worktree);
92
- const filePath = await fetchConfigPath(candidates);
93
- if (!filePath) return parseConfig({});
67
+ async function fetchConfig(worktreePath) {
68
+ let result;
94
69
  try {
95
- const config = await loadConfigFile(filePath);
96
- return resolveConfigPaths(parseConfig(config), filePath);
70
+ result = await cosmiconfig(libraryName, {
71
+ searchPlaces: CONFIG_FILES,
72
+ stopDir: worktreePath
73
+ }).search(await realpath(process.cwd()));
97
74
  } catch (error) {
98
- throw new PortoError('configInvalid', `${filePath}: ${error instanceof Error ? error.message : String(error)}`, {
75
+ throw new PortoError('configInvalid', error instanceof Error ? error.message : String(error), {
99
76
  cause: error
100
77
  });
101
78
  }
79
+ if (!result) return {};
80
+ const config = result.config;
81
+ const settings = parseConfig(config && 'object' == typeof config && 1 === Object.keys(config).length && 'default' in config ? config.default : config);
82
+ const directoryPath = node_path.dirname(result.filepath);
83
+ for (const key of [
84
+ 'envFile',
85
+ 'jsonFile'
86
+ ]){
87
+ const configuredPath = settings[key];
88
+ if ('string' == typeof configuredPath) settings[key] = node_path.resolve(directoryPath, configuredPath);
89
+ }
90
+ return settings;
102
91
  }
103
- export { DEFAULT_ENV_FILE, applyReserveDefaults, config_name as name, defineConfig, fetchConfig, libraryName, parseConfig, version };
92
+ export { DEFAULT_CONFIG, applyReserveDefaults, config_name as name, defineConfig, fetchConfig, libraryName, parseConfig, resolveOutputSettings, version };
package/dist/errors.d.ts CHANGED
@@ -1,8 +1,4 @@
1
1
  export declare const ERRORS_BY_KEY: {
2
- readonly blockUnavailable: {
3
- readonly instruction: 'Release unused blocks or choose another range.';
4
- readonly message: 'No free port block remains in the TCP port range.';
5
- };
6
2
  readonly configInvalid: {
7
3
  readonly instruction: 'Check porto.config.ts or porto.config.js.';
8
4
  readonly message: 'Invalid Porto configuration.';
@@ -16,11 +12,11 @@ export declare const ERRORS_BY_KEY: {
16
12
  readonly message: 'Lifecycle hook failed.';
17
13
  };
18
14
  readonly mappingInvalid: {
19
- readonly instruction: 'Use unique variable names, valid callbacks, and a block large enough for all entries.';
15
+ readonly instruction: 'Use unique variable names, valid callbacks, and a slot large enough for all entries.';
20
16
  readonly message: 'Invalid variables.';
21
17
  };
22
18
  readonly offsetInvalid: {
23
- readonly instruction: 'Choose an integer offset inside the block.';
19
+ readonly instruction: 'Choose an integer offset inside the slot.';
24
20
  readonly message: 'Invalid port offset.';
25
21
  };
26
22
  readonly optionsInvalid: {
@@ -31,16 +27,32 @@ export declare const ERRORS_BY_KEY: {
31
27
  readonly instruction: 'Stop the services using these ports and try again.';
32
28
  readonly message: 'Cannot release reservations while ports are in use.';
33
29
  };
30
+ readonly rangeMismatch: {
31
+ readonly instruction: 'Use the repository start and size, or release all slots before changing them.';
32
+ readonly message: 'Port range settings differ from the repository registry.';
33
+ };
34
34
  readonly registryInvalid: {
35
- readonly instruction: 'Restore or repair the reservation file before continuing.';
35
+ readonly instruction: 'Restore or repair the slot file before continuing.';
36
36
  readonly message: 'Cannot read reservation.';
37
37
  };
38
38
  readonly reservationNotFound: {
39
- readonly instruction: 'Run porto reserve first.';
40
- readonly message: 'No reservation for the current worktree.';
39
+ readonly instruction: 'Run porto show --all to list slots or porto reserve to reserve one.';
40
+ readonly message: 'No matching port slot.';
41
+ };
42
+ readonly slotIndexInvalid: {
43
+ readonly instruction: 'Choose a non-negative integer slot index.';
44
+ readonly message: 'Invalid slot index.';
45
+ };
46
+ readonly slotSelectionInvalid: {
47
+ readonly instruction: 'Use a slot number or --all.';
48
+ readonly message: 'Cannot combine a slot number with --all.';
49
+ };
50
+ readonly slotUnavailable: {
51
+ readonly instruction: 'Release unused slots or choose another range.';
52
+ readonly message: 'No free port slot remains in the TCP port range.';
41
53
  };
42
54
  readonly worktreeNotFound: {
43
- readonly instruction: 'Run Porto inside a regular Git checkout or linked worktree.';
55
+ readonly instruction: 'Run Porto inside a regular Git worktree.';
44
56
  readonly message: 'Porto must run inside a Git working tree.';
45
57
  };
46
58
  };
package/dist/errors.js CHANGED
@@ -1,8 +1,4 @@
1
1
  const ERRORS_BY_KEY = {
2
- blockUnavailable: {
3
- instruction: 'Release unused blocks or choose another range.',
4
- message: 'No free port block remains in the TCP port range.'
5
- },
6
2
  configInvalid: {
7
3
  instruction: 'Check porto.config.ts or porto.config.js.',
8
4
  message: 'Invalid Porto configuration.'
@@ -16,11 +12,11 @@ const ERRORS_BY_KEY = {
16
12
  message: 'Lifecycle hook failed.'
17
13
  },
18
14
  mappingInvalid: {
19
- instruction: 'Use unique variable names, valid callbacks, and a block large enough for all entries.',
15
+ instruction: 'Use unique variable names, valid callbacks, and a slot large enough for all entries.',
20
16
  message: 'Invalid variables.'
21
17
  },
22
18
  offsetInvalid: {
23
- instruction: 'Choose an integer offset inside the block.',
19
+ instruction: 'Choose an integer offset inside the slot.',
24
20
  message: 'Invalid port offset.'
25
21
  },
26
22
  optionsInvalid: {
@@ -31,16 +27,32 @@ const ERRORS_BY_KEY = {
31
27
  instruction: 'Stop the services using these ports and try again.',
32
28
  message: 'Cannot release reservations while ports are in use.'
33
29
  },
30
+ rangeMismatch: {
31
+ instruction: 'Use the repository start and size, or release all slots before changing them.',
32
+ message: 'Port range settings differ from the repository registry.'
33
+ },
34
34
  registryInvalid: {
35
- instruction: 'Restore or repair the reservation file before continuing.',
35
+ instruction: 'Restore or repair the slot file before continuing.',
36
36
  message: 'Cannot read reservation.'
37
37
  },
38
38
  reservationNotFound: {
39
- instruction: 'Run porto reserve first.',
40
- message: 'No reservation for the current worktree.'
39
+ instruction: 'Run porto show --all to list slots or porto reserve to reserve one.',
40
+ message: 'No matching port slot.'
41
+ },
42
+ slotIndexInvalid: {
43
+ instruction: 'Choose a non-negative integer slot index.',
44
+ message: 'Invalid slot index.'
45
+ },
46
+ slotSelectionInvalid: {
47
+ instruction: 'Use a slot number or --all.',
48
+ message: 'Cannot combine a slot number with --all.'
49
+ },
50
+ slotUnavailable: {
51
+ instruction: 'Release unused slots or choose another range.',
52
+ message: 'No free port slot remains in the TCP port range.'
41
53
  },
42
54
  worktreeNotFound: {
43
- instruction: 'Run Porto inside a regular Git checkout or linked worktree.',
55
+ instruction: 'Run Porto inside a regular Git worktree.',
44
56
  message: 'Porto must run inside a Git working tree.'
45
57
  }
46
58
  };
package/dist/git.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  declare function fetchGitContext(): Promise<{
2
2
  commonDirectory: string;
3
- worktree: string;
4
3
  worktreeId: string;
4
+ worktreePath: string;
5
5
  }>;
6
6
  declare function listWorktreePaths(commonDirectory: string): Promise<Map<string, string>>;
7
7
  export { fetchGitContext, listWorktreePaths };
package/dist/git.js CHANGED
@@ -17,17 +17,17 @@ async function fetchGitContext() {
17
17
  '--git-common-dir',
18
18
  '--absolute-git-dir'
19
19
  ]);
20
- const [worktreePath, commonPath, gitPath] = stdout.split(/\r?\n/u);
21
- if (!worktreePath || !commonPath || !gitPath) throw new Error('Missing Git paths.');
22
- const [worktree, commonDirectory, gitDirectory] = await Promise.all([
23
- realpath(worktreePath),
20
+ const [rootPath, commonPath, gitPath] = stdout.split(/\r?\n/u);
21
+ if (!rootPath || !commonPath || !gitPath) throw new Error('Missing Git paths.');
22
+ const [worktreePath, commonDirectory, gitDirectory] = await Promise.all([
23
+ realpath(rootPath),
24
24
  realpath(commonPath),
25
25
  realpath(gitPath)
26
26
  ]);
27
27
  return {
28
28
  commonDirectory,
29
- worktree,
30
- worktreeId: getWorktreeId(commonDirectory, gitDirectory)
29
+ worktreeId: getWorktreeId(commonDirectory, gitDirectory),
30
+ worktreePath
31
31
  };
32
32
  } catch (error) {
33
33
  throw new PortoError('worktreeNotFound', void 0, {
@@ -35,10 +35,10 @@ async function fetchGitContext() {
35
35
  });
36
36
  }
37
37
  }
38
- async function fetchLinkedWorktreeId(commonDirectory, worktree) {
39
- const gitLink = await readFile(node_path.join(worktree, '.git'), 'utf8');
38
+ async function fetchLinkedWorktreeId(commonDirectory, worktreePath) {
39
+ const gitLink = await readFile(node_path.join(worktreePath, '.git'), 'utf8');
40
40
  const gitPath = /^gitdir: (?<gitPath>.+)\r?\n?$/u.exec(gitLink)?.groups?.['gitPath'];
41
- return gitPath && getWorktreeId(commonDirectory, await realpath(node_path.resolve(worktree, gitPath)));
41
+ return gitPath && getWorktreeId(commonDirectory, await realpath(node_path.resolve(worktreePath, gitPath)));
42
42
  }
43
43
  async function listWorktreePaths(commonDirectory) {
44
44
  const { stdout } = await execFileAsync('git', [
@@ -52,9 +52,9 @@ async function listWorktreePaths(commonDirectory) {
52
52
  const [location, ...flags] = entry.split('\0');
53
53
  if (!location?.startsWith('worktree ') || flags.some((flag)=>'bare' === flag || flag.startsWith('prunable '))) return;
54
54
  try {
55
- const worktree = await realpath(location.slice(9));
56
- const worktreeId = 0 === index ? '.' : await fetchLinkedWorktreeId(commonDirectory, worktree);
57
- if (worktreeId) worktreePathsById.set(worktreeId, worktree);
55
+ const worktreePath = await realpath(location.slice(9));
56
+ const worktreeId = 0 === index ? '.' : await fetchLinkedWorktreeId(commonDirectory, worktreePath);
57
+ if (worktreeId) worktreePathsById.set(worktreeId, worktreePath);
58
58
  } catch (error) {
59
59
  if (!checkIsFileMissing(error)) throw error;
60
60
  }
package/dist/index.d.ts CHANGED
@@ -1,45 +1,100 @@
1
1
  import type { ReservationRecord } from './registry.js';
2
- import { buildBlock } from './ports.js';
3
- type PortBlock = ReturnType<typeof buildBlock>;
2
+ import { buildSlot } from './ports.js';
3
+ type PortSlot = ReturnType<typeof buildSlot<ReservationRecord>>;
4
4
  type ReservationStats = Omit<ReservationRecord, 'worktreeId'> & {
5
- end: number;
5
+ index: number;
6
6
  isExpired: boolean;
7
7
  };
8
- declare function cleanup(): Promise<{
9
- end: number;
10
- getPort(offset?: number): number;
11
- index: number;
12
- start: number;
13
- }[]>;
14
- declare function current(): Promise<{
15
- end: number;
16
- getPort(offset?: number): number;
17
- index: number;
18
- start: number;
19
- }[]>;
20
- declare function release(): Promise<({
21
- end: number;
8
+ declare function cleanupSlots(): Promise<({
9
+ env: boolean;
10
+ envFile: string;
11
+ jsonFile: string | false;
12
+ silent: boolean;
13
+ expiresAt: string | null;
14
+ firstPort: number;
15
+ host?: string | undefined;
16
+ idleTtlMinutes: number;
17
+ keep: boolean;
18
+ lastPort: number;
19
+ lastUsedAt: string;
20
+ ports: number[];
21
+ vars: {
22
+ [k: string]: string | number;
23
+ };
24
+ worktreeId: string;
25
+ worktreePath: string;
26
+ } & {
22
27
  getPort(offset?: number): number;
23
28
  index: number;
24
- start: number;
25
- } & {
26
- ports: number[];
27
29
  })[]>;
28
- declare function stats(): Promise<{
30
+ declare function getAllSlots(): Promise<{
29
31
  index: number;
30
- lastUsedAt: string;
31
- ports: Array<number>;
32
- end: number;
33
32
  isExpired: boolean;
34
- start: number;
35
- worktree: string;
33
+ worktreePath: string;
34
+ env: boolean;
35
+ envFile: string;
36
+ jsonFile: string | false;
37
+ silent: boolean;
38
+ expiresAt: string | null;
39
+ firstPort: number;
36
40
  host?: string | undefined;
37
41
  idleTtlMinutes: number;
38
42
  keep: boolean;
39
- size: number;
43
+ lastPort: number;
44
+ lastUsedAt: string;
45
+ ports: number[];
46
+ vars: {
47
+ [k: string]: string | number;
48
+ };
40
49
  }[]>;
41
- export { cleanup, current, release, stats };
42
- export type { PortBlock, ReservationStats };
50
+ declare function getSlot(slotIndex?: number): Promise<({
51
+ env: boolean;
52
+ envFile: string;
53
+ jsonFile: string | false;
54
+ silent: boolean;
55
+ expiresAt: string | null;
56
+ firstPort: number;
57
+ host?: string | undefined;
58
+ idleTtlMinutes: number;
59
+ keep: boolean;
60
+ lastPort: number;
61
+ lastUsedAt: string;
62
+ ports: number[];
63
+ vars: {
64
+ [k: string]: string | number;
65
+ };
66
+ worktreeId: string;
67
+ worktreePath: string;
68
+ } & {
69
+ getPort(offset?: number): number;
70
+ index: number;
71
+ }) | undefined>;
72
+ declare function releaseAllSlots(force?: boolean): Promise<({
73
+ env: boolean;
74
+ envFile: string;
75
+ jsonFile: string | false;
76
+ silent: boolean;
77
+ expiresAt: string | null;
78
+ firstPort: number;
79
+ host?: string | undefined;
80
+ idleTtlMinutes: number;
81
+ keep: boolean;
82
+ lastPort: number;
83
+ lastUsedAt: string;
84
+ ports: number[];
85
+ vars: {
86
+ [k: string]: string | number;
87
+ };
88
+ worktreeId: string;
89
+ worktreePath: string;
90
+ } & {
91
+ getPort(offset?: number): number;
92
+ index: number;
93
+ })[]>;
94
+ declare function releaseSlot(force?: boolean): Promise<PortSlot | undefined>;
95
+ declare function releaseSlot(slotIndex: number | undefined, force?: boolean): Promise<PortSlot | undefined>;
96
+ export { cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot };
97
+ export type { PortSlot, ReservationStats };
43
98
  export { BusyPortsError } from './busy-ports-error.js';
44
99
  export { defineConfig } from './config.js';
45
100
  export type { PortoConfig } from './config.js';
package/dist/index.js CHANGED
@@ -1,57 +1,69 @@
1
- import { remove, sortBy } from "es-toolkit";
2
- import { BusyPortsError } from "./busy-ports-error.js";
1
+ import { PortoError } from "./error.js";
3
2
  import { fetchGitContext, listWorktreePaths } from "./git.js";
4
- import { buildBlock, listBusyPorts } from "./ports.js";
3
+ import { buildSlot } from "./ports.js";
5
4
  import { updateRegistry } from "./registry.js";
6
- import { checkIsExpired, removeExpiredRecords, reserve } from "./reserve.js";
7
- async function cleanup() {
5
+ import { checkIsExpired, releaseRecord, removeExpiredRecords, reserve } from "./reserve.js";
6
+ async function cleanupSlots() {
8
7
  const { commonDirectory } = await fetchGitContext();
9
- return updateRegistry(commonDirectory, (records)=>removeExpiredRecords(records, Date.now()));
8
+ return updateRegistry(commonDirectory, (registry)=>removeExpiredRecords(registry, Date.now()));
10
9
  }
11
- async function current() {
12
- const { commonDirectory, worktreeId } = await fetchGitContext();
13
- return updateRegistry(commonDirectory, (records)=>records.filter((record)=>record.worktreeId === worktreeId).map((record)=>buildBlock(record)));
10
+ async function getAllSlots() {
11
+ const { commonDirectory } = await fetchGitContext();
12
+ const worktreePathsById = await listWorktreePaths(commonDirectory);
13
+ return updateRegistry(commonDirectory, ({ slots })=>{
14
+ const now = Date.now();
15
+ return Object.entries(slots).flatMap(([key, record])=>{
16
+ const index = Number(key);
17
+ const { worktreeId, ...slotFields } = record;
18
+ const worktreePath = worktreePathsById.get(worktreeId) ?? record.worktreePath;
19
+ return [
20
+ {
21
+ ...slotFields,
22
+ index,
23
+ isExpired: checkIsExpired(record, now),
24
+ worktreePath
25
+ }
26
+ ];
27
+ });
28
+ });
14
29
  }
15
- async function release() {
30
+ async function getSlot(slotIndex) {
31
+ if (void 0 !== slotIndex && (!Number.isSafeInteger(slotIndex) || slotIndex < 0)) throw new PortoError('slotIndexInvalid');
16
32
  const { commonDirectory, worktreeId } = await fetchGitContext();
17
- return updateRegistry(commonDirectory, async (records)=>{
18
- const currentRecords = records.filter((record)=>record.worktreeId === worktreeId);
19
- const portsByRecord = await Promise.all(currentRecords.map(async (record)=>{
20
- const block = buildBlock(record);
21
- const ports = await listBusyPorts(block.start, block.end, {
22
- host: record.host
23
- });
24
- return ports.map((port)=>({
25
- block: block.index,
26
- port
27
- }));
28
- }));
29
- const busyPorts = portsByRecord.flat();
30
- if (busyPorts.length > 0) throw new BusyPortsError(busyPorts);
31
- remove(records, (record)=>record.worktreeId === worktreeId);
32
- return currentRecords.map((record)=>Object.assign(buildBlock(record), {
33
- ports: record.ports
34
- }));
33
+ return updateRegistry(commonDirectory, ({ slots })=>{
34
+ if (void 0 !== slotIndex) {
35
+ const record = slots[slotIndex];
36
+ return record ? buildSlot(record, slotIndex) : void 0;
37
+ }
38
+ const found = Object.entries(slots).find(([, record])=>record.worktreeId === worktreeId);
39
+ return found ? buildSlot(found[1], Number(found[0])) : void 0;
35
40
  });
36
41
  }
37
- async function stats() {
42
+ async function releaseAllSlots(force = false) {
38
43
  const { commonDirectory } = await fetchGitContext();
39
- const worktreePathsById = await listWorktreePaths(commonDirectory);
40
- return updateRegistry(commonDirectory, (records)=>sortBy(records.map(({ worktreeId, ...record })=>{
41
- const { end, start } = buildBlock(record);
42
- const worktree = worktreePathsById.get(worktreeId) ?? record.worktree;
43
- return {
44
- ...record,
45
- end,
46
- isExpired: checkIsExpired(record, Date.now()),
47
- start,
48
- worktree
49
- };
50
- }), [
51
- 'start',
52
- 'worktree'
53
- ]));
44
+ return updateRegistry(commonDirectory, async (registry)=>{
45
+ const releasedSlots = [];
46
+ for (const [key, record] of Object.entries(registry.slots)){
47
+ const index = Number(key);
48
+ releasedSlots.push(await releaseRecord(registry, index, record, force));
49
+ }
50
+ return releasedSlots;
51
+ });
52
+ }
53
+ async function releaseSlot(slotIndex, force = false) {
54
+ const selected = 'boolean' == typeof slotIndex ? void 0 : slotIndex;
55
+ const forced = 'boolean' == typeof slotIndex ? slotIndex : force;
56
+ if (void 0 !== selected && (!Number.isSafeInteger(selected) || selected < 0)) throw new PortoError('slotIndexInvalid');
57
+ const { commonDirectory, worktreeId } = await fetchGitContext();
58
+ return updateRegistry(commonDirectory, (registry)=>{
59
+ if (void 0 !== selected) {
60
+ const record = registry.slots[selected];
61
+ return record ? releaseRecord(registry, selected, record, forced) : void 0;
62
+ }
63
+ const found = Object.entries(registry.slots).find(([, record])=>record.worktreeId === worktreeId);
64
+ return found ? releaseRecord(registry, Number(found[0]), found[1], forced) : void 0;
65
+ });
54
66
  }
67
+ export { BusyPortsError } from "./busy-ports-error.js";
55
68
  export { defineConfig } from "./config.js";
56
- export { PortoError } from "./error.js";
57
- export { BusyPortsError, cleanup, current, release, reserve, stats };
69
+ export { PortoError, cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot, reserve };
package/dist/output.d.ts CHANGED
@@ -1,18 +1,19 @@
1
- import type { PortBlock, ReservationStats } from './index.js';
2
- type Environment = Record<string, number | string>;
1
+ import type { PortSlot, ReservationStats } from './index.js';
2
+ type Environment = SlotVars;
3
+ type SlotVars = Record<string, number | string>;
3
4
  declare function fetchExportPaths(settings: {
4
5
  env: boolean;
5
6
  envFile: string;
6
7
  jsonFile: false | string;
7
8
  }, commonDirectory: string): Promise<{
8
- environmentPath: string | undefined;
9
+ envPath: string | undefined;
9
10
  jsonPath: string | undefined;
10
11
  }>;
11
- declare function formatEnvironment(environment: Environment): string;
12
- declare function formatReserveOutput(block: PortBlock, environment: Environment | undefined, isJson: boolean): string;
12
+ declare function formatEnvironment(vars: SlotVars): string;
13
+ declare function formatReserveOutput(slot: PortSlot, vars: SlotVars | undefined, isJson: boolean): string;
13
14
  declare function formatTable(headers: Array<string>, rows: Array<Array<string>>): string;
14
- declare function formatStatsTable(reservations: Array<ReservationStats>): string;
15
- declare function updateEnvironmentFile(filePath: string, environment: Environment, commonDirectory?: string): Promise<void>;
16
- declare function writeReserveJsonFile(filePath: string, block: PortBlock, environment: Environment | undefined): Promise<void>;
15
+ declare function formatStatsTable(slots: Array<ReservationStats>): string;
16
+ declare function updateEnvironmentFile(filePath: string, vars: SlotVars, commonDirectory?: string): Promise<void>;
17
+ declare function writeReserveJsonFile(filePath: string, slot: PortSlot, vars: SlotVars | undefined): Promise<void>;
17
18
  export { fetchExportPaths, formatEnvironment, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile, };
18
- export type { Environment };
19
+ export type { Environment, SlotVars };