@buildkitgg/dev-domains 0.0.0-stage → 0.0.2

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +727 -2
  4. package/dist/cli/command.d.ts +3 -0
  5. package/dist/cli/command.js +17 -0
  6. package/dist/cli/commands.d.ts +125 -0
  7. package/dist/cli/commands.js +99 -0
  8. package/dist/cli/init.d.ts +6 -0
  9. package/dist/cli/init.js +148 -0
  10. package/dist/cli/main.d.ts +2 -0
  11. package/dist/cli/main.js +13 -0
  12. package/dist/cli/terminal.d.ts +11 -0
  13. package/dist/cli/terminal.js +43 -0
  14. package/dist/config/load.d.ts +36 -0
  15. package/dist/config/load.js +68 -0
  16. package/dist/config/read.d.ts +2 -0
  17. package/dist/config/read.js +19 -0
  18. package/dist/config/schema.d.ts +73 -0
  19. package/dist/config/schema.js +71 -0
  20. package/dist/domains/resolve.d.ts +37 -0
  21. package/dist/domains/resolve.js +54 -0
  22. package/dist/node.d.ts +10 -0
  23. package/dist/node.js +16 -0
  24. package/dist/playwright.d.ts +13 -0
  25. package/dist/playwright.js +20 -0
  26. package/dist/project/detect.d.ts +3 -0
  27. package/dist/project/detect.js +101 -0
  28. package/dist/project/discovery.d.ts +6 -0
  29. package/dist/project/discovery.js +70 -0
  30. package/dist/project/identity.d.ts +6 -0
  31. package/dist/project/identity.js +44 -0
  32. package/dist/project/manifest.d.ts +11 -0
  33. package/dist/project/manifest.js +22 -0
  34. package/dist/project/package-manager.d.ts +2 -0
  35. package/dist/project/package-manager.js +28 -0
  36. package/dist/runtime/command.d.ts +4 -0
  37. package/dist/runtime/command.js +77 -0
  38. package/dist/runtime/port.d.ts +5 -0
  39. package/dist/runtime/port.js +37 -0
  40. package/dist/runtime/portless.d.ts +2 -0
  41. package/dist/runtime/portless.js +65 -0
  42. package/dist/runtime/process.d.ts +13 -0
  43. package/dist/runtime/process.js +101 -0
  44. package/dist/runtime/proxy.d.ts +10 -0
  45. package/dist/runtime/proxy.js +102 -0
  46. package/dist/runtime/state.d.ts +3 -0
  47. package/dist/runtime/state.js +8 -0
  48. package/dist/webhooks/gateway.d.ts +10 -0
  49. package/dist/webhooks/gateway.js +99 -0
  50. package/dist/webhooks/tunnel.d.ts +2 -0
  51. package/dist/webhooks/tunnel.js +27 -0
  52. package/package.json +65 -3
@@ -0,0 +1,3 @@
1
+ import { type ArgsDef, type CommandDef } from "citty";
2
+ /** Keep operational errors concise; argument/help errors remain Citty's responsibility. */
3
+ export declare function defineCliCommand<const T extends ArgsDef>(definition: CommandDef<T>): CommandDef<T>;
@@ -0,0 +1,17 @@
1
+ import { defineCommand } from "citty";
2
+ import { Cancelled } from "./terminal.js";
3
+ /** Keep operational errors concise; argument/help errors remain Citty's responsibility. */
4
+ export function defineCliCommand(definition) {
5
+ return defineCommand({
6
+ ...definition,
7
+ async run(context) {
8
+ try {
9
+ return await definition.run?.(context);
10
+ }
11
+ catch (error) {
12
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
13
+ process.exitCode = error instanceof Cancelled ? 130 : 1;
14
+ }
15
+ }
16
+ });
17
+ }
@@ -0,0 +1,125 @@
1
+ export declare const run: import("citty").CommandDef<{
2
+ readonly cwd: {
3
+ readonly type: "string";
4
+ readonly description: "Project directory";
5
+ readonly default: ".";
6
+ };
7
+ readonly config: {
8
+ readonly type: "string";
9
+ readonly description: "Explicit config file (relative to cwd)";
10
+ };
11
+ readonly endpoint: {
12
+ readonly type: "positional";
13
+ readonly description: "Endpoint name";
14
+ readonly required: false;
15
+ };
16
+ }>;
17
+ export declare const commands: {
18
+ run: import("citty").CommandDef<{
19
+ readonly cwd: {
20
+ readonly type: "string";
21
+ readonly description: "Project directory";
22
+ readonly default: ".";
23
+ };
24
+ readonly config: {
25
+ readonly type: "string";
26
+ readonly description: "Explicit config file (relative to cwd)";
27
+ };
28
+ readonly endpoint: {
29
+ readonly type: "positional";
30
+ readonly description: "Endpoint name";
31
+ readonly required: false;
32
+ };
33
+ }>;
34
+ init: import("citty").CommandDef<{
35
+ readonly cwd: {
36
+ readonly type: "string";
37
+ readonly description: "Project directory";
38
+ readonly default: ".";
39
+ };
40
+ readonly yes: {
41
+ readonly type: "boolean";
42
+ readonly description: "Accept detected defaults without prompts";
43
+ };
44
+ readonly domain: {
45
+ readonly type: "string";
46
+ readonly description: "Local domain suffix";
47
+ };
48
+ readonly project: {
49
+ readonly type: "string";
50
+ readonly description: "Project name";
51
+ };
52
+ readonly "dry-run": {
53
+ readonly type: "boolean";
54
+ readonly description: "Print the config without writing files";
55
+ };
56
+ }>;
57
+ detect: import("citty").CommandDef<{
58
+ readonly cwd: {
59
+ readonly type: "string";
60
+ readonly description: "Project directory";
61
+ readonly default: ".";
62
+ };
63
+ }>;
64
+ urls: import("citty").CommandDef<{
65
+ readonly cwd: {
66
+ readonly type: "string";
67
+ readonly description: "Project directory";
68
+ readonly default: ".";
69
+ };
70
+ readonly config: {
71
+ readonly type: "string";
72
+ readonly description: "Explicit config file (relative to cwd)";
73
+ };
74
+ }>;
75
+ setup: import("citty").CommandDef<{
76
+ readonly cwd: {
77
+ readonly type: "string";
78
+ readonly description: "Project directory";
79
+ readonly default: ".";
80
+ };
81
+ readonly config: {
82
+ readonly type: "string";
83
+ readonly description: "Explicit config file (relative to cwd)";
84
+ };
85
+ }>;
86
+ status: import("citty").CommandDef<{
87
+ readonly cwd: {
88
+ readonly type: "string";
89
+ readonly description: "Project directory";
90
+ readonly default: ".";
91
+ };
92
+ readonly config: {
93
+ readonly type: "string";
94
+ readonly description: "Explicit config file (relative to cwd)";
95
+ };
96
+ }>;
97
+ doctor: import("citty").CommandDef<{
98
+ readonly cwd: {
99
+ readonly type: "string";
100
+ readonly description: "Project directory";
101
+ readonly default: ".";
102
+ };
103
+ readonly config: {
104
+ readonly type: "string";
105
+ readonly description: "Explicit config file (relative to cwd)";
106
+ };
107
+ }>;
108
+ tunnel: import("citty").CommandDef<{
109
+ readonly cwd: {
110
+ readonly type: "string";
111
+ readonly description: "Project directory";
112
+ readonly default: ".";
113
+ };
114
+ readonly config: {
115
+ readonly type: "string";
116
+ readonly description: "Explicit config file (relative to cwd)";
117
+ };
118
+ readonly endpoint: {
119
+ readonly type: "positional";
120
+ readonly description: "Endpoint name";
121
+ readonly required: false;
122
+ };
123
+ }>;
124
+ schema: import("citty").CommandDef<import("citty").ArgsDef>;
125
+ };
@@ -0,0 +1,99 @@
1
+ import { z } from "zod";
2
+ import { loadProject } from "../config/load.js";
3
+ import { configSchema } from "../config/schema.js";
4
+ import { resolveEndpoints } from "../domains/resolve.js";
5
+ import { detectConfig } from "../project/detect.js";
6
+ import { projectIdentity } from "../project/identity.js";
7
+ import { runEndpoint } from "../runtime/portless.js";
8
+ import { withSignals } from "../runtime/process.js";
9
+ import { proxyCommand } from "../runtime/proxy.js";
10
+ import { runTunnel } from "../webhooks/tunnel.js";
11
+ import { defineCliCommand as defineCommand } from "./command.js";
12
+ import { initialize } from "./init.js";
13
+ import { chooseEndpoint, output, text } from "./terminal.js";
14
+ const location = {
15
+ cwd: { type: "string", description: "Project directory", default: "." },
16
+ config: { type: "string", description: "Explicit config file (relative to cwd)" }
17
+ };
18
+ const selection = {
19
+ ...location,
20
+ endpoint: { type: "positional", description: "Endpoint name", required: false }
21
+ };
22
+ export const run = defineCommand({
23
+ meta: { description: "Run a detected or configured server through Portless" },
24
+ args: selection,
25
+ async run({ args }) {
26
+ const project = await loadProject(args.cwd, args.config);
27
+ const endpoints = resolveEndpoints(project);
28
+ const name = await chooseEndpoint(endpoints, args.endpoint);
29
+ const endpoint = endpoints.find((entry) => entry.service === name);
30
+ text(`${name}: ${endpoint.origin}`);
31
+ process.exitCode = await withSignals((signal) => runEndpoint(project, endpoint, signal));
32
+ }
33
+ });
34
+ const proxy = (action, description) => defineCommand({
35
+ meta: { description },
36
+ args: location,
37
+ async run({ args }) {
38
+ const project = await loadProject(args.cwd, args.config);
39
+ process.exitCode = (await withSignals((signal) => proxyCommand(project, action, signal))).code;
40
+ }
41
+ });
42
+ export const commands = {
43
+ run,
44
+ init: defineCommand({
45
+ meta: { description: "Detect tools and save project configuration" },
46
+ args: {
47
+ cwd: location.cwd,
48
+ yes: { type: "boolean", description: "Accept detected defaults without prompts" },
49
+ domain: { type: "string", description: "Local domain suffix" },
50
+ project: { type: "string", description: "Project name" },
51
+ "dry-run": { type: "boolean", description: "Print the config without writing files" }
52
+ },
53
+ async run({ args }) {
54
+ await initialize(args.cwd, { yes: args.yes, domain: args.domain, project: args.project, dryRun: args["dry-run"] });
55
+ }
56
+ }),
57
+ detect: defineCommand({
58
+ meta: { description: "Print detected defaults without reading executable config" },
59
+ args: { cwd: location.cwd },
60
+ async run({ args }) {
61
+ output(await detectConfig((await projectIdentity(args.cwd)).root));
62
+ }
63
+ }),
64
+ urls: defineCommand({
65
+ meta: { description: "Print domains and callback URLs as JSON" },
66
+ args: location,
67
+ async run({ args }) {
68
+ output(resolveEndpoints(await loadProject(args.cwd, args.config)).map(({ service, origin, hostname, callbacks, endpoint }) => ({
69
+ service,
70
+ origin,
71
+ hostname,
72
+ callbacks,
73
+ webhookOrigin: endpoint.tunnel?.publicUrl
74
+ })));
75
+ }
76
+ }),
77
+ setup: proxy("setup", "Start Portless with the project's proxy settings"),
78
+ status: proxy("status", "Show active Portless routes"),
79
+ doctor: proxy("doctor", "Check Portless, DNS, and certificate trust"),
80
+ tunnel: defineCommand({
81
+ meta: { description: "Expose configured webhook POST paths through a tunnel" },
82
+ args: selection,
83
+ async run({ args }) {
84
+ const project = await loadProject(args.cwd, args.config);
85
+ const endpoints = resolveEndpoints(project).filter((entry) => entry.endpoint.tunnel);
86
+ if (!endpoints.length) {
87
+ throw new Error("No webhook tunnels configured. Run init or add an endpoint.tunnel configuration.");
88
+ }
89
+ const name = await chooseEndpoint(endpoints, args.endpoint);
90
+ process.exitCode = await withSignals((signal) => runTunnel(project, endpoints.find((entry) => entry.service === name), signal));
91
+ }
92
+ }),
93
+ schema: defineCommand({
94
+ meta: { description: "Print the JSON Schema for editor configuration" },
95
+ run() {
96
+ output(z.toJSONSchema(configSchema, { io: "input", unrepresentable: "any" }));
97
+ }
98
+ })
99
+ };
@@ -0,0 +1,6 @@
1
+ export declare function initialize(cwd: string, options: {
2
+ yes?: boolean;
3
+ domain?: string;
4
+ project?: string;
5
+ dryRun?: boolean;
6
+ }): Promise<void>;
@@ -0,0 +1,148 @@
1
+ import * as prompts from "@clack/prompts";
2
+ import { z } from "zod";
3
+ import { findConfig, saveConfig } from "../config/load.js";
4
+ import { configSchema } from "../config/schema.js";
5
+ import { resolveEndpoints } from "../domains/resolve.js";
6
+ import { detectConfig } from "../project/detect.js";
7
+ import { projectIdentity } from "../project/identity.js";
8
+ import { answer, Cancelled, intro, output, text } from "./terminal.js";
9
+ async function ask(message, value, validate) {
10
+ return answer(await prompts.text({
11
+ message,
12
+ defaultValue: value,
13
+ placeholder: value,
14
+ validate: (input) => validate?.(input?.trim() || value)
15
+ }));
16
+ }
17
+ async function commandInput() {
18
+ const value = await ask('Command as a JSON argument array, for example ["node", "server.js"]', '["node", "server.js"]', (input) => {
19
+ try {
20
+ z.array(z.string().min(1)).min(1).parse(JSON.parse(input));
21
+ return undefined;
22
+ }
23
+ catch {
24
+ return 'Use a JSON array, for example ["node", "server.js"].';
25
+ }
26
+ });
27
+ return z.array(z.string().min(1)).min(1).parse(JSON.parse(value));
28
+ }
29
+ export async function initialize(cwd, options) {
30
+ const identity = await projectIdentity(cwd);
31
+ if (await findConfig(identity.root, identity.root)) {
32
+ throw new Error("Configuration already exists. Edit it directly; init does not overwrite files.");
33
+ }
34
+ const candidate = await detectConfig(identity.root);
35
+ candidate.project = options.project || candidate.project;
36
+ candidate.domain = options.domain || "localhost";
37
+ const detectedE2E = new Set(Object.entries(candidate.endpoints)
38
+ .filter(([, endpoint]) => endpoint.kind === "e2e")
39
+ .map(([key]) => key));
40
+ if (options.yes) {
41
+ candidate.endpoints = Object.fromEntries(Object.entries(candidate.endpoints).filter(([, endpoint]) => endpoint.kind !== "e2e"));
42
+ }
43
+ if (!options.yes) {
44
+ if (!process.stdin.isTTY) {
45
+ throw new Error("Interactive setup needs a terminal. Use init --yes to accept detected defaults.");
46
+ }
47
+ intro();
48
+ prompts.note("Use arrow keys to move, Space to select, and Enter to continue. Ctrl+C cancels.", "Keyboard");
49
+ candidate.project = await ask("Project name", candidate.project, (value) => configSchema.shape.project.safeParse(value).success ? undefined : "Use a lowercase DNS label.");
50
+ candidate.domain = await ask("Local domain suffix", candidate.domain, (value) => configSchema.shape.domain.safeParse(value).success ? undefined : "Use a domain without protocol, path, or port.");
51
+ const entries = Object.entries(candidate.endpoints);
52
+ if (entries.length) {
53
+ const selected = answer(await prompts.multiselect({
54
+ showInstructions: false,
55
+ message: "Which detected servers should have domains?",
56
+ required: true,
57
+ initialValues: entries.filter(([, endpoint]) => endpoint.kind !== "e2e").map(([key]) => key),
58
+ options: entries.map(([key, endpoint]) => ({
59
+ value: key,
60
+ label: key,
61
+ hint: `${endpoint.cwd} / ${endpoint.script || endpoint.command?.join(" ")}${endpoint.kind === "e2e" ? " (dedicated Playwright server)" : ""}`
62
+ }))
63
+ }));
64
+ candidate.endpoints = Object.fromEntries(entries.filter(([key]) => selected.includes(key)));
65
+ }
66
+ else {
67
+ prompts.note("No dev server scripts were detected. Add a command that listens on PORT or accepts {port}.", "Add a server");
68
+ candidate.endpoints.app = {
69
+ command: await commandInput(),
70
+ primaryName: "{project}",
71
+ name: "{project}-{worktree}"
72
+ };
73
+ }
74
+ const additions = {};
75
+ for (const [key, endpoint] of Object.entries(candidate.endpoints)) {
76
+ endpoint.primaryName = await ask(`Primary checkout name for ${key} ({project}, {service} supported)`, endpoint.primaryName || "{project}-{service}");
77
+ endpoint.name = await ask(`Worktree name for ${key} ({project}, {worktree}, {service} supported)`, endpoint.name || "{project}-{worktree}-{service}");
78
+ if (endpoint.kind === "e2e") {
79
+ prompts.note("This starts a separate copy of the app server. For frameworks with build locks, use DEV_DOMAINS_OUTPUT_DIR for a separate output directory. Configure Playwright to use this endpoint; databases remain shared.", "Test server isolation");
80
+ }
81
+ if (endpoint.kind === "storybook" || endpoint.kind === "e2e") {
82
+ continue;
83
+ }
84
+ const capabilities = answer(await prompts.multiselect({
85
+ showInstructions: false,
86
+ message: `Optional capabilities for ${key}`,
87
+ required: false,
88
+ options: [
89
+ { value: "auth", label: "Authentication callback paths" },
90
+ ...(!detectedE2E.has(`${key}-e2e`) ? [{ value: "e2e", label: "Dedicated Playwright server" }] : []),
91
+ { value: "webhooks", label: "Webhook tunnel" }
92
+ ]
93
+ }));
94
+ if (capabilities.includes("auth")) {
95
+ endpoint.auth = (await ask("Callback paths, separated by commas", "/callback"))
96
+ .split(",")
97
+ .map((value) => value.trim());
98
+ }
99
+ if (capabilities.includes("e2e")) {
100
+ const script = await ask("Script for the dedicated test server", endpoint.script || "dev");
101
+ const name = `${key}-e2e`;
102
+ if (candidate.endpoints[name]) {
103
+ throw new Error(`Endpoint ${name} already exists`);
104
+ }
105
+ additions[name] = {
106
+ ...endpoint,
107
+ kind: "e2e",
108
+ command: undefined,
109
+ script,
110
+ primaryName: "{project}-{service}",
111
+ name: "{project}-{worktree}-{service}",
112
+ auth: [],
113
+ env: { DEV_DOMAINS_OUTPUT_DIR: `.dev-domains/${name}` }
114
+ };
115
+ prompts.note("For frameworks with build locks, configure the test server to use DEV_DOMAINS_OUTPUT_DIR as a separate output directory. Databases remain shared.", "Test server isolation");
116
+ }
117
+ if (capabilities.includes("webhooks")) {
118
+ prompts.note("Enter a tunnel command that uses {url} for its target. Credentials stay in the provider's environment or login store. Exposure starts only with dev-domains tunnel.", "Public webhook access");
119
+ endpoint.tunnel = {
120
+ command: await commandInput(),
121
+ paths: (await ask("Allowed POST paths, separated by commas", "/api/webhooks"))
122
+ .split(",")
123
+ .map((value) => value.trim())
124
+ };
125
+ }
126
+ }
127
+ Object.assign(candidate.endpoints, additions);
128
+ }
129
+ const config = configSchema.parse(candidate);
130
+ const endpoints = resolveEndpoints({ config, ...identity, file: undefined });
131
+ if (options.dryRun) {
132
+ output(candidate);
133
+ return;
134
+ }
135
+ if (!options.yes) {
136
+ prompts.note(endpoints.map((endpoint) => `${endpoint.service}: ${endpoint.origin}`).join("\n"), "Review domains");
137
+ if (!answer(await prompts.confirm({ message: "Save dev-domains.json?", initialValue: true }))) {
138
+ throw new Cancelled();
139
+ }
140
+ }
141
+ const file = await saveConfig(identity.root, candidate);
142
+ if (options.yes) {
143
+ text(`Saved ${file}\nNext: dev-domains setup, then dev-domains run <endpoint>`);
144
+ }
145
+ else {
146
+ prompts.outro(`Saved ${file}\nNext: dev-domains setup, then dev-domains run <endpoint>`);
147
+ }
148
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { defineCommand, runMain } from "citty";
4
+ import { z } from "zod";
5
+ import { commands } from "./commands.js";
6
+ const { version } = z
7
+ .object({ version: z.string() })
8
+ .parse(JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")));
9
+ await runMain(defineCommand({
10
+ meta: { name: "dev-domains", version, description: "Stable local domains for every app and checkout" },
11
+ default: "run",
12
+ subCommands: commands
13
+ }));
@@ -0,0 +1,11 @@
1
+ export declare class Cancelled extends Error {
2
+ constructor();
3
+ }
4
+ export declare function answer<T>(value: T): Exclude<T, symbol>;
5
+ export declare function intro(): void;
6
+ export declare function output(value: unknown): void;
7
+ export declare function text(value: string): void;
8
+ export declare function chooseEndpoint(names: {
9
+ service: string;
10
+ origin: string;
11
+ }[], selected?: string): Promise<string>;
@@ -0,0 +1,43 @@
1
+ import { styleText } from "node:util";
2
+ import * as prompts from "@clack/prompts";
3
+ export class Cancelled extends Error {
4
+ constructor() {
5
+ super("Setup cancelled. No configuration was written.");
6
+ }
7
+ }
8
+ export function answer(value) {
9
+ if (typeof value === "symbol") {
10
+ throw new Cancelled();
11
+ }
12
+ return value;
13
+ }
14
+ export function intro() {
15
+ prompts.intro(`${styleText(["bgBlue", "white"], " BUILDKIT ")} / Development domains`);
16
+ }
17
+ export function output(value) {
18
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
19
+ }
20
+ export function text(value) {
21
+ process.stdout.write(`${value}\n`);
22
+ }
23
+ export async function chooseEndpoint(names, selected) {
24
+ if (selected) {
25
+ const endpoint = names.find((entry) => entry.service === selected);
26
+ if (!endpoint) {
27
+ throw new Error(`Unknown endpoint ${selected}. Available: ${names.map((entry) => entry.service).join(", ")}`);
28
+ }
29
+ return endpoint.service;
30
+ }
31
+ if (names.length === 1) {
32
+ return names[0].service;
33
+ }
34
+ if (!process.stdin.isTTY) {
35
+ throw new Error(`Specify an endpoint: ${names.map((entry) => entry.service).join(", ")}`);
36
+ }
37
+ intro();
38
+ return answer(await prompts.select({
39
+ showInstructions: false,
40
+ message: "Which endpoint should run?",
41
+ options: names.map((entry) => ({ value: entry.service, label: entry.service, hint: entry.origin }))
42
+ }));
43
+ }
@@ -0,0 +1,36 @@
1
+ import { type DevDomainsConfig } from "./schema.js";
2
+ export declare function findConfig(cwd: string, boundary: string): Promise<string | undefined>;
3
+ export declare function loadProject(cwd: string, explicitFile?: string): Promise<{
4
+ config: {
5
+ $schema?: string | undefined;
6
+ project: string;
7
+ domain: string;
8
+ proxy: {
9
+ domains?: string[] | undefined;
10
+ port: number;
11
+ https: boolean;
12
+ syncHosts: boolean;
13
+ };
14
+ packageManager: "bun" | "npm" | "pnpm" | "yarn";
15
+ endpoints: Record<string, {
16
+ kind: "app" | "e2e" | "storybook";
17
+ cwd: string;
18
+ name: string;
19
+ primaryName: string;
20
+ command?: string[] | undefined;
21
+ script?: string | undefined;
22
+ framework: "custom" | "next" | "storybook" | "vite";
23
+ env: Record<string, string>;
24
+ auth: string[];
25
+ tunnel?: {
26
+ command: string[];
27
+ paths: string[];
28
+ publicUrl?: string | undefined;
29
+ } | undefined;
30
+ }>;
31
+ };
32
+ root: string;
33
+ worktree: string | null;
34
+ file: string | undefined;
35
+ }>;
36
+ export declare function saveConfig(root: string, config: DevDomainsConfig): Promise<string>;
@@ -0,0 +1,68 @@
1
+ import { access, realpath, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { detectConfig } from "../project/detect.js";
4
+ import { projectIdentity } from "../project/identity.js";
5
+ import { readConfigFile } from "./read.js";
6
+ import { configSchema } from "./schema.js";
7
+ const filenames = [
8
+ "dev-domains.config.ts",
9
+ "dev-domains.config.mts",
10
+ "dev-domains.config.js",
11
+ "dev-domains.config.mjs",
12
+ "dev-domains.config.json",
13
+ "dev-domains.json"
14
+ ];
15
+ export async function findConfig(cwd, boundary) {
16
+ let directory = cwd;
17
+ while (true) {
18
+ const matches = [];
19
+ for (const name of filenames) {
20
+ try {
21
+ await access(path.join(directory, name));
22
+ matches.push(path.join(directory, name));
23
+ }
24
+ catch {
25
+ /* Not present. */
26
+ }
27
+ }
28
+ if (matches.length > 1) {
29
+ throw new Error(`Multiple dev-domains configs in ${directory}; keep one.`);
30
+ }
31
+ if (matches[0]) {
32
+ return matches[0];
33
+ }
34
+ const parent = path.dirname(directory);
35
+ if (directory === boundary || directory === parent) {
36
+ return undefined;
37
+ }
38
+ directory = parent;
39
+ }
40
+ }
41
+ export async function loadProject(cwd, explicitFile) {
42
+ const identity = await projectIdentity(cwd);
43
+ const file = explicitFile
44
+ ? await realpath(path.resolve(cwd, explicitFile))
45
+ : await findConfig(await realpath(cwd), identity.root);
46
+ let input;
47
+ const root = file ? path.dirname(file) : identity.root;
48
+ if (file) {
49
+ input = await readConfigFile(file);
50
+ }
51
+ else {
52
+ input = await detectConfig(root);
53
+ }
54
+ const result = configSchema.safeParse(input);
55
+ if (!result.success) {
56
+ throw new Error(`Invalid dev-domains configuration:\n${result.error.issues.map((issue) => `${issue.path.join(".") || "config"}: ${issue.message}`).join("\n")}`);
57
+ }
58
+ return { config: result.data, root, worktree: identity.worktree, file };
59
+ }
60
+ export async function saveConfig(root, config) {
61
+ configSchema.parse(config);
62
+ if (await findConfig(root, root)) {
63
+ throw new Error("A configuration already exists. Edit it instead of overwriting it.");
64
+ }
65
+ const file = path.join(root, "dev-domains.json");
66
+ await writeFile(file, `${JSON.stringify(config, null, 2)}\n`, { flag: "wx" });
67
+ return file;
68
+ }
@@ -0,0 +1,2 @@
1
+ /** c12 is deliberately limited to the selected local file. */
2
+ export declare function readConfigFile(file: string): Promise<unknown>;
@@ -0,0 +1,19 @@
1
+ import path from "node:path";
2
+ import { loadConfig } from "c12";
3
+ /** c12 is deliberately limited to the selected local file. */
4
+ export async function readConfigFile(file) {
5
+ return (await loadConfig({
6
+ cwd: path.dirname(file),
7
+ configFile: file,
8
+ configFileRequired: true,
9
+ name: "dev-domains",
10
+ dotenv: false,
11
+ rcFile: false,
12
+ globalRc: false,
13
+ packageJson: false,
14
+ envName: false,
15
+ omit$Keys: false,
16
+ extend: false,
17
+ giget: false
18
+ })).config;
19
+ }