@salesforce/ui-bundle-template-feature-angular-search 0.0.0-stage → 12.14.0

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