@salesforce/ui-bundle-template-feature-angular-language-switcher 12.5.4

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 (253) hide show
  1. package/LICENSE.txt +82 -0
  2. package/README.md +193 -0
  3. package/dist/.forceignore +15 -0
  4. package/dist/.husky/pre-commit +4 -0
  5. package/dist/.prettierignore +11 -0
  6. package/dist/.prettierrc +17 -0
  7. package/dist/CHANGELOG.md +5238 -0
  8. package/dist/README.md +77 -0
  9. package/dist/config/project-scratch-def.json +13 -0
  10. package/dist/eslint.config.js +7 -0
  11. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/.forceignore +15 -0
  12. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/.graphqlrc.yml +2 -0
  13. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/.postcssrc.json +5 -0
  14. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/.prettierignore +8 -0
  15. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/.prettierrc +12 -0
  16. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/CHANGELOG.md +4 -0
  17. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/README.md +85 -0
  18. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/angular.json +98 -0
  19. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/codegen.yml +95 -0
  20. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/components.json +6 -0
  21. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/e2e/app.spec.ts +15 -0
  22. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/esbuild/api-version.mjs +17 -0
  23. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/esbuild/graphql-codegen.mjs +13 -0
  24. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/eslint-plugin-angular-graphql.js +148 -0
  25. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/eslint.config.js +76 -0
  26. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/feature-angular-language-switcher.uibundle-meta.xml +7 -0
  27. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/middleware/html.mjs +3 -0
  28. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/middleware/proxy.mjs +12 -0
  29. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/package.json +69 -0
  30. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/playwright.config.ts +25 -0
  31. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/public/favicon.ico +0 -0
  32. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/scripts/get-graphql-schema.mjs +69 -0
  33. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/scripts/rewrite-e2e-assets.mjs +30 -0
  34. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/api/data-client.service.spec.ts +184 -0
  35. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/api/data-client.service.ts +74 -0
  36. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/app.config.ts +20 -0
  37. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/app.html +1 -0
  38. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/app.routes.ts +26 -0
  39. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/app.spec.ts +18 -0
  40. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/app.ts +15 -0
  41. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/layout/app-layout/app-layout.html +51 -0
  42. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/layout/app-layout/app-layout.spec.ts +63 -0
  43. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/layout/app-layout/app-layout.ts +27 -0
  44. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/alert/alert.html +27 -0
  45. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/alert/alert.ts +41 -0
  46. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/button/button.html +27 -0
  47. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/button/button.ts +66 -0
  48. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/card/card.ts +100 -0
  49. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/collapsible/collapsible.html +38 -0
  50. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/collapsible/collapsible.ts +21 -0
  51. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/date-picker/date-picker.html +20 -0
  52. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/date-picker/date-picker.ts +49 -0
  53. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/date-range-picker/date-range-picker.html +20 -0
  54. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/date-range-picker/date-range-picker.ts +69 -0
  55. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/dialog/dialog.html +20 -0
  56. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/dialog/dialog.ts +40 -0
  57. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/dropdown-menu/dropdown-menu.html +20 -0
  58. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/dropdown-menu/dropdown-menu.ts +100 -0
  59. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/field/field.html +15 -0
  60. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/field/field.ts +28 -0
  61. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/field-appearance.ts +8 -0
  62. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/field-size.ts +8 -0
  63. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/icon/icon.ts +68 -0
  64. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/input/input.html +34 -0
  65. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/input/input.ts +79 -0
  66. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/label/label.ts +21 -0
  67. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/paginator/paginator.html +74 -0
  68. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/paginator/paginator.ts +93 -0
  69. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/paginator/types.ts +13 -0
  70. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/popover/popover.html +13 -0
  71. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/popover/popover.ts +37 -0
  72. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/select/select.html +36 -0
  73. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/select/select.ts +63 -0
  74. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/separator/separator.ts +31 -0
  75. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/skeleton/skeleton.ts +20 -0
  76. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/components/ui/spinner/spinner.ts +28 -0
  77. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/features/language-switcher/__examples__/html-middleware-site-example.ts +41 -0
  78. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/features/language-switcher/__examples__/language-switcher-example.ts +41 -0
  79. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/features/language-switcher/build-language-url.ts +158 -0
  80. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/features/language-switcher/index.ts +28 -0
  81. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/features/language-switcher/language-switcher.html +22 -0
  82. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/features/language-switcher/language-switcher.ts +110 -0
  83. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/features/language-switcher/languages.ts +46 -0
  84. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/pages/home/home.html +6 -0
  85. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/pages/home/home.spec.ts +23 -0
  86. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/pages/home/home.ts +13 -0
  87. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/pages/not-found/not-found.html +12 -0
  88. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/pages/not-found/not-found.spec.ts +33 -0
  89. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/pages/not-found/not-found.ts +15 -0
  90. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/alert/hlm-alert-action.ts +14 -0
  91. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/alert/hlm-alert-description.ts +17 -0
  92. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/alert/hlm-alert-title.ts +17 -0
  93. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/alert/hlm-alert.ts +35 -0
  94. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/alert/index.ts +16 -0
  95. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/button/hlm-button.token.ts +22 -0
  96. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/button/hlm-button.ts +72 -0
  97. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/button/index.ts +6 -0
  98. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/calendar/hlm-calendar-multi.ts +195 -0
  99. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/calendar/hlm-calendar-range.ts +194 -0
  100. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/calendar/hlm-calendar.ts +189 -0
  101. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/calendar/hlm-month-year-calendar.ts +119 -0
  102. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/calendar/index.ts +16 -0
  103. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card-action.ts +12 -0
  104. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card-avatar.ts +14 -0
  105. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card-content.ts +12 -0
  106. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card-description.ts +12 -0
  107. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card-footer.ts +12 -0
  108. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card-header.ts +15 -0
  109. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card-title.ts +12 -0
  110. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card.token.ts +19 -0
  111. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/hlm-card.ts +22 -0
  112. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/card/index.ts +28 -0
  113. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/collapsible/hlm-collapsible-content.ts +14 -0
  114. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/collapsible/hlm-collapsible-trigger.ts +9 -0
  115. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/collapsible/hlm-collapsible.ts +15 -0
  116. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/collapsible/index.ts +13 -0
  117. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-multi-input.ts +104 -0
  118. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-picker-anchor.ts +23 -0
  119. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-picker-input.ts +118 -0
  120. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-picker-multi.token.ts +109 -0
  121. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-picker-multi.ts +220 -0
  122. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-picker-trigger.ts +104 -0
  123. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-picker.token.ts +69 -0
  124. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-picker.ts +203 -0
  125. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-range-input.ts +120 -0
  126. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-range-picker.token.ts +86 -0
  127. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-date-range-picker.ts +252 -0
  128. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-month-year-input.ts +105 -0
  129. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-month-year-picker.token.ts +89 -0
  130. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/hlm-month-year-picker.ts +196 -0
  131. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/date-picker/index.ts +38 -0
  132. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-close.ts +9 -0
  133. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-content.ts +74 -0
  134. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-description.ts +17 -0
  135. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-footer.ts +15 -0
  136. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-header.ts +12 -0
  137. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-overlay.ts +27 -0
  138. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-portal.ts +8 -0
  139. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-title.ts +14 -0
  140. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog-trigger.ts +14 -0
  141. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog.service.ts +46 -0
  142. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/hlm-dialog.ts +24 -0
  143. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dialog/index.ts +35 -0
  144. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-checkbox-indicator.ts +21 -0
  145. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-checkbox.ts +54 -0
  146. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-focus-on-hover.ts +35 -0
  147. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-group.ts +14 -0
  148. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-item-sub-indicator.ts +19 -0
  149. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-item.ts +42 -0
  150. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-label.ts +20 -0
  151. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-radio-indicator.ts +21 -0
  152. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-radio.ts +49 -0
  153. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-separator.ts +12 -0
  154. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-shortcut.ts +15 -0
  155. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-sub-trigger.ts +52 -0
  156. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-sub.ts +53 -0
  157. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-token.ts +26 -0
  158. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu-trigger.ts +46 -0
  159. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/hlm-dropdown-menu.ts +57 -0
  160. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/dropdown-menu/index.ts +49 -0
  161. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-content.ts +12 -0
  162. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-description.ts +53 -0
  163. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-error.ts +100 -0
  164. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-group.ts +15 -0
  165. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-label.ts +17 -0
  166. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-legend.ts +19 -0
  167. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-separator.ts +24 -0
  168. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-set.ts +15 -0
  169. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field-title.ts +15 -0
  170. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/hlm-field.ts +47 -0
  171. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/field/index.ts +34 -0
  172. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input/hlm-input.ts +21 -0
  173. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input/index.ts +5 -0
  174. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input-group/hlm-input-group-addon.ts +40 -0
  175. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input-group/hlm-input-group-button.ts +47 -0
  176. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input-group/hlm-input-group-input.ts +17 -0
  177. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input-group/hlm-input-group-text.ts +14 -0
  178. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input-group/hlm-input-group.ts +18 -0
  179. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/input-group/index.ts +19 -0
  180. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/label/hlm-label.ts +17 -0
  181. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/label/index.ts +5 -0
  182. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/label/label.html +11 -0
  183. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-numbered-pagination-query-params.ts +191 -0
  184. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-numbered-pagination.ts +290 -0
  185. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-pagination-content.ts +12 -0
  186. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-pagination-ellipsis.ts +27 -0
  187. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-pagination-item.ts +7 -0
  188. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-pagination-link.ts +51 -0
  189. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-pagination-next.ts +65 -0
  190. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-pagination-previous.ts +65 -0
  191. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/hlm-pagination.ts +19 -0
  192. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/pagination/index.ts +31 -0
  193. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/hlm-popover-content.ts +25 -0
  194. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/hlm-popover-description.ts +12 -0
  195. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/hlm-popover-header.ts +12 -0
  196. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/hlm-popover-portal.ts +8 -0
  197. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/hlm-popover-title.ts +12 -0
  198. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/hlm-popover-trigger.ts +14 -0
  199. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/hlm-popover.ts +23 -0
  200. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/popover/index.ts +25 -0
  201. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-content.ts +44 -0
  202. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-group.ts +14 -0
  203. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-item.ts +36 -0
  204. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-label.ts +14 -0
  205. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-multiple.ts +37 -0
  206. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-placeholder.ts +17 -0
  207. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-portal.ts +8 -0
  208. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-scroll-down.ts +22 -0
  209. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-scroll-up.ts +22 -0
  210. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-separator.ts +14 -0
  211. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-trigger.ts +59 -0
  212. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-value-template.ts +5 -0
  213. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-value.ts +18 -0
  214. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-values-content.ts +9 -0
  215. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select-values.ts +5 -0
  216. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/hlm-select.ts +37 -0
  217. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/select/index.ts +52 -0
  218. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/separator/hlm-separator.ts +19 -0
  219. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/separator/index.ts +5 -0
  220. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/skeleton/hlm-skeleton.ts +14 -0
  221. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/skeleton/index.ts +5 -0
  222. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/spinner/hlm-spinner.ts +26 -0
  223. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/spinner/index.ts +5 -0
  224. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/utils/hlm.ts +313 -0
  225. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/utils/index.ts +2 -0
  226. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/shared/utils/provide-spartan-hlm.ts +34 -0
  227. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/app/utils/async-data.ts +99 -0
  228. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/index.html +13 -0
  229. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/main.ts +5 -0
  230. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/styles.css +139 -0
  231. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/src/types/sf-globals.d.ts +23 -0
  232. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/tsconfig.app.json +11 -0
  233. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/tsconfig.json +36 -0
  234. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/tsconfig.spec.json +10 -0
  235. package/dist/force-app/main/default/uiBundles/feature-angular-language-switcher/ui-bundle.json +7 -0
  236. package/dist/jest.config.js +6 -0
  237. package/dist/package-lock.json +12554 -0
  238. package/dist/package.json +46 -0
  239. package/dist/scripts/apex/hello.apex +10 -0
  240. package/dist/scripts/gitignore-templates.json +4 -0
  241. package/dist/scripts/graphql-search.sh +191 -0
  242. package/dist/scripts/org-setup-config-schema.mjs +132 -0
  243. package/dist/scripts/org-setup-dev.mjs +114 -0
  244. package/dist/scripts/org-setup-url.mjs +108 -0
  245. package/dist/scripts/org-setup-utils.mjs +569 -0
  246. package/dist/scripts/org-setup-xml.mjs +278 -0
  247. package/dist/scripts/org-setup.config.json +5 -0
  248. package/dist/scripts/org-setup.mjs +2537 -0
  249. package/dist/scripts/sf-project-setup.mjs +103 -0
  250. package/dist/scripts/soql/account.soql +6 -0
  251. package/dist/scripts/validate-org-setup-config.mjs +38 -0
  252. package/dist/sfdx-project.json +12 -0
  253. package/package.json +46 -0
@@ -0,0 +1,2537 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * One-command setup: login, deploy, optional permset/data, GraphQL schema/codegen, UI bundle build.
4
+ * Use this script to make setup easier for each app generated from this template.
5
+ *
6
+ * Usage:
7
+ * node scripts/org-setup.mjs --target-org <alias> # interactive step picker (all selected)
8
+ * node scripts/org-setup.mjs # prompt to pick an authenticated org
9
+ * node scripts/org-setup.mjs --target-org <alias> --yes # skip picker, run all steps
10
+ * node scripts/org-setup.mjs --target-org afv5 --skip-data --skip-ui-bundle-build
11
+ * node scripts/org-setup.mjs --target-org myorg --ui-bundle-name my-app
12
+ *
13
+ * Login is an unconditional precondition (not a toggleable step); the dev server
14
+ * is launched separately via `npm run dev:preview` (scripts/org-setup-dev.mjs).
15
+ *
16
+ * Steps (in order):
17
+ * login (precondition) — sf org login web only if org not already connected; always runs before deploy
18
+ * 1. uiBundle — (all UI bundles) npm install && npm run build so dist exists for deploy (skip with --skip-ui-bundle-build)
19
+ * 2. deploy — sf project deploy start --target-org <alias> (requires dist for entity deployment)
20
+ * 3. permset — assign permsets per org-setup.config.json (skip with --skip-permset; override via --permset-name)
21
+ * 4. data — prepare unique fields + sf data import tree (skipped if no data dir/plan)
22
+ * 5. graphql — (in UI bundle) npm run graphql:schema then npm run graphql:codegen
23
+ *
24
+ * Permset assignment config (scripts/org-setup.config.json):
25
+ * {
26
+ * "permsetAssignments": {
27
+ * "defaultAssignee": "skip",
28
+ * "assignments": {
29
+ * "My_Permset": { "assignee": "currentUser" },
30
+ * "Guest_Permset": { "assignee": "guestUser" },
31
+ * "Internal_Only": { "assignee": "skip" }
32
+ * }
33
+ * }
34
+ * }
35
+ * Assignee values: "currentUser", "guestUser", or "skip". For "guestUser" the
36
+ * site is derived from the single networks/<siteName>.network-meta.xml the app
37
+ * ships — it is not restated per assignment.
38
+ * Unlisted permsets resolve to "defaultAssignee" (default "skip").
39
+ */
40
+
41
+ import { spawnSync, spawn as nodeSpawn } from 'node:child_process';
42
+ import { resolve, dirname, join } from 'node:path';
43
+ import { fileURLToPath } from 'node:url';
44
+ import {
45
+ readdirSync,
46
+ existsSync,
47
+ readFileSync,
48
+ writeFileSync,
49
+ mkdirSync,
50
+ mkdtempSync,
51
+ rmSync,
52
+ openSync,
53
+ closeSync,
54
+ } from 'node:fs';
55
+ import { tmpdir } from 'node:os';
56
+
57
+ import { validateConfig } from './org-setup-config-schema.mjs';
58
+ import {
59
+ addProfileToMemberGroups,
60
+ enableSelfRegInXml,
61
+ setLogoutUrl,
62
+ NetworkXmlError,
63
+ } from './org-setup-xml.mjs';
64
+ import {
65
+ isAbsoluteLogoutUrl,
66
+ pickCommunityBaseUrl,
67
+ resolveLogoutUrl,
68
+ } from './org-setup-url.mjs';
69
+ import {
70
+ discoverAllUIBundleDirs as discoverAllUIBundleDirsIn,
71
+ discoverUIBundleDir as discoverUIBundleDirIn,
72
+ resolveTargetOrg,
73
+ evaluateLicenseRows,
74
+ validateProfileNameForSoql,
75
+ validateSoqlName,
76
+ validateApiName,
77
+ escapeSoqlString,
78
+ parseApexInsertResults,
79
+ planApexBatches,
80
+ } from './org-setup-utils.mjs';
81
+
82
+ const __dirname = dirname(fileURLToPath(import.meta.url));
83
+ const ROOT = resolve(__dirname, '..');
84
+
85
+ /**
86
+ * Thrown by step runners (run/runAsync) when a subprocess fails. The per-step
87
+ * orchestration in main() catches it, records the failure in the result ledger,
88
+ * and either aborts (fail-fast steps) or continues (skippable steps).
89
+ */
90
+ class StepError extends Error {}
91
+
92
+ const APEX_TMP_PREFIX = 'org-setup-';
93
+ // Legacy fixed-name temp files that older versions of this script wrote to ROOT
94
+ // and could leave behind on a hard kill. Swept at startup for backward cleanup.
95
+ const LEGACY_ROOT_TMP_FILES = ['.tmp-setup-selfreg.apex', '.tmp-setup-delete.apex'];
96
+
97
+ /**
98
+ * Remove leftover Apex temp artifacts from a prior hard-killed run (cleanup AT
99
+ * START). Two sources: per-run dirs under os.tmpdir() created by
100
+ * withApexTempDir, and legacy fixed-name files this script used to write to
101
+ * ROOT. Best-effort: a failure to remove one entry never blocks setup.
102
+ *
103
+ * Scoped to DIRECTORY entries only: the per-run artifacts are dirs created by
104
+ * withApexTempDir via mkdtempSync, whereas the per-org lock files share the same
105
+ * `org-setup-` prefix but are plain files (`org-setup-lock-<org>.lock`). Sweeping
106
+ * files too would delete a live run's lock before acquireOrgLock could see it,
107
+ * defeating the concurrency guard. The dir sweep is still intentionally broad
108
+ * across PIDs; the per-target-org lock acquired in main() is what makes that
109
+ * safe — only one live run per org.
110
+ */
111
+ function sweepStaleApexTempDirs() {
112
+ const base = tmpdir();
113
+ let entries = [];
114
+ try {
115
+ entries = readdirSync(base, { withFileTypes: true });
116
+ } catch {
117
+ /* tmpdir unreadable — nothing to sweep */
118
+ }
119
+ for (const entry of entries) {
120
+ if (entry.isDirectory() && entry.name.startsWith(APEX_TMP_PREFIX)) {
121
+ try {
122
+ rmSync(join(base, entry.name), { recursive: true, force: true });
123
+ } catch {
124
+ /* best effort */
125
+ }
126
+ }
127
+ }
128
+ for (const legacy of LEGACY_ROOT_TMP_FILES) {
129
+ const p = resolve(ROOT, legacy);
130
+ if (existsSync(p)) {
131
+ try {
132
+ rmSync(p, { force: true });
133
+ } catch {
134
+ /* best effort */
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Run `fn(writeApex)` with a private temp dir under os.tmpdir() that is ALWAYS
142
+ * removed afterwards (cleanup IN FINALLY), even when fn throws or
143
+ * the spawned Apex step fails. `writeApex(basename, contents)` writes a file in
144
+ * that dir and returns its absolute path. Replaces the old fixed-name
145
+ * `.tmp-setup-*.apex` files in ROOT, which collided across concurrent runs and
146
+ * leaked on throw.
147
+ */
148
+ function withApexTempDir(fn) {
149
+ const dir = mkdtempSync(join(tmpdir(), APEX_TMP_PREFIX));
150
+ try {
151
+ return fn((basename, contents) => {
152
+ const p = join(dir, basename);
153
+ writeFileSync(p, contents);
154
+ return p;
155
+ });
156
+ } finally {
157
+ try {
158
+ rmSync(dir, { recursive: true, force: true });
159
+ } catch {
160
+ /* best effort */
161
+ }
162
+ }
163
+ }
164
+
165
+ /** Filesystem-safe lock path for a target org. */
166
+ function orgLockPath(targetOrg) {
167
+ const safe = String(targetOrg).replace(/[^a-zA-Z0-9._-]/g, '_');
168
+ return join(tmpdir(), `org-setup-lock-${safe}.lock`);
169
+ }
170
+
171
+ /**
172
+ * Liveness probe: signal 0 throws ESRCH if the pid is gone, EPERM if it exists
173
+ * but we can't signal it (still alive, owned by another user).
174
+ */
175
+ function isProcessAlive(pid) {
176
+ try {
177
+ process.kill(pid, 0);
178
+ return true;
179
+ } catch (e) {
180
+ return e.code === 'EPERM';
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Acquire a single-host advisory per-target-org lock. If a LIVE
186
+ * run already holds it, exit early with a clear message rather than interleaving
187
+ * destructive Apex (deletes/imports) against the same org. A lock left by a
188
+ * hard-killed run (dead pid) is reclaimed. Different-org runs use different lock
189
+ * files and proceed in parallel.
190
+ *
191
+ * Released via process.on('exit') — NOT a finally block — because main() exits
192
+ * through process.exit() (the runStep fail-fast path, the end-of-run summary,
193
+ * and the top-level .catch), and process.exit() does not run finally blocks.
194
+ */
195
+ function acquireOrgLock(targetOrg) {
196
+ const lockPath = orgLockPath(targetOrg);
197
+ if (existsSync(lockPath)) {
198
+ const holder = Number(readFileSync(lockPath, 'utf8').trim());
199
+ if (holder && isProcessAlive(holder)) {
200
+ console.error(
201
+ `\nAnother org-setup run (pid ${holder}) is already targeting "${targetOrg}".\n` +
202
+ `Wait for it to finish, or if it was killed, remove ${lockPath} and retry.`,
203
+ );
204
+ process.exit(1);
205
+ }
206
+ // Stale lock (holder dead / hard-killed) — reclaim it.
207
+ rmSync(lockPath, { force: true });
208
+ }
209
+ // O_EXCL ('wx') create closes the check-then-write race between two
210
+ // near-simultaneous runs: the loser gets EEXIST.
211
+ let fd;
212
+ try {
213
+ fd = openSync(lockPath, 'wx');
214
+ } catch (e) {
215
+ if (e.code === 'EEXIST') {
216
+ console.error(
217
+ `\nAnother org-setup run just acquired the lock for "${targetOrg}". Retry shortly.`,
218
+ );
219
+ process.exit(1);
220
+ }
221
+ throw e;
222
+ }
223
+ writeFileSync(fd, String(process.pid));
224
+ closeSync(fd);
225
+
226
+ process.on('exit', () => {
227
+ try {
228
+ rmSync(lockPath, { force: true });
229
+ } catch {
230
+ /* best effort */
231
+ }
232
+ });
233
+ }
234
+
235
+ /**
236
+ * npm strips .gitignore from published packages — generate them on first run.
237
+ * Templates are stored in scripts/gitignore-templates.json (generated at build
238
+ * time from the actual .gitignore files) so the content lives in one place.
239
+ * The JSON may not exist in git-cloned distributions where .gitignore is
240
+ * already present, so loading is best-effort.
241
+ */
242
+ function loadGitignoreTemplates() {
243
+ const templatesPath = resolve(__dirname, 'gitignore-templates.json');
244
+ if (!existsSync(templatesPath)) return null;
245
+ try {
246
+ return JSON.parse(readFileSync(templatesPath, 'utf8'));
247
+ } catch {
248
+ return null;
249
+ }
250
+ }
251
+
252
+ function ensureGitignore(dir, content) {
253
+ if (!content) return;
254
+ const gitignorePath = resolve(dir, '.gitignore');
255
+ if (!existsSync(gitignorePath)) {
256
+ writeFileSync(gitignorePath, content, 'utf8');
257
+ console.log(`Created .gitignore in ${dir}`);
258
+ }
259
+ }
260
+
261
+ function resolveSfdxSource() {
262
+ const sfdxPath = resolve(ROOT, 'sfdx-project.json');
263
+ if (!existsSync(sfdxPath)) {
264
+ console.error('Error: sfdx-project.json not found at project root.');
265
+ process.exit(1);
266
+ }
267
+ const sfdxProject = JSON.parse(readFileSync(sfdxPath, 'utf8'));
268
+ const pkgDir = sfdxProject?.packageDirectories?.[0]?.path;
269
+ if (!pkgDir) {
270
+ console.error('Error: No packageDirectories[].path found in sfdx-project.json.');
271
+ process.exit(1);
272
+ }
273
+ return resolve(ROOT, pkgDir, 'main', 'default');
274
+ }
275
+
276
+ const SFDX_SOURCE = resolveSfdxSource();
277
+ const UIBUNDLES_DIR = resolve(SFDX_SOURCE, 'uiBundles');
278
+ const DATA_DIR = resolve(SFDX_SOURCE, 'data');
279
+ const DATA_PLAN = resolve(SFDX_SOURCE, 'data/data-plan.json');
280
+
281
+ function parseArgs() {
282
+ const args = process.argv.slice(2);
283
+ let targetOrg = null;
284
+ let uiBundleName = null;
285
+ /** If non-empty, only these names are assigned; otherwise all discovered from the project. */
286
+ const permsetNamesExplicit = [];
287
+ let yes = false;
288
+ const flags = {
289
+ skipDeploy: false,
290
+ skipPermset: false,
291
+ skipRole: false,
292
+ skipData: false,
293
+ skipGraphql: false,
294
+ skipUIBundleBuild: false,
295
+ skipSelfReg: false,
296
+ skipSocialLogin: false,
297
+ };
298
+ for (let i = 0; i < args.length; i++) {
299
+ if (args[i] === '--target-org' && args[i + 1]) {
300
+ targetOrg = args[++i];
301
+ } else if (args[i] === '--ui-bundle-name' && args[i + 1]) {
302
+ uiBundleName = args[++i];
303
+ } else if (args[i] === '--permset-name' && args[i + 1]) {
304
+ permsetNamesExplicit.push(args[++i]);
305
+ } else if (args[i] === '--skip-deploy') flags.skipDeploy = true;
306
+ else if (args[i] === '--skip-permset') flags.skipPermset = true;
307
+ else if (args[i] === '--skip-role') flags.skipRole = true;
308
+ else if (args[i] === '--skip-data') flags.skipData = true;
309
+ else if (args[i] === '--skip-self-reg') flags.skipSelfReg = true;
310
+ else if (args[i] === '--skip-social-login') flags.skipSocialLogin = true;
311
+ else if (args[i] === '--skip-graphql') flags.skipGraphql = true;
312
+ else if (args[i] === '--skip-ui-bundle-build') flags.skipUIBundleBuild = true;
313
+ // --skip-login and --skip-dev are retired: login is now an unconditional
314
+ // precondition and the dev step moved to `npm run dev:preview`.
315
+ // Accept them silently as no-ops so existing invocations don't hard-error.
316
+ else if (args[i] === '--skip-login' || args[i] === '--skip-dev') {
317
+ /* no-op (retired flag) */
318
+ } else if (args[i] === '--yes' || args[i] === '-y') yes = true;
319
+ else if (args[i] === '--help' || args[i] === '-h') {
320
+ console.log(`
321
+ Setup CLI — one-command setup for apps in this project
322
+
323
+ Usage:
324
+ node scripts/org-setup.mjs [--target-org <alias>] [options]
325
+
326
+ Options:
327
+ --target-org <alias> Target Salesforce org alias (e.g. myorg). If omitted, you
328
+ are prompted to pick from authenticated orgs (or the
329
+ default org is used when not running interactively).
330
+ --ui-bundle-name <name> UI bundle folder name under uiBundles/ (default: auto-detect)
331
+ --permset-name <name> Assign only this permission set (repeatable). Default: all sets under permissionsets/
332
+ --skip-deploy Do not deploy metadata
333
+ --skip-permset Do not assign permission set
334
+ --skip-social-login Do not enable social login (auth providers + community profile)
335
+ --skip-data Do not prepare data or run data import
336
+ --skip-graphql Do not fetch schema or run GraphQL codegen
337
+ --skip-ui-bundle-build Do not npm install / build the UI bundle
338
+ -y, --yes Skip interactive step picker; run all enabled steps immediately
339
+ -h, --help Show this help
340
+
341
+ To launch the dev server after setup, run: npm run dev:preview
342
+
343
+ Permset config (scripts/org-setup.config.json):
344
+ Control per-permset assignment via a config file. Example:
345
+ {
346
+ "permsetAssignments": {
347
+ "defaultAssignee": "skip",
348
+ "assignments": {
349
+ "My_Permset": { "assignee": "currentUser" },
350
+ "Guest_Permset": { "assignee": "guestUser" },
351
+ "Internal_Only": { "assignee": "skip" }
352
+ }
353
+ }
354
+ }
355
+ Assignee values: "currentUser", "guestUser", or "skip". For "guestUser" the site
356
+ is derived from the single networks/<siteName>.network-meta.xml the app ships.
357
+ Unlisted permsets resolve to "defaultAssignee" (default "skip").
358
+ `);
359
+ process.exit(0);
360
+ }
361
+ }
362
+ // NOTE: no hard-exit on a missing --target-org here. Resolution is
363
+ // deferred to resolveTargetOrg(), which either prompts (TTY) or falls back to
364
+ // the default org / exits with a clear message (non-TTY).
365
+ return { targetOrg, uiBundleName, permsetNamesExplicit, yes, ...flags };
366
+ }
367
+
368
+ // Bundle discovery lives in org-setup-utils.mjs so org-setup-dev.mjs shares it verbatim.
369
+ // These thin wrappers bind the shared helpers to this script's UIBUNDLES_DIR and
370
+ // keep the existing call-site signatures. discoverUIBundleDir carries the
371
+ // multi-bundle acknowledgment (TTY picker / non-TTY warning).
372
+ function discoverAllUIBundleDirs(uiBundleName) {
373
+ return discoverAllUIBundleDirsIn(UIBUNDLES_DIR, uiBundleName);
374
+ }
375
+
376
+ function discoverUIBundleDir(uiBundleName) {
377
+ return discoverUIBundleDirIn(UIBUNDLES_DIR, uiBundleName);
378
+ }
379
+
380
+ /** API names from permissionsets/*.permissionset-meta.xml in the first package directory. */
381
+ function discoverPermissionSetNames() {
382
+ const dir = resolve(SFDX_SOURCE, 'permissionsets');
383
+ if (!existsSync(dir)) return [];
384
+ const names = [];
385
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
386
+ if (!entry.isFile()) continue;
387
+ const m = entry.name.match(/^(.+)\.permissionset-meta\.xml$/);
388
+ if (m) names.push(m[1]);
389
+ }
390
+ return names.sort();
391
+ }
392
+
393
+ const CONFIG_PATH = resolve(__dirname, 'org-setup.config.json');
394
+
395
+ /**
396
+ * Read + validate org-setup.config.json ONCE, against the shared zod schema
397
+ * (the same `validateConfig` the build/CI gate uses). Exits non-zero with the
398
+ * precise zod issues if the config is invalid — before any step runs.
399
+ *
400
+ * Returns the validated config object (zod defaults applied), or an empty
401
+ * object when the file is absent (every section is optional).
402
+ *
403
+ * This is the single source of truth: loadPermsetConfig / loadRoleConfig /
404
+ * loadSelfRegConfig all read from the object it returns, so they no longer
405
+ * parse or defensively swallow errors.
406
+ */
407
+ function loadValidatedConfig() {
408
+ if (!existsSync(CONFIG_PATH)) return {};
409
+ const result = validateConfig(readFileSync(CONFIG_PATH, 'utf8'), CONFIG_PATH);
410
+ if (!result.ok) {
411
+ console.error('Invalid org-setup.config.json:');
412
+ for (const err of result.errors) console.error(` - ${err}`);
413
+ process.exit(1);
414
+ }
415
+ return result.data;
416
+ }
417
+
418
+ /**
419
+ * Derive the site name from the single networks/<siteName>.network-meta.xml the
420
+ * app ships. An app ships exactly one site, so the site name is derivable from
421
+ * deployed metadata rather than restated per-assignment. Returns
422
+ * null when there is no networks dir or no .network-meta.xml file.
423
+ */
424
+ function deriveSiteName() {
425
+ const networksDir = resolve(SFDX_SOURCE, 'networks');
426
+ if (!existsSync(networksDir)) return null;
427
+ const files = readdirSync(networksDir)
428
+ .filter((f) => f.endsWith('.network-meta.xml'))
429
+ .sort();
430
+ if (files.length === 0) return null;
431
+ // An app ships exactly one site; if a developer added a second, derivation is
432
+ // ambiguous — fail loudly rather than silently bind to an arbitrary site.
433
+ if (files.length > 1) {
434
+ throw new StepError(
435
+ `cannot derive guest site: multiple network metadata files found in ${networksDir} (${files.join(', ')}); guestUser assignment requires exactly one`,
436
+ );
437
+ }
438
+ const siteName = files[0].replace(/\.network-meta\.xml$/, '');
439
+ // The site name is interpolated into SOQL (Network lookup, guest-user lookup),
440
+ // so validate it here — the single chokepoint both callers pass through. Its
441
+ // source is the metadata filename, not org-setup.config.json, so point the fix
442
+ // there.
443
+ validateSoqlName(siteName, 'site name', {
444
+ remediation: `the networks/<siteName>.network-meta.xml filename (currently "${files[0]}")`,
445
+ });
446
+ return siteName;
447
+ }
448
+
449
+ /**
450
+ * Permset assignment configuration, read from the already-validated config.
451
+ *
452
+ * Config shape:
453
+ * {
454
+ * "permsetAssignments": {
455
+ * "defaultAssignee": "skip",
456
+ * "assignments": {
457
+ * "My_Permset": { "assignee": "currentUser" },
458
+ * "My_Guest_Permset": { "assignee": "guestUser" },
459
+ * "Internal_Only": { "assignee": "skip" }
460
+ * }
461
+ * }
462
+ * }
463
+ *
464
+ * Assignee values:
465
+ * "currentUser" — assign to the user running the script
466
+ * "skip" — do not assign this permset
467
+ * "guestUser" — resolve the site guest user automatically (site derived from
468
+ * the single networks/<siteName>.network-meta.xml the app ships)
469
+ *
470
+ * Unlisted permsets resolve to `defaultAssignee` (default "skip").
471
+ *
472
+ * Returns { defaultAssignee: string, assignments: Record<string, { assignee: string }> }
473
+ */
474
+ function loadPermsetConfig(config) {
475
+ const section = config.permsetAssignments;
476
+ if (!section) return { defaultAssignee: 'skip', assignments: {} };
477
+ return {
478
+ defaultAssignee: section.defaultAssignee,
479
+ assignments: section.assignments,
480
+ };
481
+ }
482
+
483
+ /** Resolve the effective assignment config for a given permset name. */
484
+ function resolveAssignment(permsetName, permsetConfig) {
485
+ const override = permsetConfig.assignments[permsetName];
486
+ if (!override) return { assignee: permsetConfig.defaultAssignee };
487
+ return { assignee: override.assignee };
488
+ }
489
+
490
+ /**
491
+ * Role assignment config, read from the already-validated config.
492
+ *
493
+ * Config shape:
494
+ * { "role": { "assignee": "currentUser", "roleName": "Admin" } }
495
+ *
496
+ * Returns null if no "role" section exists in config (the step is hidden).
497
+ */
498
+ function loadRoleConfig(config) {
499
+ const section = config.role;
500
+ if (!section) return null;
501
+ return {
502
+ assignee: section.assignee,
503
+ roleName: section.roleName,
504
+ };
505
+ }
506
+
507
+ /**
508
+ * Self-registration config, read from the already-validated config. The site is
509
+ * NOT stored here — it is derived from the single
510
+ * networks/<siteName>.network-meta.xml the app ships, exactly like
511
+ * the guestUser permset path. deriveSiteName() is called lazily inside the
512
+ * selfReg step body so its "multiple network files" StepError is recorded in
513
+ * the ledger rather than escaping config load.
514
+ *
515
+ * Config shape:
516
+ * {
517
+ * "selfRegistration": {
518
+ * "selfRegProfile": "myapp Profile",
519
+ * "accountName": "My Self-Reg Account"
520
+ * }
521
+ * }
522
+ *
523
+ * Returns null if no "selfRegistration" section exists in config (the step is hidden).
524
+ */
525
+ function loadSelfRegConfig(config) {
526
+ const section = config.selfRegistration;
527
+ if (!section) return null;
528
+ return {
529
+ selfRegProfile: section.selfRegProfile,
530
+ accountName: section.accountName,
531
+ };
532
+ }
533
+
534
+ /**
535
+ * Social login config, read from the already-validated config.
536
+ *
537
+ * Config shape:
538
+ * {
539
+ * "socialLogin": {
540
+ * "communityMemberProfile": "Customer Community User",
541
+ * "authProviderNames": ["Google", "Facebook", "My_SAML_Provider"],
542
+ * "communityUserPermset": "myapp_Guest_User_Api_Access" // optional
543
+ * }
544
+ * }
545
+ *
546
+ * - communityMemberProfile: profile added to NetworkMemberGroup (required for access)
547
+ * - authProviderNames: DeveloperNames of AuthProvider (OAuth) or SamlSsoConfig (SAML) records to link to site
548
+ * - communityUserPermset: permset assigned to community users so getCurrentUser()
549
+ * works (requires PermissionsApiEnabled for UI API GraphQL via /sf/api/)
550
+ *
551
+ * Returns null if no "socialLogin" section exists in config (the step is hidden).
552
+ */
553
+ function loadSocialLoginConfig(config) {
554
+ const section = config.socialLogin;
555
+ if (!section) return null;
556
+ return {
557
+ communityMemberProfile: section.communityMemberProfile,
558
+ authProviderNames: section.authProviderNames,
559
+ communityUserPermset: section.communityUserPermset || null,
560
+ };
561
+ }
562
+
563
+ /**
564
+ * Logout URL config, read from the already-validated config. Returns the string
565
+ * (a site-relative path like "/myapp/", or an absolute URL) or null when no
566
+ * "logoutUrl" is set (the step is then a no-op).
567
+ */
568
+ function loadLogoutUrlConfig(config) {
569
+ return config.logoutUrl ?? null;
570
+ }
571
+
572
+ /**
573
+ * Enable the "Allow using standard external profiles for self-registration,
574
+ * user creation, and login" org setting via Metadata API deploy.
575
+ *
576
+ * This setting is required for SSO registration handlers to create users with
577
+ * standard community profiles (e.g. "Customer Community User"). Without it,
578
+ * auth providers return FIELD_INTEGRITY_EXCEPTION on user insert.
579
+ *
580
+ * The correct metadata field is `enableOotbProfExtUserOpsEnable` in
581
+ * CommunitiesSettings. The REST/Tooling API approaches also fail on many
582
+ * org types. Deploying via Metadata API is the most reliable method.
583
+ */
584
+ function enableExternalProfiles(targetOrg) {
585
+ const dir = mkdtempSync(join(tmpdir(), APEX_TMP_PREFIX));
586
+ try {
587
+ // Create a minimal sfdx project with just the Communities setting
588
+ const settingsDir = join(dir, 'force-app', 'main', 'default', 'settings');
589
+ mkdirSync(settingsDir, { recursive: true });
590
+
591
+ writeFileSync(join(dir, 'sfdx-project.json'), JSON.stringify({
592
+ packageDirectories: [{ path: 'force-app', default: true }],
593
+ sourceApiVersion: '68.0',
594
+ }));
595
+
596
+ writeFileSync(join(settingsDir, 'Communities.settings-meta.xml'), [
597
+ '<?xml version="1.0" encoding="UTF-8"?>',
598
+ '<CommunitiesSettings xmlns="http://soap.sforce.com/2006/04/metadata">',
599
+ ' <enableOotbProfExtUserOpsEnable>true</enableOotbProfExtUserOpsEnable>',
600
+ '</CommunitiesSettings>',
601
+ ].join('\n'));
602
+
603
+ const result = spawnSync('sf', [
604
+ 'project', 'deploy', 'start',
605
+ '--target-org', targetOrg,
606
+ '--source-dir', join(dir, 'force-app'),
607
+ '--json',
608
+ ], { cwd: dir, stdio: 'pipe', shell: true, timeout: 120000 });
609
+
610
+ const out = result.stdout?.toString() || '';
611
+ let deployResult;
612
+ try { deployResult = JSON.parse(out); } catch { deployResult = null; }
613
+
614
+ if (deployResult?.status === 0 || deployResult?.result?.status === 'Succeeded') {
615
+ console.log(' Enabled "Allow using standard external profiles" org setting.');
616
+ } else {
617
+ // Check if it failed because the setting is already enabled or not deployable
618
+ const errMsg = deployResult?.message || deployResult?.result?.details?.componentFailures?.[0]?.problem || '';
619
+ if (errMsg.includes('already') || errMsg.includes('enableOotbProfExtUserOpsEnable')) {
620
+ console.log(' Warning: could not deploy "Allow standard external profiles" setting.');
621
+ console.log(` Detail: ${errMsg}`);
622
+ console.log(' The setting may already be active. Enable manually via Setup > Digital Experiences > Settings if needed.');
623
+ } else {
624
+ console.log(' Warning: could not enable "Allow standard external profiles".');
625
+ console.log(` Deploy result: ${errMsg || 'unknown error'}`);
626
+ console.log(' Enable manually via Setup > Digital Experiences > Settings.');
627
+ }
628
+ }
629
+ } finally {
630
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Enable Auth Providers for a community by creating AuthConfigProviders junction
636
+ * records via Anonymous Apex + REST API callouts.
637
+ *
638
+ * React (Site Container) sites intentionally hide SSO configuration in the Admin
639
+ * UI, so this must be done programmatically. The approach:
640
+ * 1. Query the AuthConfig record for the site (one per community).
641
+ * 2. Query AuthProvider records by DeveloperName.
642
+ * 3. Query SamlSsoConfig records by DeveloperName (for SAML providers).
643
+ * 4. Check existing AuthConfigProviders to avoid duplicates.
644
+ * 5. Create missing AuthConfigProviders via REST API (DML is not allowed on this object).
645
+ *
646
+ * AuthConfig.AuthOptionsAuthProvider auto-flips to true when AuthConfigProviders
647
+ * are inserted — no separate update needed.
648
+ *
649
+ * @param {string[]} authProviderNames - DeveloperNames of AuthProvider or SamlSsoConfig records
650
+ * @param {string} siteName - Name of the Network/community
651
+ * @param {string} targetOrg - Target org alias
652
+ */
653
+ function enableAuthProvidersForSite(authProviderNames, siteName, targetOrg) {
654
+ // DML is not allowed on AuthConfigProviders, so we use Anonymous Apex with
655
+ // HTTP callouts to the REST API to create the junction records.
656
+ // Whitelist each DeveloperName before it is interpolated into the generated
657
+ // Apex `DeveloperName IN (…)` literal — same call-site guard the data-import
658
+ // path applies with validateApiName, and defense-in-depth alongside the
659
+ // up-front socialLogin validation in main(). loadSocialLoginConfig already
660
+ // rejects an empty list, so the resulting literal is never empty here.
661
+ const providerNamesLiteral = authProviderNames
662
+ .map((n) => `'${validateSoqlName(n, 'socialLogin.authProviderNames entry')}'`)
663
+ .join(', ');
664
+
665
+ const apex = `
666
+ // Enable Auth Providers (OAuth + SAML) for community "${siteName}"
667
+ Http http = new Http();
668
+ String baseUrl = Url.getOrgDomainUrl().toExternalForm();
669
+ String token = UserInfo.getSessionId();
670
+
671
+ // Step 1: Find the AuthConfig for this site
672
+ List<AuthConfig> authConfigs = [
673
+ SELECT Id, Url
674
+ FROM AuthConfig
675
+ WHERE Url LIKE '%${siteName}%'
676
+ LIMIT 1
677
+ ];
678
+ if (authConfigs.isEmpty()) {
679
+ System.debug('ERROR_NO_AUTHCONFIG');
680
+ return;
681
+ }
682
+ AuthConfig ac = authConfigs[0];
683
+ System.debug('AUTHCONFIG_FOUND:' + ac.Id + ':' + ac.Url);
684
+
685
+ // Step 2: Query AuthProvider records by DeveloperName (OAuth providers)
686
+ List<AuthProvider> oauthProviders = [
687
+ SELECT Id, DeveloperName, FriendlyName
688
+ FROM AuthProvider
689
+ WHERE DeveloperName IN (${providerNamesLiteral})
690
+ ];
691
+ System.debug('OAUTH_PROVIDERS_FOUND:' + oauthProviders.size());
692
+
693
+ // Step 3: Query SamlSsoConfig records by DeveloperName (SAML providers)
694
+ List<SamlSsoConfig> samlProviders = [
695
+ SELECT Id, DeveloperName
696
+ FROM SamlSsoConfig
697
+ WHERE DeveloperName IN (${providerNamesLiteral})
698
+ ];
699
+ System.debug('SAML_PROVIDERS_FOUND:' + samlProviders.size());
700
+
701
+ // Combine both into a unified list with (Id, DeveloperName, Type)
702
+ List<Map<String, String>> allProviders = new List<Map<String, String>>();
703
+ for (AuthProvider ap : oauthProviders) {
704
+ allProviders.add(new Map<String, String>{
705
+ 'Id' => ap.Id,
706
+ 'DeveloperName' => ap.DeveloperName,
707
+ 'Type' => 'OAuth'
708
+ });
709
+ }
710
+ for (SamlSsoConfig sp : samlProviders) {
711
+ allProviders.add(new Map<String, String>{
712
+ 'Id' => sp.Id,
713
+ 'DeveloperName' => sp.DeveloperName,
714
+ 'Type' => 'SAML'
715
+ });
716
+ }
717
+
718
+ if (allProviders.isEmpty()) {
719
+ System.debug('ERROR_NO_PROVIDERS');
720
+ return;
721
+ }
722
+ System.debug('TOTAL_PROVIDERS_FOUND:' + allProviders.size());
723
+
724
+ // Fail fast if any requested provider name did not resolve to an AuthProvider
725
+ // (OAuth) or SamlSsoConfig (SAML) record. The isEmpty() check above only catches
726
+ // the case where NONE resolve; comparing the found DeveloperNames against the
727
+ // requested list also catches the strict-subset case (e.g. ["Google","Typo"]
728
+ // links Google but must not silently drop "Typo"). This runs BEFORE any junction
729
+ // record is created, so linking is all-or-nothing. Case-insensitive because SOQL
730
+ // "DeveloperName IN (...)" matches case-insensitively, so a stored DeveloperName
731
+ // may differ in case from the configured value and must not read as "missing".
732
+ Set<String> foundProviderNames = new Set<String>();
733
+ for (AuthProvider ap : oauthProviders) {
734
+ foundProviderNames.add(ap.DeveloperName.toLowerCase());
735
+ }
736
+ for (SamlSsoConfig sp : samlProviders) {
737
+ foundProviderNames.add(sp.DeveloperName.toLowerCase());
738
+ }
739
+ List<String> missingProviderNames = new List<String>();
740
+ for (String requestedName : new List<String>{${providerNamesLiteral}}) {
741
+ if (!foundProviderNames.contains(requestedName.toLowerCase())) {
742
+ missingProviderNames.add(requestedName);
743
+ }
744
+ }
745
+ if (!missingProviderNames.isEmpty()) {
746
+ System.debug('MISSING_PROVIDERS:' + String.join(missingProviderNames, ','));
747
+ return;
748
+ }
749
+
750
+ // Step 4: Check existing AuthConfigProviders to avoid duplicates
751
+ Set<Id> existingProviderIds = new Set<Id>();
752
+ for (AuthConfigProviders acp : [
753
+ SELECT AuthProviderId FROM AuthConfigProviders WHERE AuthConfigId = :ac.Id
754
+ ]) {
755
+ existingProviderIds.add(acp.AuthProviderId);
756
+ }
757
+
758
+ // Step 5: Create missing junction records via REST API
759
+ Integer inserted = 0;
760
+ for (Map<String, String> provider : allProviders) {
761
+ String providerId = provider.get('Id');
762
+ String providerName = provider.get('DeveloperName');
763
+ String providerType = provider.get('Type');
764
+
765
+ if (existingProviderIds.contains(providerId)) {
766
+ System.debug('ALREADY_LINKED:' + providerName + ':' + providerType);
767
+ continue;
768
+ }
769
+ HttpRequest req = new HttpRequest();
770
+ req.setEndpoint(baseUrl + '/services/data/v62.0/sobjects/AuthConfigProviders');
771
+ req.setMethod('POST');
772
+ req.setHeader('Authorization', 'Bearer ' + token);
773
+ req.setHeader('Content-Type', 'application/json');
774
+ req.setBody('{"AuthConfigId":"' + ac.Id + '","AuthProviderId":"' + providerId + '"}');
775
+ HttpResponse res = http.send(req);
776
+ if (res.getStatusCode() == 201 || res.getStatusCode() == 200) {
777
+ System.debug('INSERTED:' + providerName + ':' + providerType);
778
+ inserted++;
779
+ } else {
780
+ System.debug('INSERT_FAILED:' + providerName + ':' + providerType + ':' + res.getStatusCode() + ':' + res.getBody());
781
+ }
782
+ }
783
+ if (inserted == 0 && existingProviderIds.size() >= allProviders.size()) {
784
+ System.debug('ALL_ALREADY_LINKED');
785
+ } else {
786
+ System.debug('TOTAL_INSERTED:' + inserted);
787
+ }
788
+ `;
789
+
790
+ const apexOut = withApexTempDir((writeApex) => {
791
+ const tmpApex = writeApex('auth-providers.apex', apex);
792
+ const result = spawnSync('sf', [
793
+ 'apex', 'run', '--target-org', targetOrg, '--file', tmpApex,
794
+ ], { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 60000 });
795
+ const out = result.stdout?.toString() || '';
796
+ const err = result.stderr?.toString() || '';
797
+ if (result.status !== 0 && !out.includes('Compiled successfully')) {
798
+ process.stderr.write(err || out);
799
+ throw new StepError('failed to execute AuthConfigProviders apex');
800
+ }
801
+ return out;
802
+ });
803
+
804
+ // Parse output for status — match only |DEBUG| lines to avoid false positives
805
+ // from the "Execute Anonymous:" source echo that sf apex run always prints.
806
+ if (apexOut.match(/\|DEBUG\|ERROR_NO_AUTHCONFIG/)) {
807
+ throw new StepError(`no AuthConfig found for site "${siteName}" — ensure the site is published/active`);
808
+ }
809
+ if (apexOut.match(/\|DEBUG\|ERROR_NO_PROVIDERS/)) {
810
+ throw new StepError(`no AuthProvider or SamlSsoConfig records found for names: ${authProviderNames.join(', ')} — create them in Setup first`);
811
+ }
812
+ // A SOQL `DeveloperName IN (…)` query silently returns fewer rows for names
813
+ // that don't exist, so the ERROR_NO_PROVIDERS guard above (which only fires
814
+ // when NONE resolve) let a single typo'd name slip through unnoticed whenever
815
+ // at least one other name matched. The Apex now diffs the requested names
816
+ // against the resolved ones (case-insensitively, since SOQL matches that way)
817
+ // and emits MISSING_PROVIDERS naming the offenders — nothing is linked when it
818
+ // fires (all-or-nothing, checked before any insert).
819
+ const missingMatch = apexOut.match(/\|DEBUG\|MISSING_PROVIDERS:([^\n]+)/);
820
+ if (missingMatch) {
821
+ const missing = missingMatch[1].trim();
822
+ throw new StepError(`some configured auth providers were not found: ${missing} — check for typos, or create them in Setup first (nothing was linked)`);
823
+ }
824
+
825
+ // Check for insert failures
826
+ const insertFails = [...apexOut.matchAll(/\|DEBUG\|INSERT_FAILED:([^:]+):(OAuth|SAML):(\d+):([^\n]+)/g)];
827
+ if (insertFails.length > 0) {
828
+ for (const m of insertFails) {
829
+ console.error(` ✖ ${m[1]} (${m[2]}) — HTTP ${m[3]}: ${m[4].trim()}`);
830
+ }
831
+ throw new StepError(`failed to link ${insertFails.length} Auth Provider(s) to site AuthConfig`);
832
+ }
833
+
834
+ const totalMatch = apexOut.match(/\|DEBUG\|TOTAL_INSERTED:(\d+)/);
835
+ if (totalMatch) {
836
+ console.log(` Linked ${totalMatch[1]} Auth Provider(s) to site "${siteName}".`);
837
+ } else if (apexOut.match(/\|DEBUG\|ALL_ALREADY_LINKED/)) {
838
+ console.log(` All Auth Provider(s) already linked to site "${siteName}"; no changes needed.`);
839
+ }
840
+
841
+ // Log individual provider statuses
842
+ const alreadyLinked = [...apexOut.matchAll(/\|DEBUG\|ALREADY_LINKED:([^:]+):(OAuth|SAML)/g)];
843
+ for (const m of alreadyLinked) {
844
+ console.log(` ✔ ${m[1]} (${m[2]}, already linked)`);
845
+ }
846
+ const inserted = [...apexOut.matchAll(/\|DEBUG\|INSERTED:([^:]+):(OAuth|SAML)/g)];
847
+ for (const m of inserted) {
848
+ console.log(` + ${m[1]} (${m[2]}, newly linked)`);
849
+ }
850
+ }
851
+
852
+ /**
853
+ * Add a community user profile to the NetworkMemberGroup so that SSO-registered
854
+ * users (who get assigned this profile by the registration handler) can access
855
+ * the community.
856
+ *
857
+ * Without this, users created by the SSO registration handler get
858
+ * "NO_ACCESS: User was not authorized for the community".
859
+ *
860
+ * @param {string} profileName - Profile name to add (e.g. "Customer Community User")
861
+ * @param {string} siteName - Name of the Network/community
862
+ * @param {string} targetOrg - Target org alias
863
+ */
864
+ function addCommunityMemberProfile(profileName, siteName, targetOrg) {
865
+ // Query Network Id
866
+ const netQuery = `SELECT Id FROM Network WHERE Name = '${siteName}'`;
867
+ const netResult = spawnSync('sf', [
868
+ 'data', 'query', '--query', netQuery, '--target-org', targetOrg, '--json',
869
+ ], { cwd: ROOT, encoding: 'utf8' });
870
+ let networkId = null;
871
+ if (netResult.status === 0) {
872
+ try {
873
+ const json = JSON.parse(netResult.stdout);
874
+ networkId = json.result?.records?.[0]?.Id || null;
875
+ } catch { /* fall through */ }
876
+ }
877
+ if (!networkId) {
878
+ throw new StepError(`could not find Network "${siteName}" in org`);
879
+ }
880
+
881
+ // Query Profile Id
882
+ const profQuery = `SELECT Id FROM Profile WHERE Name = '${profileName}'`;
883
+ const profResult = spawnSync('sf', [
884
+ 'data', 'query', '--query', profQuery, '--target-org', targetOrg, '--json',
885
+ ], { cwd: ROOT, encoding: 'utf8' });
886
+ let profileId = null;
887
+ if (profResult.status === 0) {
888
+ try {
889
+ const json = JSON.parse(profResult.stdout);
890
+ profileId = json.result?.records?.[0]?.Id || null;
891
+ } catch { /* fall through */ }
892
+ }
893
+ if (!profileId) {
894
+ throw new StepError(`could not find Profile "${profileName}" in org`);
895
+ }
896
+
897
+ // Check if already a member
898
+ const memberQuery = `SELECT Id FROM NetworkMemberGroup WHERE NetworkId = '${networkId}' AND ParentId = '${profileId}'`;
899
+ const memberResult = spawnSync('sf', [
900
+ 'data', 'query', '--query', memberQuery, '--target-org', targetOrg, '--json',
901
+ ], { cwd: ROOT, encoding: 'utf8' });
902
+ let alreadyExists = false;
903
+ if (memberResult.status === 0) {
904
+ try {
905
+ const json = JSON.parse(memberResult.stdout);
906
+ alreadyExists = (json.result?.records?.length || 0) > 0;
907
+ } catch { /* proceed to create */ }
908
+ }
909
+ if (alreadyExists) {
910
+ console.log(` Profile "${profileName}" is already a member of community "${siteName}"; skipping.`);
911
+ return;
912
+ }
913
+
914
+ // Create NetworkMemberGroup record
915
+ const createResult = spawnSync('sf', [
916
+ 'data', 'create', 'record',
917
+ '--sobject', 'NetworkMemberGroup',
918
+ '--values', `NetworkId='${networkId}' ParentId='${profileId}'`,
919
+ '--target-org', targetOrg,
920
+ '--json',
921
+ ], { cwd: ROOT, encoding: 'utf8' });
922
+ if (createResult.status !== 0) {
923
+ const out = (createResult.stderr || '') + (createResult.stdout || '');
924
+ if (out) process.stderr.write(out);
925
+ throw new StepError(`failed to add profile "${profileName}" to NetworkMemberGroup for "${siteName}"`);
926
+ }
927
+ try {
928
+ const json = JSON.parse(createResult.stdout);
929
+ const id = json.result?.id;
930
+ console.log(` Added profile "${profileName}" to community "${siteName}" (NetworkMemberGroup: ${id}).`);
931
+ } catch {
932
+ console.log(` Added profile "${profileName}" to community "${siteName}".`);
933
+ }
934
+ }
935
+
936
+ /**
937
+ * Assign a permission set to all existing community users with a given profile.
938
+ *
939
+ * After SSO login, community users need the app's API-enabled permset so that
940
+ * getCurrentUser() (which calls UI API GraphQL via the /sf/api/ proxy) works.
941
+ * Without PermissionsApiEnabled the proxy returns API_DISABLED_FOR_ORG and the
942
+ * React app treats the user as unauthenticated.
943
+ *
944
+ * This is idempotent: already-assigned users are skipped.
945
+ */
946
+ function assignPermsetToCommunityUsers(permsetName, profileName, targetOrg) {
947
+ // Resolve PermissionSet Id
948
+ const psQuery = `SELECT Id FROM PermissionSet WHERE Name = '${permsetName}'`;
949
+ const psResult = spawnSync('sf', [
950
+ 'data', 'query', '--query', psQuery, '--target-org', targetOrg, '--json',
951
+ ], { cwd: ROOT, encoding: 'utf8' });
952
+ let permsetId = null;
953
+ if (psResult.status === 0) {
954
+ try {
955
+ const json = JSON.parse(psResult.stdout);
956
+ permsetId = json.result?.records?.[0]?.Id || null;
957
+ } catch { /* fall through */ }
958
+ }
959
+ if (!permsetId) {
960
+ throw new StepError(`could not find PermissionSet "${permsetName}" in org`);
961
+ }
962
+
963
+ // Find community users on the given profile who do NOT already have the permset
964
+ const usersQuery = [
965
+ `SELECT Id, Username FROM User`,
966
+ `WHERE Profile.Name = '${profileName}'`,
967
+ `AND IsActive = true`,
968
+ `AND UserType IN ('CspLitePortal', 'CustomerSuccess', 'PowerCustomerSuccess')`,
969
+ `AND Id NOT IN (SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSetId = '${permsetId}')`,
970
+ ].join(' ');
971
+ const usersResult = spawnSync('sf', [
972
+ 'data', 'query', '--query', usersQuery, '--target-org', targetOrg, '--json',
973
+ ], { cwd: ROOT, encoding: 'utf8' });
974
+ let users = [];
975
+ if (usersResult.status === 0) {
976
+ try {
977
+ const json = JSON.parse(usersResult.stdout);
978
+ users = json.result?.records || [];
979
+ } catch { /* empty list */ }
980
+ }
981
+
982
+ if (users.length === 0) {
983
+ console.log(` No community users on profile "${profileName}" need permset "${permsetName}"; skipping.`);
984
+ return;
985
+ }
986
+
987
+ // Assign the permset to each user
988
+ let assigned = 0;
989
+ for (const user of users) {
990
+ const createResult = spawnSync('sf', [
991
+ 'data', 'create', 'record',
992
+ '--sobject', 'PermissionSetAssignment',
993
+ '--values', `PermissionSetId='${permsetId}' AssigneeId='${user.Id}'`,
994
+ '--target-org', targetOrg,
995
+ '--json',
996
+ ], { cwd: ROOT, encoding: 'utf8' });
997
+ if (createResult.status === 0) {
998
+ assigned++;
999
+ } else {
1000
+ // Log but don't fail — user might already have it via race condition
1001
+ const out = (createResult.stdout || '') + (createResult.stderr || '');
1002
+ if (!out.includes('DUPLICATE_VALUE')) {
1003
+ console.warn(` Warning: could not assign "${permsetName}" to ${user.Username}: ${out.slice(0, 120)}`);
1004
+ }
1005
+ }
1006
+ }
1007
+ console.log(` Assigned permset "${permsetName}" to ${assigned}/${users.length} community user(s).`);
1008
+ }
1009
+
1010
+ /**
1011
+ * Ensure the self-registration profile is listed in networkMemberGroups.
1012
+ * This must happen BEFORE the initial deploy so that the profile is a recognised
1013
+ * site member when subsequent steps (selfRegProfile, selfRegistration=true) are deployed.
1014
+ */
1015
+ function ensureNetworkMemberProfile(selfRegConfig, siteName) {
1016
+ const { selfRegProfile } = selfRegConfig;
1017
+ if (!siteName || !selfRegProfile) return;
1018
+
1019
+ const networkXmlPath = resolve(SFDX_SOURCE, 'networks', `${siteName}.network-meta.xml`);
1020
+ if (!existsSync(networkXmlPath)) {
1021
+ console.log(` Network metadata not found: ${networkXmlPath}; skipping member group update.`);
1022
+ return;
1023
+ }
1024
+ const xml = readFileSync(networkXmlPath, 'utf8');
1025
+
1026
+ // Parse + assert the target node exists, then mutate via a targeted edit.
1027
+ // This is the BEST-EFFORT pre-deploy prep (not inside runStep, see lines
1028
+ // ~1050): on a missing <networkMemberGroups> node we surface a LOUD
1029
+ // console.error but do NOT throw — a bare throw here aborts before deploy and
1030
+ // bypasses the ledger. The authoritative failure is recorded later by the
1031
+ // post-deploy selfReg step.
1032
+ let result;
1033
+ try {
1034
+ result = addProfileToMemberGroups(xml, selfRegProfile);
1035
+ } catch (e) {
1036
+ if (e instanceof NetworkXmlError) {
1037
+ console.error(
1038
+ ` ERROR: cannot add self-reg profile to ${siteName}.network-meta.xml — ${e.message}. ` +
1039
+ `Continuing pre-deploy; the self-registration step will record the authoritative failure.`,
1040
+ );
1041
+ return;
1042
+ }
1043
+ throw e;
1044
+ }
1045
+
1046
+ if (!result.changed) {
1047
+ console.log(` Profile "${selfRegProfile}" already in networkMemberGroups; no update needed.`);
1048
+ return;
1049
+ }
1050
+ writeFileSync(networkXmlPath, result.xml);
1051
+ console.log(` Added profile "${selfRegProfile}" to networkMemberGroups in ${siteName}.network-meta.xml`);
1052
+ }
1053
+
1054
+ const CONNECT_API_VERSION = '62.0';
1055
+
1056
+ /**
1057
+ * Fetch the org's Experience Cloud communities via the Connect API and return the
1058
+ * `communities` array (possibly empty). Used to discover a site's public origin so
1059
+ * a shipped, site-relative logout path can be resolved to the absolute URL the
1060
+ * platform requires. Throws on transport/parse failure so the caller degrades to a
1061
+ * loud skip. (v62.0 is a safe floor — the /connect/communities resource is stable
1062
+ * across API versions.)
1063
+ */
1064
+ function fetchCommunities(targetOrg) {
1065
+ const res = spawnSync('sf', [
1066
+ 'api', 'request', 'rest',
1067
+ `/services/data/v${CONNECT_API_VERSION}/connect/communities`,
1068
+ '--target-org', targetOrg,
1069
+ ], { cwd: ROOT, encoding: 'utf8', timeout: 60000 });
1070
+ if (res.status !== 0) {
1071
+ throw new Error(`Connect communities query failed (sf exit ${res.status ?? 1})`);
1072
+ }
1073
+ let json;
1074
+ try {
1075
+ json = JSON.parse(res.stdout);
1076
+ } catch {
1077
+ throw new Error('could not parse the Connect communities response as JSON');
1078
+ }
1079
+ return Array.isArray(json.communities) ? json.communities : [];
1080
+ }
1081
+
1082
+ /**
1083
+ * Set the site's <logoutUrl> in the network metadata AFTER the initial deploy, then
1084
+ * re-deploy just the network — mirroring the self-registration step.
1085
+ *
1086
+ * Post-deploy (not folded into the main deploy) because the value must be an
1087
+ * ABSOLUTE URL: the platform rejects a relative logout URL at deploy ("The logout
1088
+ * page URL must be an absolute URL."). Apps ship a domain-independent, site-relative
1089
+ * path in org-setup.config.json; it is resolved here against the site's Experience
1090
+ * Cloud origin, which is only discoverable (via the Connect communities API) once
1091
+ * the site exists — i.e. after the main deploy. An already-absolute config value is
1092
+ * used as-is (no lookup).
1093
+ *
1094
+ * Best-effort, mirroring ensureNetworkMemberProfile: a missing network file, a
1095
+ * failure to resolve the absolute URL, a malformed-XML NetworkXmlError, or a failed
1096
+ * network re-deploy each log a LOUD console.error but do NOT throw — the logout URL
1097
+ * is a convenience that must not abort the whole setup. In particular, if the org's
1098
+ * Network emailSenderAddress has drifted from the shipped value, that field blocks
1099
+ * the network deploy; the message then points the operator at the site's
1100
+ * Administration settings. The helper's idempotency check makes a configured re-run
1101
+ * a byte-for-byte no-op with no deploy.
1102
+ */
1103
+ function ensureLogoutUrl(logoutUrl, siteName, targetOrg) {
1104
+ if (!siteName || !logoutUrl) return;
1105
+
1106
+ const networkXmlPath = resolve(SFDX_SOURCE, 'networks', `${siteName}.network-meta.xml`);
1107
+ if (!existsSync(networkXmlPath)) {
1108
+ console.log(` Network metadata not found: ${networkXmlPath}; skipping logout URL update.`);
1109
+ return;
1110
+ }
1111
+
1112
+ // Resolve the shipped (site-relative or absolute) config value to the absolute
1113
+ // URL the platform requires. A relative value needs the site's Experience Cloud
1114
+ // origin, discovered from the org's communities.
1115
+ let absoluteUrl;
1116
+ try {
1117
+ let baseUrl = null;
1118
+ if (!isAbsoluteLogoutUrl(logoutUrl)) {
1119
+ baseUrl = pickCommunityBaseUrl(fetchCommunities(targetOrg), logoutUrl, siteName);
1120
+ }
1121
+ absoluteUrl = resolveLogoutUrl(logoutUrl, baseUrl);
1122
+ } catch (e) {
1123
+ console.error(
1124
+ ` ERROR: cannot resolve an absolute logout URL for "${siteName}" — ${e.message}. ` +
1125
+ `Skipping; set the logout URL manually in the site's Administration settings.`,
1126
+ );
1127
+ return;
1128
+ }
1129
+
1130
+ const xml = readFileSync(networkXmlPath, 'utf8');
1131
+ let result;
1132
+ try {
1133
+ result = setLogoutUrl(xml, absoluteUrl);
1134
+ } catch (e) {
1135
+ if (e instanceof NetworkXmlError) {
1136
+ console.error(
1137
+ ` ERROR: cannot set logout URL in ${siteName}.network-meta.xml — ${e.message}. ` +
1138
+ `Skipping; set <logoutUrl> manually in the site's Administration settings.`,
1139
+ );
1140
+ return;
1141
+ }
1142
+ throw e;
1143
+ }
1144
+
1145
+ if (!result.changed) {
1146
+ console.log(` Logout URL already set to "${absoluteUrl}" in ${siteName}.network-meta.xml; no update needed.`);
1147
+ return;
1148
+ }
1149
+ writeFileSync(networkXmlPath, result.xml);
1150
+ console.log(` Set <logoutUrl>${absoluteUrl}</logoutUrl> in ${siteName}.network-meta.xml`);
1151
+
1152
+ // Re-deploy ONLY the network file (mirrors enableSelfRegistration). Best-effort:
1153
+ // a non-zero exit (e.g. the org's emailSenderAddress differs from the shipped
1154
+ // value and can't be updated) logs loudly and continues.
1155
+ const deployResult = spawnSync('sf', [
1156
+ 'project', 'deploy', 'start',
1157
+ '--target-org', targetOrg,
1158
+ '--source-dir', networkXmlPath,
1159
+ ], { cwd: ROOT, stdio: 'inherit', shell: true, timeout: 120000 });
1160
+ if (deployResult.status !== 0) {
1161
+ console.error(
1162
+ ` ERROR: failed to deploy <logoutUrl> for "${siteName}" (sf exit ${deployResult.status ?? 1}). ` +
1163
+ `If the org's Network emailSenderAddress differs from the shipped value it blocks this deploy — ` +
1164
+ `set the logout URL manually in the site's Administration settings.`,
1165
+ );
1166
+ return;
1167
+ }
1168
+ console.log(` Deployed <logoutUrl> for "${siteName}".`);
1169
+ }
1170
+
1171
+ /**
1172
+ * Enable self-registration for an Experience Cloud network.
1173
+ *
1174
+ * 1. Modify the network metadata XML to set selfRegistration=true and add selfRegProfile.
1175
+ * 2. Re-deploy the modified network metadata.
1176
+ * 3. Create an Account record (idempotent).
1177
+ * 4. Create a NetworkSelfRegistration record linking the Account to the Network (idempotent).
1178
+ */
1179
+ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
1180
+ const { selfRegProfile, accountName } = selfRegConfig;
1181
+
1182
+ // 1. Modify network metadata XML
1183
+ const networkXmlPath = resolve(SFDX_SOURCE, 'networks', `${siteName}.network-meta.xml`);
1184
+ if (!existsSync(networkXmlPath)) {
1185
+ throw new StepError(`network metadata not found: ${networkXmlPath}`);
1186
+ }
1187
+ const xml = readFileSync(networkXmlPath, 'utf8');
1188
+
1189
+ // Parse + assert the <selfRegistration> node exists, then mutate via a
1190
+ // targeted edit. This runs inside
1191
+ // runStep(selfReg, failFast:false) (line ~1211), so a missing node must throw
1192
+ // a StepError — caught, recorded `failed`, non-zero exit — rather than the
1193
+ // old silent no-op. The helper's idempotency check
1194
+ // (already true / selfRegProfile present) yields changed:false here.
1195
+ let result;
1196
+ try {
1197
+ result = enableSelfRegInXml(xml, selfRegProfile);
1198
+ } catch (e) {
1199
+ if (e instanceof NetworkXmlError) {
1200
+ throw new StepError(`${siteName}.network-meta.xml: ${e.message}`);
1201
+ }
1202
+ throw e;
1203
+ }
1204
+
1205
+ if (!result.changed) {
1206
+ console.log(` Network "${siteName}" already has self-registration configured; skipping metadata update and deploy.`);
1207
+ } else {
1208
+ writeFileSync(networkXmlPath, result.xml);
1209
+ console.log(` Updated ${siteName}.network-meta.xml: selfRegistration=true, selfRegProfile=${selfRegProfile}`);
1210
+
1211
+ // Re-deploy only the network file
1212
+ const deployResult = spawnSync('sf', [
1213
+ 'project', 'deploy', 'start',
1214
+ '--target-org', targetOrg,
1215
+ '--source-dir', networkXmlPath,
1216
+ ], { cwd: ROOT, stdio: 'inherit', shell: true, timeout: 120000 });
1217
+ if (deployResult.status !== 0) {
1218
+ throw new StepError(`failed to deploy updated network metadata (exit ${deployResult.status ?? 1})`);
1219
+ }
1220
+ }
1221
+
1222
+ // 3. Create Account (idempotent).
1223
+ // accountName is a free-form display value (e.g. "O'Brien Rentals & Co.") that
1224
+ // legitimately contains punctuation, so it is ESCAPED rather than whitelisted:
1225
+ // escape it for the SOQL read here, and create it via Apex below
1226
+ // (apexLiteral-escaped) rather than the `--values Name='...'` CLI arg, whose
1227
+ // space-separated key=value parsing an escaped name cannot safely satisfy.
1228
+ const acctQuery = `SELECT Id FROM Account WHERE Name = '${escapeSoqlString(accountName)}' LIMIT 1`;
1229
+ const acctQueryResult = spawnSync('sf', [
1230
+ 'data', 'query',
1231
+ '--query', acctQuery,
1232
+ '--target-org', targetOrg,
1233
+ '--json',
1234
+ ], { cwd: ROOT, encoding: 'utf8' });
1235
+ let accountId = null;
1236
+ if (acctQueryResult.status === 0) {
1237
+ try {
1238
+ const json = JSON.parse(acctQueryResult.stdout);
1239
+ accountId = json.result?.records?.[0]?.Id || null;
1240
+ } catch { /* proceed to create */ }
1241
+ }
1242
+ if (accountId) {
1243
+ console.log(` Account "${accountName}" already exists (${accountId}); skipping creation.`);
1244
+ } else {
1245
+ // Create via Anonymous Apex (apexLiteral escapes the name) instead of
1246
+ // `sf data create record --values`: the CLI parses --values as
1247
+ // space-separated key=value pairs, so a name with a space, quote, or `&`
1248
+ // either mis-parses or opens a field-injection surface. Apex string
1249
+ // escaping closes that off and mirrors the NSR create just below.
1250
+ const apex = [
1251
+ `Account acct = new Account(Name = ${apexLiteral(accountName)});`,
1252
+ `insert acct;`,
1253
+ `System.debug('ACCOUNT_CREATED:' + acct.Id);`,
1254
+ ].join('\n');
1255
+ const apexOut = withApexTempDir((writeApex) => {
1256
+ const tmpApex = writeApex('account.apex', apex);
1257
+ const apexResult = spawnSync('sf', [
1258
+ 'apex', 'run', '--target-org', targetOrg, '--file', tmpApex,
1259
+ ], { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 60000 });
1260
+ const out = apexResult.stdout?.toString() || '';
1261
+ if (apexResult.status !== 0 && !out.includes('Compiled successfully')) {
1262
+ process.stderr.write(apexResult.stderr?.toString() || out);
1263
+ throw new StepError(`failed to create Account "${accountName}"`);
1264
+ }
1265
+ return out;
1266
+ });
1267
+ const acctMatch = apexOut.match(/ACCOUNT_CREATED:(\w+)/);
1268
+ if (!acctMatch) {
1269
+ throw new StepError('failed to parse Account creation result');
1270
+ }
1271
+ accountId = acctMatch[1];
1272
+ console.log(` Created Account "${accountName}" (${accountId}).`);
1273
+ }
1274
+
1275
+ // 4. Query Network Id
1276
+ const netQuery = `SELECT Id FROM Network WHERE Name = '${siteName}'`;
1277
+ const netResult = spawnSync('sf', [
1278
+ 'data', 'query',
1279
+ '--query', netQuery,
1280
+ '--target-org', targetOrg,
1281
+ '--json',
1282
+ ], { cwd: ROOT, encoding: 'utf8' });
1283
+ let networkId = null;
1284
+ if (netResult.status === 0) {
1285
+ try {
1286
+ const json = JSON.parse(netResult.stdout);
1287
+ networkId = json.result?.records?.[0]?.Id || null;
1288
+ } catch { /* fall through */ }
1289
+ }
1290
+ if (!networkId) {
1291
+ throw new StepError(`could not find Network "${siteName}" in org`);
1292
+ }
1293
+ console.log(` Found Network "${siteName}" (${networkId}).`);
1294
+
1295
+ // 5. Create NetworkSelfRegistration (idempotent)
1296
+ const nsrQuery = `SELECT Id FROM NetworkSelfRegistration WHERE NetworkId = '${networkId}'`;
1297
+ const nsrResult = spawnSync('sf', [
1298
+ 'data', 'query',
1299
+ '--query', nsrQuery,
1300
+ '--target-org', targetOrg,
1301
+ '--json',
1302
+ ], { cwd: ROOT, encoding: 'utf8' });
1303
+ let nsrExists = false;
1304
+ if (nsrResult.status === 0) {
1305
+ try {
1306
+ const json = JSON.parse(nsrResult.stdout);
1307
+ nsrExists = (json.result?.records?.length || 0) > 0;
1308
+ } catch { /* proceed to create */ }
1309
+ }
1310
+ if (nsrExists) {
1311
+ console.log(' NetworkSelfRegistration record already exists; skipping.');
1312
+ } else {
1313
+ const apex = [
1314
+ `Account acct = [SELECT Id FROM Account WHERE Id = '${accountId}' LIMIT 1];`,
1315
+ `NetworkSelfRegistration nsr = new NetworkSelfRegistration();`,
1316
+ `nsr.AccountId = acct.Id;`,
1317
+ `nsr.NetworkId = '${networkId}';`,
1318
+ `insert nsr;`,
1319
+ `System.debug('NSR_CREATED:' + nsr.Id);`,
1320
+ ].join('\n');
1321
+ const apexOut = withApexTempDir((writeApex) => {
1322
+ const tmpApex = writeApex('selfreg.apex', apex);
1323
+ const apexResult = spawnSync('sf', [
1324
+ 'apex', 'run', '--target-org', targetOrg, '--file', tmpApex,
1325
+ ], { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 60000 });
1326
+ const out = apexResult.stdout?.toString() || '';
1327
+ if (apexResult.status !== 0 && !out.includes('Compiled successfully')) {
1328
+ process.stderr.write(apexResult.stderr?.toString() || out);
1329
+ throw new StepError('failed to create NetworkSelfRegistration record');
1330
+ }
1331
+ return out;
1332
+ });
1333
+ const nsrMatch = apexOut.match(/NSR_CREATED:(\w+)/);
1334
+ if (nsrMatch) {
1335
+ console.log(` Created NetworkSelfRegistration (${nsrMatch[1]}).`);
1336
+ } else {
1337
+ console.log(' NetworkSelfRegistration creation executed.');
1338
+ }
1339
+ }
1340
+ }
1341
+
1342
+ /**
1343
+ * Assign a role to the current user so that Experience Cloud self-registration
1344
+ * works correctly.
1345
+ */
1346
+ function assignRoleToCurrentUser(roleName, targetOrg) {
1347
+ validateSoqlName(roleName, 'role name');
1348
+ const roleQuery = `SELECT Id FROM UserRole WHERE Name = '${roleName}'`;
1349
+ const roleResult = spawnSync('sf', [
1350
+ 'data', 'query',
1351
+ '--query', roleQuery,
1352
+ '--target-org', targetOrg,
1353
+ '--json',
1354
+ ], { cwd: ROOT, encoding: 'utf8' });
1355
+ if (roleResult.status !== 0) {
1356
+ if (roleResult.stderr) console.error(roleResult.stderr);
1357
+ throw new StepError(`failed to query role "${roleName}" in org`);
1358
+ }
1359
+ let roleId;
1360
+ try {
1361
+ const json = JSON.parse(roleResult.stdout);
1362
+ const records = json.result?.records;
1363
+ if (!records || records.length === 0) {
1364
+ throw new StepError(`role "${roleName}" not found in org`);
1365
+ }
1366
+ roleId = records[0].Id;
1367
+ } catch (err) {
1368
+ if (err instanceof StepError) throw err;
1369
+ throw new StepError(`failed to parse role query result for "${roleName}"`);
1370
+ }
1371
+
1372
+ const orgResult = spawnSync('sf', [
1373
+ 'org', 'display',
1374
+ '--target-org', targetOrg,
1375
+ '--json',
1376
+ ], { cwd: ROOT, encoding: 'utf8' });
1377
+ if (orgResult.status !== 0) {
1378
+ throw new StepError('failed to resolve current user from org');
1379
+ }
1380
+ let username;
1381
+ try {
1382
+ const json = JSON.parse(orgResult.stdout);
1383
+ username = json.result?.username;
1384
+ if (!username) {
1385
+ throw new StepError('could not determine current username from org display');
1386
+ }
1387
+ } catch (err) {
1388
+ if (err instanceof StepError) throw err;
1389
+ throw new StepError('failed to parse org display result');
1390
+ }
1391
+
1392
+ const userQuery = `SELECT Id, UserRoleId FROM User WHERE Username = '${username}'`;
1393
+ const userResult = spawnSync('sf', [
1394
+ 'data', 'query',
1395
+ '--query', userQuery,
1396
+ '--target-org', targetOrg,
1397
+ '--json',
1398
+ ], { cwd: ROOT, encoding: 'utf8' });
1399
+ if (userResult.status === 0) {
1400
+ try {
1401
+ const json = JSON.parse(userResult.stdout);
1402
+ const userRecord = json.result?.records?.[0];
1403
+ if (userRecord?.UserRoleId) {
1404
+ console.log(` User ${username} already has a role assigned; skipping to avoid overriding.`);
1405
+ return;
1406
+ }
1407
+ } catch { /* continue */ }
1408
+ }
1409
+
1410
+ const updateResult = spawnSync('sf', [
1411
+ 'data', 'update', 'record',
1412
+ '--sobject', 'User',
1413
+ '--where', `Username='${username}'`,
1414
+ '--values', `UserRoleId='${roleId}'`,
1415
+ '--target-org', targetOrg,
1416
+ '--json',
1417
+ ], { cwd: ROOT, encoding: 'utf8' });
1418
+ if (updateResult.status === 0) {
1419
+ console.log(` Role "${roleName}" assigned to ${username}.`);
1420
+ } else {
1421
+ const out = (updateResult.stderr?.toString() || '') + (updateResult.stdout?.toString() || '');
1422
+ if (out) console.error(out);
1423
+ throw new StepError(`failed to assign role "${roleName}" to ${username}`);
1424
+ }
1425
+ }
1426
+
1427
+ /**
1428
+ * Query the org for the guest user of the given site.
1429
+ *
1430
+ * Salesforce auto-creates a guest profile named "<Site> Profile" for each
1431
+ * Experience Cloud site. The old `Profile.Name LIKE '%<siteName>%'` substring
1432
+ * match collided across sites — e.g. site "shop" also matched "shop-admin"'s
1433
+ * guest profile — and then blindly took records[0]. This uses an exact match on
1434
+ * the profile name instead. SOQL string equality on a text field is
1435
+ * case-insensitive by default (it wraps both sides in UPPER()), so a site whose
1436
+ * label casing differs from the derived name still matches without explicit
1437
+ * normalization. siteName is whitelist-validated at the deriveSiteName()
1438
+ * chokepoint, so it is safe to interpolate here.
1439
+ *
1440
+ * Residual limitation: on a non-English org the auto-generated " Profile" suffix
1441
+ * may be localized, in which case no row matches and the assignment soft-skips
1442
+ * (returned null) with a clear message — the caller records that as a skip, not
1443
+ * a crash.
1444
+ *
1445
+ * Returns the guest Username, or null (with a logged reason) when the query
1446
+ * fails, no guest user exists, or the match is ambiguous.
1447
+ */
1448
+ function resolveGuestUsername(siteName, targetOrg) {
1449
+ const query =
1450
+ `SELECT Username FROM User ` +
1451
+ `WHERE Profile.Name = '${siteName} Profile' AND UserType = 'Guest'`;
1452
+ const result = spawnSync('sf', [
1453
+ 'data', 'query',
1454
+ '--query', query,
1455
+ '--target-org', targetOrg,
1456
+ '--json',
1457
+ ], { cwd: ROOT, encoding: 'utf8' });
1458
+ if (result.status !== 0) {
1459
+ console.error(` Failed to query guest user for site "${siteName}".`);
1460
+ if (result.stderr) console.error(result.stderr);
1461
+ return null;
1462
+ }
1463
+ try {
1464
+ const json = JSON.parse(result.stdout);
1465
+ const records = json.result?.records;
1466
+ if (!records || records.length === 0) {
1467
+ console.error(` No guest user found for site "${siteName}" (looked for profile "${siteName} Profile").`);
1468
+ return null;
1469
+ }
1470
+ if (records.length > 1) {
1471
+ const names = records.map((r) => r.Username).join(', ');
1472
+ console.error(
1473
+ ` Ambiguous guest user for site "${siteName}": ${records.length} guest users share ` +
1474
+ `profile "${siteName} Profile" (${names}); refusing to guess.`,
1475
+ );
1476
+ return null;
1477
+ }
1478
+ return records[0].Username;
1479
+ } catch {
1480
+ console.error(` Failed to parse guest user query result for site "${siteName}".`);
1481
+ return null;
1482
+ }
1483
+ }
1484
+
1485
+ /**
1486
+ * License pre-check for self-registration. Query the UserLicense that the
1487
+ * selfRegProfile belongs to and decide whether self-registration can proceed.
1488
+ * The profile name is validate-and-fail: a SOQL-special character throws a config
1489
+ * error rather than being escaped — profile names are developer-authored config,
1490
+ * not user input, so a `'` / `\` / control char is a mistake to surface loudly.
1491
+ *
1492
+ * Selection is on the stable LicenseDefinitionKey; the seat math lives in JS
1493
+ * (evaluateLicenseRows) because SOQL cannot compare two fields. A query failure
1494
+ * or 0 rows is treated as "not satisfied" (soft skip), not a hard error.
1495
+ *
1496
+ * @returns {{ satisfied: boolean, reason: string|null }}
1497
+ */
1498
+ function checkSelfRegLicense(selfRegConfig, targetOrg) {
1499
+ const profileName = validateProfileNameForSoql(selfRegConfig.selfRegProfile);
1500
+ const query =
1501
+ `SELECT UserLicense.LicenseDefinitionKey, UserLicense.Name, UserLicense.Status, ` +
1502
+ `UserLicense.TotalLicenses, UserLicense.UsedLicenses ` +
1503
+ `FROM Profile WHERE Name = '${profileName}'`;
1504
+ const result = spawnSync('sf', [
1505
+ 'data', 'query',
1506
+ '--query', query,
1507
+ '--target-org', targetOrg,
1508
+ '--json',
1509
+ ], { cwd: ROOT, encoding: 'utf8' });
1510
+
1511
+ if (result.status !== 0) {
1512
+ if (result.stderr) console.error(result.stderr);
1513
+ return {
1514
+ satisfied: false,
1515
+ reason: `could not query the UserLicense for profile "${profileName}" (sf data query failed)`,
1516
+ };
1517
+ }
1518
+ let rows;
1519
+ try {
1520
+ rows = JSON.parse(result.stdout).result?.records ?? [];
1521
+ } catch {
1522
+ return {
1523
+ satisfied: false,
1524
+ reason: `could not parse the UserLicense query result for profile "${profileName}"`,
1525
+ };
1526
+ }
1527
+ const { satisfied, reason } = evaluateLicenseRows(rows, profileName);
1528
+ return { satisfied, reason };
1529
+ }
1530
+
1531
+ /**
1532
+ * Read the UserLicense the selfRegProfile requires straight from the local
1533
+ * profile metadata's <userLicense> element. The deploy pre-check runs BEFORE
1534
+ * the profile is deployed, so querying the org's Profile table returns 0 rows
1535
+ * and can only report "profile missing" — which never tells the user which
1536
+ * license to add. The profile source we are about to deploy is the
1537
+ * authoritative declaration of the required license.
1538
+ *
1539
+ * @returns {string|null} the license name, or null if the file / field is absent
1540
+ */
1541
+ function readProfileUserLicense(selfRegProfile) {
1542
+ const profilePath = resolve(SFDX_SOURCE, 'profiles', `${selfRegProfile}.profile-meta.xml`);
1543
+ if (!existsSync(profilePath)) return null;
1544
+ const xml = readFileSync(profilePath, 'utf8');
1545
+ const m = xml.match(/<userLicense>\s*([^<]+?)\s*<\/userLicense>/);
1546
+ return m ? m[1].trim() : null;
1547
+ }
1548
+
1549
+ /**
1550
+ * Deploy license pre-check. `sf project deploy start` fails with a
1551
+ * cryptic error when the org lacks the UserLicense the selfRegProfile's metadata
1552
+ * declares. Resolve the required license NAME from the local profile source, then
1553
+ * query the org's UserLicense by that name so a miss names the actual license the
1554
+ * admin must add — not the not-yet-deployed profile. Seat/status math is shared
1555
+ * with the self-reg gate via evaluateLicenseRows.
1556
+ *
1557
+ * @returns {{ satisfied: boolean, reason: string|null }}
1558
+ */
1559
+ function checkDeployLicense(selfRegConfig, targetOrg) {
1560
+ const licenseName = readProfileUserLicense(selfRegConfig.selfRegProfile);
1561
+ // No <userLicense> in the profile source (or profile file absent) — nothing to
1562
+ // gate on; let deploy proceed and surface any real error on its own.
1563
+ if (!licenseName) return { satisfied: true, reason: null };
1564
+
1565
+ const query =
1566
+ `SELECT LicenseDefinitionKey, Name, Status, TotalLicenses, UsedLicenses ` +
1567
+ `FROM UserLicense WHERE Name = '${escapeSoqlString(licenseName)}'`;
1568
+ const result = spawnSync('sf', [
1569
+ 'data', 'query',
1570
+ '--query', query,
1571
+ '--target-org', targetOrg,
1572
+ '--json',
1573
+ ], { cwd: ROOT, encoding: 'utf8' });
1574
+
1575
+ if (result.status !== 0) {
1576
+ if (result.stderr) console.error(result.stderr);
1577
+ return { satisfied: false, reason: `could not query UserLicense "${licenseName}" (sf data query failed)` };
1578
+ }
1579
+ let rows;
1580
+ try {
1581
+ rows = JSON.parse(result.stdout).result?.records ?? [];
1582
+ } catch {
1583
+ return { satisfied: false, reason: `could not parse the UserLicense query result for "${licenseName}"` };
1584
+ }
1585
+ if (rows.length === 0) {
1586
+ return {
1587
+ satisfied: false,
1588
+ reason: `required license "${licenseName}" is not present in the org — add it before deploying`,
1589
+ };
1590
+ }
1591
+ // evaluateLicenseRows expects the license nested under `.UserLicense` (its
1592
+ // Profile-query shape); reshape the direct UserLicense rows to match so the
1593
+ // seat/status logic — and its license-named messages — stay shared.
1594
+ return evaluateLicenseRows(rows.map((r) => ({ UserLicense: r })), selfRegConfig.selfRegProfile);
1595
+ }
1596
+
1597
+ function isOrgConnected(targetOrg) {
1598
+ const result = spawnSync('sf', ['org', 'display', '--target-org', targetOrg, '--json'], {
1599
+ cwd: ROOT,
1600
+ stdio: 'pipe',
1601
+ shell: true,
1602
+ });
1603
+ return result.status === 0;
1604
+ }
1605
+
1606
+ function apexLiteral(value) {
1607
+ if (value === null || value === undefined) return 'null';
1608
+ if (typeof value === 'boolean') return String(value);
1609
+ if (typeof value === 'number') return String(value);
1610
+ const s = String(value);
1611
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return `Date.valueOf('${s}')`;
1612
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(s)) {
1613
+ const dt = s.replace('T', ' ').replace(/\.\d+/, '').replace('Z', '');
1614
+ return `DateTime.valueOf('${dt}')`;
1615
+ }
1616
+ return "'" + s.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'";
1617
+ }
1618
+
1619
+ function buildApexInsert(sobject, records, refIds) {
1620
+ // The sobject type and every field key land as bare identifiers inside the
1621
+ // generated Apex (`new ${sobject}()`, `r.put('${key}', …)`), where they can't
1622
+ // be quoted-and-escaped like a value — so they get the strict API-name
1623
+ // whitelist. refIds are the record referenceIds echoed back through a JSON
1624
+ // marker; they carry no Apex-identifier role, so escaping (not whitelisting)
1625
+ // is the right treatment for their single-quoted literal. All three come from
1626
+ // app-shipped seed fixtures, so a violation is a fixture bug surfaced loudly.
1627
+ validateApiName(sobject, 'sobject type');
1628
+ const lines = [
1629
+ 'Database.DMLOptions dmlOpts = new Database.DMLOptions();',
1630
+ // Intentional: bypass duplicate rules for seed-data import. These are
1631
+ // controlled fixtures the app ships, not user input, and duplicate-rule
1632
+ // blocks (plus matching-service timeouts the REST Sforce-Duplicate-Rule-Action
1633
+ // header can't override) would abort an otherwise-valid setup.
1634
+ 'dmlOpts.DuplicateRuleHeader.allowSave = true;',
1635
+ `List<${sobject}> recs = new List<${sobject}>();`,
1636
+ ];
1637
+ for (const rec of records) {
1638
+ lines.push(`{ ${sobject} r = new ${sobject}();`);
1639
+ for (const [key, val] of Object.entries(rec)) {
1640
+ if (key === 'attributes') continue;
1641
+ validateApiName(key, `field API name on ${sobject}`);
1642
+ lines.push(`r.put('${key}', ${apexLiteral(val)});`);
1643
+ }
1644
+ lines.push('recs.add(r); }');
1645
+ }
1646
+ lines.push('Database.SaveResult[] results = Database.insert(recs, dmlOpts);');
1647
+ const refArray = refIds.map((r) => `'${escapeSoqlString(r)}'`).join(',');
1648
+ lines.push(`String[] refs = new String[]{${refArray}};`);
1649
+ // Emit ONE machine-readable line instead of one System.debug per record: a
1650
+ // JSON array of {ref, id?|err?}. The Node side parses this with
1651
+ // parseApexInsertResults and treats a missing/unparseable marker as a hard
1652
+ // batch failure (a truncated debug line must not read as "0 errors"). Measured
1653
+ // batching keeps each batch — and thus this payload — well under the log line
1654
+ // size.
1655
+ lines.push('List<Object> setupOut = new List<Object>();');
1656
+ lines.push('for (Integer i = 0; i < results.size(); i++) {');
1657
+ lines.push(' Map<String,Object> m = new Map<String,Object>{ \'ref\' => refs[i] };');
1658
+ lines.push(' if (results[i].isSuccess()) { m.put(\'id\', results[i].getId()); }');
1659
+ lines.push(' else { m.put(\'err\', results[i].getErrors()[0].getMessage()); }');
1660
+ lines.push(' setupOut.add(m);');
1661
+ lines.push('}');
1662
+ // Use LoggingLevel.ERROR to ensure this critical line appears near the end of
1663
+ // the debug log and isn't truncated by excessive DEBUG-level noise from DML
1664
+ // operations, workflow rules, or process builders that fire during insert.
1665
+ lines.push("System.debug(LoggingLevel.ERROR, 'SETUP_RESULT_JSON:' + JSON.serialize(setupOut));");
1666
+ return lines.join('\n');
1667
+ }
1668
+
1669
+ /**
1670
+ * Interactive multi-select: arrow keys navigate, space toggles, 'a' toggles all, enter confirms.
1671
+ * Returns a boolean[] matching the input order. Falls through immediately when stdin is not a TTY.
1672
+ */
1673
+ async function promptSteps(steps) {
1674
+ if (!process.stdin.isTTY) return steps.map((s) => s.enabled);
1675
+
1676
+ // `selected` stays indexed by ORIGINAL step order (so the caller's
1677
+ // selections[i] → stepDefs[i] mapping is unchanged); unavailable steps remain
1678
+ // false. Only available steps are shown and navigable — unavailable steps are
1679
+ // hidden entirely rather than rendered greyed-out.
1680
+ const selected = steps.map((s) => s.enabled);
1681
+ const visible = steps.map((s, i) => ({ step: s, index: i })).filter(({ step }) => step.available);
1682
+ let cursor = 0;
1683
+ const RST = '\x1B[0m';
1684
+ const CYAN = '\x1B[36m';
1685
+ const GREEN = '\x1B[32m';
1686
+
1687
+ /** Strip ANSI escape sequences to get visible character count. */
1688
+ function visibleLength(str) {
1689
+ return str.replace(/\x1B\[[0-9;]*m/g, '').length;
1690
+ }
1691
+
1692
+ /** Count how many terminal rows a set of lines occupies (accounting for wrapping). */
1693
+ function terminalRows(lines) {
1694
+ const cols = process.stdout.columns || 80;
1695
+ let rows = 0;
1696
+ for (const line of lines) {
1697
+ const len = visibleLength(line);
1698
+ rows += len === 0 ? 1 : Math.ceil(len / cols);
1699
+ }
1700
+ return rows;
1701
+ }
1702
+
1703
+ function render() {
1704
+ return visible.map(({ step, index }, row) => {
1705
+ const ptr = row === cursor ? `${CYAN}❯${RST}` : ' ';
1706
+ const chk = selected[index] ? `${GREEN}●${RST}` : '○';
1707
+ return `${ptr} ${chk} ${step.label}`;
1708
+ });
1709
+ }
1710
+
1711
+ let prevRows = 0;
1712
+
1713
+ return new Promise((resolve) => {
1714
+ process.stdin.setRawMode(true);
1715
+ process.stdin.resume();
1716
+ process.stdin.setEncoding('utf8');
1717
+ process.stdout.write('\x1B[?25l');
1718
+ console.log('\nSelect steps (↑↓ move, space toggle, a all, enter confirm):\n');
1719
+ const initialLines = render();
1720
+ prevRows = terminalRows(initialLines);
1721
+ process.stdout.write(initialLines.join('\n') + '\n');
1722
+
1723
+ function redraw() {
1724
+ process.stdout.write(`\x1B[${prevRows}A`);
1725
+ const lines = render();
1726
+ for (const line of lines) process.stdout.write(`\x1B[2K${line}\n`);
1727
+ prevRows = terminalRows(lines);
1728
+ }
1729
+
1730
+ process.stdin.on('data', (key) => {
1731
+ if (key === '\x03') {
1732
+ process.stdout.write('\x1B[?25h\n');
1733
+ process.exit(0);
1734
+ }
1735
+ if (key === '\r' || key === '\n') {
1736
+ process.stdout.write('\x1B[?25h');
1737
+ process.stdin.setRawMode(false);
1738
+ process.stdin.pause();
1739
+ process.stdin.removeAllListeners('data');
1740
+ console.log();
1741
+ resolve(selected);
1742
+ return;
1743
+ }
1744
+ // Note: `cursor` indexes `visible`; `selected` is indexed by ORIGINAL step
1745
+ // order. Map through visible[cursor].index before touching `selected`.
1746
+ if (key === ' ') {
1747
+ const { index } = visible[cursor];
1748
+ selected[index] = !selected[index];
1749
+ redraw();
1750
+ return;
1751
+ }
1752
+ if (key === 'a') {
1753
+ const allOn = visible.every(({ index }) => selected[index]);
1754
+ for (const { index } of visible) selected[index] = !allOn;
1755
+ redraw();
1756
+ return;
1757
+ }
1758
+ if (key === '\x1B[A' || key === 'k') {
1759
+ cursor = Math.max(0, cursor - 1);
1760
+ redraw();
1761
+ } else if (key === '\x1B[B' || key === 'j') {
1762
+ cursor = Math.min(visible.length - 1, cursor + 1);
1763
+ redraw();
1764
+ }
1765
+ });
1766
+ });
1767
+ }
1768
+
1769
+ function run(name, cmd, args, opts = {}) {
1770
+ const { cwd = ROOT, optional = false } = opts;
1771
+ console.log('\n---', name, '---');
1772
+ const result = spawnSync(cmd, args, {
1773
+ cwd,
1774
+ stdio: 'inherit',
1775
+ shell: true,
1776
+ ...(opts.env && { env: opts.env }),
1777
+ ...(opts.timeout && { timeout: opts.timeout }),
1778
+ });
1779
+ if (result.status !== 0 && !optional) {
1780
+ throw new StepError(`${name} (exit ${result.status ?? 1})`);
1781
+ }
1782
+ return result;
1783
+ }
1784
+
1785
+ /** Promise-based spawn for parallel execution. Always uses stdio: 'pipe'. */
1786
+ function spawnAsync(cmd, args, opts = {}) {
1787
+ return new Promise((resolve, reject) => {
1788
+ const proc = nodeSpawn(cmd, args, {
1789
+ cwd: opts.cwd || ROOT,
1790
+ stdio: 'pipe',
1791
+ shell: true,
1792
+ ...(opts.timeout && { timeout: opts.timeout }),
1793
+ });
1794
+ let stdout = '';
1795
+ let stderr = '';
1796
+ proc.stdout.on('data', (d) => { stdout += d.toString(); });
1797
+ proc.stderr.on('data', (d) => { stderr += d.toString(); });
1798
+ proc.on('close', (code) => resolve({ status: code, stdout, stderr }));
1799
+ proc.on('error', reject);
1800
+ });
1801
+ }
1802
+
1803
+ /** Async version of run() for parallel steps. Captures output and prints on failure. */
1804
+ async function runAsync(name, cmd, args, opts = {}) {
1805
+ const { cwd = ROOT, optional = false } = opts;
1806
+ const result = await spawnAsync(cmd, args, { cwd, ...(opts.timeout && { timeout: opts.timeout }) });
1807
+ if (result.status !== 0 && !optional) {
1808
+ if (result.stdout) process.stdout.write(result.stdout);
1809
+ if (result.stderr) process.stderr.write(result.stderr);
1810
+ throw new StepError(`${name} (exit ${result.status ?? 1})`);
1811
+ }
1812
+ return result;
1813
+ }
1814
+
1815
+ /**
1816
+ * In-memory result ledger. Each selected step records exactly one outcome:
1817
+ * ok — the step ran and succeeded
1818
+ * skipped — the step was not selected, or had no config section (intentional)
1819
+ * failed — the step ran and failed (with a human-readable reason)
1820
+ * The end-of-run summary is rendered from this ledger and the process exits
1821
+ * non-zero whenever any step is `failed` (fail-fast or skippable alike).
1822
+ *
1823
+ * @typedef {{ key: string, label: string, status: 'ok'|'skipped'|'failed', reason?: string, failFast?: boolean }} StepResult
1824
+ */
1825
+ const results = [];
1826
+ function recordOk(step) {
1827
+ results.push({ key: step.key, label: step.label, status: 'ok', failFast: step.failFast });
1828
+ }
1829
+ function recordSkipped(step, reason) {
1830
+ results.push({ key: step.key, label: step.label, status: 'skipped', reason, failFast: step.failFast });
1831
+ }
1832
+ function recordFailed(step, reason) {
1833
+ results.push({ key: step.key, label: step.label, status: 'failed', reason, failFast: step.failFast });
1834
+ }
1835
+
1836
+ /** True if any step in the ledger failed. */
1837
+ function finalExitCode() {
1838
+ return results.some((r) => r.status === 'failed') ? 1 : 0;
1839
+ }
1840
+
1841
+ const SUMMARY_GLYPH = { ok: '✔', skipped: '–', failed: '✖' };
1842
+
1843
+ /**
1844
+ * Render the end-of-run summary. Always called — on success, on a fail-fast
1845
+ * abort (partial: only steps reached so far are present), and on a clean finish
1846
+ * that had skippable failures. Failed rows are listed last so the real problem
1847
+ * is the last thing the developer sees.
1848
+ */
1849
+ function printSummary(targetOrg) {
1850
+ const ordered = [
1851
+ ...results.filter((r) => r.status !== 'failed'),
1852
+ ...results.filter((r) => r.status === 'failed'),
1853
+ ];
1854
+ const pad = Math.max(0, ...ordered.map((r) => r.key.length));
1855
+ console.log(`\nSetup summary (target org: ${targetOrg})`);
1856
+ for (const r of ordered) {
1857
+ const glyph = SUMMARY_GLYPH[r.status] ?? ' ';
1858
+ const key = r.key.padEnd(pad);
1859
+ let line = ` ${glyph} ${key} ${r.status}`;
1860
+ if (r.reason) line += ` (${r.reason})`;
1861
+ if (r.status === 'failed') line += r.failFast ? ' [fail-fast — aborted]' : ' [skippable — continued]';
1862
+ console.log(line);
1863
+ }
1864
+ const failures = results.filter((r) => r.status === 'failed').length;
1865
+ if (failures > 0) {
1866
+ console.log(`Setup completed with ${failures} failure(s). Exiting 1.`);
1867
+ } else {
1868
+ console.log('Setup complete.');
1869
+ }
1870
+ }
1871
+
1872
+ /**
1873
+ * Run one step body, recording its outcome in the ledger and honoring the
1874
+ * step's fixed `failFast` classification. The body either completes (→ ok),
1875
+ * throws a StepError (→ failed), or throws something unexpected (→ failed,
1876
+ * with the raw message). On a fail-fast failure this prints the partial
1877
+ * summary and exits non-zero immediately; on a skippable failure it records
1878
+ * and returns so the run continues.
1879
+ */
1880
+ async function runStep(step, targetOrg, body) {
1881
+ try {
1882
+ await body();
1883
+ recordOk(step);
1884
+ } catch (err) {
1885
+ const reason = err instanceof StepError ? err.message : (err?.message ?? String(err));
1886
+ recordFailed(step, reason);
1887
+ console.error(`\nStep "${step.key}" failed: ${reason}`);
1888
+ if (step.failFast) {
1889
+ printSummary(targetOrg);
1890
+ process.exit(1);
1891
+ }
1892
+ }
1893
+ }
1894
+
1895
+ async function main() {
1896
+ // Cleanup AT START: remove Apex temp artifacts left by a prior hard-killed run.
1897
+ // Safe to run before the per-org lock is acquired because it only removes
1898
+ // org-setup-* temp DIRECTORIES and legacy ROOT temp files — never the
1899
+ // org-setup-lock-<org>.lock files (plain files), so it cannot clobber a
1900
+ // concurrent run's live lock.
1901
+ sweepStaleApexTempDirs();
1902
+
1903
+ // Ensure .gitignore files exist (npm strips them from published packages).
1904
+ const gitignoreTemplates = loadGitignoreTemplates();
1905
+ if (gitignoreTemplates) {
1906
+ ensureGitignore(ROOT, gitignoreTemplates.sfdx);
1907
+ if (existsSync(UIBUNDLES_DIR)) {
1908
+ for (const entry of readdirSync(UIBUNDLES_DIR, { withFileTypes: true })) {
1909
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
1910
+ ensureGitignore(resolve(UIBUNDLES_DIR, entry.name), gitignoreTemplates.webapp);
1911
+ }
1912
+ }
1913
+ }
1914
+ }
1915
+
1916
+ const parsed = parseArgs();
1917
+ const {
1918
+ uiBundleName,
1919
+ permsetNamesExplicit,
1920
+ yes,
1921
+ skipDeploy: argSkipDeploy,
1922
+ skipPermset: argSkipPermset,
1923
+ skipRole: argSkipRole,
1924
+ skipSelfReg: argSkipSelfReg,
1925
+ skipSocialLogin: argSkipSocialLogin,
1926
+ skipData: argSkipData,
1927
+ skipGraphql: argSkipGraphql,
1928
+ skipUIBundleBuild: argSkipUIBundleBuild,
1929
+ } = parsed;
1930
+
1931
+ // Resolve the target org up front: explicit --target-org is used verbatim;
1932
+ // otherwise prompt (TTY) or fall back to the default org / exit.
1933
+ const targetOrg = await resolveTargetOrg(parsed);
1934
+
1935
+ // Per-target-org lock: acquired right after the start-of-run
1936
+ // sweep and before any step runs, so two runs against the same org cannot
1937
+ // interleave destructive Apex. The startup sweep above deliberately skips lock
1938
+ // files, so it never races this. Released on process exit.
1939
+ acquireOrgLock(targetOrg);
1940
+
1941
+ const permsetNames =
1942
+ permsetNamesExplicit.length > 0 ? permsetNamesExplicit : discoverPermissionSetNames();
1943
+ const permsetStepLabel =
1944
+ permsetNames.length === 0
1945
+ ? 'Permset — (none under permissionsets/)'
1946
+ : permsetNames.length <= 3
1947
+ ? `Permset — assign ${permsetNames.join(', ')}`
1948
+ : `Permset — assign ${permsetNames.length} permission sets`;
1949
+
1950
+ // Validate org-setup.config.json ONCE, before any step runs. The three
1951
+ // load*Config helpers read from this already-validated object.
1952
+ const config = loadValidatedConfig();
1953
+
1954
+ const hasDataPlan = existsSync(DATA_PLAN) && existsSync(DATA_DIR);
1955
+ const roleConfig = loadRoleConfig(config);
1956
+ const hasRoleConfig = roleConfig !== null;
1957
+ const selfRegConfig = loadSelfRegConfig(config);
1958
+ const hasSelfRegConfig = selfRegConfig !== null;
1959
+ const socialLoginConfig = loadSocialLoginConfig(config);
1960
+ const hasSocialLoginConfig = socialLoginConfig !== null;
1961
+ const logoutUrl = loadLogoutUrlConfig(config);
1962
+
1963
+ // Validate the selfRegProfile name for SOQL-safety up front, alongside the
1964
+ // config validation and BEFORE any org mutation (login/deploy). A quote /
1965
+ // backslash / control char is a config mistake, not a runtime value to
1966
+ // escape — fail fast here with a clean, actionable message rather than
1967
+ // letting the license gate throw a raw stack trace deep in the run after deploy.
1968
+ if (hasSelfRegConfig) {
1969
+ try {
1970
+ validateProfileNameForSoql(selfRegConfig.selfRegProfile);
1971
+ } catch (err) {
1972
+ console.error(`Invalid org-setup.config.json:\n - ${err.message}`);
1973
+ process.exit(1);
1974
+ }
1975
+ }
1976
+
1977
+ // Same fail-fast treatment for the socialLogin identifiers, alongside the
1978
+ // self-reg guard above and BEFORE any org mutation. communityMemberProfile,
1979
+ // every authProviderNames entry, and the optional communityUserPermset are all
1980
+ // interpolated into generated SOQL / CLI value strings — the Profile and
1981
+ // PermissionSet `WHERE Name = '…'` lookups, the AuthProvider/SamlSsoConfig
1982
+ // `DeveloperName IN (…)` list, and the NetworkMemberGroup/User queries. These
1983
+ // are developer-authored identifiers the app ships, so a quote / backslash /
1984
+ // control char is a config mistake to surface loudly here rather than a value
1985
+ // to silently escape (same rationale as validateSoqlName's self-reg use).
1986
+ if (hasSocialLoginConfig) {
1987
+ try {
1988
+ validateSoqlName(socialLoginConfig.communityMemberProfile, 'socialLogin.communityMemberProfile');
1989
+ for (const providerName of socialLoginConfig.authProviderNames ?? []) {
1990
+ validateSoqlName(providerName, 'socialLogin.authProviderNames entry');
1991
+ }
1992
+ if (socialLoginConfig.communityUserPermset) {
1993
+ validateSoqlName(socialLoginConfig.communityUserPermset, 'socialLogin.communityUserPermset');
1994
+ }
1995
+ } catch (err) {
1996
+ console.error(`Invalid org-setup.config.json:\n - ${err.message}`);
1997
+ process.exit(1);
1998
+ }
1999
+ }
2000
+
2001
+ // failFast is a fixed, implementer-owned classification — NOT
2002
+ // user-configurable. A fail-fast failure aborts the run immediately; a
2003
+ // skippable failure is recorded and the run continues. The exit code is
2004
+ // non-zero on any failure regardless of class.
2005
+ // Login is NOT in this picker: it is an unconditional precondition run before
2006
+ // deploy, not a toggleable step. The dev step is also gone: launching the dev
2007
+ // server moved to `npm run dev:preview`, so setup terminates cleanly after
2008
+ // graphql.
2009
+ const stepDefs = [
2010
+ { key: 'uiBundleBuild', label: 'UI Bundle Build — npm install + build (pre-deploy)', enabled: !argSkipUIBundleBuild, available: true, failFast: true },
2011
+ { key: 'deploy', label: 'Deploy — sf project deploy start', enabled: !argSkipDeploy, available: true, failFast: true },
2012
+ { key: 'permset', label: permsetStepLabel, enabled: !argSkipPermset, available: true, failFast: false },
2013
+ { key: 'role', label: `Role — assign "${roleConfig?.roleName ?? '?'}" to current user`, enabled: !argSkipRole && hasRoleConfig, available: hasRoleConfig, failFast: false },
2014
+ { key: 'selfReg', label: 'Self-Registration — enable for site', enabled: !argSkipSelfReg && hasSelfRegConfig, available: hasSelfRegConfig, failFast: false },
2015
+ { key: 'socialLogin', label: 'Social Login — enable auth providers + community profile', enabled: !argSkipSocialLogin && hasSocialLoginConfig, available: hasSocialLoginConfig, failFast: false },
2016
+ { key: 'data', label: 'Data — delete + import records via Apex', enabled: !argSkipData && hasDataPlan, available: hasDataPlan, failFast: true },
2017
+ { key: 'graphql', label: 'GraphQL — schema introspect + codegen', enabled: !argSkipGraphql, available: true, failFast: true },
2018
+ ];
2019
+
2020
+ const selections = yes ? stepDefs.map((s) => s.enabled) : await promptSteps(stepDefs);
2021
+ const on = {};
2022
+ stepDefs.forEach((s, i) => {
2023
+ on[s.key] = selections[i];
2024
+ });
2025
+
2026
+ const skipUIBundleBuild = !on.uiBundleBuild;
2027
+ const skipDeploy = !on.deploy;
2028
+ const skipPermset = !on.permset;
2029
+ const skipRole = !on.role;
2030
+ const skipSelfReg = !on.selfReg;
2031
+ const skipSocialLogin = !on.socialLogin;
2032
+ const skipData = !on.data;
2033
+ const skipGraphql = !on.graphql;
2034
+
2035
+ const needsUIBundle = !skipUIBundleBuild || !skipGraphql;
2036
+ const uiBundleDir = needsUIBundle ? await discoverUIBundleDir(uiBundleName) : null;
2037
+ const doData = !skipData;
2038
+
2039
+ console.log('Setup — target org:', targetOrg, '| UI bundle:', uiBundleDir ?? '(none)');
2040
+ console.log(
2041
+ 'Steps: login=always deploy=%s permset=%s role=%s selfReg=%s socialLogin=%s data=%s graphql=%s uiBundle=%s',
2042
+ !skipDeploy,
2043
+ !skipPermset,
2044
+ !skipRole,
2045
+ !skipSelfReg,
2046
+ !skipSocialLogin,
2047
+ doData,
2048
+ !skipGraphql,
2049
+ !skipUIBundleBuild
2050
+ );
2051
+
2052
+ // Login is an unconditional precondition: it is not part of
2053
+ // the step picker and cannot be skipped. It still no-ops when the org is already
2054
+ // connected, and stays fail-fast — a failed browser login aborts before deploy.
2055
+ const loginStep = { key: 'login', label: 'Login — org authentication', failFast: true };
2056
+ await runStep(loginStep, targetOrg, async () => {
2057
+ if (isOrgConnected(targetOrg)) {
2058
+ console.log('\n--- Login ---');
2059
+ console.log(`Org ${targetOrg} is already authenticated; skipping browser login.`);
2060
+ } else {
2061
+ run('Login (browser)', 'sf', ['org', 'login', 'web', '--alias', targetOrg]);
2062
+ }
2063
+ });
2064
+
2065
+ // Ensure the self-reg profile is in networkMemberGroups before deploy so that
2066
+ // subsequent selfRegProfile / selfRegistration updates don't fail. This is
2067
+ // best-effort prep: if the site can't be derived (no network file, or the
2068
+ // ambiguous multi-network case where deriveSiteName throws), skip the prep
2069
+ // silently here — the selfReg step records that derivation failure as a
2070
+ // skippable StepError, so it stays in the ledger instead of aborting pre-deploy.
2071
+ if (!skipDeploy && selfRegConfig) {
2072
+ let preDeploySiteName = null;
2073
+ try {
2074
+ preDeploySiteName = deriveSiteName();
2075
+ } catch {
2076
+ // ambiguous derivation — surfaced by the selfReg step below
2077
+ }
2078
+ if (preDeploySiteName) {
2079
+ console.log('\n--- Ensure network member profile (pre-deploy) ---');
2080
+ ensureNetworkMemberProfile(selfRegConfig, preDeploySiteName);
2081
+ }
2082
+ }
2083
+
2084
+ // Build all UI Bundles before deploy so dist exists for entity deployment
2085
+ const uiBundleBuildStep = stepDefs.find((s) => s.key === 'uiBundleBuild');
2086
+ let preDeployBundlesBuilt = false;
2087
+ if (!skipUIBundleBuild) {
2088
+ if (!skipDeploy) {
2089
+ await runStep(uiBundleBuildStep, targetOrg, () => {
2090
+ const allUIBundleDirs = discoverAllUIBundleDirs(uiBundleName);
2091
+ for (const dir of allUIBundleDirs) {
2092
+ const name = dir.split(/[/\\]/).pop();
2093
+ run(`UI Bundle install (${name})`, 'npm', ['install'], { cwd: dir });
2094
+ run(`UI Bundle build (${name})`, 'npm', ['run', 'build'], { cwd: dir });
2095
+ }
2096
+ });
2097
+ preDeployBundlesBuilt = true;
2098
+ }
2099
+ // When skipDeploy, the bundle build happens in the GraphQL section below;
2100
+ // its outcome is recorded there.
2101
+ } else {
2102
+ recordSkipped(uiBundleBuildStep, 'not selected');
2103
+ }
2104
+
2105
+ const deployStep = stepDefs.find((s) => s.key === 'deploy');
2106
+ if (!skipDeploy) {
2107
+ await runStep(deployStep, targetOrg, () => {
2108
+ // License pre-check: deploy fails with a cryptic error when the
2109
+ // org lacks the UserLicense the selfRegProfile's metadata requires. Verify a
2110
+ // seat is available BEFORE `sf project deploy start` so the run aborts with a
2111
+ // clean message NAMING the missing license. The required license is read from
2112
+ // the local profile source (the profile isn't in the org yet pre-deploy, so
2113
+ // querying it would only report "profile missing"). Only gates when self-reg
2114
+ // is configured — that config names the profile the license is derived from.
2115
+ if (selfRegConfig) {
2116
+ const licenseGate = checkDeployLicense(selfRegConfig, targetOrg);
2117
+ if (!licenseGate.satisfied) {
2118
+ throw new StepError(`deploy blocked — ${licenseGate.reason}`);
2119
+ }
2120
+ }
2121
+ run('Deploy metadata', 'sf', ['project', 'deploy', 'start', '--target-org', targetOrg], {
2122
+ timeout: 180000,
2123
+ });
2124
+ });
2125
+ } else {
2126
+ recordSkipped(deployStep, 'not selected');
2127
+ }
2128
+
2129
+ // Set the site's logout URL AFTER deploy so members land back on THIS site after
2130
+ // logging out (not the org default-site login, which in a multi-site org can be a
2131
+ // different community). Post-deploy because the deployed value must be an ABSOLUTE
2132
+ // URL (the platform rejects a relative one) and the shipped site-relative path is
2133
+ // resolved against the site's community origin — which only exists once the site
2134
+ // is deployed. Independent of self-reg; best-effort (a failure logs loudly, does
2135
+ // not abort). An ambiguous multi-network app can't auto-target a single site, so
2136
+ // derivation failure skips it.
2137
+ if (!skipDeploy && logoutUrl) {
2138
+ let logoutSiteName = null;
2139
+ try {
2140
+ logoutSiteName = deriveSiteName();
2141
+ } catch {
2142
+ // ambiguous derivation (multiple network files) — skip logout URL prep
2143
+ }
2144
+ if (logoutSiteName) {
2145
+ console.log('\n--- Ensure logout URL (post-deploy) ---');
2146
+ ensureLogoutUrl(logoutUrl, logoutSiteName, targetOrg);
2147
+ }
2148
+ }
2149
+
2150
+ const permsetStep = stepDefs.find((s) => s.key === 'permset');
2151
+ if (!skipPermset) {
2152
+ await runStep(permsetStep, targetOrg, async () => {
2153
+ const permsetConfig = loadPermsetConfig(config);
2154
+ if (permsetNames.length === 0) {
2155
+ console.log('\n--- Assign permission sets ---');
2156
+ console.log('No permission sets found under permissionsets/ and none passed via --permset-name; skipping.');
2157
+ return;
2158
+ }
2159
+ console.log('\n--- Assign permission sets ---');
2160
+
2161
+ // Resolve assignments (guest user lookups etc.) then run all sf assign calls in parallel.
2162
+ //
2163
+ // A guest-user resolution failure (no derivable site, or no guest user yet)
2164
+ // is collected — NOT thrown mid-loop. Throwing here would unwind the whole
2165
+ // runStep body before Promise.all and silently drop every assignment already
2166
+ // queued (e.g. a currentUser permset that sorts ahead of a guestUser one and
2167
+ // never depended on the site at all). Resolvable assignments still run; the
2168
+ // combined failure is thrown at the end so the step is still recorded failed.
2169
+ const assignmentJobs = [];
2170
+ const resolutionFailures = [];
2171
+ for (const permsetName of permsetNames) {
2172
+ const assignment = resolveAssignment(permsetName, permsetConfig);
2173
+ if (assignment.assignee === 'skip') {
2174
+ console.log(`Permission set "${permsetName}" — skipped (config).`);
2175
+ continue;
2176
+ }
2177
+ let effectiveUsername = null;
2178
+ if (assignment.assignee === 'guestUser') {
2179
+ // Site name is derived from the single network metadata file the app
2180
+ // ships — never restated per-assignment.
2181
+ const siteName = deriveSiteName();
2182
+ if (!siteName) {
2183
+ console.error(`Permission set "${permsetName}" — assignee is "guestUser" but no networks/<siteName>.network-meta.xml was found to derive the site; skipping.`);
2184
+ resolutionFailures.push(`${permsetName} (no network metadata to derive site)`);
2185
+ continue;
2186
+ }
2187
+ effectiveUsername = resolveGuestUsername(siteName, targetOrg);
2188
+ if (!effectiveUsername) {
2189
+ console.error(`Permission set "${permsetName}" — could not resolve guest user for site "${siteName}"; skipping.`);
2190
+ resolutionFailures.push(`${permsetName} (could not resolve guest user for site "${siteName}")`);
2191
+ continue;
2192
+ }
2193
+ console.log(` Resolved guest user for site "${siteName}": ${effectiveUsername}`);
2194
+ }
2195
+ assignmentJobs.push({ permsetName, effectiveUsername });
2196
+ }
2197
+
2198
+ // Run all permset assignment calls in parallel.
2199
+ const assignResults = await Promise.all(assignmentJobs.map(async ({ permsetName, effectiveUsername }) => {
2200
+ const sfArgs = ['org', 'assign', 'permset', '--name', permsetName, '--target-org', targetOrg];
2201
+ if (effectiveUsername) {
2202
+ sfArgs.push('--on-behalf-of', effectiveUsername);
2203
+ }
2204
+ const assigneeLabel = effectiveUsername || 'current user';
2205
+ const result = await spawnAsync('sf', sfArgs);
2206
+ return { permsetName, assigneeLabel, result };
2207
+ }));
2208
+
2209
+ const failures = [];
2210
+ for (const { permsetName, assigneeLabel, result } of assignResults) {
2211
+ if (result.status === 0) {
2212
+ console.log(`Permission set "${permsetName}" assigned to ${assigneeLabel}.`);
2213
+ } else {
2214
+ const out = (result.stderr || '') + (result.stdout || '');
2215
+ if (out.includes('Duplicate') && out.includes('PermissionSet')) {
2216
+ console.log(`Permission set "${permsetName}" already assigned to ${assigneeLabel}; skipping.`);
2217
+ } else if (out.includes('not found') && out.includes('target org')) {
2218
+ console.log(`Permission set "${permsetName}" not in org; skipping.`);
2219
+ } else {
2220
+ if (result.stdout) process.stdout.write(result.stdout);
2221
+ if (result.stderr) process.stderr.write(result.stderr);
2222
+ failures.push(`${permsetName} (exit ${result.status ?? 1})`);
2223
+ }
2224
+ }
2225
+ }
2226
+ const allFailures = [...resolutionFailures, ...failures];
2227
+ if (allFailures.length > 0) {
2228
+ throw new StepError(`failed to assign permission set(s): ${allFailures.join(', ')}`);
2229
+ }
2230
+ });
2231
+ } else {
2232
+ recordSkipped(permsetStep, 'not selected');
2233
+ }
2234
+
2235
+ const roleStep = stepDefs.find((s) => s.key === 'role');
2236
+ if (!skipRole) {
2237
+ console.log('\n--- Assign role ---');
2238
+ // Config shape (assignee === 'currentUser', non-empty roleName) is guaranteed
2239
+ // by the schema, so there is nothing to re-check here — the step either ran
2240
+ // (ok) or its assignment threw (failed). No manual recordSkipped inference.
2241
+ await runStep(roleStep, targetOrg, () => {
2242
+ assignRoleToCurrentUser(roleConfig.roleName, targetOrg);
2243
+ });
2244
+ } else {
2245
+ recordSkipped(roleStep, roleStep.available ? 'not selected' : 'no config');
2246
+ }
2247
+
2248
+ const selfRegStep = stepDefs.find((s) => s.key === 'selfReg');
2249
+ if (!skipSelfReg) {
2250
+ // License pre-check: self-registration requires a seat on the
2251
+ // UserLicense the selfRegProfile belongs to. Verify it BEFORE running the step
2252
+ // — recordSkipped is only reachable here, ahead of runStep (mirroring the
2253
+ // not-selected branch); once inside a step body an unmet precondition could
2254
+ // only record `failed`. A missing / inactive / seatless license is a soft
2255
+ // precondition, not a setup failure, so warn + recordSkipped and move on.
2256
+ const licenseGate = checkSelfRegLicense(selfRegConfig, targetOrg);
2257
+ if (!licenseGate.satisfied) {
2258
+ console.warn(`\n--- Self-registration skipped ---\n ⚠ ${licenseGate.reason}`);
2259
+ recordSkipped(selfRegStep, licenseGate.reason);
2260
+ } else {
2261
+ console.log('\n--- Enable self-registration ---');
2262
+ // Config shape (selfRegProfile, accountName) is guaranteed by the schema.
2263
+ // The site is derived inside the step body so a "multiple network files"
2264
+ // StepError is recorded in the ledger rather than escaping. No manual
2265
+ // recordSkipped inference.
2266
+ await runStep(selfRegStep, targetOrg, () => {
2267
+ const siteName = deriveSiteName();
2268
+ if (!siteName) {
2269
+ throw new StepError(
2270
+ 'self-registration is configured but no networks/<siteName>.network-meta.xml was found to derive the site',
2271
+ );
2272
+ }
2273
+ enableSelfRegistration(selfRegConfig, siteName, targetOrg);
2274
+ });
2275
+ }
2276
+ } else {
2277
+ recordSkipped(selfRegStep, selfRegStep.available ? 'not selected' : 'no config');
2278
+ }
2279
+
2280
+ const socialLoginStep = stepDefs.find((s) => s.key === 'socialLogin');
2281
+ if (!skipSocialLogin) {
2282
+ console.log('\n--- Social Login — enable auth providers + community profile ---');
2283
+ await runStep(socialLoginStep, targetOrg, () => {
2284
+ const siteName = deriveSiteName();
2285
+ if (!siteName) {
2286
+ throw new StepError(
2287
+ 'socialLogin is configured but no networks/<siteName>.network-meta.xml was found to derive the site',
2288
+ );
2289
+ }
2290
+
2291
+ const totalSubSteps = socialLoginConfig.communityUserPermset ? 4 : 3;
2292
+
2293
+ // Sub-step 1: Enable "Allow using standard external profiles" org setting.
2294
+ // This is required so the SSO registration handler can create users with
2295
+ // standard community profiles (e.g. "Customer Community User").
2296
+ console.log(` [1/${totalSubSteps}] Enabling "Allow standard external profiles" setting...`);
2297
+ enableExternalProfiles(targetOrg);
2298
+
2299
+ // Sub-step 2: Link Auth Providers to the site's AuthConfig.
2300
+ // React (Site Container) sites hide SSO config in Admin UI, so this must
2301
+ // be done programmatically via AuthConfig/AuthConfigProviders records.
2302
+ console.log(` [2/${totalSubSteps}] Linking Auth Providers to site AuthConfig...`);
2303
+ enableAuthProvidersForSite(socialLoginConfig.authProviderNames, siteName, targetOrg);
2304
+
2305
+ // Sub-step 3: Add the community member profile to NetworkMemberGroup.
2306
+ // Without this, users created by the registration handler get
2307
+ // "NO_ACCESS: User was not authorized for the community".
2308
+ console.log(` [3/${totalSubSteps}] Adding community member profile to NetworkMemberGroup...`);
2309
+ addCommunityMemberProfile(socialLoginConfig.communityMemberProfile, siteName, targetOrg);
2310
+
2311
+ // Sub-step 4 (optional): Assign API-enabled permset to community users.
2312
+ // Without this, getCurrentUser() fails because UI API GraphQL requires
2313
+ // PermissionsApiEnabled which the standard community profile lacks.
2314
+ if (socialLoginConfig.communityUserPermset) {
2315
+ console.log(` [4/${totalSubSteps}] Assigning API permset to community users...`);
2316
+ assignPermsetToCommunityUsers(
2317
+ socialLoginConfig.communityUserPermset,
2318
+ socialLoginConfig.communityMemberProfile,
2319
+ targetOrg,
2320
+ );
2321
+ }
2322
+ });
2323
+ } else {
2324
+ recordSkipped(socialLoginStep, socialLoginStep.available ? 'not selected' : 'no config');
2325
+ }
2326
+
2327
+ const dataStep = stepDefs.find((s) => s.key === 'data');
2328
+ if (doData) {
2329
+ await runStep(dataStep, targetOrg, () => {
2330
+ // Prepare data for uniqueness (run before import so repeat imports don't conflict).
2331
+ // Per-app data normalization (reference remapping, unique-field mangling) ships with
2332
+ // the app's seed data as data/prepare-import-unique-fields.js — this script stays
2333
+ // object-agnostic and simply runs it if present.
2334
+ const prepareScript = resolve(DATA_DIR, 'prepare-import-unique-fields.js');
2335
+ if (existsSync(prepareScript)) {
2336
+ run('Prepare data (unique fields)', 'node', [prepareScript, '--data-dir', DATA_DIR], {
2337
+ cwd: ROOT,
2338
+ });
2339
+ }
2340
+
2341
+ // Delete existing records so every run inserts the full dataset without duplicate conflicts.
2342
+ // Reverse plan order ensures children are removed before parents (FK safety).
2343
+ console.log('\n--- Clean existing data for fresh import ---');
2344
+ const planEntries = JSON.parse(readFileSync(DATA_PLAN, 'utf8'));
2345
+ const sobjectsReversed = [...planEntries.map((e) => e.sobject)].reverse();
2346
+ // One private temp dir for both the delete sweep and the import batches;
2347
+ // always removed in finally, even if a batch throws.
2348
+ withApexTempDir((writeApex) => {
2349
+ for (const sobject of sobjectsReversed) {
2350
+ // Bare identifier inside a dynamic-SOQL string literal — whitelist it (the
2351
+ // same guard buildApexInsert applies) so a malformed data-plan sobject
2352
+ // can't alter the delete query.
2353
+ validateApiName(sobject, 'sobject type');
2354
+ const apexCode = [
2355
+ 'try {',
2356
+ ` List<SObject> recs = Database.query('SELECT Id FROM ${sobject} LIMIT 10000');`,
2357
+ ' if (!recs.isEmpty()) {',
2358
+ ' Database.delete(recs, false);',
2359
+ ' Database.emptyRecycleBin(recs);',
2360
+ ' }',
2361
+ '} catch (Exception e) {',
2362
+ ' // non-deletable records (e.g. Contact linked to Case) are skipped via allOrNone=false',
2363
+ '}',
2364
+ ].join('\n');
2365
+ const tmpApex = writeApex('data.apex', apexCode);
2366
+ spawnSync('sf', ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex], {
2367
+ cwd: ROOT,
2368
+ stdio: 'pipe',
2369
+ shell: true,
2370
+ timeout: 60000,
2371
+ });
2372
+ console.log(` ${sobject}: cleaned`);
2373
+ }
2374
+
2375
+ // Import via Anonymous Apex with Database.DMLOptions.duplicateRuleHeader.allowSave = true.
2376
+ // This bypasses both duplicate-rule blocks AND matching-service timeouts that the REST
2377
+ // API headers (Sforce-Duplicate-Rule-Action) cannot override.
2378
+ console.log('\n--- Data import (Apex) ---');
2379
+ const refMap = new Map();
2380
+ // Apex anonymous code is capped at ~1M chars total, but each batch is much
2381
+ // smaller in practice. The real constraint is the SETUP_RESULT_JSON debug log
2382
+ // line: Salesforce truncates debug lines at ~5KB, and large batches produce
2383
+ // JSON arrays that exceed that limit. With RESULT_JSON_PER_RECORD = 150 and
2384
+ // MAX_BATCH = 100, the worst-case output is ~15KB of JSON, which fits
2385
+ // comfortably after the debug-line prefix and the marker.
2386
+ const APEX_CHAR_LIMIT = 25000;
2387
+ const APEX_MAX_BATCH = 100;
2388
+
2389
+ for (const entry of planEntries) {
2390
+ for (const file of entry.files) {
2391
+ const data = JSON.parse(readFileSync(resolve(DATA_DIR, file), 'utf8'));
2392
+ const records = data.records || [];
2393
+
2394
+ for (const rec of records) {
2395
+ for (const key of Object.keys(rec)) {
2396
+ if (key === 'attributes') continue;
2397
+ const val = rec[key];
2398
+ if (typeof val === 'string' && val.startsWith('@')) {
2399
+ const actual = refMap.get(val.slice(1));
2400
+ if (actual) {
2401
+ rec[key] = actual;
2402
+ } else if (refMap.size > 0) {
2403
+ console.warn(` Warning: unresolved ref ${val} in ${file}`);
2404
+ }
2405
+ }
2406
+ }
2407
+ }
2408
+
2409
+ // Measured batching: size each record's rendered Apex (using
2410
+ // the same apexLiteral the insert uses) and pack batches under the char
2411
+ // limit, instead of the old estCharsPerRec = 40 + fields*55 guess that
2412
+ // under-counted long text fields and could overflow the anon-Apex limit.
2413
+ // Overhead is measured from the real builder with zero records so the
2414
+ // fixed boilerplate can't drift from buildApexInsert. Each record also
2415
+ // grows the per-batch `String[] refs = new String[]{'…',…}` line, so its
2416
+ // rendered refId literal is counted here too (mirroring the same
2417
+ // referenceId/_idx fallback the batch emit uses) — otherwise sizing
2418
+ // under-counts and a packed batch could edge past APEX_CHAR_LIMIT.
2419
+ //
2420
+ // CRITICAL: also account for the SETUP_RESULT_JSON output size. The
2421
+ // System.debug line can exceed the Salesforce debug log line limit when
2422
+ // the serialized JSON array is large. Estimate ~85 chars per success
2423
+ // result ({"ref":"_idxNNN","id":"001XXXXXXXXXXXXXXX"}) and ~150 chars per
2424
+ // potential error ({"ref":"_idxNNN","err":"typical error message"}), taking
2425
+ // the higher value to be conservative. This ensures the batching prevents
2426
+ // log truncation that would fail parseApexInsertResults.
2427
+ const overhead = buildApexInsert(entry.sobject, [], []).length;
2428
+ const RESULT_JSON_PER_RECORD = 150;
2429
+ const recordSizes = records.map((rec, i) => {
2430
+ let size = `{ ${entry.sobject} r = new ${entry.sobject}();\n`.length + 'recs.add(r); }\n'.length;
2431
+ for (const [key, val] of Object.entries(rec)) {
2432
+ if (key === 'attributes') continue;
2433
+ size += `r.put('${key}', ${apexLiteral(val)});\n`.length;
2434
+ }
2435
+ const refId = rec.attributes?.referenceId || `_idx${i}`;
2436
+ size += `'${escapeSoqlString(refId)}',`.length;
2437
+ // Add the estimated size of this record's JSON result entry in the
2438
+ // SETUP_RESULT_JSON output. Without this, large batches can produce
2439
+ // debug log lines that exceed Salesforce's limit and get truncated.
2440
+ size += RESULT_JSON_PER_RECORD;
2441
+ return size;
2442
+ });
2443
+ const batches = planApexBatches(recordSizes, {
2444
+ charLimit: APEX_CHAR_LIMIT,
2445
+ maxBatch: APEX_MAX_BATCH,
2446
+ overhead,
2447
+ });
2448
+
2449
+ let imported = 0;
2450
+ for (const { start, count } of batches) {
2451
+ const batch = records.slice(start, start + count);
2452
+ const refIds = batch.map((r, j) => r.attributes?.referenceId || `_idx${start + j}`);
2453
+ const apex = buildApexInsert(entry.sobject, batch, refIds);
2454
+ const tmpApex = writeApex('data.apex', apex);
2455
+ const apexResult = spawnSync(
2456
+ 'sf',
2457
+ ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex],
2458
+ { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 120000 }
2459
+ );
2460
+ const apexOut = apexResult.stdout?.toString() || '';
2461
+ const apexErr = apexResult.stderr?.toString() || '';
2462
+ if (apexResult.status !== 0 && !apexOut.includes('Compiled successfully')) {
2463
+ process.stderr.write(apexErr || apexOut);
2464
+ throw new StepError(`${entry.sobject}: apex execution failed`);
2465
+ }
2466
+ const parsed = parseApexInsertResults(apexOut);
2467
+ if (!parsed.ok) {
2468
+ // A missing/truncated result marker must fail loudly — never read as
2469
+ // "0 errors" and let a partial import look successful.
2470
+ process.stderr.write(apexErr || apexOut);
2471
+ throw new StepError(`data import (${entry.sobject}) — ${parsed.error}`);
2472
+ }
2473
+ if (parsed.errors.length) {
2474
+ for (const e of parsed.errors.slice(0, 5)) {
2475
+ console.error(` ${e.ref}: ${e.message.trim()}`);
2476
+ }
2477
+ if (parsed.errors.length > 5) console.error(` ... and ${parsed.errors.length - 5} more`);
2478
+ throw new StepError(`data import (${entry.sobject}) — ${parsed.errors.length} record error(s)`);
2479
+ }
2480
+ if (entry.saveRefs) {
2481
+ for (const s of parsed.successes) refMap.set(s.ref, s.id);
2482
+ }
2483
+ imported += parsed.successes.length;
2484
+ }
2485
+ console.log(` ${entry.sobject}: imported ${imported} records`);
2486
+ }
2487
+ }
2488
+ });
2489
+ });
2490
+ } else {
2491
+ recordSkipped(dataStep, dataStep.available ? 'not selected' : 'no data plan');
2492
+ }
2493
+
2494
+ const graphqlStep = stepDefs.find((s) => s.key === 'graphql');
2495
+ if (!skipGraphql) {
2496
+ await runStep(graphqlStep, targetOrg, () => {
2497
+ run('UI Bundle npm install', 'npm', ['install'], { cwd: uiBundleDir });
2498
+ run('GraphQL schema (introspect)', 'npm', ['run', 'graphql:schema'], {
2499
+ cwd: uiBundleDir,
2500
+ env: { ...process.env, SF_TARGET_ORG: targetOrg },
2501
+ });
2502
+ run('GraphQL codegen', 'npm', ['run', 'graphql:codegen'], { cwd: uiBundleDir });
2503
+ run('UI Bundle build (post-codegen)', 'npm', ['run', 'build'], { cwd: uiBundleDir });
2504
+ });
2505
+ } else {
2506
+ recordSkipped(graphqlStep, 'not selected');
2507
+ if (!skipUIBundleBuild && skipDeploy && !preDeployBundlesBuilt) {
2508
+ // The pre-deploy build never ran (deploy was skipped); build here and
2509
+ // record the uiBundleBuild outcome that the pre-deploy branch would have.
2510
+ await runStep(uiBundleBuildStep, targetOrg, () => {
2511
+ run('UI Bundle npm install', 'npm', ['install'], { cwd: uiBundleDir });
2512
+ run('UI Bundle build', 'npm', ['run', 'build'], { cwd: uiBundleDir });
2513
+ });
2514
+ preDeployBundlesBuilt = true;
2515
+ }
2516
+ }
2517
+
2518
+ // When uiBundleBuild was selected but the dedicated pre-deploy build never ran
2519
+ // (deploy skipped and graphql selected), the build happened inside the graphql
2520
+ // step — which is fail-fast, so reaching here means it succeeded. Record ok.
2521
+ if (!skipUIBundleBuild && !preDeployBundlesBuilt && !results.some((r) => r.key === 'uiBundleBuild')) {
2522
+ recordOk(uiBundleBuildStep);
2523
+ }
2524
+
2525
+ // Setup terminates cleanly here. Launching the dev server is
2526
+ // no longer part of setup — run `npm run dev:preview` (scripts/org-setup-dev.mjs) for that.
2527
+ printSummary(targetOrg);
2528
+ if (finalExitCode() === 0) {
2529
+ console.log('\nTo launch the dev server, run: npm run dev:preview');
2530
+ }
2531
+ process.exit(finalExitCode());
2532
+ }
2533
+
2534
+ main().catch((err) => {
2535
+ console.error(err);
2536
+ process.exit(1);
2537
+ });