neon 2.1.2 → 2.29.1

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 (166) hide show
  1. package/LICENSE.md +178 -0
  2. package/README.md +601 -0
  3. package/dist/analytics.js +156 -0
  4. package/dist/api.js +665 -0
  5. package/dist/auth.js +127 -0
  6. package/dist/callback.html +51 -0
  7. package/dist/cli.js +9 -0
  8. package/dist/commands/auth.js +214 -0
  9. package/dist/commands/bootstrap.js +481 -0
  10. package/dist/commands/branches.js +481 -0
  11. package/dist/commands/bucket.js +543 -0
  12. package/dist/commands/checkout.js +289 -0
  13. package/dist/commands/config.js +544 -0
  14. package/dist/commands/connection_string.js +172 -0
  15. package/dist/commands/data_api.js +285 -0
  16. package/dist/commands/databases.js +82 -0
  17. package/dist/commands/deploy.js +26 -0
  18. package/dist/commands/dev.js +698 -0
  19. package/dist/commands/env.js +166 -0
  20. package/dist/commands/functions.js +373 -0
  21. package/dist/commands/index.js +54 -0
  22. package/dist/commands/init.js +73 -0
  23. package/dist/commands/ip_allow.js +137 -0
  24. package/dist/commands/link.js +1121 -0
  25. package/dist/commands/neon_auth.js +1028 -0
  26. package/dist/commands/operations.js +28 -0
  27. package/dist/commands/orgs.js +24 -0
  28. package/dist/commands/projects.js +372 -0
  29. package/dist/commands/psql.js +62 -0
  30. package/dist/commands/roles.js +65 -0
  31. package/dist/commands/schema_diff.js +151 -0
  32. package/dist/commands/set_context.js +29 -0
  33. package/dist/commands/status.js +40 -0
  34. package/dist/commands/user.js +15 -0
  35. package/dist/commands/vpc_endpoints.js +134 -0
  36. package/dist/config.js +11 -0
  37. package/dist/config_format.js +72 -0
  38. package/dist/context.js +177 -0
  39. package/dist/current_branch_fast_path.js +55 -0
  40. package/dist/dev/env.js +240 -0
  41. package/dist/dev/functions.js +70 -0
  42. package/dist/dev/inputs.js +63 -0
  43. package/dist/dev/runtime.js +146 -0
  44. package/dist/env.js +36 -0
  45. package/dist/env_file.js +159 -0
  46. package/dist/errors.js +80 -0
  47. package/dist/functions_api.js +44 -0
  48. package/dist/help.js +146 -0
  49. package/dist/index.js +234 -0
  50. package/dist/log.js +18 -0
  51. package/dist/parameters.gen.js +480 -0
  52. package/dist/pkg.js +25 -0
  53. package/dist/psql/cli.js +53 -0
  54. package/dist/psql/command/cmd_cond.js +437 -0
  55. package/dist/psql/command/cmd_connect.js +820 -0
  56. package/dist/psql/command/cmd_copy.js +1035 -0
  57. package/dist/psql/command/cmd_describe.js +1815 -0
  58. package/dist/psql/command/cmd_format.js +922 -0
  59. package/dist/psql/command/cmd_io.js +2193 -0
  60. package/dist/psql/command/cmd_lo.js +393 -0
  61. package/dist/psql/command/cmd_meta.js +970 -0
  62. package/dist/psql/command/cmd_misc.js +187 -0
  63. package/dist/psql/command/cmd_pipeline.js +1148 -0
  64. package/dist/psql/command/cmd_restrict.js +171 -0
  65. package/dist/psql/command/cmd_show.js +766 -0
  66. package/dist/psql/command/dispatch.js +343 -0
  67. package/dist/psql/command/inputQueue.js +42 -0
  68. package/dist/psql/command/shared.js +71 -0
  69. package/dist/psql/complete/filenames.js +139 -0
  70. package/dist/psql/complete/index.js +104 -0
  71. package/dist/psql/complete/matcher.js +315 -0
  72. package/dist/psql/complete/psqlVars.js +247 -0
  73. package/dist/psql/complete/queries.js +493 -0
  74. package/dist/psql/complete/rules.js +2424 -0
  75. package/dist/psql/core/common.js +1253 -0
  76. package/dist/psql/core/help.js +576 -0
  77. package/dist/psql/core/mainloop.js +1360 -0
  78. package/dist/psql/core/prompt.js +440 -0
  79. package/dist/psql/core/settings.js +684 -0
  80. package/dist/psql/core/sqlHelp.js +1066 -0
  81. package/dist/psql/core/startup.js +846 -0
  82. package/dist/psql/core/syncVars.js +116 -0
  83. package/dist/psql/core/variables.js +287 -0
  84. package/dist/psql/describe/formatters.js +1290 -0
  85. package/dist/psql/describe/processNamePattern.js +270 -0
  86. package/dist/psql/describe/queries.js +2378 -0
  87. package/dist/psql/describe/versionGate.js +43 -0
  88. package/dist/psql/index.js +2030 -0
  89. package/dist/psql/io/history.js +299 -0
  90. package/dist/psql/io/input.js +120 -0
  91. package/dist/psql/io/lineEditor/buffer.js +325 -0
  92. package/dist/psql/io/lineEditor/complete.js +227 -0
  93. package/dist/psql/io/lineEditor/filename.js +159 -0
  94. package/dist/psql/io/lineEditor/index.js +894 -0
  95. package/dist/psql/io/lineEditor/keymap.js +745 -0
  96. package/dist/psql/io/lineEditor/vt100.js +363 -0
  97. package/dist/psql/io/pgpass.js +202 -0
  98. package/dist/psql/io/pgservice.js +194 -0
  99. package/dist/psql/io/psqlrc.js +422 -0
  100. package/dist/psql/print/aligned.js +1765 -0
  101. package/dist/psql/print/asciidoc.js +248 -0
  102. package/dist/psql/print/crosstab.js +463 -0
  103. package/dist/psql/print/csv.js +95 -0
  104. package/dist/psql/print/html.js +258 -0
  105. package/dist/psql/print/json.js +96 -0
  106. package/dist/psql/print/latex.js +396 -0
  107. package/dist/psql/print/pager.js +267 -0
  108. package/dist/psql/print/troff.js +258 -0
  109. package/dist/psql/print/unaligned.js +119 -0
  110. package/dist/psql/print/units.js +135 -0
  111. package/dist/psql/scanner/slash.js +515 -0
  112. package/dist/psql/scanner/sql.js +914 -0
  113. package/dist/psql/scanner/stringutils.js +394 -0
  114. package/dist/psql/types/backslash.js +1 -0
  115. package/dist/psql/types/connection.js +1 -0
  116. package/dist/psql/types/index.js +7 -0
  117. package/dist/psql/types/printer.js +1 -0
  118. package/dist/psql/types/repl.js +1 -0
  119. package/dist/psql/types/scanner.js +24 -0
  120. package/dist/psql/types/settings.js +1 -0
  121. package/dist/psql/types/variables.js +1 -0
  122. package/dist/psql/wire/connection.js +2858 -0
  123. package/dist/psql/wire/copy.js +108 -0
  124. package/dist/psql/wire/notify.js +59 -0
  125. package/dist/psql/wire/pipeline.js +521 -0
  126. package/dist/psql/wire/protocol.js +466 -0
  127. package/dist/psql/wire/sasl.js +296 -0
  128. package/dist/psql/wire/tls.js +602 -0
  129. package/dist/storage_api.js +147 -0
  130. package/dist/test_utils/fixtures.js +122 -0
  131. package/dist/test_utils/oauth_server.js +9 -0
  132. package/dist/types.js +1 -0
  133. package/dist/utils/api_enums.js +33 -0
  134. package/dist/utils/auth.js +5 -0
  135. package/dist/utils/branch_notice.js +22 -0
  136. package/dist/utils/branch_picker.js +103 -0
  137. package/dist/utils/compute_units.js +28 -0
  138. package/dist/utils/enrichers.js +161 -0
  139. package/dist/utils/esbuild.js +158 -0
  140. package/dist/utils/formats.js +18 -0
  141. package/dist/utils/middlewares.js +20 -0
  142. package/dist/utils/package_manager.js +68 -0
  143. package/dist/utils/point_in_time.js +56 -0
  144. package/dist/utils/psql.js +120 -0
  145. package/dist/utils/string.js +5 -0
  146. package/dist/utils/ui.js +59 -0
  147. package/dist/utils/zip.js +4 -0
  148. package/dist/writer.js +97 -0
  149. package/package.json +117 -14
  150. package/.jshintrc +0 -3
  151. package/CHANGELOG.markdown +0 -22
  152. package/LICENSE +0 -21
  153. package/README.markdown +0 -76
  154. package/bower.json +0 -23
  155. package/license.txt +0 -9
  156. package/neon.js +0 -234
  157. package/stdlib/bubbling_support.js +0 -32
  158. package/stdlib/custom_event.js +0 -54
  159. package/stdlib/custom_event_support.js +0 -195
  160. package/stdlib/index.js +0 -7
  161. package/stdlib/node_support.js +0 -123
  162. package/stdlib/widget.js +0 -340
  163. package/test/neon_browser.html +0 -11
  164. package/test/neon_stdlib_browser.html +0 -15
  165. package/test/neon_stdlib_test.js +0 -84
  166. package/test/neon_test.js +0 -64
@@ -0,0 +1,481 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, relative, resolve } from "node:path";
3
+ import chalk from "chalk";
4
+ import { BootstrapInputError, ensureTargetUsable, FALLBACK_TEMPLATES, fetchTemplates, findTemplate, scaffoldTemplate, templateIds, } from "neon-init/bootstrap";
5
+ import prompts from "prompts";
6
+ import { isCi } from "../env.js";
7
+ import { log } from "../log.js";
8
+ import { detectPackageManager, installedPackageManagers, runCommand, } from "../utils/package_manager.js";
9
+ // The directory positional is optional: omitting it in an interactive terminal
10
+ // prompts for one. In a non-interactive context a missing directory is an error.
11
+ export const command = "bootstrap [directory]";
12
+ export const describe = "Scaffold a new project from a Neon starter template";
13
+ export const builder = (argv) => argv
14
+ .usage("$0 bootstrap [directory] [options]")
15
+ .positional("directory", {
16
+ describe: 'Directory to scaffold into. Use "." for the current directory. Omit to be prompted.',
17
+ type: "string",
18
+ })
19
+ .options({
20
+ template: {
21
+ describe: "Template to use (skips the interactive picker). Run with --list-templates to see available templates.",
22
+ type: "string",
23
+ },
24
+ "list-templates": {
25
+ alias: ["list", "ls"],
26
+ describe: "List available templates and exit.",
27
+ type: "boolean",
28
+ default: false,
29
+ },
30
+ force: {
31
+ describe: "Scaffold into the target directory even if it is not empty (colliding files are overwritten).",
32
+ type: "boolean",
33
+ default: false,
34
+ },
35
+ agent: {
36
+ describe: "Emit a JSON state-machine response designed for AI agents instead of prompting. The output is a single JSON object with a discriminated `status` field describing the next step.",
37
+ type: "boolean",
38
+ default: false,
39
+ },
40
+ default: {
41
+ alias: "y",
42
+ describe: "Quick start: scaffold the default template (or --template) and run the usual setup (install dependencies, git init) without prompting. Linking is left to you since it needs a project choice.",
43
+ type: "boolean",
44
+ default: false,
45
+ },
46
+ install: {
47
+ describe: "Install dependencies after scaffolding. In interactive mode this is offered as a prompt; use --no-install to skip without being asked.",
48
+ type: "boolean",
49
+ default: true,
50
+ },
51
+ git: {
52
+ describe: "Initialize a git repository after scaffolding. In interactive mode this is offered as a prompt; use --no-git to skip without being asked.",
53
+ type: "boolean",
54
+ default: true,
55
+ },
56
+ link: {
57
+ describe: "Run `neon link` in the scaffolded directory after installing. In interactive mode this is offered as a prompt; use --no-link to skip without being asked.",
58
+ type: "boolean",
59
+ default: true,
60
+ },
61
+ })
62
+ .example("$0 bootstrap my-app", "Create ./my-app from an interactively chosen template")
63
+ .example("$0 bootstrap . --template hono", "Scaffold the Hono template into the current directory")
64
+ .example("$0 bootstrap my-app --default", "Quick start: scaffold the default template and run setup without prompting")
65
+ .example("$0 bootstrap my-app --template hono --agent", "Scaffold without prompting and emit the JSON state machine for AI agents")
66
+ .strict();
67
+ export const handler = async (props) => {
68
+ if (props.listTemplates) {
69
+ const templates = await fetchTemplates();
70
+ for (const t of templates) {
71
+ const services = t.services && t.services.length > 0
72
+ ? ` [${t.services.join(" · ")}]`
73
+ : "";
74
+ process.stdout.write(`${t.id} — ${t.description}${services}\n`);
75
+ }
76
+ return;
77
+ }
78
+ if (props.agent) {
79
+ await runAgentSafely(props);
80
+ return;
81
+ }
82
+ const templates = await resolveTemplateList(props);
83
+ // --default is a non-interactive quick start: it fills in the template and
84
+ // directory and runs setup without asking, so it must not fall into the
85
+ // prompt path even on a TTY.
86
+ const interactive = !props.default && Boolean(process.stdout.isTTY) && !isCi();
87
+ const template = await resolveSelectedTemplate(props, interactive, templates);
88
+ const targetDir = await resolveTargetDir(props, interactive, template);
89
+ ensureTargetUsable(targetDir, props.force);
90
+ await scaffold(template, targetDir);
91
+ printScaffolded(template, targetDir);
92
+ await runPostScaffoldSteps(props, targetDir, interactive);
93
+ };
94
+ /**
95
+ * The template list to choose from. When --template is given we try the
96
+ * built-in fallback list first to avoid a network round-trip, only fetching the
97
+ * remote manifest if the id isn't one of the defaults.
98
+ */
99
+ const resolveTemplateList = async (props) => props.template && findTemplate(FALLBACK_TEMPLATES, props.template)
100
+ ? FALLBACK_TEMPLATES
101
+ : fetchTemplates();
102
+ /**
103
+ * The picker label for a template: the title first, then the Neon services it
104
+ * uses as a dim, italic suffix, e.g. "Hono API … Postgres · Functions". The
105
+ * suffix is styled with chalk.dim (and italic) only — never a foreground color —
106
+ * so it survives the cyan/underline `prompts` paints over the focused row: dim
107
+ * and italic reset with their own SGRs, leaving the row's color and underline
108
+ * intact. Descriptions are intentionally omitted to keep the picker uncluttered.
109
+ */
110
+ const formatTemplateTitle = (template) => {
111
+ if (!template.services || template.services.length === 0) {
112
+ return template.title;
113
+ }
114
+ return `${template.title} ${chalk.dim.italic(template.services.join(" · "))}`;
115
+ };
116
+ const resolveSelectedTemplate = async (props, interactive, templates) => {
117
+ if (props.template) {
118
+ const template = findTemplate(templates, props.template);
119
+ if (!template) {
120
+ throw new Error(`Unknown template "${props.template}". Available templates: ${templateIds(templates)}.`);
121
+ }
122
+ return template;
123
+ }
124
+ // --default with no --template falls back to the first (default) template so
125
+ // a bare `neon bootstrap my-app --default` works end to end.
126
+ if (props.default) {
127
+ const fallback = templates[0];
128
+ if (!fallback) {
129
+ throw new Error("No templates available to scaffold from.");
130
+ }
131
+ return fallback;
132
+ }
133
+ if (!interactive) {
134
+ throw new Error(`No template selected. Re-run in an interactive terminal to pick one, or pass --template <id>. Available templates: ${templateIds(templates)}.`);
135
+ }
136
+ const { id } = await prompts({
137
+ onState: onPromptState,
138
+ type: "select",
139
+ name: "id",
140
+ message: "Which template would you like to use?",
141
+ choices: templates.map((template) => ({
142
+ title: formatTemplateTitle(template),
143
+ value: template.id,
144
+ })),
145
+ initial: 0,
146
+ });
147
+ const template = findTemplate(templates, id);
148
+ if (!template) {
149
+ throw new Error("No template selected.");
150
+ }
151
+ return template;
152
+ };
153
+ const resolveTargetDir = async (props, interactive, template) => {
154
+ let dir = props.directory;
155
+ if (dir === undefined) {
156
+ // --default supplies a directory (the template's name) so the quick start
157
+ // needs nothing but a template.
158
+ if (props.default) {
159
+ return resolve(process.cwd(), defaultDirName(template));
160
+ }
161
+ if (!interactive) {
162
+ throw new Error('No target directory given. Pass one, e.g. `neon bootstrap my-app` (or "." for the current directory).');
163
+ }
164
+ const { value } = await prompts({
165
+ onState: onPromptState,
166
+ type: "text",
167
+ name: "value",
168
+ message: "Where should we scaffold your project?",
169
+ initial: defaultDirName(template),
170
+ validate: (input) => input && input.trim().length > 0
171
+ ? true
172
+ : 'Enter a directory (use "." for the current directory).',
173
+ });
174
+ dir = String(value).trim();
175
+ }
176
+ return resolve(process.cwd(), dir === "." ? "" : dir);
177
+ };
178
+ const defaultDirName = (template) => template.source.subdir.split("/").pop() || template.id;
179
+ /**
180
+ * Download and materialize the template into `targetDir`. The actual
181
+ * download/extract/write lives in the shared `neon-init/bootstrap` core
182
+ * (exec-bit and symlink fidelity, graceful symlink fallback); here we just
183
+ * frame it with progress logging. Returns the number of files written.
184
+ */
185
+ const scaffold = async (template, targetDir) => {
186
+ log.info('Fetching template "%s" from GitHub…', template.id);
187
+ const filesWritten = await scaffoldTemplate(template, targetDir, {
188
+ onWarn: (message) => {
189
+ log.warning(message);
190
+ },
191
+ });
192
+ log.info("Scaffolded %d files into %s.", filesWritten, targetDir);
193
+ return filesWritten;
194
+ };
195
+ // ----------------------------------------------------------------------------
196
+ // Post-scaffold steps (install dependencies, git init, link to a Neon project)
197
+ // ----------------------------------------------------------------------------
198
+ /**
199
+ * After a human scaffold, offer the things you almost always do next: install
200
+ * dependencies, initialize a git repo, and link the directory to a Neon
201
+ * project. In an interactive terminal each is a y/n prompt (skippable up front
202
+ * with --no-install / --no-git / --no-link); `--default` runs install + git
203
+ * without asking; otherwise we just print the manual steps so nothing runs
204
+ * behind the user's back. Agent mode never reaches here — it returns these as
205
+ * structured `next_steps` instead (see {@link runAgent}).
206
+ */
207
+ const runPostScaffoldSteps = async (props, targetDir, interactive) => {
208
+ const detected = detectPackageManager();
209
+ if (props.default) {
210
+ await runDefaultSteps(props, targetDir, detected ?? "npm");
211
+ return;
212
+ }
213
+ if (!interactive) {
214
+ printNextSteps(targetDir, detected ?? "npm", {
215
+ installed: false,
216
+ suggestLink: true,
217
+ });
218
+ return;
219
+ }
220
+ // The package manager used for the install (and shown in the closing hint).
221
+ // When we couldn't infer it from the invocation we ask, so a globally
222
+ // installed `neon` doesn't silently force npm on a bun/pnpm user.
223
+ let pm = detected ?? "npm";
224
+ let installed = false;
225
+ if (props.install && (await confirm(installPrompt(detected)))) {
226
+ pm = detected ?? (await selectPackageManager());
227
+ installed = await runCommand(pm, ["install"], targetDir);
228
+ }
229
+ if (props.git &&
230
+ !isGitRepo(targetDir) &&
231
+ (await confirm("Initialize a git repository?"))) {
232
+ await initGitRepo(targetDir);
233
+ }
234
+ // `neon link` pulls env vars, which loads this project's neon.ts — and that
235
+ // evaluation needs the dependencies installed. So when deps weren't installed
236
+ // and the scaffold ships a neon.ts, skip the link prompt (it would just fail)
237
+ // and tell the user how to finish by hand.
238
+ if (props.link) {
239
+ if (!installed && hasNeonConfig(targetDir)) {
240
+ log.info("Skipping the Neon link step: `neon link` reads this project's neon.ts " +
241
+ `to pull env vars, which needs its dependencies. Run \`${pm} install\`, ` +
242
+ "then `neon link`.");
243
+ }
244
+ else if (await confirm("Link this project to a Neon project now? (runs neon link)")) {
245
+ await runNeonLink(props, targetDir);
246
+ // link prints its own summary (and pulls env), so end with just the run hint.
247
+ printNextSteps(targetDir, pm, { installed, suggestLink: false });
248
+ return;
249
+ }
250
+ }
251
+ printNextSteps(targetDir, pm, { installed, suggestLink: true });
252
+ };
253
+ const installPrompt = (detected) => detected
254
+ ? `Install dependencies with ${detected}?`
255
+ : "Install dependencies?";
256
+ /**
257
+ * `--default` quick start: run install + git init without prompting, honoring
258
+ * --no-install / --no-git. Linking is intentionally skipped — it needs an
259
+ * org/project choice we can't make non-interactively — so we point at it in the
260
+ * closing hint instead.
261
+ */
262
+ const runDefaultSteps = async (props, targetDir, pm) => {
263
+ log.info("Quick start (--default): running setup without prompting.");
264
+ let installed = false;
265
+ if (props.install) {
266
+ installed = await runCommand(pm, ["install"], targetDir);
267
+ }
268
+ if (props.git && !isGitRepo(targetDir)) {
269
+ await initGitRepo(targetDir);
270
+ }
271
+ printNextSteps(targetDir, pm, { installed, suggestLink: true });
272
+ };
273
+ const isGitRepo = (dir) => existsSync(join(dir, ".git"));
274
+ // Config filenames the runtime loads (mirrors @neon/config). A scaffold
275
+ // that ships one makes `neon link`'s env pull evaluate it — which needs deps.
276
+ const NEON_CONFIG_FILENAMES = ["neon.ts", "neon.mts", "neon.js", "neon.mjs"];
277
+ const hasNeonConfig = (dir) => NEON_CONFIG_FILENAMES.some((name) => existsSync(join(dir, name)));
278
+ /**
279
+ * Initialize a git repository in the scaffolded directory. Just `git init` — we
280
+ * deliberately don't auto-commit, both to avoid failing on a machine with no
281
+ * git identity configured and to leave the first commit to the user.
282
+ */
283
+ const initGitRepo = async (dir) => {
284
+ await runCommand("git", ["init"], dir);
285
+ };
286
+ const confirm = async (message) => {
287
+ const { value } = await prompts({
288
+ onState: onPromptState,
289
+ type: "confirm",
290
+ name: "value",
291
+ message,
292
+ initial: true,
293
+ });
294
+ return value === true;
295
+ };
296
+ /**
297
+ * Ask which package manager to install with when we couldn't infer one from the
298
+ * invocation. Offers the managers actually installed (npm preselected); with
299
+ * one or none installed there's nothing to choose, so it returns that one (or
300
+ * npm) without prompting. A cancelled prompt falls back to npm.
301
+ */
302
+ const selectPackageManager = async () => {
303
+ const installed = installedPackageManagers();
304
+ if (installed.length <= 1) {
305
+ return installed[0] ?? "npm";
306
+ }
307
+ const { pm } = await prompts({
308
+ onState: onPromptState,
309
+ type: "select",
310
+ name: "pm",
311
+ message: "Which package manager should we use?",
312
+ choices: installed.map((manager) => ({
313
+ title: manager,
314
+ value: manager,
315
+ })),
316
+ initial: Math.max(0, installed.indexOf("npm")),
317
+ });
318
+ return pm ?? "npm";
319
+ };
320
+ /**
321
+ * Re-invoke this same CLI as `neon link` inside the scaffolded directory, so the
322
+ * new project's `.neon` context (and pulled `.env`) land in the right place and
323
+ * link's own interactive picker drives org/project/branch selection. Re-execing
324
+ * (rather than calling the handler in-process) keeps link running with `cwd` set
325
+ * to the target dir, which is where its env pull writes.
326
+ */
327
+ const runNeonLink = async (props, targetDir) => {
328
+ const args = [process.argv[1], "link"];
329
+ if (props.apiKey) {
330
+ args.push("--api-key", props.apiKey);
331
+ }
332
+ args.push("--api-host", props.apiHost, "--output", props.output);
333
+ await runCommand(process.execPath, args, targetDir);
334
+ };
335
+ const printScaffolded = (template, targetDir) => {
336
+ log.info("");
337
+ log.info('Done. Scaffolded "%s" into %s.', template.title, isCurrentDir(targetDir)
338
+ ? "the current directory"
339
+ : displayDir(targetDir));
340
+ };
341
+ /**
342
+ * The closing "Next steps" hint. Skips `cd` for the current directory, omits
343
+ * the install line once deps are in, and only nudges `neon link` when linking
344
+ * wasn't already offered/run — so the user never sees a step they just did.
345
+ */
346
+ const printNextSteps = (targetDir, pm, opts) => {
347
+ log.info("");
348
+ log.info("Next steps:");
349
+ if (!isCurrentDir(targetDir)) {
350
+ log.info(" cd %s", displayDir(targetDir));
351
+ }
352
+ if (!opts.installed) {
353
+ log.info(" %s install", pm);
354
+ }
355
+ if (opts.suggestLink) {
356
+ log.info(" neon link");
357
+ }
358
+ log.info(" See the README to run it.");
359
+ log.info("");
360
+ };
361
+ const runAgentSafely = async (props) => {
362
+ try {
363
+ await runAgent(props);
364
+ }
365
+ catch (err) {
366
+ emitAgent(toAgentError(err));
367
+ process.exit(1);
368
+ }
369
+ };
370
+ /**
371
+ * The `--agent` flow: resolve what the flags determine and emit one JSON object
372
+ * describing either the next input needed (`needs_template` / `needs_directory`)
373
+ * or the terminal result (`scaffolded`). Unlike interactive mode it never
374
+ * prompts and never runs install/git/link itself — those come back as structured
375
+ * `next_steps` so the agent can confirm with the user and run them (the link
376
+ * step chains into `neon link --agent`).
377
+ */
378
+ const runAgent = async (props) => {
379
+ if (!props.template) {
380
+ const templates = await fetchTemplates();
381
+ emitAgent({
382
+ status: "needs_template",
383
+ instruction: `Ask the user which template to scaffold, then re-run the next_command_template with the chosen --template value${props.directory ? "" : " and a target directory"}.`,
384
+ options: templates.map((template) => ({
385
+ id: template.id,
386
+ title: template.title,
387
+ description: template.description,
388
+ ...(template.services ? { services: template.services } : {}),
389
+ })),
390
+ next_command_template: `neon bootstrap --agent ${props.directory ? shellArg(props.directory) : "<directory>"} --template <template_id>`,
391
+ });
392
+ return;
393
+ }
394
+ const templates = await resolveTemplateList(props);
395
+ const template = findTemplate(templates, props.template);
396
+ if (!template) {
397
+ throw new BootstrapInputError(`Unknown template "${props.template}". Available templates: ${templateIds(templates)}.`, "UNKNOWN_TEMPLATE");
398
+ }
399
+ if (props.directory === undefined) {
400
+ emitAgent({
401
+ status: "needs_directory",
402
+ instruction: 'Ask the user which directory to scaffold into (use "." for the current directory), then re-run the next_command_template with it.',
403
+ next_command_template: `neon bootstrap --agent <directory> --template ${shellArg(template.id)}`,
404
+ });
405
+ return;
406
+ }
407
+ const targetDir = resolve(process.cwd(), props.directory === "." ? "" : props.directory);
408
+ ensureTargetUsable(targetDir, props.force);
409
+ const filesWritten = await scaffold(template, targetDir);
410
+ const dir = displayDir(targetDir);
411
+ const runIn = isCurrentDir(targetDir) ? "" : `cd ${shellArg(dir)} && `;
412
+ emitAgent({
413
+ status: "scaffolded",
414
+ directory: targetDir,
415
+ template: { id: template.id, title: template.title },
416
+ files_written: filesWritten,
417
+ next_steps: [
418
+ {
419
+ action: "install_dependencies",
420
+ instruction: "Ask the user whether to install dependencies, then run this in the project directory.",
421
+ command: `${runIn}npm install`,
422
+ },
423
+ {
424
+ action: "initialize_git",
425
+ instruction: "Ask the user whether to initialize a git repository in the project directory.",
426
+ command: `${runIn}git init`,
427
+ },
428
+ {
429
+ action: "link_neon_project",
430
+ instruction: "Ask the user whether to link the project to a Neon project now. This runs the link state machine — follow its JSON output for the next step.",
431
+ command: `${runIn}neon link --agent`,
432
+ },
433
+ ],
434
+ message: `Scaffolded "${template.title}" (${filesWritten} files) into ${dir}. Offer the next_steps to the user: install dependencies, initialize git, then link a Neon project.`,
435
+ });
436
+ };
437
+ const emitAgent = (response) => {
438
+ process.stdout.write(`${JSON.stringify(response, null, 2)}\n`);
439
+ };
440
+ const toAgentError = (err) => {
441
+ if (err instanceof BootstrapInputError) {
442
+ return { status: "error", code: err.agentCode, message: err.message };
443
+ }
444
+ if (err instanceof Error) {
445
+ return {
446
+ status: "error",
447
+ code: "INTERNAL_ERROR",
448
+ message: err.message,
449
+ };
450
+ }
451
+ return { status: "error", code: "INTERNAL_ERROR", message: String(err) };
452
+ };
453
+ // ----------------------------------------------------------------------------
454
+ // Path display helpers
455
+ // ----------------------------------------------------------------------------
456
+ const isCurrentDir = (targetDir) => relative(process.cwd(), targetDir) === "";
457
+ /**
458
+ * The path to show the user: the bare relative path for the common
459
+ * `bootstrap my-app` case, the absolute path when the target sits outside the
460
+ * cwd (a deep `../../..` is noise), and "." for the current directory.
461
+ */
462
+ const displayDir = (targetDir) => {
463
+ const rel = relative(process.cwd(), targetDir);
464
+ if (rel === "") {
465
+ return ".";
466
+ }
467
+ return rel.startsWith("..") ? targetDir : rel;
468
+ };
469
+ const shellArg = (value) => {
470
+ if (/^[A-Za-z0-9._:/-]+$/.test(value)) {
471
+ return value;
472
+ }
473
+ return `'${value.replace(/'/g, `'\\''`)}'`;
474
+ };
475
+ const onPromptState = (state) => {
476
+ if (state.aborted) {
477
+ process.stdout.write("\x1B[?25h");
478
+ process.stdout.write("\n");
479
+ process.exit(1);
480
+ }
481
+ };