@salesforce/templates 66.13.5 → 66.13.7

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 (281) 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 +680 -408
  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 +690 -418
  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 +1409 -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 +953 -714
  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_/_ls_/LanguageSwitcher.tsx +116 -0
  30. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_ls_/__examples__/language-switcher-example.tsx +36 -0
  31. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_ls_/__examples__/vite-config-site-example.ts +44 -0
  32. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_ls_/buildLanguageUrl.ts +158 -0
  33. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_ls_/index.ts +28 -0
  34. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_ls_/languages.ts +46 -0
  35. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/authentication/components/SocialLogin.tsx +141 -0
  36. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/authentication/pages/Login.tsx +2 -0
  37. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/README.md +246 -0
  38. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/api/apiUtils.ts +56 -0
  39. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/api/orgApiVersionService.ts +37 -0
  40. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/api/searchableContentTypesService.ts +116 -0
  41. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/channelResolver.ts +40 -0
  42. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/cmsQueryFragment.ts +97 -0
  43. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/contentTypeSessionCache.ts +134 -0
  44. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/contentTypeUtils.ts +38 -0
  45. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/hooks/useSearchableContentTypes.ts +128 -0
  46. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/index.ts +54 -0
  47. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/parseResponse.ts +65 -0
  48. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/searchChannel.ts +15 -0
  49. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/types.ts +66 -0
  50. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/registry.ts +38 -0
  51. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/sobject/index.ts +19 -0
  52. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/sobject/parseResponse.ts +56 -0
  53. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/sobject/queryFragment.ts +141 -0
  54. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/types.ts +101 -0
  55. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/api/distinctValuesService.ts +84 -0
  56. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/api/searchService.ts +136 -0
  57. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/GlobalSearchBox.tsx +98 -0
  58. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/MergedSearchResults.tsx +294 -0
  59. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/Search.tsx +203 -0
  60. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/SearchResults.tsx +88 -0
  61. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/SourceSection.tsx +187 -0
  62. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/PaginationControls.tsx +185 -0
  63. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/ScopeSelector.tsx +107 -0
  64. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/SearchBar.tsx +55 -0
  65. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/SortControl.tsx +62 -0
  66. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/ActiveFilters.tsx +61 -0
  67. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/DefaultFilterPanel.tsx +125 -0
  68. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/{_os_/components → search/components/filters}/FilterContext.tsx +7 -20
  69. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/BooleanFilter.tsx +50 -0
  70. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/DateRangeFilter.tsx +160 -0
  71. 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
  72. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/MultiSelectFilter.tsx +89 -0
  73. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/NumericRangeFilter.tsx +108 -0
  74. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/SelectFilter.tsx +46 -0
  75. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/TextFilter.tsx +52 -0
  76. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/results/CmsResultRow.tsx +101 -0
  77. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/results/DefaultResultRow.tsx +109 -0
  78. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/results/resolveResultRenderer.ts +49 -0
  79. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/config.json +88 -0
  80. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/constants.ts +8 -0
  81. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/{_os_ → search}/hooks/useAsyncData.ts +3 -10
  82. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/hooks/useDistinctValues.ts +59 -0
  83. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/hooks/useSearch.ts +966 -0
  84. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/index.ts +115 -0
  85. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/loadConfig.ts +14 -0
  86. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/queryBuilder.ts +100 -0
  87. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/types.ts +376 -0
  88. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/debounce.ts +17 -0
  89. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/fieldUtils.ts +14 -0
  90. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/filterUtils.ts +285 -0
  91. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/sortUtils.ts +34 -0
  92. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/api/graphqlClient.ts +24 -8
  93. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/appLayout.tsx +7 -0
  94. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/components/CustomerWebClientChat.tsx +74 -0
  95. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/{_f_/_os_/components → components}/ObjectBreadcrumb.tsx +7 -2
  96. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/components/ui/button.tsx +1 -1
  97. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/components/ui/datePicker.tsx +2 -2
  98. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/components/ui/table.tsx +9 -2
  99. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/index.ts +8 -0
  100. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/pages/AccountObjectDetailPage.tsx +53 -18
  101. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/pages/Home.tsx +3 -27
  102. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/pages/TestChatPage.tsx +26 -0
  103. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/routes.tsx +21 -8
  104. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/types/chat.ts +36 -0
  105. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/types/globals.d.ts +23 -0
  106. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/{_f_/_os_/utils/fieldUtils.ts → utils/accountFields.ts} +9 -0
  107. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/tsconfig.json +2 -2
  108. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/tsconfig.tsbuildinfo +1 -0
  109. package/lib/templates/project/reactexternalapp/_p_/_m_/classes/UIBundleSocialLoginConfig.cls +133 -0
  110. package/lib/templates/project/reactexternalapp/_p_/_m_/classes/UIBundleSocialLoginConfig.cls-meta.xml +5 -0
  111. package/lib/templates/project/reactexternalapp/_p_/_m_/classes/UIBundleSocialLoginConfig_Test.cls +101 -0
  112. package/lib/templates/project/reactexternalapp/_p_/_m_/classes/UIBundleSocialLoginConfig_Test.cls-meta.xml +5 -0
  113. package/lib/templates/project/reactexternalapp/_p_/_m_/package.xml +4 -0
  114. package/lib/templates/project/reactexternalapp/package.json +8 -2
  115. package/lib/templates/project/reactexternalapp/scripts/org-setup-config-schema.mjs +120 -0
  116. package/lib/templates/project/reactexternalapp/scripts/org-setup-dev.mjs +87 -0
  117. package/lib/templates/project/reactexternalapp/scripts/org-setup-utils.mjs +569 -0
  118. package/lib/templates/project/reactexternalapp/scripts/org-setup-xml.mjs +182 -0
  119. package/lib/templates/project/reactexternalapp/scripts/org-setup.config.json +6 -2
  120. package/lib/templates/project/reactexternalapp/scripts/org-setup.mjs +1509 -328
  121. package/lib/templates/project/reactexternalapp/scripts/validate-org-setup-config.mjs +38 -0
  122. package/lib/templates/project/reactinternalapp/CHANGELOG.md +1223 -0
  123. package/lib/templates/project/reactinternalapp/PRD.md +35 -0
  124. package/lib/templates/project/reactinternalapp/README.md +14 -10
  125. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/package-lock.json +813 -538
  126. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/package.json +10 -9
  127. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/README.md +246 -0
  128. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/api/apiUtils.ts +56 -0
  129. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/api/orgApiVersionService.ts +37 -0
  130. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/api/searchableContentTypesService.ts +116 -0
  131. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/channelResolver.ts +40 -0
  132. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/cmsQueryFragment.ts +97 -0
  133. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/contentTypeSessionCache.ts +134 -0
  134. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/contentTypeUtils.ts +38 -0
  135. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/hooks/useSearchableContentTypes.ts +128 -0
  136. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/index.ts +54 -0
  137. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/parseResponse.ts +65 -0
  138. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/searchChannel.ts +15 -0
  139. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/cms/types.ts +66 -0
  140. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/registry.ts +38 -0
  141. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/sobject/index.ts +19 -0
  142. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/sobject/parseResponse.ts +56 -0
  143. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/sobject/queryFragment.ts +141 -0
  144. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/adapters/types.ts +101 -0
  145. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/api/distinctValuesService.ts +84 -0
  146. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/api/searchService.ts +136 -0
  147. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/GlobalSearchBox.tsx +98 -0
  148. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/MergedSearchResults.tsx +294 -0
  149. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/Search.tsx +203 -0
  150. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/SearchResults.tsx +88 -0
  151. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/SourceSection.tsx +187 -0
  152. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/PaginationControls.tsx +185 -0
  153. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/ScopeSelector.tsx +107 -0
  154. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/SearchBar.tsx +55 -0
  155. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/controls/SortControl.tsx +62 -0
  156. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/ActiveFilters.tsx +61 -0
  157. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/DefaultFilterPanel.tsx +125 -0
  158. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/{_os_/components → search/components/filters}/FilterContext.tsx +7 -20
  159. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/BooleanFilter.tsx +50 -0
  160. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/DateRangeFilter.tsx +160 -0
  161. 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
  162. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/MultiSelectFilter.tsx +89 -0
  163. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/NumericRangeFilter.tsx +108 -0
  164. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/SelectFilter.tsx +46 -0
  165. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/filters/inputs/TextFilter.tsx +52 -0
  166. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/results/CmsResultRow.tsx +101 -0
  167. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/results/DefaultResultRow.tsx +109 -0
  168. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/components/results/resolveResultRenderer.ts +49 -0
  169. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/config.json +88 -0
  170. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/constants.ts +8 -0
  171. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/{_os_ → search}/hooks/useAsyncData.ts +3 -10
  172. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/hooks/useDistinctValues.ts +59 -0
  173. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/hooks/useSearch.ts +966 -0
  174. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/index.ts +115 -0
  175. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/loadConfig.ts +14 -0
  176. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/queryBuilder.ts +100 -0
  177. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/types.ts +376 -0
  178. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/debounce.ts +17 -0
  179. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/fieldUtils.ts +14 -0
  180. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/filterUtils.ts +285 -0
  181. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/search/utils/sortUtils.ts +34 -0
  182. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/components/AgentforceConversationClient.tsx +16 -132
  183. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/{_f_/_os_/components → components}/ObjectBreadcrumb.tsx +7 -2
  184. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/components/ui/button.tsx +1 -1
  185. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/components/ui/datePicker.tsx +2 -2
  186. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/components/ui/table.tsx +9 -2
  187. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/pages/AccountObjectDetailPage.tsx +49 -16
  188. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/pages/Home.tsx +3 -27
  189. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/routes.tsx +12 -5
  190. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/{_f_/_os_/utils/fieldUtils.ts → utils/accountFields.ts} +9 -0
  191. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/tsconfig.json +2 -2
  192. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/tsconfig.tsbuildinfo +1 -0
  193. package/lib/templates/project/reactinternalapp/package.json +4 -2
  194. package/lib/templates/project/reactinternalapp/scripts/org-setup-config-schema.mjs +24 -0
  195. package/lib/templates/project/reactinternalapp/scripts/org-setup-dev.mjs +87 -0
  196. package/lib/templates/project/reactinternalapp/scripts/org-setup-utils.mjs +569 -0
  197. package/lib/templates/project/reactinternalapp/scripts/org-setup-xml.mjs +182 -0
  198. package/lib/templates/project/reactinternalapp/scripts/org-setup.mjs +1162 -214
  199. package/lib/templates/uiBundles/angularbasic/angular.json +1 -1
  200. package/lib/templates/uiBundles/angularbasic/eslint-plugin-angular-graphql.js +148 -0
  201. package/lib/templates/uiBundles/angularbasic/eslint.config.js +9 -1
  202. package/lib/templates/uiBundles/angularbasic/package-lock.json +680 -408
  203. package/lib/templates/uiBundles/angularbasic/package.json +2 -2
  204. package/lib/templates/uiBundles/reactbasic/package-lock.json +738 -440
  205. package/lib/utils/template-placeholders.js +14 -0
  206. package/lib/utils/template-placeholders.js.map +1 -1
  207. package/lib/utils/uiBundleTemplateUtils.d.ts +5 -1
  208. package/lib/utils/uiBundleTemplateUtils.js +7 -1
  209. package/lib/utils/uiBundleTemplateUtils.js.map +1 -1
  210. package/package.json +7 -7
  211. package/lib/templates/project/reactexternalapp/AGENT.md +0 -252
  212. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/accountSearchService.ts +0 -46
  213. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/distinctAccountIndustries.graphql +0 -19
  214. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/distinctAccountTypes.graphql +0 -19
  215. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/getAccountDetail.graphql +0 -121
  216. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/searchAccounts.graphql +0 -51
  217. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/pages/AccountObjectDetailPage.tsx +0 -355
  218. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/pages/AccountSearch.tsx +0 -304
  219. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/pages/Home.tsx +0 -34
  220. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/api/objectSearchService.ts +0 -82
  221. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/ActiveFilters.tsx +0 -89
  222. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/PaginationControls.tsx +0 -109
  223. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/SearchBar.tsx +0 -41
  224. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/SortControl.tsx +0 -143
  225. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/BooleanFilter.tsx +0 -78
  226. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/DateFilter.tsx +0 -128
  227. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/DateRangeFilter.tsx +0 -70
  228. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/MultiSelectFilter.tsx +0 -97
  229. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/NumericRangeFilter.tsx +0 -167
  230. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/SearchFilter.tsx +0 -52
  231. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/SelectFilter.tsx +0 -97
  232. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/TextFilter.tsx +0 -93
  233. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/hooks/useDebouncedCallback.ts +0 -34
  234. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/hooks/useObjectSearchParams.ts +0 -254
  235. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/utils/debounce.ts +0 -25
  236. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/utils/filterUtils.ts +0 -404
  237. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/utils/sortUtils.ts +0 -38
  238. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/api/account/accountSearchService.ts +0 -46
  239. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/api/account/query/distinctAccountIndustries.graphql +0 -19
  240. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/api/account/query/distinctAccountTypes.graphql +0 -19
  241. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/api/account/query/searchAccounts.graphql +0 -51
  242. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/api/graphql-operations-types.ts +0 -11260
  243. package/lib/templates/project/reactexternalapp/_p_/_m_/_w_/_a_/src/pages/AccountSearch.tsx +0 -297
  244. package/lib/templates/project/reactexternalapp/scripts/prepare-import-unique-fields.js +0 -122
  245. package/lib/templates/project/reactinternalapp/AGENT.md +0 -252
  246. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/accountSearchService.ts +0 -46
  247. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/distinctAccountIndustries.graphql +0 -19
  248. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/distinctAccountTypes.graphql +0 -19
  249. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/getAccountDetail.graphql +0 -121
  250. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/api/query/searchAccounts.graphql +0 -51
  251. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/pages/AccountObjectDetailPage.tsx +0 -355
  252. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/pages/AccountSearch.tsx +0 -304
  253. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/_ex_/pages/Home.tsx +0 -34
  254. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/api/objectSearchService.ts +0 -82
  255. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/ActiveFilters.tsx +0 -89
  256. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/PaginationControls.tsx +0 -109
  257. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/SearchBar.tsx +0 -41
  258. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/SortControl.tsx +0 -143
  259. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/BooleanFilter.tsx +0 -78
  260. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/DateFilter.tsx +0 -128
  261. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/DateRangeFilter.tsx +0 -70
  262. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/MultiSelectFilter.tsx +0 -97
  263. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/NumericRangeFilter.tsx +0 -167
  264. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/SearchFilter.tsx +0 -52
  265. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/SelectFilter.tsx +0 -97
  266. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/components/filters/TextFilter.tsx +0 -93
  267. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/hooks/useDebouncedCallback.ts +0 -34
  268. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/hooks/useObjectSearchParams.ts +0 -254
  269. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/utils/debounce.ts +0 -25
  270. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/utils/filterUtils.ts +0 -404
  271. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/_f_/_os_/utils/sortUtils.ts +0 -38
  272. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/api/account/accountSearchService.ts +0 -46
  273. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/api/account/query/distinctAccountIndustries.graphql +0 -19
  274. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/api/account/query/distinctAccountTypes.graphql +0 -19
  275. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/api/account/query/searchAccounts.graphql +0 -51
  276. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/api/graphql-operations-types.ts +0 -11260
  277. package/lib/templates/project/reactinternalapp/_p_/_m_/_w_/_a_/src/pages/AccountSearch.tsx +0 -297
  278. package/lib/templates/project/reactinternalapp/scripts/prepare-import-unique-fields.js +0 -122
  279. /package/lib/templates/project/angularextapp/_p_/_m_/{permissionsets → _ps_}/angularextapp_Guest_User_Api_Access.permissionset-meta.xml +0 -0
  280. /package/lib/templates/project/angularintapp/_p_/_m_/{permissionsets → _ps_}/angularintapp_Access.permissionset-meta.xml +0 -0
  281. /package/lib/templates/project/reactinternalapp/_p_/_m_/{permissionsets → _ps_}/reactinternalapp_Access.permissionset-meta.xml +0 -0
@@ -5,19 +5,21 @@
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
  * {
@@ -37,11 +39,39 @@
37
39
  */
38
40
 
39
41
  import { spawnSync, spawn as nodeSpawn } from 'node:child_process';
40
- import { resolve, dirname } from 'node:path';
42
+ import { resolve, dirname, join } from 'node:path';
41
43
  import { fileURLToPath } from 'node:url';
42
- 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';
43
56
 
44
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';
45
75
 
46
76
  const __dirname = dirname(fileURLToPath(import.meta.url));
47
77
  const ROOT = resolve(__dirname, '..');
@@ -53,6 +83,149 @@ const ROOT = resolve(__dirname, '..');
53
83
  */
54
84
  class StepError extends Error {}
55
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
+
56
229
  /**
57
230
  * npm strips .gitignore from published packages — generate them on first run.
58
231
  * Templates are stored in scripts/gitignore-templates.json (generated at build
@@ -107,7 +280,6 @@ function parseArgs() {
107
280
  const permsetNamesExplicit = [];
108
281
  let yes = false;
109
282
  const flags = {
110
- skipLogin: false,
111
283
  skipDeploy: false,
112
284
  skipPermset: false,
113
285
  skipRole: false,
@@ -115,7 +287,7 @@ function parseArgs() {
115
287
  skipGraphql: false,
116
288
  skipUIBundleBuild: false,
117
289
  skipSelfReg: false,
118
- skipDev: false,
290
+ skipSocialLogin: false,
119
291
  };
120
292
  for (let i = 0; i < args.length; i++) {
121
293
  if (args[i] === '--target-org' && args[i + 1]) {
@@ -124,39 +296,44 @@ function parseArgs() {
124
296
  uiBundleName = args[++i];
125
297
  } else if (args[i] === '--permset-name' && args[i + 1]) {
126
298
  permsetNamesExplicit.push(args[++i]);
127
- } else if (args[i] === '--skip-login') flags.skipLogin = true;
128
- else if (args[i] === '--skip-deploy') flags.skipDeploy = true;
299
+ } else if (args[i] === '--skip-deploy') flags.skipDeploy = true;
129
300
  else if (args[i] === '--skip-permset') flags.skipPermset = true;
130
301
  else if (args[i] === '--skip-role') flags.skipRole = true;
131
302
  else if (args[i] === '--skip-data') flags.skipData = true;
132
303
  else if (args[i] === '--skip-self-reg') flags.skipSelfReg = true;
304
+ else if (args[i] === '--skip-social-login') flags.skipSocialLogin = true;
133
305
  else if (args[i] === '--skip-graphql') flags.skipGraphql = true;
134
306
  else if (args[i] === '--skip-ui-bundle-build') flags.skipUIBundleBuild = true;
135
- else if (args[i] === '--skip-dev') flags.skipDev = true;
136
- 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;
137
313
  else if (args[i] === '--help' || args[i] === '-h') {
138
314
  console.log(`
139
315
  Setup CLI — one-command setup for apps in this project
140
316
 
141
317
  Usage:
142
- node scripts/org-setup.mjs --target-org <alias> [options]
143
-
144
- Required:
145
- --target-org <alias> Target Salesforce org alias (e.g. myorg)
318
+ node scripts/org-setup.mjs [--target-org <alias>] [options]
146
319
 
147
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).
148
324
  --ui-bundle-name <name> UI bundle folder name under uiBundles/ (default: auto-detect)
149
325
  --permset-name <name> Assign only this permission set (repeatable). Default: all sets under permissionsets/
150
- --skip-login Skip login step (login is auto-skipped if org is already connected)
151
326
  --skip-deploy Do not deploy metadata
152
327
  --skip-permset Do not assign permission set
328
+ --skip-social-login Do not enable social login (auth providers + community profile)
153
329
  --skip-data Do not prepare data or run data import
154
330
  --skip-graphql Do not fetch schema or run GraphQL codegen
155
331
  --skip-ui-bundle-build Do not npm install / build the UI bundle
156
- --skip-dev Do not launch the dev server at the end
157
332
  -y, --yes Skip interactive step picker; run all enabled steps immediately
158
333
  -h, --help Show this help
159
334
 
335
+ To launch the dev server after setup, run: npm run dev:preview
336
+
160
337
  Permset config (scripts/org-setup.config.json):
161
338
  Control per-permset assignment via a config file. Example:
162
339
  {
@@ -176,41 +353,22 @@ Permset config (scripts/org-setup.config.json):
176
353
  process.exit(0);
177
354
  }
178
355
  }
179
- if (!targetOrg) {
180
- console.error('Error: --target-org <alias> is required.');
181
- process.exit(1);
182
- }
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).
183
359
  return { targetOrg, uiBundleName, permsetNamesExplicit, yes, ...flags };
184
360
  }
185
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).
186
366
  function discoverAllUIBundleDirs(uiBundleName) {
187
- if (!existsSync(UIBUNDLES_DIR)) {
188
- console.error(`Error: uiBundles directory not found: ${UIBUNDLES_DIR}`);
189
- process.exit(1);
190
- }
191
- const entries = readdirSync(UIBUNDLES_DIR, { withFileTypes: true });
192
- const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith('.'));
193
- if (dirs.length === 0) {
194
- console.error(`Error: No UI bundle folder found under ${UIBUNDLES_DIR}`);
195
- process.exit(1);
196
- }
197
- if (uiBundleName) {
198
- const requested = dirs.find((d) => d.name === uiBundleName);
199
- if (!requested) {
200
- console.error(`Error: UI bundle directory not found: ${uiBundleName}`);
201
- process.exit(1);
202
- }
203
- return [resolve(UIBUNDLES_DIR, requested.name)];
204
- }
205
- return dirs.map((d) => resolve(UIBUNDLES_DIR, d.name));
367
+ return discoverAllUIBundleDirsIn(UIBUNDLES_DIR, uiBundleName);
206
368
  }
207
369
 
208
370
  function discoverUIBundleDir(uiBundleName) {
209
- const all = discoverAllUIBundleDirs(uiBundleName);
210
- if (all.length > 1 && !uiBundleName) {
211
- console.log(`Multiple UI bundles found; using first: ${all[0].split(/[/\\]/).pop()}`);
212
- }
213
- return all[0];
371
+ return discoverUIBundleDirIn(UIBUNDLES_DIR, uiBundleName);
214
372
  }
215
373
 
216
374
  /** API names from permissionsets/*.permissionset-meta.xml in the first package directory. */
@@ -254,7 +412,7 @@ function loadValidatedConfig() {
254
412
  /**
255
413
  * Derive the site name from the single networks/<siteName>.network-meta.xml the
256
414
  * app ships. An app ships exactly one site, so the site name is derivable from
257
- * deployed metadata rather than restated per-assignment (spec §5.2). Returns
415
+ * deployed metadata rather than restated per-assignment. Returns
258
416
  * null when there is no networks dir or no .network-meta.xml file.
259
417
  */
260
418
  function deriveSiteName() {
@@ -271,7 +429,15 @@ function deriveSiteName() {
271
429
  `cannot derive guest site: multiple network metadata files found in ${networksDir} (${files.join(', ')}); guestUser assignment requires exactly one`,
272
430
  );
273
431
  }
274
- return files[0].replace(/\.network-meta\.xml$/, '');
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;
275
441
  }
276
442
 
277
443
  /**
@@ -335,7 +501,7 @@ function loadRoleConfig(config) {
335
501
  /**
336
502
  * Self-registration config, read from the already-validated config. The site is
337
503
  * NOT stored here — it is derived from the single
338
- * networks/<siteName>.network-meta.xml the app ships (spec §5.2), exactly like
504
+ * networks/<siteName>.network-meta.xml the app ships, exactly like
339
505
  * the guestUser permset path. deriveSiteName() is called lazily inside the
340
506
  * selfReg step body so its "multiple network files" StepError is recorded in
341
507
  * the ledger rather than escaping config load.
@@ -359,6 +525,435 @@ function loadSelfRegConfig(config) {
359
525
  };
360
526
  }
361
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));
571
+ try {
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}).`);
878
+ } catch {
879
+ console.log(` Added profile "${profileName}" to community "${siteName}".`);
880
+ }
881
+ }
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
+
362
957
  /**
363
958
  * Ensure the self-registration profile is listed in networkMemberGroups.
364
959
  * This must happen BEFORE the initial deploy so that the profile is a recognised
@@ -375,20 +970,31 @@ function ensureNetworkMemberProfile(selfRegConfig, siteName) {
375
970
  }
376
971
  const xml = readFileSync(networkXmlPath, 'utf8');
377
972
 
378
- // Check if profile is already in networkMemberGroups
379
- const profileEscaped = selfRegProfile.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
380
- const profileRegex = new RegExp(`<profile>\\s*${profileEscaped}\\s*</profile>`);
381
- 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) {
382
994
  console.log(` Profile "${selfRegProfile}" already in networkMemberGroups; no update needed.`);
383
995
  return;
384
996
  }
385
-
386
- // Add the profile to networkMemberGroups
387
- const updatedXml = xml.replace(
388
- /(<networkMemberGroups>)/,
389
- `$1\n <profile>${selfRegProfile}</profile>`
390
- );
391
- writeFileSync(networkXmlPath, updatedXml);
997
+ writeFileSync(networkXmlPath, result.xml);
392
998
  console.log(` Added profile "${selfRegProfile}" to networkMemberGroups in ${siteName}.network-meta.xml`);
393
999
  }
394
1000
 
@@ -410,23 +1016,26 @@ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
410
1016
  }
411
1017
  const xml = readFileSync(networkXmlPath, 'utf8');
412
1018
 
413
- // Skip network modification and deploy if self-registration is already configured
414
- const alreadyEnabled = /<selfRegistration>true<\/selfRegistration>/.test(xml);
415
- const alreadyHasProfile = /<selfRegProfile>/.test(xml);
416
- 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) {
417
1036
  console.log(` Network "${siteName}" already has self-registration configured; skipping metadata update and deploy.`);
418
1037
  } else {
419
- // Set selfRegistration to true and add selfRegProfile
420
- let updatedXml = xml.replace(
421
- /<selfRegistration>false<\/selfRegistration>/,
422
- '<selfRegistration>true</selfRegistration>'
423
- );
424
- updatedXml = updatedXml.replace(
425
- /(\s*)(<selfRegistration>)/,
426
- `$1<selfRegProfile>${selfRegProfile}</selfRegProfile>\n$1$2`
427
- );
428
-
429
- writeFileSync(networkXmlPath, updatedXml);
1038
+ writeFileSync(networkXmlPath, result.xml);
430
1039
  console.log(` Updated ${siteName}.network-meta.xml: selfRegistration=true, selfRegProfile=${selfRegProfile}`);
431
1040
 
432
1041
  // Re-deploy only the network file
@@ -440,8 +1049,13 @@ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
440
1049
  }
441
1050
  }
442
1051
 
443
- // 3. Create Account (idempotent)
444
- 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`;
445
1059
  const acctQueryResult = spawnSync('sf', [
446
1060
  'data', 'query',
447
1061
  '--query', acctQuery,
@@ -458,24 +1072,34 @@ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
458
1072
  if (accountId) {
459
1073
  console.log(` Account "${accountName}" already exists (${accountId}); skipping creation.`);
460
1074
  } else {
461
- const createResult = spawnSync('sf', [
462
- 'data', 'create', 'record',
463
- '--sobject', 'Account',
464
- '--values', `Name='${accountName}'`,
465
- '--target-org', targetOrg,
466
- '--json',
467
- ], { cwd: ROOT, encoding: 'utf8' });
468
- if (createResult.status !== 0) {
469
- if (createResult.stderr) console.error(createResult.stderr);
470
- throw new StepError(`failed to create Account "${accountName}"`);
471
- }
472
- try {
473
- const json = JSON.parse(createResult.stdout);
474
- accountId = json.result?.id;
475
- console.log(` Created Account "${accountName}" (${accountId}).`);
476
- } catch {
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) {
477
1099
  throw new StepError('failed to parse Account creation result');
478
1100
  }
1101
+ accountId = acctMatch[1];
1102
+ console.log(` Created Account "${accountName}" (${accountId}).`);
479
1103
  }
480
1104
 
481
1105
  // 4. Query Network Id
@@ -516,7 +1140,6 @@ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
516
1140
  if (nsrExists) {
517
1141
  console.log(' NetworkSelfRegistration record already exists; skipping.');
518
1142
  } else {
519
- const tmpApex = resolve(ROOT, '.tmp-setup-selfreg.apex');
520
1143
  const apex = [
521
1144
  `Account acct = [SELECT Id FROM Account WHERE Id = '${accountId}' LIMIT 1];`,
522
1145
  `NetworkSelfRegistration nsr = new NetworkSelfRegistration();`,
@@ -525,16 +1148,18 @@ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
525
1148
  `insert nsr;`,
526
1149
  `System.debug('NSR_CREATED:' + nsr.Id);`,
527
1150
  ].join('\n');
528
- writeFileSync(tmpApex, apex);
529
- const apexResult = spawnSync('sf', [
530
- 'apex', 'run', '--target-org', targetOrg, '--file', tmpApex,
531
- ], { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 60000 });
532
- const apexOut = apexResult.stdout?.toString() || '';
533
- if (existsSync(tmpApex)) unlinkSync(tmpApex);
534
- if (apexResult.status !== 0 && !apexOut.includes('Compiled successfully')) {
535
- process.stderr.write(apexResult.stderr?.toString() || apexOut);
536
- throw new StepError('failed to create NetworkSelfRegistration record');
537
- }
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
+ });
538
1163
  const nsrMatch = apexOut.match(/NSR_CREATED:(\w+)/);
539
1164
  if (nsrMatch) {
540
1165
  console.log(` Created NetworkSelfRegistration (${nsrMatch[1]}).`);
@@ -549,6 +1174,7 @@ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
549
1174
  * works correctly.
550
1175
  */
551
1176
  function assignRoleToCurrentUser(roleName, targetOrg) {
1177
+ validateSoqlName(roleName, 'role name');
552
1178
  const roleQuery = `SELECT Id FROM UserRole WHERE Name = '${roleName}'`;
553
1179
  const roleResult = spawnSync('sf', [
554
1180
  'data', 'query',
@@ -629,10 +1255,30 @@ function assignRoleToCurrentUser(roleName, targetOrg) {
629
1255
  }
630
1256
 
631
1257
  /**
632
- * 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.
633
1277
  */
634
1278
  function resolveGuestUsername(siteName, targetOrg) {
635
- 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'`;
636
1282
  const result = spawnSync('sf', [
637
1283
  'data', 'query',
638
1284
  '--query', query,
@@ -648,7 +1294,15 @@ function resolveGuestUsername(siteName, targetOrg) {
648
1294
  const json = JSON.parse(result.stdout);
649
1295
  const records = json.result?.records;
650
1296
  if (!records || records.length === 0) {
651
- 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
+ );
652
1306
  return null;
653
1307
  }
654
1308
  return records[0].Username;
@@ -658,6 +1312,118 @@ function resolveGuestUsername(siteName, targetOrg) {
658
1312
  }
659
1313
  }
660
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
+
661
1427
  function isOrgConnected(targetOrg) {
662
1428
  const result = spawnSync('sf', ['org', 'display', '--target-org', targetOrg, '--json'], {
663
1429
  cwd: ROOT,
@@ -681,8 +1447,20 @@ function apexLiteral(value) {
681
1447
  }
682
1448
 
683
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');
684
1458
  const lines = [
685
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.
686
1464
  'dmlOpts.DuplicateRuleHeader.allowSave = true;',
687
1465
  `List<${sobject}> recs = new List<${sobject}>();`,
688
1466
  ];
@@ -690,17 +1468,31 @@ function buildApexInsert(sobject, records, refIds) {
690
1468
  lines.push(`{ ${sobject} r = new ${sobject}();`);
691
1469
  for (const [key, val] of Object.entries(rec)) {
692
1470
  if (key === 'attributes') continue;
1471
+ validateApiName(key, `field API name on ${sobject}`);
693
1472
  lines.push(`r.put('${key}', ${apexLiteral(val)});`);
694
1473
  }
695
1474
  lines.push('recs.add(r); }');
696
1475
  }
697
1476
  lines.push('Database.SaveResult[] results = Database.insert(recs, dmlOpts);');
698
- const refArray = refIds.map((r) => `'${r}'`).join(',');
1477
+ const refArray = refIds.map((r) => `'${escapeSoqlString(r)}'`).join(',');
699
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>();');
700
1486
  lines.push('for (Integer i = 0; i < results.size(); i++) {');
701
- lines.push(" if (results[i].isSuccess()) System.debug('REF:' + refs[i] + ':' + results[i].getId());");
702
- 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);');
703
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));");
704
1496
  return lines.join('\n');
705
1497
  }
706
1498
 
@@ -931,6 +1723,13 @@ async function runStep(step, targetOrg, body) {
931
1723
  }
932
1724
 
933
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
+
934
1733
  // Ensure .gitignore files exist (npm strips them from published packages).
935
1734
  const gitignoreTemplates = loadGitignoreTemplates();
936
1735
  if (gitignoreTemplates) {
@@ -944,21 +1743,30 @@ async function main() {
944
1743
  }
945
1744
  }
946
1745
 
1746
+ const parsed = parseArgs();
947
1747
  const {
948
- targetOrg,
949
1748
  uiBundleName,
950
1749
  permsetNamesExplicit,
951
1750
  yes,
952
- skipLogin: argSkipLogin,
953
1751
  skipDeploy: argSkipDeploy,
954
1752
  skipPermset: argSkipPermset,
955
1753
  skipRole: argSkipRole,
956
1754
  skipSelfReg: argSkipSelfReg,
1755
+ skipSocialLogin: argSkipSocialLogin,
957
1756
  skipData: argSkipData,
958
1757
  skipGraphql: argSkipGraphql,
959
1758
  skipUIBundleBuild: argSkipUIBundleBuild,
960
- skipDev: argSkipDev,
961
- } = 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);
962
1770
 
963
1771
  const permsetNames =
964
1772
  permsetNamesExplicit.length > 0 ? permsetNamesExplicit : discoverPermissionSetNames();
@@ -969,8 +1777,8 @@ async function main() {
969
1777
  ? `Permset — assign ${permsetNames.join(', ')}`
970
1778
  : `Permset — assign ${permsetNames.length} permission sets`;
971
1779
 
972
- // Validate org-setup.config.json ONCE, before any step runs (spec §5.2). The
973
- // three load*Config helpers read from this already-validated object.
1780
+ // Validate org-setup.config.json ONCE, before any step runs. The three
1781
+ // load*Config helpers read from this already-validated object.
974
1782
  const config = loadValidatedConfig();
975
1783
 
976
1784
  const hasDataPlan = existsSync(DATA_PLAN) && existsSync(DATA_DIR);
@@ -978,21 +1786,64 @@ async function main() {
978
1786
  const hasRoleConfig = roleConfig !== null;
979
1787
  const selfRegConfig = loadSelfRegConfig(config);
980
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
+ }
981
1805
 
982
- // failFast is a fixed, implementer-owned classification (spec §5.2) — NOT
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
+ }
1829
+
1830
+ // failFast is a fixed, implementer-owned classification — NOT
983
1831
  // user-configurable. A fail-fast failure aborts the run immediately; a
984
1832
  // skippable failure is recorded and the run continues. The exit code is
985
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.
986
1838
  const stepDefs = [
987
- { key: 'login', label: 'Login — org authentication', enabled: !argSkipLogin, available: true, failFast: true },
988
1839
  { key: 'uiBundleBuild', label: 'UI Bundle Build — npm install + build (pre-deploy)', enabled: !argSkipUIBundleBuild, available: true, failFast: true },
989
1840
  { key: 'deploy', label: 'Deploy — sf project deploy start', enabled: !argSkipDeploy, available: true, failFast: true },
990
1841
  { key: 'permset', label: permsetStepLabel, enabled: !argSkipPermset, available: true, failFast: false },
991
1842
  { key: 'role', label: `Role — assign "${roleConfig?.roleName ?? '?'}" to current user`, enabled: !argSkipRole && hasRoleConfig, available: hasRoleConfig, failFast: false },
992
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 },
993
1845
  { key: 'data', label: 'Data — delete + import records via Apex', enabled: !argSkipData && hasDataPlan, available: hasDataPlan, failFast: true },
994
1846
  { key: 'graphql', label: 'GraphQL — schema introspect + codegen', enabled: !argSkipGraphql, available: true, failFast: true },
995
- { key: 'dev', label: 'Dev — launch dev server', enabled: !argSkipDev, available: true, failFast: false },
996
1847
  ];
997
1848
 
998
1849
  const selections = yes ? stepDefs.map((s) => s.enabled) : await promptSteps(stepDefs);
@@ -1001,49 +1852,44 @@ async function main() {
1001
1852
  on[s.key] = selections[i];
1002
1853
  });
1003
1854
 
1004
- const skipLogin = !on.login;
1005
1855
  const skipUIBundleBuild = !on.uiBundleBuild;
1006
1856
  const skipDeploy = !on.deploy;
1007
1857
  const skipPermset = !on.permset;
1008
1858
  const skipRole = !on.role;
1009
1859
  const skipSelfReg = !on.selfReg;
1860
+ const skipSocialLogin = !on.socialLogin;
1010
1861
  const skipData = !on.data;
1011
1862
  const skipGraphql = !on.graphql;
1012
- const skipDev = !on.dev;
1013
1863
 
1014
- const needsUIBundle = !skipUIBundleBuild || !skipGraphql || !skipDev;
1015
- const uiBundleDir = needsUIBundle ? discoverUIBundleDir(uiBundleName) : null;
1864
+ const needsUIBundle = !skipUIBundleBuild || !skipGraphql;
1865
+ const uiBundleDir = needsUIBundle ? await discoverUIBundleDir(uiBundleName) : null;
1016
1866
  const doData = !skipData;
1017
1867
 
1018
1868
  console.log('Setup — target org:', targetOrg, '| UI bundle:', uiBundleDir ?? '(none)');
1019
1869
  console.log(
1020
- 'Steps: login=%s deploy=%s permset=%s role=%s selfReg=%s data=%s graphql=%s uiBundle=%s dev=%s',
1021
- !skipLogin,
1870
+ 'Steps: login=always deploy=%s permset=%s role=%s selfReg=%s socialLogin=%s data=%s graphql=%s uiBundle=%s',
1022
1871
  !skipDeploy,
1023
1872
  !skipPermset,
1024
1873
  !skipRole,
1025
1874
  !skipSelfReg,
1875
+ !skipSocialLogin,
1026
1876
  doData,
1027
1877
  !skipGraphql,
1028
- !skipUIBundleBuild,
1029
- !skipDev
1878
+ !skipUIBundleBuild
1030
1879
  );
1031
1880
 
1032
- const loginStep = stepDefs.find((s) => s.key === 'login');
1033
- if (!skipLogin) {
1034
- await runStep(loginStep, targetOrg, async () => {
1035
- if (isOrgConnected(targetOrg)) {
1036
- console.log('\n--- Login ---');
1037
- console.log(`Org ${targetOrg} is already authenticated; skipping browser login.`);
1038
- } else {
1039
- // Login is fail-fast (spec §5.2): drop the previous { optional: true } so a
1040
- // failed browser login records `failed`, prints the summary, and aborts.
1041
- run('Login (browser)', 'sf', ['org', 'login', 'web', '--alias', targetOrg]);
1042
- }
1043
- });
1044
- } else {
1045
- recordSkipped(loginStep, 'not selected');
1046
- }
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 () => {
1886
+ if (isOrgConnected(targetOrg)) {
1887
+ console.log('\n--- Login ---');
1888
+ console.log(`Org ${targetOrg} is already authenticated; skipping browser login.`);
1889
+ } else {
1890
+ run('Login (browser)', 'sf', ['org', 'login', 'web', '--alias', targetOrg]);
1891
+ }
1892
+ });
1047
1893
 
1048
1894
  // Ensure the self-reg profile is in networkMemberGroups before deploy so that
1049
1895
  // subsequent selfRegProfile / selfRegistration updates don't fail. This is
@@ -1088,6 +1934,19 @@ async function main() {
1088
1934
  const deployStep = stepDefs.find((s) => s.key === 'deploy');
1089
1935
  if (!skipDeploy) {
1090
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
+ }
1091
1950
  run('Deploy metadata', 'sf', ['project', 'deploy', 'start', '--target-org', targetOrg], {
1092
1951
  timeout: 180000,
1093
1952
  });
@@ -1126,7 +1985,7 @@ async function main() {
1126
1985
  let effectiveUsername = null;
1127
1986
  if (assignment.assignee === 'guestUser') {
1128
1987
  // Site name is derived from the single network metadata file the app
1129
- // ships (spec §5.2) — never restated per-assignment.
1988
+ // ships — never restated per-assignment.
1130
1989
  const siteName = deriveSiteName();
1131
1990
  if (!siteName) {
1132
1991
  console.error(`Permission set "${permsetName}" — assignee is "guestUser" but no networks/<siteName>.network-meta.xml was found to derive the site; skipping.`);
@@ -1196,41 +2055,95 @@ async function main() {
1196
2055
 
1197
2056
  const selfRegStep = stepDefs.find((s) => s.key === 'selfReg');
1198
2057
  if (!skipSelfReg) {
1199
- console.log('\n--- Enable self-registration ---');
1200
- // Config shape (selfRegProfile, accountName) is guaranteed by the schema.
1201
- // The site is derived inside the step body so a "multiple network files"
1202
- // StepError is recorded in the ledger rather than escaping. No manual
1203
- // recordSkipped inference.
1204
- await runStep(selfRegStep, targetOrg, () => {
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);
2068
+ } else {
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
+ });
2083
+ }
2084
+ } else {
2085
+ recordSkipped(selfRegStep, selfRegStep.available ? 'not selected' : 'no config');
2086
+ }
2087
+
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, () => {
1205
2092
  const siteName = deriveSiteName();
1206
2093
  if (!siteName) {
1207
2094
  throw new StepError(
1208
- 'self-registration is configured but no networks/<siteName>.network-meta.xml was found to derive the site',
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,
1209
2128
  );
1210
2129
  }
1211
- enableSelfRegistration(selfRegConfig, siteName, targetOrg);
1212
2130
  });
1213
2131
  } else {
1214
- recordSkipped(selfRegStep, selfRegStep.available ? 'not selected' : 'no config');
2132
+ recordSkipped(socialLoginStep, socialLoginStep.available ? 'not selected' : 'no config');
1215
2133
  }
1216
2134
 
1217
2135
  const dataStep = stepDefs.find((s) => s.key === 'data');
1218
2136
  if (doData) {
1219
2137
  await runStep(dataStep, targetOrg, () => {
1220
- // Prepare data for uniqueness (run before import so repeat imports don't conflict)
1221
- const prepareScript = resolve(__dirname, 'prepare-import-unique-fields.js');
1222
- run('Prepare data (unique fields)', 'node', [prepareScript, '--data-dir', DATA_DIR], {
1223
- cwd: ROOT,
1224
- });
1225
- // Normalize Lease__c Tenant refs to 1–15 so all refs resolve (Tenant__c.json has 15 records)
1226
- const leasePath = resolve(DATA_DIR, 'Lease__c.json');
1227
- if (existsSync(leasePath)) {
1228
- let leaseContent = readFileSync(leasePath, 'utf8');
1229
- leaseContent = leaseContent.replace(/@TenantRef(\d+)/g, (_m, n) => {
1230
- const k = ((parseInt(n, 10) - 1) % 15) + 1;
1231
- return `@TenantRef${k}`;
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,
1232
2146
  });
1233
- writeFileSync(leasePath, leaseContent);
1234
2147
  }
1235
2148
 
1236
2149
  // Delete existing records so every run inserts the full dataset without duplicate conflicts.
@@ -1238,8 +2151,14 @@ async function main() {
1238
2151
  console.log('\n--- Clean existing data for fresh import ---');
1239
2152
  const planEntries = JSON.parse(readFileSync(DATA_PLAN, 'utf8'));
1240
2153
  const sobjectsReversed = [...planEntries.map((e) => e.sobject)].reverse();
1241
- 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) => {
1242
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');
1243
2162
  const apexCode = [
1244
2163
  'try {',
1245
2164
  ` List<SObject> recs = Database.query('SELECT Id FROM ${sobject} LIMIT 10000');`,
@@ -1251,7 +2170,7 @@ async function main() {
1251
2170
  ' // non-deletable records (e.g. Contact linked to Case) are skipped via allOrNone=false',
1252
2171
  '}',
1253
2172
  ].join('\n');
1254
- writeFileSync(tmpApex, apexCode);
2173
+ const tmpApex = writeApex('data.apex', apexCode);
1255
2174
  spawnSync('sf', ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex], {
1256
2175
  cwd: ROOT,
1257
2176
  stdio: 'pipe',
@@ -1260,15 +2179,20 @@ async function main() {
1260
2179
  });
1261
2180
  console.log(` ${sobject}: cleaned`);
1262
2181
  }
1263
- if (existsSync(tmpApex)) unlinkSync(tmpApex);
1264
2182
 
1265
2183
  // Import via Anonymous Apex with Database.DMLOptions.duplicateRuleHeader.allowSave = true.
1266
2184
  // This bypasses both duplicate-rule blocks AND matching-service timeouts that the REST
1267
2185
  // API headers (Sforce-Duplicate-Rule-Action) cannot override.
1268
- console.log('\n--- Data import tree ---');
2186
+ console.log('\n--- Data import (Apex) ---');
1269
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.
1270
2194
  const APEX_CHAR_LIMIT = 25000;
1271
- const APEX_MAX_BATCH = 200;
2195
+ const APEX_MAX_BATCH = 100;
1272
2196
 
1273
2197
  for (const entry of planEntries) {
1274
2198
  for (const file of entry.files) {
@@ -1290,16 +2214,52 @@ async function main() {
1290
2214
  }
1291
2215
  }
1292
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
+
1293
2257
  let imported = 0;
1294
- const sampleRec = records[0] || {};
1295
- const fieldsPerRec = Object.keys(sampleRec).filter((k) => k !== 'attributes').length;
1296
- const estCharsPerRec = 40 + fieldsPerRec * 55;
1297
- const batchSize = Math.min(APEX_MAX_BATCH, Math.max(5, Math.floor(APEX_CHAR_LIMIT / estCharsPerRec)));
1298
- for (let i = 0; i < records.length; i += batchSize) {
1299
- const batch = records.slice(i, i + batchSize);
1300
- 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}`);
1301
2261
  const apex = buildApexInsert(entry.sobject, batch, refIds);
1302
- writeFileSync(tmpApex, apex);
2262
+ const tmpApex = writeApex('data.apex', apex);
1303
2263
  const apexResult = spawnSync(
1304
2264
  'sf',
1305
2265
  ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex],
@@ -1311,24 +2271,29 @@ async function main() {
1311
2271
  process.stderr.write(apexErr || apexOut);
1312
2272
  throw new StepError(`${entry.sobject}: apex execution failed`);
1313
2273
  }
1314
- const okMatches = [...apexOut.matchAll(/\|DEBUG\|REF:([^:\n]+):(\w+)/g)];
1315
- const errMatches = [...apexOut.matchAll(/\|DEBUG\|ERR:([^:\n]+):([^\n]+)/g)];
1316
- if (errMatches.length) {
1317
- for (const m of errMatches.slice(0, 5)) {
1318
- 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()}`);
1319
2284
  }
1320
- if (errMatches.length > 5) console.error(` ... and ${errMatches.length - 5} more`);
1321
- throw new StepError(`data import tree (${entry.sobject}) — ${errMatches.length} record error(s)`);
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)`);
1322
2287
  }
1323
2288
  if (entry.saveRefs) {
1324
- for (const m of okMatches) refMap.set(m[1], m[2]);
2289
+ for (const s of parsed.successes) refMap.set(s.ref, s.id);
1325
2290
  }
1326
- imported += okMatches.length;
2291
+ imported += parsed.successes.length;
1327
2292
  }
1328
2293
  console.log(` ${entry.sobject}: imported ${imported} records`);
1329
2294
  }
1330
2295
  }
1331
- if (existsSync(tmpApex)) unlinkSync(tmpApex);
2296
+ });
1332
2297
  });
1333
2298
  } else {
1334
2299
  recordSkipped(dataStep, dataStep.available ? 'not selected' : 'no data plan');
@@ -1365,29 +2330,12 @@ async function main() {
1365
2330
  recordOk(uiBundleBuildStep);
1366
2331
  }
1367
2332
 
1368
- const devStep = stepDefs.find((s) => s.key === 'dev');
1369
- if (!skipDev) {
1370
- // dev is skippable and terminal: a failure here is a local runtime issue
1371
- // (port in use, tooling), not a broken setup. Print the summary BEFORE the
1372
- // (blocking, long-lived) dev server starts so the developer sees the setup
1373
- // outcome up front; the server then runs in the foreground until Ctrl+C.
1374
- recordOk(devStep);
1375
- printSummary(targetOrg);
1376
- console.log('\n--- Launching dev server (Ctrl+C to stop) ---\n');
1377
- const devResult = run('Dev server', 'npm', ['run', 'dev'], { cwd: uiBundleDir, optional: true });
1378
- if (devResult.status !== 0) {
1379
- // Replace the optimistic `ok` with a skippable failure and reprint.
1380
- const row = results.find((r) => r.key === 'dev');
1381
- row.status = 'failed';
1382
- row.reason = 'dev server failed to start — setup itself completed; check local runtime';
1383
- printSummary(targetOrg);
1384
- }
1385
- process.exit(finalExitCode());
1386
- } else {
1387
- recordSkipped(devStep, 'not selected');
1388
- }
1389
-
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.
1390
2335
  printSummary(targetOrg);
2336
+ if (finalExitCode() === 0) {
2337
+ console.log('\nTo launch the dev server, run: npm run dev:preview');
2338
+ }
1391
2339
  process.exit(finalExitCode());
1392
2340
  }
1393
2341