@salesforce/ui-bundle-template-base-sfdx-project 11.12.1 → 11.13.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/CHANGELOG.md CHANGED
@@ -3,6 +3,24 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [11.13.0](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.12.2...v11.13.0) (2026-07-09)
7
+
8
+
9
+ ### Features
10
+
11
+ * **org-setup:** @W-23043735@ org-setup.mjs UX enhancements ([#709](https://github.com/salesforce-experience-platform-emu/webapps/issues/709)) ([ad7f480](https://github.com/salesforce-experience-platform-emu/webapps/commit/ad7f480232a363a6f6dfd9df13bce6e32e24ac46))
12
+
13
+
14
+
15
+ ## [11.12.2](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.12.1...v11.12.2) (2026-07-09)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **template:** harden org-setup.mjs XML editing + temp-file/lock hygiene (W-23043734) ([#704](https://github.com/salesforce-experience-platform-emu/webapps/issues/704)) ([9dc682e](https://github.com/salesforce-experience-platform-emu/webapps/commit/9dc682efe168c1758a40d677b55d8da83add653e))
21
+
22
+
23
+
6
24
  ## [11.12.1](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.12.0...v11.12.1) (2026-07-08)
7
25
 
8
26
  **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
package/README.md CHANGED
@@ -12,6 +12,55 @@ npm run sf-project-setup
12
12
 
13
13
  This installs dependencies in the UI Bundle, builds it, and starts the Vite dev server. Use this after cloning or extracting the project.
14
14
 
15
+ ## Set up the org
16
+
17
+ `npm run setup` configures a target org from this project in one command: it logs in
18
+ (a required precondition — auto-skipped if the org is already connected), deploys
19
+ metadata, assigns permission sets, imports sample data, refreshes the GraphQL
20
+ schema/types, and builds the UI Bundle. When `--target-org` is omitted it uses your
21
+ default org or, in an interactive terminal, prompts you to pick one.
22
+
23
+ ```bash
24
+ npm run setup -- --target-org <alias> # or omit --target-org to use the default / pick
25
+ ```
26
+
27
+ Setup does **not** start the dev server. Once the org is set up, use `dev:preview` to
28
+ refresh the GraphQL types against the org and launch the Vite dev server on its own:
29
+
30
+ ```bash
31
+ npm run dev:preview
32
+ ```
33
+
34
+ ### Setup configuration (`scripts/org-setup.config.json`)
35
+
36
+ `org-setup.config.json` controls which steps run and how. Every top-level section is
37
+ optional; an absent section hides its step. It is validated against a shared schema
38
+ at build/CI time and again at the start of every `npm run setup`, so a malformed
39
+ config fails fast rather than misbehaving.
40
+
41
+ ```jsonc
42
+ {
43
+ "permsetAssignments": {
44
+ "assignments": {
45
+ "My_Access": { "assignee": "currentUser" }
46
+ }
47
+ },
48
+ "role": { "assignee": "currentUser", "roleName": "Admin" },
49
+ "selfRegistration": {
50
+ "selfRegProfile": "My Prospect Profile",
51
+ "accountName": "My Self-Registration"
52
+ }
53
+ }
54
+ ```
55
+
56
+ When a `selfRegistration` section is present, setup runs a **license pre-check**
57
+ before configuring self-registration: it derives the required `UserLicense` from the
58
+ configured `selfRegProfile` (matched on the stable `LicenseDefinitionKey`, not the
59
+ display name) and, if the org lacks that license or has no available seats, **warns
60
+ and skips** self-registration instead of reporting success — so prospect login can't
61
+ silently fail on an under-provisioned org. No separate license field is configured;
62
+ the requirement always follows the profile the flow assigns.
63
+
15
64
  ## How Do You Plan to Deploy Your Changes?
16
65
 
17
66
  Do you want to deploy a set of changes, or create a self-contained application? Choose a [development model](https://developer.salesforce.com/tools/vscode/en/user-guide/development-models).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salesforce/ui-bundle-template-base-sfdx-project",
3
- "version": "11.12.1",
3
+ "version": "11.13.0",
4
4
  "description": "Base SFDX project template",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "publishConfig": {
@@ -21,9 +21,11 @@
21
21
  "prettier": "prettier --write \"**/*.{cls,cmp,component,css,html,js,json,md,page,trigger,xml,yaml,yml}\"",
22
22
  "prettier:verify": "prettier --check \"**/*.{cls,cmp,component,css,html,js,json,md,page,trigger,xml,yaml,yml}\"",
23
23
  "precommit": "lint-staged",
24
- "setup": "node scripts/org-setup.mjs"
24
+ "setup": "node scripts/org-setup.mjs",
25
+ "dev:preview": "node scripts/org-setup-dev.mjs"
25
26
  },
26
27
  "dependencies": {
28
+ "fast-xml-parser": "^5.9.3",
27
29
  "zod": "^3.24.1"
28
30
  },
29
31
  "devDependencies": {
@@ -50,6 +50,13 @@ export const ConfigSchema = z
50
50
  // No siteName: the site is derived from the single
51
51
  // networks/<siteName>.network-meta.xml the app ships (see spec §5.2),
52
52
  // exactly like the guestUser permset path.
53
+ //
54
+ // selfRegProfile also drives the M1 license pre-check (W-23043735):
55
+ // setup derives the required UserLicense from this profile
56
+ // (Profile.UserLicense, matched on the stable LicenseDefinitionKey) and
57
+ // warns + skips self-registration when the org lacks it or has no seats.
58
+ // No separate license field is declared — the requirement can't drift
59
+ // from the profile the flow actually assigns.
53
60
  selfRegProfile: z.string().min(1),
54
61
  accountName: z.string().min(1),
55
62
  })
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Dev preview: refresh the GraphQL schema/types against a target org, then launch
4
+ * the Vite dev server (spec §5.5, M4). This is the step that used to be the final
5
+ * `dev` stage of org-setup.mjs — extracted here so `npm run setup` terminates
6
+ * cleanly after graphql, and the long-lived dev server is an explicit, separate
7
+ * `npm run dev:preview`.
8
+ *
9
+ * Unlike setup, this does NOT log in or deploy — it assumes the org is already
10
+ * set up. It shares org/bundle resolution and the process runner with org-setup
11
+ * via org-setup-utils.mjs.
12
+ *
13
+ * Usage:
14
+ * npm run dev:preview # prompt to pick an org + bundle
15
+ * npm run dev:preview -- --target-org myorg
16
+ * npm run dev:preview -- --target-org myorg --ui-bundle-name my-app
17
+ *
18
+ * Flow (in order):
19
+ * 1. resolve target org (explicit --target-org, else prompt / default org)
20
+ * 2. resolve UI bundle (explicit --ui-bundle-name, else picker / warning)
21
+ * 3. npm install (in the UI bundle)
22
+ * 4. npm run graphql:schema (SF_TARGET_ORG=<org>) — introspect the live schema
23
+ * 5. npm run graphql:codegen — regenerate typed operations
24
+ * 6. npm run dev (blocking, Ctrl+C to stop)
25
+ */
26
+
27
+ import { resolve, dirname } from 'node:path';
28
+ import { fileURLToPath } from 'node:url';
29
+
30
+ import { run, resolveSfdxSource, discoverUIBundleDir, resolveTargetOrg } from './org-setup-utils.mjs';
31
+
32
+ const __dirname = dirname(fileURLToPath(import.meta.url));
33
+ const ROOT = resolve(__dirname, '..');
34
+
35
+ function parseArgs() {
36
+ const args = process.argv.slice(2);
37
+ let targetOrg = null;
38
+ let uiBundleName = null;
39
+ for (let i = 0; i < args.length; i++) {
40
+ if (args[i] === '--target-org' && args[i + 1]) {
41
+ targetOrg = args[++i];
42
+ } else if (args[i] === '--ui-bundle-name' && args[i + 1]) {
43
+ uiBundleName = args[++i];
44
+ } else if (args[i] === '--help' || args[i] === '-h') {
45
+ console.log(`
46
+ Dev preview — refresh GraphQL types then launch the Vite dev server
47
+
48
+ Usage:
49
+ npm run dev:preview -- [--target-org <alias>] [--ui-bundle-name <name>]
50
+
51
+ Options:
52
+ --target-org <alias> Target Salesforce org alias. If omitted, you are prompted
53
+ to pick from authenticated orgs (or the default org is used).
54
+ --ui-bundle-name <name> UI bundle folder under uiBundles/ (default: auto-detect / prompt)
55
+ -h, --help Show this help
56
+ `);
57
+ process.exit(0);
58
+ }
59
+ }
60
+ return { targetOrg, uiBundleName };
61
+ }
62
+
63
+ async function main() {
64
+ const parsed = parseArgs();
65
+
66
+ const targetOrg = await resolveTargetOrg(parsed);
67
+ const uiBundlesDir = resolve(resolveSfdxSource(ROOT), 'uiBundles');
68
+ const uiBundleDir = await discoverUIBundleDir(uiBundlesDir, parsed.uiBundleName);
69
+
70
+ console.log('Dev preview — target org:', targetOrg, '| UI bundle:', uiBundleDir);
71
+
72
+ run('UI Bundle npm install', 'npm', ['install'], { cwd: uiBundleDir });
73
+ run('GraphQL schema (introspect)', 'npm', ['run', 'graphql:schema'], {
74
+ cwd: uiBundleDir,
75
+ env: { ...process.env, SF_TARGET_ORG: targetOrg },
76
+ });
77
+ run('GraphQL codegen', 'npm', ['run', 'graphql:codegen'], { cwd: uiBundleDir });
78
+
79
+ console.log('\n--- Launching dev server (Ctrl+C to stop) ---\n');
80
+ const devResult = run('Dev server', 'npm', ['run', 'dev'], { cwd: uiBundleDir, optional: true });
81
+ process.exit(devResult.status ?? 0);
82
+ }
83
+
84
+ main().catch((err) => {
85
+ console.error(err);
86
+ process.exit(1);
87
+ });
@@ -0,0 +1,369 @@
1
+ /**
2
+ * Shared helpers for the org-setup scripts (W-23043735, spec §5.2/§5.6/Q9).
3
+ *
4
+ * Factored out of org-setup.mjs so BOTH `org-setup.mjs` and `org-setup-dev.mjs` import the
5
+ * same primitives instead of duplicating them:
6
+ * - process runners (`run`, `runAsync`, `spawnAsync`)
7
+ * - SFDX path + UI-bundle discovery (`resolveSfdxSource`, `discoverAllUIBundleDirs`,
8
+ * `discoverUIBundleDir` — with the multi-bundle acknowledgment of §5.1 item 2)
9
+ * - the interactive `--target-org` fallback (`resolveTargetOrg`) and its
10
+ * single-select picker (`promptSelect`)
11
+ * - pure, unit-testable logic for the license gate, SOQL-name validation, org-list
12
+ * parsing, and the non-TTY multi-bundle warning
13
+ *
14
+ * IMPORTANT: this module is side-effect-free at import time — no top-level
15
+ * readFileSync / process.exit / CLI run — so it can be imported by tests and by
16
+ * org-setup-dev.mjs without triggering org-setup's main(). All I/O happens inside the
17
+ * exported functions, only when they are called. Errors are plain `Error`s (not
18
+ * org-setup's StepError) to avoid an import cycle; runStep handles both alike.
19
+ */
20
+
21
+ import { spawnSync } from 'node:child_process';
22
+ import { readdirSync, existsSync, readFileSync } from 'node:fs';
23
+ import { resolve } from 'node:path';
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Pure logic (no I/O) — unit-testable in isolation.
27
+ // ---------------------------------------------------------------------------
28
+
29
+ /**
30
+ * Validate that a profile name is safe to interpolate into a SOQL `WHERE Name =
31
+ * '<name>'` clause (spec §5.3, Q10 — validate-and-fail, NOT an escaper). The
32
+ * `selfRegProfile` is developer-authored config the app ships, and license /
33
+ * profile names are not expected to contain special characters, so a `'`, `\`,
34
+ * or control char is treated as a config mistake to surface loudly rather than a
35
+ * value to silently escape. Returns the name unchanged when valid; throws a
36
+ * clear config error otherwise. AC-8.
37
+ */
38
+ export function validateProfileNameForSoql(name) {
39
+ const s = String(name);
40
+ // SOQL string delimiter (') and escape char (\) would break/inject the query;
41
+ // control chars (C0 + DEL) have no legitimate place in a profile name.
42
+ if (/['\\]/.test(s) || /[\x00-\x1f\x7f]/.test(s)) {
43
+ throw new Error(
44
+ `selfRegProfile name "${name}" contains an unsupported character ` +
45
+ `(quotes, backslashes, and control characters are not allowed). ` +
46
+ `Fix the profile name in org-setup.config.json.`,
47
+ );
48
+ }
49
+ return s;
50
+ }
51
+
52
+ /**
53
+ * Decide whether the self-reg profile's UserLicense is satisfied, from the rows
54
+ * a `SELECT UserLicense.LicenseDefinitionKey, UserLicense.Name, UserLicense.Status,
55
+ * UserLicense.TotalLicenses, UserLicense.UsedLicenses FROM Profile WHERE Name = '…'`
56
+ * query returns (spec §5.3). The seat math MUST be done here in JS — SOQL cannot
57
+ * compare two fields (Q3, verified live). Matches/report on the stable
58
+ * `LicenseDefinitionKey`, never the display Name (AC-2b).
59
+ *
60
+ * satisfied ⇔ Status === 'Active' && (total === -1 [unlimited sentinel] || total - used > 0).
61
+ * 0 rows / null UserLicense ⇒ not satisfied, with a reason naming the profile.
62
+ *
63
+ * @returns {{ satisfied: boolean, reason: string|null, license: {key,label,status,total,used}|null }}
64
+ */
65
+ export function evaluateLicenseRows(rows, profileName) {
66
+ const lic = Array.isArray(rows) ? rows[0]?.UserLicense : null;
67
+ if (!lic) {
68
+ return {
69
+ satisfied: false,
70
+ reason: `no UserLicense found for profile "${profileName}" — the profile is missing in the org or its name is misspelled`,
71
+ license: null,
72
+ };
73
+ }
74
+ const key = lic.LicenseDefinitionKey ?? null;
75
+ const label = lic.Name ?? key ?? 'unknown license';
76
+ const total = Number(lic.TotalLicenses);
77
+ const used = Number(lic.UsedLicenses);
78
+ const license = { key, label, status: lic.Status, total, used };
79
+
80
+ if (lic.Status !== 'Active') {
81
+ return { satisfied: false, reason: `license ${label} (${key}) is not Active (Status=${lic.Status})`, license };
82
+ }
83
+ // Seat counts should always be integers in practice, but guard against a
84
+ // missing/non-numeric field so the skip reason stays legible (not "NaN/NaN").
85
+ if (!Number.isFinite(total) || !Number.isFinite(used)) {
86
+ return { satisfied: false, reason: `could not read seat counts for license ${label} (${key})`, license };
87
+ }
88
+ // -1 is the documented "unlimited" sentinel (defensive — unverified live, §5.3).
89
+ if (total === -1 || total - used > 0) {
90
+ return { satisfied: true, reason: null, license };
91
+ }
92
+ return {
93
+ satisfied: false,
94
+ reason: `license ${label} (${key}) has no available seats (${used}/${total} used)`,
95
+ license,
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Parse `sf org list --json` defensively into a flat org list + the default org
101
+ * (spec §5.1 item 3; mirrors isOrgConnected's try/catch tolerance). Collects
102
+ * every array under `result` (nonScratchOrgs, scratchOrgs, sandboxes, devHubs, …)
103
+ * so the picker sees all authenticated orgs; the default is the entry marked
104
+ * `isDefaultUsername`. Malformed / unexpected JSON ⇒ empty result (caller then
105
+ * falls back to the clear error).
106
+ *
107
+ * @returns {{ orgs: Array<{alias:string|null, username:string, isDefault:boolean}>, defaultOrg: string|null }}
108
+ */
109
+ export function parseOrgList(jsonText) {
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(jsonText);
113
+ } catch {
114
+ return { orgs: [], defaultOrg: null };
115
+ }
116
+ const result = parsed?.result;
117
+ if (!result || typeof result !== 'object') return { orgs: [], defaultOrg: null };
118
+
119
+ const orgs = [];
120
+ const seen = new Set();
121
+ for (const val of Object.values(result)) {
122
+ if (!Array.isArray(val)) continue;
123
+ for (const entry of val) {
124
+ if (!entry || typeof entry !== 'object' || !entry.username) continue;
125
+ if (seen.has(entry.username)) continue;
126
+ seen.add(entry.username);
127
+ orgs.push({
128
+ alias: entry.alias ?? null,
129
+ username: entry.username,
130
+ isDefault: entry.isDefaultUsername === true,
131
+ });
132
+ }
133
+ }
134
+ const def = orgs.find((o) => o.isDefault);
135
+ return { orgs, defaultOrg: def ? (def.alias ?? def.username) : null };
136
+ }
137
+
138
+ /**
139
+ * Multi-line warning for the non-TTY multi-bundle case (spec §5.1 item 2, AC-4b):
140
+ * there is nothing to interactively acknowledge, so keep the deterministic
141
+ * `all[0]` pick but never do it silently — name every bundle, the chosen one, and
142
+ * the `--ui-bundle-name` remedy.
143
+ */
144
+ export function buildMultiBundleWarning(allBundleNames, chosen) {
145
+ return [
146
+ `⚠ Multiple UI bundles found under uiBundles/ (${allBundleNames.length}):`,
147
+ ...allBundleNames.map((n) => ` - ${n}${n === chosen ? ' ← using this one' : ''}`),
148
+ ` Using "${chosen}" (first alphabetically). To deploy a different bundle, re-run with:`,
149
+ ` --ui-bundle-name <name>`,
150
+ ].join('\n');
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Process runner (moved from org-setup.mjs; plain Error to avoid an import cycle).
155
+ // Only the synchronous `run` is shared — org-setup-dev.mjs runs its steps serially. The
156
+ // async spawn variants stay local to org-setup.mjs where the parallel permset
157
+ // path uses them, so this module exposes no caller-less surface.
158
+ // ---------------------------------------------------------------------------
159
+
160
+ export function run(name, cmd, args, opts = {}) {
161
+ const { cwd = process.cwd(), optional = false } = opts;
162
+ console.log('\n---', name, '---');
163
+ const result = spawnSync(cmd, args, {
164
+ cwd,
165
+ stdio: 'inherit',
166
+ shell: true,
167
+ ...(opts.env && { env: opts.env }),
168
+ ...(opts.timeout && { timeout: opts.timeout }),
169
+ });
170
+ if (result.status !== 0 && !optional) {
171
+ throw new Error(`${name} (exit ${result.status ?? 1})`);
172
+ }
173
+ return result;
174
+ }
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // SFDX paths + UI-bundle discovery.
178
+ // ---------------------------------------------------------------------------
179
+
180
+ /**
181
+ * Resolve the first package directory's source root (main/default) from
182
+ * sfdx-project.json under `root`. Exits non-zero with a clear message when the
183
+ * project file or packageDirectories path is missing. Called explicitly by each
184
+ * entry script (not at import) so this module stays side-effect-free.
185
+ */
186
+ export function resolveSfdxSource(root) {
187
+ const sfdxPath = resolve(root, 'sfdx-project.json');
188
+ if (!existsSync(sfdxPath)) {
189
+ console.error('Error: sfdx-project.json not found at project root.');
190
+ process.exit(1);
191
+ }
192
+ const sfdxProject = JSON.parse(readFileSync(sfdxPath, 'utf8'));
193
+ const pkgDir = sfdxProject?.packageDirectories?.[0]?.path;
194
+ if (!pkgDir) {
195
+ console.error('Error: No packageDirectories[].path found in sfdx-project.json.');
196
+ process.exit(1);
197
+ }
198
+ return resolve(root, pkgDir, 'main', 'default');
199
+ }
200
+
201
+ /** Basename of a bundle dir path, cross-platform. */
202
+ function bundleName(dir) {
203
+ return dir.split(/[/\\]/).pop();
204
+ }
205
+
206
+ /**
207
+ * All UI bundle directories under `uiBundlesDir` (alphabetical, hidden dirs
208
+ * excluded). When `uiBundleName` is given, returns just that one (erroring if it
209
+ * doesn't exist). Exits non-zero when the uiBundles dir or a named bundle is
210
+ * missing.
211
+ */
212
+ export function discoverAllUIBundleDirs(uiBundlesDir, uiBundleName) {
213
+ if (!existsSync(uiBundlesDir)) {
214
+ console.error(`Error: uiBundles directory not found: ${uiBundlesDir}`);
215
+ process.exit(1);
216
+ }
217
+ const entries = readdirSync(uiBundlesDir, { withFileTypes: true });
218
+ const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith('.'));
219
+ if (dirs.length === 0) {
220
+ console.error(`Error: No UI bundle folder found under ${uiBundlesDir}`);
221
+ process.exit(1);
222
+ }
223
+ if (uiBundleName) {
224
+ const requested = dirs.find((d) => d.name === uiBundleName);
225
+ if (!requested) {
226
+ console.error(`Error: UI bundle directory not found: ${uiBundleName}`);
227
+ process.exit(1);
228
+ }
229
+ return [resolve(uiBundlesDir, requested.name)];
230
+ }
231
+ return dirs.map((d) => resolve(uiBundlesDir, d.name));
232
+ }
233
+
234
+ /**
235
+ * Resolve the single UI bundle to operate on, with the multi-bundle
236
+ * acknowledgment of spec §5.1 item 2 (Q5). When >1 bundle exists and no
237
+ * `--ui-bundle-name` was given:
238
+ * - TTY: present a single-select picker (all bundles, alphabetical all[0]
239
+ * preselected) — enter accepts all[0], arrows choose another (AC-4).
240
+ * - non-TTY: keep the deterministic all[0] pick but emit the multi-line warning
241
+ * (AC-4b) — never a silent pick.
242
+ * Explicit `--ui-bundle-name` short-circuits both (no prompt, no warning; AC-4c).
243
+ */
244
+ export async function discoverUIBundleDir(uiBundlesDir, uiBundleName) {
245
+ const all = discoverAllUIBundleDirs(uiBundlesDir, uiBundleName);
246
+ if (all.length > 1 && !uiBundleName) {
247
+ const names = all.map(bundleName);
248
+ if (process.stdin.isTTY) {
249
+ const idx = await promptSelect(names, {
250
+ prompt: 'Multiple UI bundles found — select which one to deploy:',
251
+ preselectedIndex: 0,
252
+ });
253
+ return all[idx];
254
+ }
255
+ console.warn(buildMultiBundleWarning(names, names[0]));
256
+ }
257
+ return all[0];
258
+ }
259
+
260
+ // ---------------------------------------------------------------------------
261
+ // Interactive single-select picker + --target-org fallback.
262
+ // ---------------------------------------------------------------------------
263
+
264
+ /**
265
+ * Interactive single-select: arrow keys navigate, enter confirms. Returns the
266
+ * chosen index. Falls through to `preselectedIndex` immediately when stdin is not
267
+ * a TTY. Built on the same raw-mode scaffolding as promptSteps (org-setup.mjs)
268
+ * but selects exactly one item (spec §5.1 items 2 & 3).
269
+ */
270
+ export function promptSelect(options, { prompt = 'Select an option:', preselectedIndex = 0 } = {}) {
271
+ if (!process.stdin.isTTY || options.length === 0) return Promise.resolve(preselectedIndex);
272
+
273
+ let cursor = Math.min(Math.max(0, preselectedIndex), options.length - 1);
274
+ const RST = '\x1B[0m';
275
+ const CYAN = '\x1B[36m';
276
+ const GREEN = '\x1B[32m';
277
+
278
+ function render() {
279
+ return options.map((label, row) => {
280
+ const ptr = row === cursor ? `${CYAN}❯${RST}` : ' ';
281
+ const chk = row === cursor ? `${GREEN}●${RST}` : '○';
282
+ return `${ptr} ${chk} ${label}`;
283
+ });
284
+ }
285
+
286
+ return new Promise((resolvePromise) => {
287
+ process.stdin.setRawMode(true);
288
+ process.stdin.resume();
289
+ process.stdin.setEncoding('utf8');
290
+ process.stdout.write('\x1B[?25l');
291
+ console.log(`\n${prompt} (↑↓ move, enter confirm):\n`);
292
+ let prevRows = options.length;
293
+ process.stdout.write(render().join('\n') + '\n');
294
+
295
+ function redraw() {
296
+ process.stdout.write(`\x1B[${prevRows}A`);
297
+ const lines = render();
298
+ for (const line of lines) process.stdout.write(`\x1B[2K${line}\n`);
299
+ prevRows = lines.length;
300
+ }
301
+
302
+ process.stdin.on('data', (key) => {
303
+ if (key === '\x03') {
304
+ process.stdout.write('\x1B[?25h\n');
305
+ process.exit(0);
306
+ }
307
+ if (key === '\r' || key === '\n') {
308
+ process.stdout.write('\x1B[?25h');
309
+ process.stdin.setRawMode(false);
310
+ process.stdin.pause();
311
+ process.stdin.removeAllListeners('data');
312
+ console.log();
313
+ resolvePromise(cursor);
314
+ return;
315
+ }
316
+ if (key === '\x1B[A' || key === 'k') {
317
+ cursor = Math.max(0, cursor - 1);
318
+ redraw();
319
+ } else if (key === '\x1B[B' || key === 'j') {
320
+ cursor = Math.min(options.length - 1, cursor + 1);
321
+ redraw();
322
+ }
323
+ });
324
+ });
325
+ }
326
+
327
+ /**
328
+ * Resolve the target org (spec §5.1 item 3, §15). When `--target-org` is supplied
329
+ * it is returned verbatim with NO `sf org list` call (AC-7, byte-for-byte the
330
+ * scripted path). Otherwise discover authenticated orgs via `sf org list --json`
331
+ * and:
332
+ * - TTY: present a picker with the default org at the top and preselected
333
+ * (AC-5); enter selects the default.
334
+ * - non-TTY: use the default org if resolvable, else exit 1 with a clear
335
+ * message (AC-6).
336
+ */
337
+ export async function resolveTargetOrg(parsed) {
338
+ if (parsed.targetOrg) return parsed.targetOrg;
339
+
340
+ const listResult = spawnSync('sf', ['org', 'list', '--json'], {
341
+ encoding: 'utf8',
342
+ shell: true,
343
+ });
344
+ const { orgs, defaultOrg } = parseOrgList(listResult.status === 0 ? listResult.stdout : '');
345
+
346
+ if (process.stdin.isTTY && orgs.length > 0) {
347
+ // Default org first + preselected; the rest keep sf's order.
348
+ const ordered = [...orgs].sort((a, b) => (b.isDefault ? 1 : 0) - (a.isDefault ? 1 : 0));
349
+ const labels = ordered.map((o) => {
350
+ const name = o.alias ?? o.username;
351
+ const suffix = o.alias && o.alias !== o.username ? ` (${o.username})` : '';
352
+ return `${name}${suffix}${o.isDefault ? ' [default]' : ''}`;
353
+ });
354
+ const idx = await promptSelect(labels, { prompt: 'Select the target org:', preselectedIndex: 0 });
355
+ const chosen = ordered[idx];
356
+ return chosen.alias ?? chosen.username;
357
+ }
358
+
359
+ if (defaultOrg) {
360
+ console.log(`No --target-org given; using the default org: ${defaultOrg}`);
361
+ return defaultOrg;
362
+ }
363
+
364
+ console.error(
365
+ 'Error: --target-org <alias> is required. No default org is set and this is not an ' +
366
+ 'interactive terminal. Set a default org (sf config set target-org=<alias>) or pass --target-org.',
367
+ );
368
+ process.exit(1);
369
+ }