@salesforce/templates 66.13.5 → 66.13.6

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