@salesforce/webapp-template-app-react-sample-b2e-experimental 1.92.0 → 1.93.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.
@@ -15,9 +15,9 @@
15
15
  "graphql:schema": "node scripts/get-graphql-schema.mjs"
16
16
  },
17
17
  "dependencies": {
18
- "@salesforce/agentforce-conversation-client": "^1.92.0",
19
- "@salesforce/sdk-data": "^1.92.0",
20
- "@salesforce/webapp-experimental": "^1.92.0",
18
+ "@salesforce/agentforce-conversation-client": "^1.93.0",
19
+ "@salesforce/sdk-data": "^1.93.0",
20
+ "@salesforce/webapp-experimental": "^1.93.0",
21
21
  "@tailwindcss/vite": "^4.1.17",
22
22
  "@tanstack/react-form": "^1.28.4",
23
23
  "class-variance-authority": "^0.7.1",
@@ -42,7 +42,7 @@
42
42
  "@graphql-eslint/eslint-plugin": "^4.1.0",
43
43
  "@graphql-tools/utils": "^11.0.0",
44
44
  "@playwright/test": "^1.49.0",
45
- "@salesforce/vite-plugin-webapp-experimental": "^1.92.0",
45
+ "@salesforce/vite-plugin-webapp-experimental": "^1.93.0",
46
46
  "@testing-library/jest-dom": "^6.6.3",
47
47
  "@testing-library/react": "^16.1.0",
48
48
  "@testing-library/user-event": "^14.5.2",
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salesforce/webapp-template-base-sfdx-project-experimental",
3
- "version": "1.92.0",
3
+ "version": "1.93.0",
4
4
  "description": "Base SFDX project template",
5
5
  "private": true,
6
6
  "files": [
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * Usage:
7
7
  * node scripts/prepare-import-unique-fields.js
8
- * node scripts/prepare-import-unique-fields.js --data-dir /path/to/force-app/main/default/data
8
+ * node scripts/prepare-import-unique-fields.js --data-dir /path/to/<sfdx-source>/data
9
9
  *
10
10
  * Expects data dir to contain (optional) JSON files:
11
11
  * Contact.json (Email with unique domain per run, LastName, FirstName, Phone — standard Contact)
@@ -18,8 +18,22 @@
18
18
  const fs = require('fs');
19
19
  const path = require('path');
20
20
 
21
- // When run from project root: scripts/prepare-import-unique-fields.js → data dir under force-app
22
- const DEFAULT_DATA_DIR = path.resolve(__dirname, '..', 'force-app/main/default/data');
21
+ function resolveSfdxSource() {
22
+ const sfdxPath = path.resolve(__dirname, '..', 'sfdx-project.json');
23
+ if (!fs.existsSync(sfdxPath)) {
24
+ console.error('Error: sfdx-project.json not found at project root.');
25
+ process.exit(1);
26
+ }
27
+ const sfdxProject = JSON.parse(fs.readFileSync(sfdxPath, 'utf8'));
28
+ const pkgDir = sfdxProject?.packageDirectories?.[0]?.path;
29
+ if (!pkgDir) {
30
+ console.error('Error: No packageDirectories[].path found in sfdx-project.json.');
31
+ process.exit(1);
32
+ }
33
+ return path.resolve(__dirname, '..', pkgDir, 'main', 'default');
34
+ }
35
+
36
+ const DEFAULT_DATA_DIR = path.resolve(resolveSfdxSource(), 'data');
23
37
 
24
38
  function parseArgs() {
25
39
  const args = process.argv.slice(2);
@@ -4,37 +4,56 @@
4
4
  * Use this script to make setup easier for each app generated from this template.
5
5
  *
6
6
  * Usage:
7
- * node scripts/setup-cli.mjs --target-org <alias> # run all steps
7
+ * node scripts/setup-cli.mjs --target-org <alias> # interactive step picker (all selected)
8
+ * node scripts/setup-cli.mjs --target-org <alias> --yes # skip picker, run all steps
8
9
  * node scripts/setup-cli.mjs --target-org afv5 --skip-login
9
10
  * node scripts/setup-cli.mjs --target-org afv5 --skip-data --skip-webapp-build
10
11
  * node scripts/setup-cli.mjs --target-org myorg --webapp-name my-app
11
12
  *
12
13
  * Steps (in order):
13
14
  * 1. login — sf org login web only if org not already connected (skip with --skip-login)
14
- * 2. deploysf project deploy start --target-org <alias>
15
- * 3. permset — sf org assign permset (skip with --skip-permset; name via --permset-name)
16
- * 4. data prepare unique fields + sf data import tree (skipped if no data dir/plan)
17
- * 5. graphql (in webapp) npm run graphql:schema then npm run graphql:codegen
18
- * 6. webapp — (in webapp) npm install && npm run build
15
+ * 2. webapp(all web apps) npm install && npm run build so dist exists for deploy (skip with --skip-webapp-build)
16
+ * 3. deploy — sf project deploy start --target-org <alias> (requires dist for entity deployment)
17
+ * 4. permset — sf org assign permset (skip with --skip-permset; name via --permset-name)
18
+ * 5. data prepare unique fields + sf data import tree (skipped if no data dir/plan)
19
+ * 6. graphql — (in webapp) npm run graphql:schema then npm run graphql:codegen
19
20
  * 7. dev — (in webapp) npm run dev — launch dev server (skip with --skip-dev)
20
21
  */
21
22
 
22
23
  import { spawnSync } from 'node:child_process';
23
24
  import { resolve, dirname } from 'node:path';
24
25
  import { fileURLToPath } from 'node:url';
25
- import { readdirSync, existsSync } from 'node:fs';
26
+ import { readdirSync, existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
26
27
 
27
28
  const __dirname = dirname(fileURLToPath(import.meta.url));
28
29
  const ROOT = resolve(__dirname, '..');
29
- const WEBAPPLICATIONS_DIR = resolve(ROOT, 'force-app/main/default/webapplications');
30
- const DATA_DIR = resolve(ROOT, 'force-app/main/default/data');
31
- const DATA_PLAN = resolve(ROOT, 'force-app/main/default/data/data-plan.json');
30
+
31
+ function resolveSfdxSource() {
32
+ const sfdxPath = resolve(ROOT, 'sfdx-project.json');
33
+ if (!existsSync(sfdxPath)) {
34
+ console.error('Error: sfdx-project.json not found at project root.');
35
+ process.exit(1);
36
+ }
37
+ const sfdxProject = JSON.parse(readFileSync(sfdxPath, 'utf8'));
38
+ const pkgDir = sfdxProject?.packageDirectories?.[0]?.path;
39
+ if (!pkgDir) {
40
+ console.error('Error: No packageDirectories[].path found in sfdx-project.json.');
41
+ process.exit(1);
42
+ }
43
+ return resolve(ROOT, pkgDir, 'main', 'default');
44
+ }
45
+
46
+ const SFDX_SOURCE = resolveSfdxSource();
47
+ const WEBAPPLICATIONS_DIR = resolve(SFDX_SOURCE, 'webapplications');
48
+ const DATA_DIR = resolve(SFDX_SOURCE, 'data');
49
+ const DATA_PLAN = resolve(SFDX_SOURCE, 'data/data-plan.json');
32
50
 
33
51
  function parseArgs() {
34
52
  const args = process.argv.slice(2);
35
53
  let targetOrg = null;
36
54
  let webappName = null;
37
55
  let permsetName = 'Property_Management_Access';
56
+ let yes = false;
38
57
  const flags = {
39
58
  skipLogin: false,
40
59
  skipDeploy: false,
@@ -58,6 +77,7 @@ function parseArgs() {
58
77
  else if (args[i] === '--skip-graphql') flags.skipGraphql = true;
59
78
  else if (args[i] === '--skip-webapp-build') flags.skipWebappBuild = true;
60
79
  else if (args[i] === '--skip-dev') flags.skipDev = true;
80
+ else if (args[i] === '--yes' || args[i] === '-y') yes = true;
61
81
  else if (args[i] === '--help' || args[i] === '-h') {
62
82
  console.log(`
63
83
  Setup CLI — one-command setup for apps in this project
@@ -78,6 +98,7 @@ Options:
78
98
  --skip-graphql Do not fetch schema or run GraphQL codegen
79
99
  --skip-webapp-build Do not npm install / build the web application
80
100
  --skip-dev Do not launch the dev server at the end
101
+ -y, --yes Skip interactive step picker; run all enabled steps immediately
81
102
  -h, --help Show this help
82
103
  `);
83
104
  process.exit(0);
@@ -87,18 +108,10 @@ Options:
87
108
  console.error('Error: --target-org <alias> is required.');
88
109
  process.exit(1);
89
110
  }
90
- return { targetOrg, webappName, permsetName, ...flags };
111
+ return { targetOrg, webappName, permsetName, yes, ...flags };
91
112
  }
92
113
 
93
- function discoverWebappDir(webappName) {
94
- if (webappName) {
95
- const dir = resolve(WEBAPPLICATIONS_DIR, webappName);
96
- if (!existsSync(dir)) {
97
- console.error(`Error: Web app directory not found: ${dir}`);
98
- process.exit(1);
99
- }
100
- return dir;
101
- }
114
+ function discoverAllWebappDirs(webappName) {
102
115
  if (!existsSync(WEBAPPLICATIONS_DIR)) {
103
116
  console.error(`Error: webapplications directory not found: ${WEBAPPLICATIONS_DIR}`);
104
117
  process.exit(1);
@@ -109,10 +122,23 @@ function discoverWebappDir(webappName) {
109
122
  console.error(`Error: No web app folder found under ${WEBAPPLICATIONS_DIR}`);
110
123
  process.exit(1);
111
124
  }
112
- if (dirs.length > 1) {
113
- console.log(`Multiple web apps found; using first: ${dirs[0].name}`);
125
+ if (webappName) {
126
+ const requested = dirs.find((d) => d.name === webappName);
127
+ if (!requested) {
128
+ console.error(`Error: Web app directory not found: ${webappName}`);
129
+ process.exit(1);
130
+ }
131
+ return [resolve(WEBAPPLICATIONS_DIR, requested.name)];
132
+ }
133
+ return dirs.map((d) => resolve(WEBAPPLICATIONS_DIR, d.name));
134
+ }
135
+
136
+ function discoverWebappDir(webappName) {
137
+ const all = discoverAllWebappDirs(webappName);
138
+ if (all.length > 1 && !webappName) {
139
+ console.log(`Multiple web apps found; using first: ${all[0].split(/[/\\]/).pop()}`);
114
140
  }
115
- return resolve(WEBAPPLICATIONS_DIR, dirs[0].name);
141
+ return all[0];
116
142
  }
117
143
 
118
144
  function isOrgConnected(targetOrg) {
@@ -124,6 +150,117 @@ function isOrgConnected(targetOrg) {
124
150
  return result.status === 0;
125
151
  }
126
152
 
153
+ function apexLiteral(value) {
154
+ if (value === null || value === undefined) return 'null';
155
+ if (typeof value === 'boolean') return String(value);
156
+ if (typeof value === 'number') return String(value);
157
+ const s = String(value);
158
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return `Date.valueOf('${s}')`;
159
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(s)) {
160
+ const dt = s.replace('T', ' ').replace(/\.\d+/, '').replace('Z', '');
161
+ return `DateTime.valueOf('${dt}')`;
162
+ }
163
+ return "'" + s.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'";
164
+ }
165
+
166
+ function buildApexInsert(sobject, records, refIds) {
167
+ const lines = [
168
+ 'Database.DMLOptions dmlOpts = new Database.DMLOptions();',
169
+ 'dmlOpts.DuplicateRuleHeader.allowSave = true;',
170
+ `List<${sobject}> recs = new List<${sobject}>();`,
171
+ ];
172
+ for (const rec of records) {
173
+ lines.push(`{ ${sobject} r = new ${sobject}();`);
174
+ for (const [key, val] of Object.entries(rec)) {
175
+ if (key === 'attributes') continue;
176
+ lines.push(`r.put('${key}', ${apexLiteral(val)});`);
177
+ }
178
+ lines.push('recs.add(r); }');
179
+ }
180
+ lines.push('Database.SaveResult[] results = Database.insert(recs, dmlOpts);');
181
+ const refArray = refIds.map((r) => `'${r}'`).join(',');
182
+ lines.push(`String[] refs = new String[]{${refArray}};`);
183
+ lines.push('for (Integer i = 0; i < results.size(); i++) {');
184
+ lines.push(" if (results[i].isSuccess()) System.debug('REF:' + refs[i] + ':' + results[i].getId());");
185
+ lines.push(" else System.debug('ERR:' + refs[i] + ':' + results[i].getErrors()[0].getMessage());");
186
+ lines.push('}');
187
+ return lines.join('\n');
188
+ }
189
+
190
+ /**
191
+ * Interactive multi-select: arrow keys navigate, space toggles, 'a' toggles all, enter confirms.
192
+ * Returns a boolean[] matching the input order. Falls through immediately when stdin is not a TTY.
193
+ */
194
+ async function promptSteps(steps) {
195
+ if (!process.stdin.isTTY) return steps.map((s) => s.enabled);
196
+
197
+ const selected = steps.map((s) => s.enabled);
198
+ let cursor = 0;
199
+ const DIM = '\x1B[2m';
200
+ const RST = '\x1B[0m';
201
+ const CYAN = '\x1B[36m';
202
+ const GREEN = '\x1B[32m';
203
+
204
+ function render() {
205
+ return steps.map((s, i) => {
206
+ const ptr = i === cursor ? `${CYAN}❯${RST}` : ' ';
207
+ if (!s.available) return `${ptr} ${DIM}○ ${s.label} (n/a)${RST}`;
208
+ const chk = selected[i] ? `${GREEN}●${RST}` : '○';
209
+ return `${ptr} ${chk} ${s.label}`;
210
+ });
211
+ }
212
+
213
+ return new Promise((resolve) => {
214
+ process.stdin.setRawMode(true);
215
+ process.stdin.resume();
216
+ process.stdin.setEncoding('utf8');
217
+ process.stdout.write('\x1B[?25l');
218
+ console.log('\nSelect steps (↑↓ move, space toggle, a all, enter confirm):\n');
219
+ process.stdout.write(render().join('\n') + '\n');
220
+
221
+ function redraw() {
222
+ process.stdout.write(`\x1B[${steps.length}A`);
223
+ for (const line of render()) process.stdout.write(`\x1B[2K${line}\n`);
224
+ }
225
+
226
+ process.stdin.on('data', (key) => {
227
+ if (key === '\x03') {
228
+ process.stdout.write('\x1B[?25h\n');
229
+ process.exit(0);
230
+ }
231
+ if (key === '\r' || key === '\n') {
232
+ process.stdout.write('\x1B[?25h');
233
+ process.stdin.setRawMode(false);
234
+ process.stdin.pause();
235
+ process.stdin.removeAllListeners('data');
236
+ console.log();
237
+ resolve(selected);
238
+ return;
239
+ }
240
+ if (key === ' ') {
241
+ if (steps[cursor].available) selected[cursor] = !selected[cursor];
242
+ redraw();
243
+ return;
244
+ }
245
+ if (key === 'a') {
246
+ const allOn = steps.every((s, i) => !s.available || selected[i]);
247
+ for (let i = 0; i < steps.length; i++) {
248
+ if (steps[i].available) selected[i] = !allOn;
249
+ }
250
+ redraw();
251
+ return;
252
+ }
253
+ if (key === '\x1B[A' || key === 'k') {
254
+ cursor = Math.max(0, cursor - 1);
255
+ redraw();
256
+ } else if (key === '\x1B[B' || key === 'j') {
257
+ cursor = Math.min(steps.length - 1, cursor + 1);
258
+ redraw();
259
+ }
260
+ });
261
+ });
262
+ }
263
+
127
264
  function run(name, cmd, args, opts = {}) {
128
265
  const { cwd = ROOT, optional = false } = opts;
129
266
  console.log('\n---', name, '---');
@@ -140,25 +277,52 @@ function run(name, cmd, args, opts = {}) {
140
277
  return result;
141
278
  }
142
279
 
143
- function main() {
280
+ async function main() {
144
281
  const {
145
282
  targetOrg,
146
283
  webappName,
147
284
  permsetName,
148
- skipLogin,
149
- skipDeploy,
150
- skipPermset,
151
- skipData,
152
- skipGraphql,
153
- skipWebappBuild,
154
- skipDev,
285
+ yes,
286
+ skipLogin: argSkipLogin,
287
+ skipDeploy: argSkipDeploy,
288
+ skipPermset: argSkipPermset,
289
+ skipData: argSkipData,
290
+ skipGraphql: argSkipGraphql,
291
+ skipWebappBuild: argSkipWebappBuild,
292
+ skipDev: argSkipDev,
155
293
  } = parseArgs();
156
294
 
157
- const webappDir = discoverWebappDir(webappName);
158
295
  const hasDataPlan = existsSync(DATA_PLAN) && existsSync(DATA_DIR);
159
- const doData = !skipData && hasDataPlan;
160
296
 
161
- console.log('Setup target org:', targetOrg, '| web app:', webappDir);
297
+ const stepDefs = [
298
+ { key: 'login', label: 'Login — org authentication', enabled: !argSkipLogin, available: true },
299
+ { key: 'webappBuild', label: 'Webapp Build — npm install + build (pre-deploy)', enabled: !argSkipWebappBuild, available: true },
300
+ { key: 'deploy', label: 'Deploy — sf project deploy start', enabled: !argSkipDeploy, available: true },
301
+ { key: 'permset', label: `Permset — assign ${permsetName}`, enabled: !argSkipPermset, available: true },
302
+ { key: 'data', label: 'Data — delete + import records via Apex', enabled: !argSkipData && hasDataPlan, available: hasDataPlan },
303
+ { key: 'graphql', label: 'GraphQL — schema introspect + codegen', enabled: !argSkipGraphql, available: true },
304
+ { key: 'dev', label: 'Dev — launch dev server', enabled: !argSkipDev, available: true },
305
+ ];
306
+
307
+ const selections = yes ? stepDefs.map((s) => s.enabled) : await promptSteps(stepDefs);
308
+ const on = {};
309
+ stepDefs.forEach((s, i) => {
310
+ on[s.key] = selections[i];
311
+ });
312
+
313
+ const skipLogin = !on.login;
314
+ const skipWebappBuild = !on.webappBuild;
315
+ const skipDeploy = !on.deploy;
316
+ const skipPermset = !on.permset;
317
+ const skipData = !on.data;
318
+ const skipGraphql = !on.graphql;
319
+ const skipDev = !on.dev;
320
+
321
+ const needsWebapp = !skipWebappBuild || !skipGraphql || !skipDev;
322
+ const webappDir = needsWebapp ? discoverWebappDir(webappName) : null;
323
+ const doData = !skipData;
324
+
325
+ console.log('Setup — target org:', targetOrg, '| web app:', webappDir ?? '(none)');
162
326
  console.log(
163
327
  'Steps: login=%s deploy=%s permset=%s data=%s graphql=%s webapp=%s dev=%s',
164
328
  !skipLogin,
@@ -169,11 +333,6 @@ function main() {
169
333
  !skipWebappBuild,
170
334
  !skipDev
171
335
  );
172
- if (skipData && hasDataPlan) {
173
- console.log('(Data dir present; use without --skip-data to run data import.)');
174
- } else if (!hasDataPlan && !skipData) {
175
- console.log('(No data plan found; skipping data step.)');
176
- }
177
336
 
178
337
  if (!skipLogin) {
179
338
  if (isOrgConnected(targetOrg)) {
@@ -184,6 +343,16 @@ function main() {
184
343
  }
185
344
  }
186
345
 
346
+ // Build all web apps before deploy so dist exists for entity deployment
347
+ if (!skipDeploy && !skipWebappBuild) {
348
+ const allWebappDirs = discoverAllWebappDirs(webappName);
349
+ for (const dir of allWebappDirs) {
350
+ const name = dir.split(/[/\\]/).pop();
351
+ run(`Web app install (${name})`, 'npm', ['install'], { cwd: dir });
352
+ run(`Web app build (${name})`, 'npm', ['run', 'build'], { cwd: dir });
353
+ }
354
+ }
355
+
187
356
  if (!skipDeploy) {
188
357
  run('Deploy metadata', 'sf', ['project', 'deploy', 'start', '--target-org', targetOrg], {
189
358
  timeout: 180000,
@@ -225,36 +394,115 @@ function main() {
225
394
  run('Prepare data (unique fields)', 'node', [prepareScript, '--data-dir', DATA_DIR], {
226
395
  cwd: ROOT,
227
396
  });
228
- // Data import tree: if only DUPLICATES_DETECTED (org duplicate rules), warn and continue
397
+ // Normalize Lease__c Tenant refs to 1–15 so all refs resolve (Tenant__c.json has 15 records)
398
+ const leasePath = resolve(DATA_DIR, 'Lease__c.json');
399
+ if (existsSync(leasePath)) {
400
+ let leaseContent = readFileSync(leasePath, 'utf8');
401
+ leaseContent = leaseContent.replace(/@TenantRef(\d+)/g, (_m, n) => {
402
+ const k = ((parseInt(n, 10) - 1) % 15) + 1;
403
+ return `@TenantRef${k}`;
404
+ });
405
+ writeFileSync(leasePath, leaseContent);
406
+ }
407
+
408
+ // Delete existing records so every run inserts the full dataset without duplicate conflicts.
409
+ // Reverse plan order ensures children are removed before parents (FK safety).
410
+ console.log('\n--- Clean existing data for fresh import ---');
411
+ const planEntries = JSON.parse(readFileSync(DATA_PLAN, 'utf8'));
412
+ const sobjectsReversed = [...planEntries.map((e) => e.sobject)].reverse();
413
+ const tmpApex = resolve(ROOT, '.tmp-setup-delete.apex');
414
+ for (const sobject of sobjectsReversed) {
415
+ const apexCode = [
416
+ 'try {',
417
+ ` List<SObject> recs = Database.query('SELECT Id FROM ${sobject} LIMIT 10000');`,
418
+ ' if (!recs.isEmpty()) {',
419
+ ' Database.delete(recs, false);',
420
+ ' Database.emptyRecycleBin(recs);',
421
+ ' }',
422
+ '} catch (Exception e) {',
423
+ ' // non-deletable records (e.g. Contact linked to Case) are skipped via allOrNone=false',
424
+ '}',
425
+ ].join('\n');
426
+ writeFileSync(tmpApex, apexCode);
427
+ spawnSync('sf', ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex], {
428
+ cwd: ROOT,
429
+ stdio: 'pipe',
430
+ shell: true,
431
+ timeout: 60000,
432
+ });
433
+ console.log(` ${sobject}: cleaned`);
434
+ }
435
+ if (existsSync(tmpApex)) unlinkSync(tmpApex);
436
+
437
+ // Import via Anonymous Apex with Database.DMLOptions.duplicateRuleHeader.allowSave = true.
438
+ // This bypasses both duplicate-rule blocks AND matching-service timeouts that the REST
439
+ // API headers (Sforce-Duplicate-Rule-Action) cannot override.
229
440
  console.log('\n--- Data import tree ---');
230
- const importResult = spawnSync(
231
- 'sf',
232
- ['data', 'import', 'tree', '--plan', DATA_PLAN, '--target-org', targetOrg, '--json'],
233
- { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 120000 }
234
- );
235
- const out = (importResult.stdout?.toString() || '') + (importResult.stderr?.toString() || '');
236
- if (importResult.status !== 0) {
237
- let onlyDuplicates = false;
238
- try {
239
- const j = JSON.parse(out);
240
- const errors = Array.isArray(j?.data) ? j.data : [];
241
- onlyDuplicates =
242
- errors.length > 0 &&
243
- errors.every((e) => e.StatusCode === 'DUPLICATES_DETECTED' || e.statusCode === 'DUPLICATES_DETECTED');
244
- } catch (_) {
245
- onlyDuplicates = out.includes('DUPLICATES_DETECTED') && /Use one of these records\?/.test(out);
246
- }
247
- if (onlyDuplicates) {
248
- console.warn(
249
- 'Data import hit org duplicate rules (e.g. Contact). Skipping import; rest of setup continues.'
250
- );
251
- } else {
252
- process.stdout.write(importResult.stdout?.toString() || '');
253
- process.stderr.write(importResult.stderr?.toString() || '');
254
- console.error('\nSetup failed at step: Data import tree');
255
- process.exit(importResult.status ?? 1);
441
+ const refMap = new Map();
442
+ const APEX_CHAR_LIMIT = 25000;
443
+ const APEX_MAX_BATCH = 200;
444
+
445
+ for (const entry of planEntries) {
446
+ for (const file of entry.files) {
447
+ const data = JSON.parse(readFileSync(resolve(DATA_DIR, file), 'utf8'));
448
+ const records = data.records || [];
449
+
450
+ for (const rec of records) {
451
+ for (const key of Object.keys(rec)) {
452
+ if (key === 'attributes') continue;
453
+ const val = rec[key];
454
+ if (typeof val === 'string' && val.startsWith('@')) {
455
+ const actual = refMap.get(val.slice(1));
456
+ if (actual) {
457
+ rec[key] = actual;
458
+ } else if (refMap.size > 0) {
459
+ console.warn(` Warning: unresolved ref ${val} in ${file}`);
460
+ }
461
+ }
462
+ }
463
+ }
464
+
465
+ let imported = 0;
466
+ const sampleRec = records[0] || {};
467
+ const fieldsPerRec = Object.keys(sampleRec).filter((k) => k !== 'attributes').length;
468
+ const estCharsPerRec = 40 + fieldsPerRec * 55;
469
+ const batchSize = Math.min(APEX_MAX_BATCH, Math.max(5, Math.floor(APEX_CHAR_LIMIT / estCharsPerRec)));
470
+ for (let i = 0; i < records.length; i += batchSize) {
471
+ const batch = records.slice(i, i + batchSize);
472
+ const refIds = batch.map((r) => r.attributes?.referenceId || `_idx${i}`);
473
+ const apex = buildApexInsert(entry.sobject, batch, refIds);
474
+ writeFileSync(tmpApex, apex);
475
+ const apexResult = spawnSync(
476
+ 'sf',
477
+ ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex],
478
+ { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 120000 }
479
+ );
480
+ const apexOut = apexResult.stdout?.toString() || '';
481
+ const apexErr = apexResult.stderr?.toString() || '';
482
+ if (apexResult.status !== 0 && !apexOut.includes('Compiled successfully')) {
483
+ console.error(` ${entry.sobject}: apex execution failed`);
484
+ process.stderr.write(apexErr || apexOut);
485
+ process.exit(1);
486
+ }
487
+ const okMatches = [...apexOut.matchAll(/\|DEBUG\|REF:([^:\n]+):(\w+)/g)];
488
+ const errMatches = [...apexOut.matchAll(/\|DEBUG\|ERR:([^:\n]+):([^\n]+)/g)];
489
+ if (errMatches.length) {
490
+ for (const m of errMatches.slice(0, 5)) {
491
+ console.error(` ${m[1]}: ${m[2].trim()}`);
492
+ }
493
+ if (errMatches.length > 5) console.error(` ... and ${errMatches.length - 5} more`);
494
+ console.error(`\nSetup failed at step: Data import tree (${entry.sobject})`);
495
+ process.exit(1);
496
+ }
497
+ if (entry.saveRefs) {
498
+ for (const m of okMatches) refMap.set(m[1], m[2]);
499
+ }
500
+ imported += okMatches.length;
501
+ }
502
+ console.log(` ${entry.sobject}: imported ${imported} records`);
256
503
  }
257
504
  }
505
+ if (existsSync(tmpApex)) unlinkSync(tmpApex);
258
506
  }
259
507
 
260
508
  if (!skipGraphql || !skipWebappBuild) {
@@ -279,4 +527,7 @@ function main() {
279
527
  }
280
528
  }
281
529
 
282
- main();
530
+ main().catch((err) => {
531
+ console.error(err);
532
+ process.exit(1);
533
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salesforce/webapp-template-app-react-sample-b2e-experimental",
3
- "version": "1.92.0",
3
+ "version": "1.93.0",
4
4
  "description": "B2E starter app template",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "author": "",
@@ -16,8 +16,8 @@
16
16
  "clean": "rm -rf dist"
17
17
  },
18
18
  "dependencies": {
19
- "@salesforce/webapp-experimental": "^1.92.0",
20
- "@salesforce/webapp-template-feature-react-global-search-experimental": "^1.92.0"
19
+ "@salesforce/webapp-experimental": "^1.93.0",
20
+ "@salesforce/webapp-template-feature-react-global-search-experimental": "^1.93.0"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@testing-library/jest-dom": "^6.6.3",
@@ -1,65 +0,0 @@
1
- ---
2
- description: No complex node -e one-liners — use temp .js files or sed/awk instead
3
- paths:
4
- - "force-app/main/default/webapplications/**/*"
5
- ---
6
-
7
- # A4D Enforcement: No `node -e` One-Liners
8
-
9
- This project **forbids** using `node -e` (or `node -p`, `node --eval`) one-liners for any operation—file manipulation, string replacement, reading/writing configs, or shell automation.
10
-
11
- ## Why This Exists
12
-
13
- Complex `node -e '...'` one-liners **silently break in Zsh** (the default macOS shell) because of:
14
-
15
- - **`!` (history expansion):** Zsh interprets `!` inside double quotes as history expansion, causing `event not found` errors or silent corruption.
16
- - **Backtick interpolation:** Template literals (`` ` ``) are interpreted as command substitution by the shell before Node.js ever sees them.
17
- - **Nested quoting:** Multi-line JS crammed into a single shell string requires fragile quote escaping that differs between Bash and Zsh.
18
-
19
- These failures are **silent and intermittent**—the command may appear to succeed while producing corrupt output.
20
-
21
- ## What To Do Instead
22
-
23
- ### For multi-line file edits or transforms
24
-
25
- 1. **Write a temporary `.js` script**, run it, then delete it:
26
-
27
- ```bash
28
- cat > /tmp/_transform.js << 'SCRIPT'
29
- const fs = require('fs');
30
- const data = JSON.parse(fs.readFileSync('package.json', 'utf8'));
31
- data.name = 'my-app';
32
- fs.writeFileSync('package.json', JSON.stringify(data, null, 2) + '\n');
33
- SCRIPT
34
- node /tmp/_transform.js && rm /tmp/_transform.js
35
- ```
36
-
37
- 2. **Use `sed` or `awk`** for simple, single-pattern replacements with careful escaping:
38
-
39
- ```bash
40
- sed -i '' 's/old-value/new-value/g' path/to/file
41
- ```
42
-
43
- 3. **Use `jq`** for JSON edits:
44
-
45
- ```bash
46
- jq '.name = "my-app"' package.json > tmp.json && mv tmp.json package.json
47
- ```
48
-
49
- 4. **Use the IDE/agent file-editing tools** (replace_in_file, write_to_file, StrReplace, Write) whenever available—these bypass the shell entirely.
50
-
51
- ### For simple, truly one-line expressions
52
-
53
- A trivial `node -e "console.log(1+1)"` with no special characters is acceptable, but **if the expression contains any of these, use a temp file instead:**
54
- - Template literals (backticks)
55
- - `!` characters
56
- - Nested quotes
57
- - Multi-line strings
58
- - `fs` read/write operations
59
-
60
- ## Violation Handling
61
-
62
- - If any prior step used a complex `node -e` one-liner, **revert and redo** using one of the approved methods above.
63
- - If a shell command fails with `event not found`, `unexpected token`, or produces garbled output, check for a `node -e` violation first.
64
-
65
- **Cross-reference:** This rule is also summarized in **webapp.md** (MUST FOLLOW #1). Both apply.