@wix/agent-skills 1.33.0 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (635) hide show
  1. package/README.md +23 -0
  2. package/package.json +2 -2
  3. package/skills/wix-app/references/DASHBOARD_PAGE.md +1 -1
  4. package/skills/wix-export/SKILL.md +83 -0
  5. package/skills/wix-harmony-editor/.publish-manifest.json +8 -0
  6. package/skills/wix-harmony-editor/COPY-SITE.md +494 -0
  7. package/skills/wix-harmony-editor/SKILL.md +317 -0
  8. package/skills/wix-harmony-editor/scripts/copy/build-description.mjs +249 -0
  9. package/skills/wix-harmony-editor/scripts/copy/check-description.mjs +225 -0
  10. package/skills/wix-harmony-editor/scripts/copy/check-mirror.mjs +89 -0
  11. package/skills/wix-harmony-editor/scripts/copy/compare-preview.mjs +76 -0
  12. package/skills/wix-harmony-editor/scripts/copy/deploy-description.mjs +212 -0
  13. package/skills/wix-harmony-editor/scripts/copy/desc-hash.mjs +44 -0
  14. package/skills/wix-harmony-editor/scripts/copy/editor-run.mjs +45 -0
  15. package/skills/wix-harmony-editor/scripts/copy/export-page.mjs +53 -0
  16. package/skills/wix-harmony-editor/scripts/copy/find-interactions.mjs +76 -0
  17. package/skills/wix-harmony-editor/scripts/copy/hide-scrollbars.mjs +16 -0
  18. package/skills/wix-harmony-editor/scripts/copy/import-media.mjs +150 -0
  19. package/skills/wix-harmony-editor/scripts/copy/link-url.mjs +27 -0
  20. package/skills/wix-harmony-editor/scripts/copy/lint-api.mjs +56 -0
  21. package/skills/wix-harmony-editor/scripts/copy/measure-source.mjs +211 -0
  22. package/skills/wix-harmony-editor/scripts/copy/merge-mirrors.mjs +29 -0
  23. package/skills/wix-harmony-editor/scripts/copy/mirror-site.mjs +92 -0
  24. package/skills/wix-harmony-editor/scripts/copy/mobile-stage.mjs +56 -0
  25. package/skills/wix-harmony-editor/scripts/copy/preview-widths.mjs +73 -0
  26. package/skills/wix-harmony-editor/scripts/copy/render-plate.mjs +67 -0
  27. package/skills/wix-harmony-editor/scripts/copy/serve-mirror.mjs +102 -0
  28. package/skills/wix-harmony-editor/scripts/copy/snapshot-capabilities.mjs +40 -0
  29. package/skills/wix-harmony-editor/scripts/copy/split-sections.mjs +191 -0
  30. package/skills/wix-harmony-editor/scripts/copy/upload-media-manager.mjs +61 -0
  31. package/skills/wix-harmony-editor/scripts/launch.sh +359 -0
  32. package/skills/wix-headless/SKILL.md +7 -2
  33. package/skills/wix-headless/references/CAPABILITIES.md +6 -1
  34. package/skills/wix-headless/references/DISCOVERY.md +2 -1
  35. package/skills/wix-headless/references/SDK_HANDOFF.md +6 -1
  36. package/skills/wix-headless/references/SEED.md +3 -2
  37. package/skills/wix-headless/references/SETUP.md +1 -0
  38. package/skills/wix-headless/references/inline-recipes/experience-donations.md +102 -0
  39. package/skills/wix-headless/references/inline-recipes/how-to-code-donations.md +146 -0
  40. package/skills/wix-headless/references/inline-recipes/setup-donations.md +15 -0
  41. package/skills/wix-headless/references/managed/CREATE.md +1 -1
  42. package/skills/wix-headless-kit/SKILL.md +110 -21
  43. package/skills/wix-headless-kit/guides/api-run.md +15 -13
  44. package/skills/wix-headless-kit/guides/existing-site.md +31 -0
  45. package/skills/wix-headless-kit/guides/migration.md +49 -17
  46. package/skills/wix-headless-kit/install/agents-md.mjs +1 -1
  47. package/skills/wix-headless-kit/install/context.mjs +61 -6
  48. package/skills/wix-headless-kit/install/pins.json +1 -1
  49. package/skills/wix-headless-kit/install/setup.mjs +107 -12
  50. package/skills/wix-headless-replatform/.publish-manifest.json +8 -0
  51. package/skills/wix-headless-replatform/SKILL.md +116 -0
  52. package/skills/wix-headless-replatform/agents/openai.yaml +6 -0
  53. package/skills/wix-headless-replatform/references/control-and-visual-fidelity-contract.md +43 -0
  54. package/skills/wix-headless-replatform/references/extraction-schema.md +187 -0
  55. package/skills/wix-headless-replatform/references/interaction-runtime-contract.md +137 -0
  56. package/skills/wix-headless-replatform/references/layout-blueprint-contract.md +41 -0
  57. package/skills/wix-headless-replatform/references/output-contract.md +93 -0
  58. package/skills/wix-headless-replatform/references/post-build-gap-contract.md +125 -0
  59. package/skills/wix-headless-replatform/references/qa-checklist.md +83 -0
  60. package/skills/wix-headless-replatform/references/safety.md +19 -0
  61. package/skills/wix-headless-replatform/references/ui-normalization-contract.md +70 -0
  62. package/skills/wix-headless-replatform/references/workflow.md +157 -0
  63. package/skills/wix-headless-replatform/registry/README.md +20 -0
  64. package/skills/wix-headless-replatform/registry/approvals/button/shadcn-default-ac60ef5.json +28 -0
  65. package/skills/wix-headless-replatform/registry/items/button/shadcn-default-ac60ef5/button.tsx +54 -0
  66. package/skills/wix-headless-replatform/registry/items/button/shadcn-default-ac60ef5/capabilities.json +60 -0
  67. package/skills/wix-headless-replatform/registry/items/button/shadcn-default-ac60ef5/contract.md +48 -0
  68. package/skills/wix-headless-replatform/registry/licenses/shadcn-ui-ac60ef5-MIT.txt +21 -0
  69. package/skills/wix-headless-replatform/registry/registry.json +36 -0
  70. package/skills/wix-headless-replatform/resources/rp-facelift/SKILL.md +32 -0
  71. package/skills/wix-headless-replatform/resources/rp-project-context/SKILL.md +62 -0
  72. package/skills/wix-headless-replatform/resources/rp-qa-gap-loop/SKILL.md +64 -0
  73. package/skills/wix-headless-replatform/resources/rp-source-evidence/SKILL.md +42 -0
  74. package/skills/wix-headless-replatform/resources/rp-ui-implementation/SKILL.md +73 -0
  75. package/skills/wix-headless-replatform/schemas/build-plan.schema.json +10 -0
  76. package/skills/wix-headless-replatform/schemas/candidate.schema.json +19 -0
  77. package/skills/wix-headless-replatform/schemas/common.schema.json +33 -0
  78. package/skills/wix-headless-replatform/schemas/decision-patch.schema.json +10 -0
  79. package/skills/wix-headless-replatform/schemas/decision-request.schema.json +10 -0
  80. package/skills/wix-headless-replatform/schemas/extraction-gap.schema.json +28 -0
  81. package/skills/wix-headless-replatform/schemas/extraction-manifest.schema.json +34 -0
  82. package/skills/wix-headless-replatform/schemas/final-report.schema.json +10 -0
  83. package/skills/wix-headless-replatform/schemas/foundation.schema.json +11 -0
  84. package/skills/wix-headless-replatform/schemas/metadata.schema.json +11 -0
  85. package/skills/wix-headless-replatform/schemas/observation-packet.schema.json +17 -0
  86. package/skills/wix-headless-replatform/schemas/page-capture.schema.json +11 -0
  87. package/skills/wix-headless-replatform/schemas/page-resolution.schema.json +33 -0
  88. package/skills/wix-headless-replatform/schemas/shared-chrome.schema.json +11 -0
  89. package/skills/wix-headless-replatform/schemas/unit.schema.json +40 -0
  90. package/skills/wix-headless-replatform/scripts/assemble-extraction.mjs +844 -0
  91. package/skills/wix-headless-replatform/scripts/benchmark-extraction.mjs +163 -0
  92. package/skills/wix-headless-replatform/scripts/browser-extraction-preflight.mjs +42 -0
  93. package/skills/wix-headless-replatform/scripts/build-extracted-homepage.mjs +228 -0
  94. package/skills/wix-headless-replatform/scripts/clear-wix-starter.mjs +87 -0
  95. package/skills/wix-headless-replatform/scripts/create-wix-project.mjs +505 -0
  96. package/skills/wix-headless-replatform/scripts/discover-urls.mjs +142 -0
  97. package/skills/wix-headless-replatform/scripts/extract-assets.mjs +140 -0
  98. package/skills/wix-headless-replatform/scripts/extract-design-system.mjs +637 -0
  99. package/skills/wix-headless-replatform/scripts/extract-interactions.mjs +1903 -0
  100. package/skills/wix-headless-replatform/scripts/extract-page.mjs +2461 -0
  101. package/skills/wix-headless-replatform/scripts/extract-seo.mjs +25 -0
  102. package/skills/wix-headless-replatform/scripts/extract-tokens.mjs +63 -0
  103. package/skills/wix-headless-replatform/scripts/finalize-extraction-report.mjs +126 -0
  104. package/skills/wix-headless-replatform/scripts/finalize-gap-review.mjs +180 -0
  105. package/skills/wix-headless-replatform/scripts/finalize-gap-review.test.mjs +98 -0
  106. package/skills/wix-headless-replatform/scripts/finalize-migration-website.mjs +103 -0
  107. package/skills/wix-headless-replatform/scripts/generate-control-state-contract.mjs +176 -0
  108. package/skills/wix-headless-replatform/scripts/generate-design-md.mjs +261 -0
  109. package/skills/wix-headless-replatform/scripts/generate-extraction-validators.mjs +25 -0
  110. package/skills/wix-headless-replatform/scripts/generate-invoice-download-backend.mjs +342 -0
  111. package/skills/wix-headless-replatform/scripts/generate-layout-blueprint.mjs +140 -0
  112. package/skills/wix-headless-replatform/scripts/generate-repeater-cms.mjs +22 -0
  113. package/skills/wix-headless-replatform/scripts/generate-route-plan.mjs +143 -0
  114. package/skills/wix-headless-replatform/scripts/generate-scene-contract.mjs +288 -0
  115. package/skills/wix-headless-replatform/scripts/generate-ui-normalization.mjs +266 -0
  116. package/skills/wix-headless-replatform/scripts/generate-visual-assets.mjs +111 -0
  117. package/skills/wix-headless-replatform/scripts/lib/browser-tooling.mjs +570 -0
  118. package/skills/wix-headless-replatform/scripts/lib/common.mjs +329 -0
  119. package/skills/wix-headless-replatform/scripts/lib/component-capabilities.mjs +121 -0
  120. package/skills/wix-headless-replatform/scripts/lib/component-registry.mjs +282 -0
  121. package/skills/wix-headless-replatform/scripts/lib/content-boundary.mjs +61 -0
  122. package/skills/wix-headless-replatform/scripts/lib/extraction-contract.mjs +374 -0
  123. package/skills/wix-headless-replatform/scripts/lib/extraction-detectors.mjs +243 -0
  124. package/skills/wix-headless-replatform/scripts/lib/extraction-validators.generated.mjs +1139 -0
  125. package/skills/wix-headless-replatform/scripts/lib/font-contract.mjs +326 -0
  126. package/skills/wix-headless-replatform/scripts/lib/frontend-automation-state.mjs +184 -0
  127. package/skills/wix-headless-replatform/scripts/lib/gap-analysis.mjs +396 -0
  128. package/skills/wix-headless-replatform/scripts/lib/html-extract.mjs +168 -0
  129. package/skills/wix-headless-replatform/scripts/lib/interaction-bootstrap.mjs +10 -0
  130. package/skills/wix-headless-replatform/scripts/lib/interaction-runtime.mjs +194 -0
  131. package/skills/wix-headless-replatform/scripts/lib/interaction-timeline.mjs +348 -0
  132. package/skills/wix-headless-replatform/scripts/lib/layout-blueprint/classifiers.mjs +141 -0
  133. package/skills/wix-headless-replatform/scripts/lib/layout-blueprint/geometry.mjs +43 -0
  134. package/skills/wix-headless-replatform/scripts/lib/layout-blueprint/vocabulary.mjs +18 -0
  135. package/skills/wix-headless-replatform/scripts/lib/ui-normalization.css +64 -0
  136. package/skills/wix-headless-replatform/scripts/optimize-svg.mjs +31 -0
  137. package/skills/wix-headless-replatform/scripts/post-build-gap.mjs +358 -0
  138. package/skills/wix-headless-replatform/scripts/provision-repeater-cms.mjs +25 -0
  139. package/skills/wix-headless-replatform/scripts/record-gap-decision.mjs +39 -0
  140. package/skills/wix-headless-replatform/scripts/replay-extraction.mjs +107 -0
  141. package/skills/wix-headless-replatform/scripts/resolve-home-page.mjs +96 -0
  142. package/skills/wix-headless-replatform/scripts/site-clone.mjs +658 -0
  143. package/skills/wix-headless-replatform/scripts/validate-font-contract.mjs +29 -0
  144. package/skills/wix-headless-replatform/scripts/verify-interactions.mjs +669 -0
  145. package/skills/wix-headless-replatform/scripts/visual-qa.mjs +370 -0
  146. package/skills/wix-headless-templates/donations/INSTRUCTIONS.md +37 -24
  147. package/skills/wix-headless-templates/donations/app/components/donations/DonateForm.tsx +49 -23
  148. package/skills/wix-headless-templates/donations/app/components/donations/DonationReceipt.tsx +6 -5
  149. package/skills/wix-headless-templates/donations/app/components/donations/GoalProgress.tsx +5 -5
  150. package/skills/wix-headless-templates/donations/app/wix/donations/campaigns.ts +4 -4
  151. package/skills/wix-headless-templates/donations/app/wix/donations/donate.ts +7 -3
  152. package/skills/wix-headless-templates/donations/app/wix/donations/donation-store.ts +2 -2
  153. package/skills/wix-headless-templates/donations/app/wix/donations/donations-core.ts +12 -9
  154. package/skills/wix-headless-templates/donations/project/src/components/donations/DonateForm.tsx +49 -23
  155. package/skills/wix-headless-templates/donations/project/src/components/donations/DonationReceipt.tsx +6 -5
  156. package/skills/wix-headless-templates/donations/project/src/components/donations/GoalProgress.tsx +5 -5
  157. package/skills/wix-headless-templates/donations/project/src/wix/donations/campaigns.ts +4 -4
  158. package/skills/wix-headless-templates/donations/project/src/wix/donations/donate.ts +7 -3
  159. package/skills/wix-headless-templates/donations/project/src/wix/donations/donation-store.ts +2 -2
  160. package/skills/wix-headless-templates/donations/project/src/wix/donations/donations-core.ts +12 -9
  161. package/skills/wix-headless-templates/donations/rest/campaigns.ts +4 -4
  162. package/skills/wix-headless-templates/donations/rest/donate.ts +7 -3
  163. package/skills/wix-headless-templates/donations/seed/SEED.md +12 -7
  164. package/skills/wix-headless-templates/donations/tests/donation-contract.test.mjs +71 -0
  165. package/skills/wix-headless-templates/donations/tests/donation-form.test.cjs +137 -0
  166. package/skills/wix-headless-templates/restaurants/INSTRUCTIONS.md +28 -14
  167. package/skills/wix-headless-templates/restaurants/app/components/restaurants/OrderCartDrawer.tsx +87 -5
  168. package/skills/wix-headless-templates/restaurants/app/hooks/restaurants/useOrderCart.ts +9 -1
  169. package/skills/wix-headless-templates/restaurants/app/wix/restaurants/order-store.ts +33 -4
  170. package/skills/wix-headless-templates/restaurants/app/wix/restaurants/ordering-core.ts +100 -5
  171. package/skills/wix-headless-templates/restaurants/app/wix/restaurants/ordering.ts +101 -15
  172. package/skills/wix-headless-templates/restaurants/app/wix/restaurants/types.ts +35 -1
  173. package/skills/wix-headless-templates/restaurants/project/src/components/restaurants/OrderCartDrawer.tsx +87 -5
  174. package/skills/wix-headless-templates/restaurants/project/src/hooks/restaurants/useOrderCart.ts +9 -1
  175. package/skills/wix-headless-templates/restaurants/project/src/wix/restaurants/order-store.ts +33 -4
  176. package/skills/wix-headless-templates/restaurants/project/src/wix/restaurants/ordering-core.ts +100 -5
  177. package/skills/wix-headless-templates/restaurants/project/src/wix/restaurants/ordering.ts +101 -15
  178. package/skills/wix-headless-templates/restaurants/project/src/wix/restaurants/types.ts +35 -1
  179. package/skills/wix-headless-templates/restaurants/rest/ordering.ts +91 -14
  180. package/skills/wix-import/SKILL.md +90 -0
  181. package/skills/wix-manage/SKILL.md +38 -10
  182. package/skills/wix-manage/references/automations/actions.md +11 -11
  183. package/skills/wix-manage/references/automations/activation-status.md +6 -9
  184. package/skills/wix-manage/references/automations/api-catalog.md +48 -32
  185. package/skills/wix-manage/references/automations/automation-model.md +97 -22
  186. package/skills/wix-manage/references/automations/bracket-expressions.md +7 -7
  187. package/skills/wix-manage/references/automations/build-and-manage-automations.md +140 -309
  188. package/skills/wix-manage/references/automations/conditions.md +187 -0
  189. package/skills/wix-manage/references/automations/schemas-and-scheduling.md +191 -0
  190. package/skills/wix-manage/references/automations/special-actions.md +210 -0
  191. package/skills/wix-manage/references/automations/triggers.md +47 -10
  192. package/skills/wix-manage/references/automations/validation-and-verification.md +320 -0
  193. package/skills/wix-manage/references/custom-apps/use-app-tools.md +124 -0
  194. package/skills/wix-manage/references/dashboard-navigation/dashboard-navigation.md +2 -1
  195. package/skills/wix-manage/references/dashboard-navigation/routes.json +249 -0
  196. package/skills/wix-manage/references/donations/create-and-update-donation-campaigns.md +139 -0
  197. package/skills/wix-manage/references/events/create-wix-event.md +136 -73
  198. package/skills/wix-manage/references/events/events-dashboard-navigation.md +81 -0
  199. package/skills/wix-manage/references/events/manage-event-guests.md +366 -0
  200. package/skills/wix-manage/references/events/manage-event-tickets.md +293 -0
  201. package/skills/wix-manage/references/events/manage-wix-events.md +313 -55
  202. package/skills/wix-manage/references/sites/manage-oauth-apps.md +1 -0
  203. package/skills/wix-manage/references/sites/upload-static-site.md +127 -8
  204. package/skills/wix-manage/references/stores/update-product-with-options.md +58 -2
  205. package/skills/wix-replatform/.publish-manifest.json +5 -5
  206. package/skills/wix-replatform/CLI.md +162 -0
  207. package/skills/wix-replatform/README.md +52 -0
  208. package/skills/wix-replatform/SKILL.md +229 -684
  209. package/skills/wix-replatform/console/account.css +1 -0
  210. package/skills/wix-replatform/console/app.css +1 -0
  211. package/skills/wix-replatform/console/app.js +117 -0
  212. package/skills/wix-replatform/console/index.html +4 -0
  213. package/skills/wix-replatform/console/json.css +11 -0
  214. package/skills/wix-replatform/lib/agent-adapters/index.js +71 -0
  215. package/skills/wix-replatform/lib/app-page-routing.js +75 -0
  216. package/skills/wix-replatform/lib/artifact-freshness.js +11 -1
  217. package/skills/wix-replatform/lib/blocked-data-requests.js +427 -0
  218. package/skills/wix-replatform/lib/census-reconciliation.js +426 -0
  219. package/skills/wix-replatform/lib/completion-report.js +1393 -13
  220. package/skills/wix-replatform/lib/config-env.js +85 -11
  221. package/skills/wix-replatform/lib/confirmed-pictures.js +212 -0
  222. package/skills/wix-replatform/lib/dependency-readiness.js +423 -0
  223. package/skills/wix-replatform/lib/dependency-recovery.js +21 -0
  224. package/skills/wix-replatform/lib/destination-choice.js +163 -0
  225. package/skills/wix-replatform/lib/destination-handoff.js +62 -0
  226. package/skills/wix-replatform/lib/destination-http.js +81 -0
  227. package/skills/wix-replatform/lib/destination-route.js +98 -0
  228. package/skills/wix-replatform/lib/destination.js +919 -0
  229. package/skills/wix-replatform/lib/discovered-census.js +231 -0
  230. package/skills/wix-replatform/lib/discovered-set-status.js +255 -0
  231. package/skills/wix-replatform/lib/document-url-guard.js +203 -0
  232. package/skills/wix-replatform/lib/entity-qa-attestation.js +339 -0
  233. package/skills/wix-replatform/lib/entity-verification.js +18 -0
  234. package/skills/wix-replatform/lib/execution-capability.js +120 -0
  235. package/skills/wix-replatform/lib/execution-log.js +170 -0
  236. package/skills/wix-replatform/lib/execution-manifest.js +20 -2
  237. package/skills/wix-replatform/lib/execution-state.js +22 -0
  238. package/skills/wix-replatform/lib/expectations-ledger.js +96 -0
  239. package/skills/wix-replatform/lib/generated-plugin-handoff.js +140 -0
  240. package/skills/wix-replatform/lib/import-readiness-contract.js +23 -0
  241. package/skills/wix-replatform/lib/import-recovery.js +800 -6
  242. package/skills/wix-replatform/lib/imported-redirect-targets.js +608 -0
  243. package/skills/wix-replatform/lib/internal-link-reconciliation.js +166 -0
  244. package/skills/wix-replatform/lib/link-audit.js +173 -0
  245. package/skills/wix-replatform/lib/link-census.js +194 -0
  246. package/skills/wix-replatform/lib/link-plan.js +148 -0
  247. package/skills/wix-replatform/lib/link-verification.js +274 -0
  248. package/skills/wix-replatform/lib/link-write-journal.js +42 -0
  249. package/skills/wix-replatform/lib/local-state.js +869 -30
  250. package/skills/wix-replatform/lib/member-completion.js +658 -0
  251. package/skills/wix-replatform/lib/member-crosswalk.js +69 -0
  252. package/skills/wix-replatform/lib/member-outcome-registry.js +265 -0
  253. package/skills/wix-replatform/lib/migration-completion.js +311 -0
  254. package/skills/wix-replatform/lib/operator-identity.js +47 -0
  255. package/skills/wix-replatform/lib/orchestration-decisions.js +248 -0
  256. package/skills/wix-replatform/lib/orchestration-preflight.js +401 -19
  257. package/skills/wix-replatform/lib/orchestration-router.js +608 -32
  258. package/skills/wix-replatform/lib/orchestration-state.js +188 -12
  259. package/skills/wix-replatform/lib/order-reference-readiness.js +30 -0
  260. package/skills/wix-replatform/lib/payments-outcome-registry.js +200 -0
  261. package/skills/wix-replatform/lib/plugin-cms-fallback.js +618 -0
  262. package/skills/wix-replatform/lib/preservation-approval-stamp.js +54 -0
  263. package/skills/wix-replatform/lib/product-media-deferral.js +96 -0
  264. package/skills/wix-replatform/lib/progress-log.js +19 -3
  265. package/skills/wix-replatform/lib/read-back-approval.js +184 -0
  266. package/skills/wix-replatform/lib/read-back-comparison.js +136 -0
  267. package/skills/wix-replatform/lib/read-back-contract.js +243 -0
  268. package/skills/wix-replatform/lib/read-back-extract.js +118 -0
  269. package/skills/wix-replatform/lib/read-back-gate.js +734 -0
  270. package/skills/wix-replatform/lib/read-back-reads.js +94 -0
  271. package/skills/wix-replatform/lib/read-back-state.js +107 -0
  272. package/skills/wix-replatform/lib/read-back-summary.js +81 -0
  273. package/skills/wix-replatform/lib/rerun-conflicts.js +334 -0
  274. package/skills/wix-replatform/lib/run-controller.js +401 -0
  275. package/skills/wix-replatform/lib/seo-outcome-registry.js +45 -0
  276. package/skills/wix-replatform/lib/setup-verification.js +148 -0
  277. package/skills/wix-replatform/lib/source-access.js +231 -0
  278. package/skills/wix-replatform/lib/source-coverage.js +1130 -0
  279. package/skills/wix-replatform/lib/source-secrets.js +277 -0
  280. package/skills/wix-replatform/lib/structured-link-patch.js +59 -0
  281. package/skills/wix-replatform/lib/task-state.js +110 -0
  282. package/skills/wix-replatform/lib/url-preservation-report.js +319 -0
  283. package/skills/wix-replatform/lib/url-preservation-state.js +349 -1
  284. package/skills/wix-replatform/lib/url-redirect-plan.js +728 -0
  285. package/skills/wix-replatform/lib/url-verification.js +315 -0
  286. package/skills/wix-replatform/lib/user-action-effects.js +42 -0
  287. package/skills/wix-replatform/lib/user-actions.js +264 -0
  288. package/skills/wix-replatform/lib/website-handoff.js +1220 -0
  289. package/skills/wix-replatform/lib/wix-client-callers.js +54 -0
  290. package/skills/wix-replatform/lib/wix-dashboard-url.js +35 -0
  291. package/skills/wix-replatform/lib/write-verification-state.js +92 -0
  292. package/skills/wix-replatform/lib/write-verification.js +274 -0
  293. package/skills/wix-replatform/resources/rp-destination/SKILL.md +137 -0
  294. package/skills/wix-replatform/resources/rp-discovery/SKILL.md +189 -16
  295. package/skills/wix-replatform/resources/rp-discovery/scripts/promote-source-coverage.js +47 -0
  296. package/skills/wix-replatform/resources/rp-execute-import/SKILL.md +869 -29
  297. package/skills/wix-replatform/resources/rp-execute-import/scripts/shipping-estimate-audit.js +70 -0
  298. package/skills/wix-replatform/resources/rp-execute-setup/SKILL.md +195 -29
  299. package/skills/wix-replatform/resources/rp-execute-setup/scripts/execute-setup.js +442 -0
  300. package/skills/wix-replatform/resources/rp-execution-policy/SKILL.md +112 -0
  301. package/skills/wix-replatform/resources/rp-execution-policy/lib/coupon-currency-plan-report.js +143 -0
  302. package/skills/wix-replatform/resources/rp-execution-policy/lib/payments-report.js +244 -0
  303. package/skills/wix-replatform/resources/rp-import-codegen/SKILL.md +2082 -38
  304. package/skills/wix-replatform/resources/rp-mapper/SKILL.md +528 -11
  305. package/skills/wix-replatform/resources/rp-mapper/lib/structure-bridge-planning.js +303 -0
  306. package/skills/wix-replatform/resources/rp-mapper/scripts/coverage-reconcile.js +88 -0
  307. package/skills/wix-replatform/resources/rp-mapper/wix-business-solutions-taxonomy.md +6 -5
  308. package/skills/wix-replatform/resources/rp-preflight/SKILL.md +40 -0
  309. package/skills/wix-replatform/resources/rp-project-intake/SKILL.md +55 -0
  310. package/skills/wix-replatform/resources/rp-quick-runtime/SKILL.md +60 -0
  311. package/skills/wix-replatform/resources/rp-quick-runtime/lib/import-progress.js +89 -0
  312. package/skills/wix-replatform/resources/rp-quick-runtime/lib/limit-recovery.js +36 -0
  313. package/skills/wix-replatform/resources/rp-quick-shopify/SKILL.md +123 -0
  314. package/skills/wix-replatform/resources/rp-quick-shopify/quick-mode.json +124 -0
  315. package/skills/wix-replatform/resources/rp-quick-shopify/scripts/quick-mode.js +522 -0
  316. package/skills/wix-replatform/resources/rp-quick-woocommerce/SKILL.md +56 -0
  317. package/skills/wix-replatform/resources/rp-quick-woocommerce/quick-mode.json +91 -0
  318. package/skills/wix-replatform/resources/rp-quick-woocommerce/scripts/quick-mode.js +255 -0
  319. package/skills/wix-replatform/resources/rp-setup-discovery/SKILL.md +80 -10
  320. package/skills/wix-replatform/resources/rp-setup-discovery/scripts/quick-setup-plan.js +44 -0
  321. package/skills/wix-replatform/resources/rp-source-csv/SKILL.md +3 -0
  322. package/skills/wix-replatform/resources/rp-source-csv/lib/csv-fileset.js +0 -0
  323. package/skills/wix-replatform/resources/rp-source-csv/scripts/csv-discovery.js +21 -1
  324. package/skills/wix-replatform/resources/rp-source-inputs/SKILL.md +66 -0
  325. package/skills/wix-replatform/resources/rp-source-sfcc/SKILL.md +153 -0
  326. package/skills/wix-replatform/resources/rp-source-shopify/SKILL.md +394 -0
  327. package/skills/wix-replatform/resources/rp-source-shopify/lib/discovery-reads.js +200 -0
  328. package/skills/wix-replatform/resources/rp-source-shopify/lib/import-findings.js +34 -0
  329. package/skills/wix-replatform/resources/rp-source-shopify/lib/shopify-bulk-sqlite-worker.js +44 -0
  330. package/skills/wix-replatform/resources/rp-source-shopify/lib/shopify-bulk.js +1470 -0
  331. package/skills/wix-replatform/resources/rp-source-shopify/lib/shopify-cli.js +446 -0
  332. package/skills/wix-replatform/resources/rp-source-shopify/lib/shopify-gift-cards.js +474 -0
  333. package/skills/wix-replatform/resources/rp-source-shopify/lib/shopify-protected-fields.js +879 -0
  334. package/skills/wix-replatform/resources/rp-source-shopify/lib/shopify-session.js +426 -0
  335. package/skills/wix-replatform/resources/rp-source-shopify/queries/articles.graphql +24 -0
  336. package/skills/wix-replatform/resources/rp-source-shopify/queries/blogs.graphql +18 -0
  337. package/skills/wix-replatform/resources/rp-source-shopify/queries/collections.graphql +40 -0
  338. package/skills/wix-replatform/resources/rp-source-shopify/queries/customers.graphql +76 -0
  339. package/skills/wix-replatform/resources/rp-source-shopify/queries/delivery-profiles.graphql +51 -0
  340. package/skills/wix-replatform/resources/rp-source-shopify/queries/discounts.graphql +35 -0
  341. package/skills/wix-replatform/resources/rp-source-shopify/queries/files.graphql +20 -0
  342. package/skills/wix-replatform/resources/rp-source-shopify/queries/gift-cards.graphql +18 -0
  343. package/skills/wix-replatform/resources/rp-source-shopify/queries/inventory.graphql +31 -0
  344. package/skills/wix-replatform/resources/rp-source-shopify/queries/locations.graphql +21 -0
  345. package/skills/wix-replatform/resources/rp-source-shopify/queries/menus.graphql +21 -0
  346. package/skills/wix-replatform/resources/rp-source-shopify/queries/metaobjects.graphql +30 -0
  347. package/skills/wix-replatform/resources/rp-source-shopify/queries/orders-core.graphql +150 -0
  348. package/skills/wix-replatform/resources/rp-source-shopify/queries/orders-fulfillments.graphql +36 -0
  349. package/skills/wix-replatform/resources/rp-source-shopify/queries/orders-refunds.graphql +48 -0
  350. package/skills/wix-replatform/resources/rp-source-shopify/queries/pages.graphql +20 -0
  351. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-customers-address.graphql +8 -0
  352. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-customers-email.graphql +6 -0
  353. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-customers-name.graphql +8 -0
  354. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-customers-phone.graphql +8 -0
  355. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-orders-address.graphql +12 -0
  356. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-orders-email.graphql +6 -0
  357. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-orders-name.graphql +13 -0
  358. package/skills/wix-replatform/resources/rp-source-shopify/queries/probe-orders-phone.graphql +13 -0
  359. package/skills/wix-replatform/resources/rp-source-shopify/queries/products.graphql +73 -0
  360. package/skills/wix-replatform/resources/rp-source-shopify/queries/url-redirects.graphql +13 -0
  361. package/skills/wix-replatform/resources/rp-source-shopify/scripts/shopify-discovery.js +693 -0
  362. package/skills/wix-replatform/resources/rp-source-shopify/scripts/shopify-extract.js +283 -0
  363. package/skills/wix-replatform/resources/rp-source-shopify/scripts/shopify-gift-card-remedy.js +191 -0
  364. package/skills/wix-replatform/resources/rp-source-shopify/scripts/shopify-session-check.js +115 -0
  365. package/skills/wix-replatform/resources/rp-source-shopify/source-schema.example.json +201 -0
  366. package/skills/wix-replatform/resources/rp-source-wordpress/PLUGIN-READ-PLANS.md +146 -0
  367. package/skills/wix-replatform/resources/rp-source-wordpress/SKILL.md +736 -22
  368. package/skills/wix-replatform/resources/rp-source-wordpress/lib/blocked-data-handlers.js +73 -0
  369. package/skills/wix-replatform/resources/rp-source-wordpress/lib/checkout-field-csv-parser.js +115 -0
  370. package/skills/wix-replatform/resources/rp-source-wordpress/lib/checkout-field-csv-parser.test-fixture.js +91 -0
  371. package/skills/wix-replatform/resources/rp-source-wordpress/lib/coupon-discovery.js +440 -0
  372. package/skills/wix-replatform/resources/rp-source-wordpress/lib/currency-gate.js +125 -0
  373. package/skills/wix-replatform/resources/rp-source-wordpress/lib/gateway-source-keys.js +252 -0
  374. package/skills/wix-replatform/resources/rp-source-wordpress/lib/gateway-source-keys.json +183 -0
  375. package/skills/wix-replatform/resources/rp-source-wordpress/lib/gateway-summary.mjs +333 -0
  376. package/skills/wix-replatform/resources/rp-source-wordpress/lib/invoice-discovery.js +426 -0
  377. package/skills/wix-replatform/resources/rp-source-wordpress/lib/plugin-disposition.js +400 -0
  378. package/skills/wix-replatform/resources/rp-source-wordpress/lib/plugin-entity-read-plan.js +633 -0
  379. package/skills/wix-replatform/resources/rp-source-wordpress/lib/plugin-knowledge.js +1127 -0
  380. package/skills/wix-replatform/resources/rp-source-wordpress/lib/refund-corroboration.js +194 -0
  381. package/skills/wix-replatform/resources/rp-source-wordpress/lib/refund-corroboration.json +100 -0
  382. package/skills/wix-replatform/resources/rp-source-wordpress/lib/sampled-ids-batch.js +157 -0
  383. package/skills/wix-replatform/resources/rp-source-wordpress/lib/secret-value-guard.js +234 -0
  384. package/skills/wix-replatform/resources/rp-source-wordpress/lib/store-currency.js +101 -0
  385. package/skills/wix-replatform/resources/rp-source-wordpress/lib/structure-bridge-reader.js +755 -0
  386. package/skills/wix-replatform/resources/rp-source-wordpress/lib/wix-wp-plugin-v2-client.js +1074 -0
  387. package/skills/wix-replatform/resources/rp-source-wordpress/lib/wix-wp-plugin-v2-client.test-fixture.js +149 -0
  388. package/skills/wix-replatform/resources/rp-source-wordpress/lib/woo-inventory.js +25 -0
  389. package/skills/wix-replatform/resources/rp-source-wordpress/lib/wp-http.js +204 -9
  390. package/skills/wix-replatform/resources/rp-source-wordpress/lib/wp-image-url.js +186 -0
  391. package/skills/wix-replatform/resources/rp-source-wordpress/lib/wp-plugin-detect.js +1422 -0
  392. package/skills/wix-replatform/resources/rp-source-wordpress/lib/wp-redirect-sources.js +343 -0
  393. package/skills/wix-replatform/resources/rp-source-wordpress/lib/wp-route-classifier.js +262 -26
  394. package/skills/wix-replatform/resources/rp-source-wordpress/lib/yoast-product-seo-evidence.js +272 -0
  395. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/README.md +373 -0
  396. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/advanced-custom-fields.json +101 -0
  397. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/back-in-stock-notifier-for-woocommerce.json +81 -0
  398. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/capabilities-pending-decision.json +128 -0
  399. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/cms-fallback-eligible.json +18 -0
  400. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/contact-form-7.json +104 -0
  401. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/facebook-for-woocommerce.json +44 -0
  402. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/fingerprint-aliases.json +49 -0
  403. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/free-gifts-for-woocommerce.json +94 -0
  404. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/index.json +863 -0
  405. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/mailpoet.json +52 -0
  406. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/membership-for-woocommerce.json +161 -0
  407. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/mwb-bookings-for-woocommerce.json +180 -0
  408. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/no-migration-needed.json +286 -0
  409. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/pricing-deals-for-woocommerce.json +79 -0
  410. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/product-extras-for-woocommerce.json +120 -0
  411. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/pw-woocommerce-gift-cards.json +128 -0
  412. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/requires-development.json +88 -0
  413. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/seo-by-rank-math.json +80 -0
  414. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/seriously-simple-podcasting.json +46 -0
  415. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/strong-testimonials.json +55 -0
  416. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/subscriptions-for-woocommerce.json +99 -0
  417. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/tablepress.json +55 -0
  418. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/the-events-calendar.json +160 -0
  419. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/ti-woocommerce-wishlist.json +81 -0
  420. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woo-checkout-field-editor-pro.json +60 -0
  421. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woo-discount-rules.json +74 -0
  422. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woo-product-bundle.json +75 -0
  423. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woocommerce-gift-cards.json +60 -0
  424. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woocommerce-other-payment-gateway.json +44 -0
  425. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woocommerce-pdf-invoices-packing-slips.json +57 -0
  426. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woocommerce-product-addon.json +141 -0
  427. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/woocommerce-progressive-discounts.json +54 -0
  428. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/wordpress-seo.json +158 -0
  429. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/wpc-composite-products.json +97 -0
  430. package/skills/wix-replatform/resources/rp-source-wordpress/plugins/wpforms-lite.json +86 -0
  431. package/skills/wix-replatform/resources/rp-source-wordpress/scripts/capture-store-settings.js +90 -0
  432. package/skills/wix-replatform/resources/rp-source-wordpress/scripts/plugin-knowledge-validate.js +51 -0
  433. package/skills/wix-replatform/resources/rp-source-wordpress/scripts/plugin-knowledge.js +103 -0
  434. package/skills/wix-replatform/resources/rp-source-wordpress/scripts/wp-discovery.js +1668 -33
  435. package/skills/wix-replatform/resources/rp-source-wordpress/scripts/wp-plugin-inventory.js +273 -0
  436. package/skills/wix-replatform/resources/rp-source-wordpress/secret-value-patterns.v1.json +11 -0
  437. package/skills/wix-replatform/resources/rp-source-wordpress/sub-parts.json +13 -0
  438. package/skills/wix-replatform/resources/rp-target-wix/SKILL.md +446 -32
  439. package/skills/wix-replatform/resources/rp-target-wix/app-page-routing-capabilities.json +36 -0
  440. package/skills/wix-replatform/resources/rp-target-wix/domains/README.md +38 -2
  441. package/skills/wix-replatform/resources/rp-target-wix/domains/SERVICE-PLUGINS.md +322 -0
  442. package/skills/wix-replatform/resources/rp-target-wix/domains/blog/docs-survey.json +70 -0
  443. package/skills/wix-replatform/resources/rp-target-wix/domains/blog/domain.json +19 -9
  444. package/skills/wix-replatform/resources/rp-target-wix/domains/blog/entities/category.json +42 -8
  445. package/skills/wix-replatform/resources/rp-target-wix/domains/blog/entities/comment.json +54 -8
  446. package/skills/wix-replatform/resources/rp-target-wix/domains/blog/entities/post.json +66 -10
  447. package/skills/wix-replatform/resources/rp-target-wix/domains/blog/entities/tag.json +38 -7
  448. package/skills/wix-replatform/resources/rp-target-wix/domains/bookings/docs-survey.json +332 -0
  449. package/skills/wix-replatform/resources/rp-target-wix/domains/bookings/domain.json +75 -0
  450. package/skills/wix-replatform/resources/rp-target-wix/domains/bookings/entities/booking.json +181 -0
  451. package/skills/wix-replatform/resources/rp-target-wix/domains/bookings/entities/service-add-on.json +130 -0
  452. package/skills/wix-replatform/resources/rp-target-wix/domains/bookings/entities/service.json +180 -0
  453. package/skills/wix-replatform/resources/rp-target-wix/domains/cms/docs-survey.json +161 -0
  454. package/skills/wix-replatform/resources/rp-target-wix/domains/cms/domain.json +15 -4
  455. package/skills/wix-replatform/resources/rp-target-wix/domains/cms/entities/collection.json +39 -7
  456. package/skills/wix-replatform/resources/rp-target-wix/domains/cms/entities/data-item.json +47 -8
  457. package/skills/wix-replatform/resources/rp-target-wix/domains/cms/entities/reference.json +7 -1
  458. package/skills/wix-replatform/resources/rp-target-wix/domains/crm/docs-survey.json +204 -0
  459. package/skills/wix-replatform/resources/rp-target-wix/domains/crm/domain.json +17 -4
  460. package/skills/wix-replatform/resources/rp-target-wix/domains/crm/entities/contact.json +159 -15
  461. package/skills/wix-replatform/resources/rp-target-wix/domains/crm/entities/email-subscription.json +80 -12
  462. package/skills/wix-replatform/resources/rp-target-wix/domains/crm/entities/label.json +48 -8
  463. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/docs-survey.json +306 -0
  464. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/domain.json +30 -7
  465. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/delivery-profile.json +171 -0
  466. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/discount-rule.json +182 -0
  467. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order-applied-discount.json +129 -0
  468. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order-invoice-document.json +192 -0
  469. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order-line-item-options.json +123 -0
  470. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order-line-item.json +60 -12
  471. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order-merchant-note.json +112 -0
  472. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order-payment.json +191 -0
  473. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order-refund.json +140 -13
  474. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/order.json +383 -18
  475. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/pickup-location.json +122 -0
  476. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/shipping-option.json +98 -0
  477. package/skills/wix-replatform/resources/rp-target-wix/domains/ecom/entities/wishlist-item.json +86 -0
  478. package/skills/wix-replatform/resources/rp-target-wix/domains/events/docs-survey.json +128 -0
  479. package/skills/wix-replatform/resources/rp-target-wix/domains/events/domain.json +38 -0
  480. package/skills/wix-replatform/resources/rp-target-wix/domains/events/entities/category.json +73 -0
  481. package/skills/wix-replatform/resources/rp-target-wix/domains/events/entities/event.json +107 -0
  482. package/skills/wix-replatform/resources/rp-target-wix/domains/events/entities/registration-form.json +89 -0
  483. package/skills/wix-replatform/resources/rp-target-wix/domains/events/entities/rsvp.json +118 -0
  484. package/skills/wix-replatform/resources/rp-target-wix/domains/events/entities/ticket-definition.json +93 -0
  485. package/skills/wix-replatform/resources/rp-target-wix/domains/forms/docs-survey.json +86 -0
  486. package/skills/wix-replatform/resources/rp-target-wix/domains/forms/domain.json +56 -0
  487. package/skills/wix-replatform/resources/rp-target-wix/domains/forms/entities/form-submission.json +121 -0
  488. package/skills/wix-replatform/resources/rp-target-wix/domains/forms/entities/form.json +134 -0
  489. package/skills/wix-replatform/resources/rp-target-wix/domains/gift-cards/docs-survey.json +41 -0
  490. package/skills/wix-replatform/resources/rp-target-wix/domains/gift-cards/domain.json +50 -0
  491. package/skills/wix-replatform/resources/rp-target-wix/domains/gift-cards/entities/gift-card-product.json +87 -0
  492. package/skills/wix-replatform/resources/rp-target-wix/domains/gift-cards/entities/gift-card.json +130 -0
  493. package/skills/wix-replatform/resources/rp-target-wix/domains/index.json +914 -24
  494. package/skills/wix-replatform/resources/rp-target-wix/domains/media/docs-survey.json +41 -0
  495. package/skills/wix-replatform/resources/rp-target-wix/domains/media/domain.json +14 -4
  496. package/skills/wix-replatform/resources/rp-target-wix/domains/media/entities/media-file.json +45 -8
  497. package/skills/wix-replatform/resources/rp-target-wix/domains/media/entities/media-folder.json +41 -7
  498. package/skills/wix-replatform/resources/rp-target-wix/domains/members/docs-survey.json +119 -0
  499. package/skills/wix-replatform/resources/rp-target-wix/domains/members/domain.json +13 -3
  500. package/skills/wix-replatform/resources/rp-target-wix/domains/members/entities/badge.json +41 -7
  501. package/skills/wix-replatform/resources/rp-target-wix/domains/members/entities/custom-field.json +82 -0
  502. package/skills/wix-replatform/resources/rp-target-wix/domains/members/entities/member-about.json +77 -0
  503. package/skills/wix-replatform/resources/rp-target-wix/domains/members/entities/member.json +165 -13
  504. package/skills/wix-replatform/resources/rp-target-wix/domains/pricing-plans/docs-survey.json +41 -0
  505. package/skills/wix-replatform/resources/rp-target-wix/domains/pricing-plans/domain.json +46 -0
  506. package/skills/wix-replatform/resources/rp-target-wix/domains/pricing-plans/entities/plan-order.json +137 -0
  507. package/skills/wix-replatform/resources/rp-target-wix/domains/pricing-plans/entities/plan.json +133 -0
  508. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/docs-survey.json +7 -0
  509. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/domain.json +36 -0
  510. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/entities/amazon-shop-connect.json +71 -0
  511. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/entities/ebay-shop-connect.json +67 -0
  512. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/entities/google-youtube-connect.json +72 -0
  513. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/entities/meta-catalog-connect.json +74 -0
  514. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/entities/pinterest-catalog-connect.json +69 -0
  515. package/skills/wix-replatform/resources/rp-target-wix/domains/sales-channels/entities/tiktok-catalog-connect.json +61 -0
  516. package/skills/wix-replatform/resources/rp-target-wix/domains/schema.json +28 -1
  517. package/skills/wix-replatform/resources/rp-target-wix/domains/seo/docs-survey.json +109 -0
  518. package/skills/wix-replatform/resources/rp-target-wix/domains/seo/domain.json +73 -0
  519. package/skills/wix-replatform/resources/rp-target-wix/domains/seo/entities/item-seo-tags.json +148 -0
  520. package/skills/wix-replatform/resources/rp-target-wix/domains/seo/entities/seo-pattern.json +91 -0
  521. package/skills/wix-replatform/resources/rp-target-wix/domains/seo/entities/site-seo-tags.json +79 -0
  522. package/skills/wix-replatform/resources/rp-target-wix/domains/site/docs-survey.json +32 -0
  523. package/skills/wix-replatform/resources/rp-target-wix/domains/site/domain.json +49 -0
  524. package/skills/wix-replatform/resources/rp-target-wix/domains/site/entities/business-contact.json +103 -0
  525. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/docs-survey.json +203 -0
  526. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/domain.json +27 -10
  527. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/back-in-stock-request.json +119 -0
  528. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/brand.json +111 -0
  529. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/category.json +52 -8
  530. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/coupon.json +214 -10
  531. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/inventory-item.json +93 -13
  532. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/product-customization.json +111 -0
  533. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/product-tag.json +52 -10
  534. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/product.json +145 -14
  535. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/promotion.json +84 -0
  536. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/review.json +178 -0
  537. package/skills/wix-replatform/resources/rp-target-wix/domains/stores/entities/subscription-product.json +87 -0
  538. package/skills/wix-replatform/resources/rp-target-wix/domains/tax/docs-survey.json +106 -0
  539. package/skills/wix-replatform/resources/rp-target-wix/domains/tax/domain.json +64 -0
  540. package/skills/wix-replatform/resources/rp-target-wix/domains/tax/entities/manual-tax-mapping.json +119 -0
  541. package/skills/wix-replatform/resources/rp-target-wix/domains/tax/entities/tax-group.json +94 -0
  542. package/skills/wix-replatform/resources/rp-target-wix/domains/tax/entities/tax-region.json +113 -0
  543. package/skills/wix-replatform/resources/rp-target-wix/domains/tax/entities/tax-settings.json +65 -0
  544. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-author-attribution.js +165 -0
  545. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-post-build-client.js +60 -0
  546. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-post-build-duplicates.js +201 -0
  547. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-post-build-ledger.js +306 -0
  548. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-post-build-report.js +229 -0
  549. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-post-build-stage.js +55 -0
  550. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-post-build.js +715 -0
  551. package/skills/wix-replatform/resources/rp-target-wix/lib/blog-post-media.js +567 -0
  552. package/skills/wix-replatform/resources/rp-target-wix/lib/bulk-results.js +73 -0
  553. package/skills/wix-replatform/resources/rp-target-wix/lib/contact-extended-fields.js +194 -0
  554. package/skills/wix-replatform/resources/rp-target-wix/lib/contact-import.js +133 -0
  555. package/skills/wix-replatform/resources/rp-target-wix/lib/contract-ledger.js +13 -4
  556. package/skills/wix-replatform/resources/rp-target-wix/lib/coupon-redemption-drift.js +491 -0
  557. package/skills/wix-replatform/resources/rp-target-wix/lib/customer-member.js +104 -0
  558. package/skills/wix-replatform/resources/rp-target-wix/lib/data-extension-schema.js +673 -0
  559. package/skills/wix-replatform/resources/rp-target-wix/lib/domain-knowledge.js +453 -2
  560. package/skills/wix-replatform/resources/rp-target-wix/lib/gift-card-balance-reconciliation.js +119 -0
  561. package/skills/wix-replatform/resources/rp-target-wix/lib/gift-card-build.js +566 -0
  562. package/skills/wix-replatform/resources/rp-target-wix/lib/gift-card-redemption-build.js +249 -0
  563. package/skills/wix-replatform/resources/rp-target-wix/lib/order-applied-discount-build.js +63 -0
  564. package/skills/wix-replatform/resources/rp-target-wix/lib/order-buyer.js +187 -0
  565. package/skills/wix-replatform/resources/rp-target-wix/lib/order-channel-build.js +64 -0
  566. package/skills/wix-replatform/resources/rp-target-wix/lib/order-history.js +1027 -0
  567. package/skills/wix-replatform/resources/rp-target-wix/lib/order-invoice-contract.js +90 -0
  568. package/skills/wix-replatform/resources/rp-target-wix/lib/order-payment-mapping.js +420 -0
  569. package/skills/wix-replatform/resources/rp-target-wix/lib/pricing-plan-definition.js +177 -0
  570. package/skills/wix-replatform/resources/rp-target-wix/lib/product-import.js +151 -0
  571. package/skills/wix-replatform/resources/rp-target-wix/lib/product-seo.js +723 -0
  572. package/skills/wix-replatform/resources/rp-target-wix/lib/seo-redirects.js +353 -0
  573. package/skills/wix-replatform/resources/rp-target-wix/lib/shipping-build.js +1437 -0
  574. package/skills/wix-replatform/resources/rp-target-wix/lib/shipping-option-stage.js +354 -0
  575. package/skills/wix-replatform/resources/rp-target-wix/lib/store-config-build.js +134 -0
  576. package/skills/wix-replatform/resources/rp-target-wix/lib/stores-category-attach.js +221 -0
  577. package/skills/wix-replatform/resources/rp-target-wix/lib/stores-inventory.js +248 -0
  578. package/skills/wix-replatform/resources/rp-target-wix/lib/stores-verification.js +86 -3
  579. package/skills/wix-replatform/resources/rp-target-wix/lib/tax-build.js +231 -0
  580. package/skills/wix-replatform/resources/rp-target-wix/lib/url-mapper-transport.js +28 -0
  581. package/skills/wix-replatform/resources/rp-target-wix/lib/value-utils.js +14 -0
  582. package/skills/wix-replatform/resources/rp-target-wix/lib/variant-correlation.js +34 -0
  583. package/skills/wix-replatform/resources/rp-target-wix/lib/wix-build.js +166 -15
  584. package/skills/wix-replatform/resources/rp-target-wix/lib/wix-target-spec.js +19 -2
  585. package/skills/wix-replatform/resources/rp-target-wix/lib/wix-writers.js +4079 -257
  586. package/skills/wix-replatform/resources/rp-target-wix/lib/write-verification.js +3 -0
  587. package/skills/wix-replatform/resources/rp-target-wix/scripts/docs-survey-sync.js +150 -0
  588. package/skills/wix-replatform/resources/rp-target-wix/scripts/domain-knowledge-validate.js +40 -2
  589. package/skills/wix-replatform/resources/rp-target-wix/scripts/verify-stores.js +6 -1
  590. package/skills/wix-replatform/resources/rp-telemetry/SKILL.md +148 -8
  591. package/skills/wix-replatform/resources/rp-telemetry/lib/bi-sink.js +83 -15
  592. package/skills/wix-replatform/resources/rp-telemetry/lib/telemetry-recorder.js +1119 -215
  593. package/skills/wix-replatform/resources/rp-telemetry/lib/transcript-digest.js +318 -0
  594. package/skills/wix-replatform/resources/rp-telemetry/scripts/meter-from-audit.js +2 -2
  595. package/skills/wix-replatform/resources/rp-telemetry/scripts/rp-telemetry.js +106 -4
  596. package/skills/wix-replatform/resources/rp-website-continuation/SKILL.md +94 -0
  597. package/skills/wix-replatform/scripts/census-reconciliation.js +25 -0
  598. package/skills/wix-replatform/scripts/cms-fallback.js +89 -0
  599. package/skills/wix-replatform/scripts/discovered-census.js +26 -0
  600. package/skills/wix-replatform/scripts/discovered-set-status.js +33 -0
  601. package/skills/wix-replatform/scripts/entity-qa-attestation.js +130 -0
  602. package/skills/wix-replatform/scripts/execution-health-check.js +415 -0
  603. package/skills/wix-replatform/scripts/execution-manifest-validate.js +1 -1
  604. package/skills/wix-replatform/scripts/execution-state-prepare.js +1 -1
  605. package/skills/wix-replatform/scripts/expectations-ledger.js +44 -0
  606. package/skills/wix-replatform/scripts/import-contract-verify.js +183 -0
  607. package/skills/wix-replatform/scripts/internal-link-audit.js +90 -0
  608. package/skills/wix-replatform/scripts/item-seo-tags-verify.js +205 -0
  609. package/skills/wix-replatform/scripts/migration-completion.js +76 -0
  610. package/skills/wix-replatform/scripts/orchestration-preflight.js +21 -2
  611. package/skills/wix-replatform/scripts/orchestration-route.js +32 -1
  612. package/skills/wix-replatform/scripts/orchestration-state.js +146 -10
  613. package/skills/wix-replatform/scripts/read-back-gate.js +175 -0
  614. package/skills/wix-replatform/scripts/replatform-console.js +146 -0
  615. package/skills/wix-replatform/scripts/replatform.js +436 -0
  616. package/skills/wix-replatform/scripts/source-secrets.js +77 -0
  617. package/skills/wix-replatform/scripts/url-redirects.js +286 -0
  618. package/skills/wix-replatform/scripts/user-action.js +58 -0
  619. package/skills/wix-replatform/scripts/website-handoff-generate.js +64 -0
  620. package/skills/wix-replatform/scripts/wix-dashboard-url.js +54 -0
  621. package/skills/wix-replatform/scripts/wix-destination.js +143 -0
  622. package/skills/wix-replatform/scripts/wix-headless-scaffold.js +762 -0
  623. package/skills/wix-vibe-headless/SKILL.md +7 -3
  624. package/skills/wix-vibe-headless/install/deploy.cjs +61 -34
  625. package/skills/wix-vibe-headless/platforms/base44.md +1 -0
  626. package/skills/wix-vibe-headless/references/donations/INSTRUCTIONS.md +88 -0
  627. package/skills/wix-vibe-headless/references/donations/app/rest/wix-donations.js +112 -0
  628. package/skills/wix-vibe-headless/references/donations/seed/SEED.md +11 -0
  629. package/skills/wix-vibe-headless/references/donations/tests/donations.test.mjs +258 -0
  630. package/skills/wix-vibe-headless/references/restaurants/INSTRUCTIONS.md +5 -2
  631. package/skills/wix-vibe-headless/references/restaurants/app/context/OrderCartContext.jsx +4 -1
  632. package/skills/wix-vibe-headless/references/restaurants/app/rest/wix-restaurants-ordering.js +67 -3
  633. package/skills/wix-vibe-headless/references/shared/app/rest/wix-client.js +4 -3
  634. package/skills/wix-manage/references/custom-apps/use-app-skills-and-app-tools.md +0 -208
  635. package/skills/wix-replatform/resources/rp-target-wix/SPEC-product-reviews-and-blog-authorship.md +0 -330
@@ -0,0 +1,1470 @@
1
+ 'use strict';
2
+
3
+ // The sequential Shopify bulk runner. One bulk operation runs at a time, for both
4
+ // callers: the discovery census and the extract. A caller supplies its own
5
+ // manifest, staging directory, ordered query list and handlers; this module owns every state, stop
6
+ // and recovery rule, so a caller adds no runner and no recovery path of its own.
7
+ //
8
+ // Query states, one atomic manifest write per change:
9
+ // pending -> starting -> running -> downloaded -> done
10
+ // \-> pending (one re-run, or an expired link)
11
+ // running | downloaded -> settling -> failed | denied (terminal; the handler runs in between)
12
+ // `settling` makes every terminal side effect recoverable: a query never becomes `failed` or
13
+ // `denied` directly. The runner writes `settling` with the outcome and the verbatim error, runs the
14
+ // outcome's handler, then writes the terminal state with the handler's result. On every start each
15
+ // `settling` entry's handler runs again before anything else, so every handler must be idempotent.
16
+ //
17
+ // run() resolves with { status: 'complete' | 'stopped' | 'awaiting_user_action', code?, message?,
18
+ // details?, manifest }. Anything else it throws is a crash: the manifest on disk is the recovery
19
+ // point, and a fresh runner over the same files resumes it.
20
+
21
+ const fs = require('node:fs');
22
+ const fsp = require('node:fs/promises');
23
+ const http = require('node:http');
24
+ const https = require('node:https');
25
+ const path = require('node:path');
26
+ const readline = require('node:readline');
27
+ const { fork } = require('node:child_process');
28
+ const { finished } = require('node:stream/promises');
29
+ const { buildShopifyCoverageRows, upsertAdapterCoverageRows, writeJsonAtomic } = require('../../../lib/source-coverage.js');
30
+ const { createUserAction, readUserAction } = require('../../../lib/user-actions.js');
31
+ const { ShopifyCliError } = require('./shopify-cli.js');
32
+ const { ShopifyExtractStop } = require('./import-findings.js');
33
+ const session = require('./shopify-session.js');
34
+
35
+ const QUERIES_DIR = path.join(__dirname, '..', 'queries');
36
+ const MANIFEST_SCHEMA_VERSION = 1;
37
+ const POLL_START_MS = 2000;
38
+ const POLL_CAP_MS = 30000;
39
+ const OVERDUE_MS = 4 * 60 * 60 * 1000;
40
+ const MAX_ATTEMPTS = 1;
41
+ const MAX_DOWNLOAD_TRIES = 3;
42
+ const MAX_LINK_RERUNS = 2;
43
+ const SNAPSHOT_PLACEHOLDER = '{{SNAPSHOT_TIME}}';
44
+ const OVERDUE_NAMESPACE = 'shopify-bulk-overdue';
45
+ const RAW_EXTRACT_DIR = 'data/source-extract';
46
+ const EXTRACT_MANIFEST_FILE = 'extract-manifest.json';
47
+ const SQLITE_WORKER = path.join(__dirname, 'shopify-bulk-sqlite-worker.js');
48
+
49
+ const STATUS_QUERY = 'query RpBulkStatus($id: ID!) { node(id: $id) { ... on BulkOperation { id status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl } } }';
50
+
51
+ // ---------------------------------------------------------------------------------------------
52
+ // The query catalog: eighteen queries, in this order, and how each one's child rows fold
53
+ // ---------------------------------------------------------------------------------------------
54
+
55
+ const MEDIA_TYPES = ['MediaImage', 'Video', 'ExternalVideo', 'Model3d', 'GenericFile'];
56
+ const DISCOUNT_APPLICATION_TYPES = ['DiscountCodeApplication', 'AutomaticDiscountApplication', 'ManualDiscountApplication', 'ScriptDiscountApplication'];
57
+
58
+ function typesTo(types, field, extra = {}) {
59
+ return Object.fromEntries(types.map((type) => [type, { field, ...extra }]));
60
+ }
61
+
62
+ // `children` maps a child row's `__typename` to the field it folds into on its parent (`into` names
63
+ // an inline object of the parent that holds the field). `rootFields` and `childFields` are the
64
+ // fields initialised to [] so an empty connection reads as empty, not absent. `inline` lists
65
+ // non-connection list fields on a root row whose elements carry nested connections: such a
66
+ // child's `__parentId` may name the inline element, so its objects are indexed by `id`.
67
+ const QUERY_CATALOG = Object.freeze([
68
+ { name: 'products', entity: 'products', rootFields: ['variants', 'media', 'metafields'], children: { ProductVariant: { field: 'variants' }, ...typesTo(MEDIA_TYPES, 'media'), Metafield: { field: 'metafields' } } },
69
+ { name: 'collections', entity: 'collections', rootFields: ['products', 'metafields'], children: { Product: { field: 'products' }, Metafield: { field: 'metafields' } } },
70
+ { name: 'customers', entity: 'customers', rootFields: ['metafields'], children: { Metafield: { field: 'metafields' } } },
71
+ { name: 'orders-core', entity: 'orders', rootFields: ['lineItems', 'shippingLines', 'discountApplications', 'metafields'], children: { LineItem: { field: 'lineItems' }, ShippingLine: { field: 'shippingLines' }, ...typesTo(DISCOUNT_APPLICATION_TYPES, 'discountApplications'), Metafield: { field: 'metafields' } } },
72
+ { name: 'orders-refunds', entity: 'orders', inline: { refunds: ['refundLineItems', 'transactions'] }, children: { RefundLineItem: { field: 'refundLineItems' }, OrderTransaction: { field: 'transactions' } } },
73
+ { name: 'orders-fulfillments', entity: 'orders', inline: { fulfillments: ['fulfillmentLineItems'] }, children: { FulfillmentLineItem: { field: 'fulfillmentLineItems' } } },
74
+ { name: 'gift-cards', entity: 'gift-cards', children: {} },
75
+ { name: 'discounts', entity: 'discounts', children: { DiscountRedeemCode: { field: 'codes', into: 'discount' } } },
76
+ { name: 'delivery-profiles', entity: 'delivery-profiles', rootFields: ['locationGroupZones'], childFields: { DeliveryLocationGroupZone: ['methodDefinitions'] }, children: { DeliveryLocationGroupZone: { field: 'locationGroupZones' }, DeliveryMethodDefinition: { field: 'methodDefinitions' } } },
77
+ { name: 'inventory', entity: 'inventory-items', rootFields: ['inventoryLevels'], children: { InventoryLevel: { field: 'inventoryLevels' } } },
78
+ { name: 'pages', entity: 'pages', children: {} },
79
+ { name: 'blogs', entity: 'blogs', children: {} },
80
+ { name: 'articles', entity: 'articles', children: {} },
81
+ { name: 'menus', entity: 'menus', children: {} },
82
+ { name: 'url-redirects', entity: 'url-redirects', children: {} },
83
+ { name: 'locations', entity: 'locations', children: {} },
84
+ { name: 'metaobjects', entity: 'metaobjects', rootFields: ['metaobjects'], children: { Metaobject: { field: 'metaobjects' } } },
85
+ { name: 'files', entity: 'files', children: {} },
86
+ ]);
87
+
88
+ const QUERY_NAMES = Object.freeze(QUERY_CATALOG.map((entry) => entry.name));
89
+ const CUSTOMER_QUERIES = Object.freeze(['customers']);
90
+ const ORDER_QUERIES = Object.freeze(['orders-core', 'orders-refunds', 'orders-fulfillments']);
91
+ const DENIAL_ATTRIBUTED_QUERIES = Object.freeze([...CUSTOMER_QUERIES, ...ORDER_QUERIES]);
92
+
93
+ function catalogEntry(name) {
94
+ const entry = QUERY_CATALOG.find((candidate) => candidate.name === name);
95
+ if (!entry) throw new Error(`unknown Shopify bulk query ${name}`);
96
+ return entry;
97
+ }
98
+
99
+ function queryFilePath(name, dir = QUERIES_DIR) {
100
+ return path.join(dir, `${name}.graphql`);
101
+ }
102
+
103
+ function readQueryFile(name, dir = QUERIES_DIR) {
104
+ return fs.readFileSync(queryFilePath(name, dir), 'utf8');
105
+ }
106
+
107
+ // The text sent for one query: the file with the snapshot time filled in, then the caller's
108
+ // projection (`projectQuery`), if it passes one, for the customer and order queries.
109
+ function generateQueryText(name, { snapshotTime, project = null, dir = QUERIES_DIR } = {}) {
110
+ let text = readQueryFile(name, dir);
111
+ if (text.includes(SNAPSHOT_PLACEHOLDER)) {
112
+ if (!snapshotTime) throw new Error(`query ${name} needs the snapshot time`);
113
+ text = text.split(SNAPSHOT_PLACEHOLDER).join(snapshotTime);
114
+ }
115
+ if (typeof project === 'function' && DENIAL_ATTRIBUTED_QUERIES.includes(name)) text = project(name, text);
116
+ return text;
117
+ }
118
+
119
+ // Static shape checks for the contract test: connections are the `edges { node }` blocks.
120
+ function stripForShape(text) {
121
+ const noComments = String(text).replace(/#[^\n]*/g, ' ');
122
+ let out = '';
123
+ let depth = 0;
124
+ let inString = false;
125
+ for (let i = 0; i < noComments.length; i += 1) {
126
+ const ch = noComments[i];
127
+ if (inString) {
128
+ if (ch === '\\') i += 1;
129
+ else if (ch === '"') inString = false;
130
+ continue;
131
+ }
132
+ if (ch === '"') { inString = true; continue; }
133
+ if (ch === '(') { depth += 1; continue; }
134
+ if (ch === ')') { depth = Math.max(0, depth - 1); continue; }
135
+ if (depth === 0) out += ch;
136
+ }
137
+ return out;
138
+ }
139
+
140
+ function connectionShape(text) {
141
+ const tokens = stripForShape(text).match(/[{}]|[A-Za-z_][A-Za-z0-9_]*/g) || [];
142
+ const stack = [];
143
+ let connections = 0;
144
+ let maxDepth = 0;
145
+ let open = 0;
146
+ for (let i = 0; i < tokens.length; i += 1) {
147
+ const token = tokens[i];
148
+ if (token === '{') {
149
+ const isEdges = tokens[i - 1] === 'edges';
150
+ stack.push(isEdges);
151
+ if (isEdges) { open += 1; connections += 1; maxDepth = Math.max(maxDepth, open); }
152
+ } else if (token === '}') {
153
+ if (stack.pop()) open -= 1;
154
+ }
155
+ }
156
+ return { connections, nestedLevels: Math.max(0, maxDepth - 1) };
157
+ }
158
+
159
+ // ---------------------------------------------------------------------------------------------
160
+ // Stops
161
+ // ---------------------------------------------------------------------------------------------
162
+
163
+ class BulkStop extends Error {
164
+ constructor(code, message, { status = 'stopped', details = {} } = {}) {
165
+ super(message);
166
+ this.name = 'BulkStop';
167
+ this.code = code;
168
+ this.status = status;
169
+ this.details = details;
170
+ }
171
+ }
172
+
173
+ const STOPPING_FAILED_CODE = 'shopify_bulk_failed';
174
+
175
+ function iso(ms) {
176
+ return new Date(ms).toISOString();
177
+ }
178
+
179
+ function entityOf(name) {
180
+ return catalogEntry(name).entity;
181
+ }
182
+
183
+ function isStopping(entry, caller) {
184
+ if (caller !== 'extract') return false;
185
+ if (entry.state === 'failed') return true;
186
+ return entry.state === 'denied' && entry.handlerOutcome && entry.handlerOutcome.attribution === 'unattributed';
187
+ }
188
+
189
+ // ---------------------------------------------------------------------------------------------
190
+ // Files: JSONL validation, folding, ndjson writing, the default file host download
191
+ // ---------------------------------------------------------------------------------------------
192
+
193
+ async function removeFile(file) {
194
+ await fsp.rm(file, { force: true });
195
+ }
196
+
197
+ async function writeTextAtomic(file, text) {
198
+ await fsp.mkdir(path.dirname(file), { recursive: true });
199
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
200
+ await fsp.writeFile(temp, text, 'utf8');
201
+ await fsp.rename(temp, file);
202
+ }
203
+
204
+ async function writeNdjsonAtomic(file, records) {
205
+ await fsp.mkdir(path.dirname(file), { recursive: true });
206
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
207
+ const out = fs.createWriteStream(temp, { encoding: 'utf8' });
208
+ let count = 0;
209
+ try {
210
+ for await (const record of records) {
211
+ if (!out.write(`${JSON.stringify(record)}\n`)) await new Promise((resolve) => out.once('drain', resolve));
212
+ count += 1;
213
+ }
214
+ out.end();
215
+ await finished(out);
216
+ await fsp.rename(temp, file);
217
+ return count;
218
+ } catch (error) {
219
+ out.destroy();
220
+ await removeFile(temp);
221
+ throw error;
222
+ }
223
+ }
224
+
225
+ async function* iterateNdjson(file) {
226
+ const input = fs.createReadStream(file, { encoding: 'utf8' });
227
+ const lines = readline.createInterface({ input, crlfDelay: Infinity });
228
+ for await (const line of lines) if (line.length) yield JSON.parse(line);
229
+ }
230
+
231
+ async function countLines(file) {
232
+ try {
233
+ await fsp.access(file);
234
+ } catch (error) {
235
+ if (error.code === 'ENOENT') return null;
236
+ throw error;
237
+ }
238
+ let count = 0;
239
+ for await (const _record of iterateNdjson(file)) count += 1;
240
+ return count;
241
+ }
242
+
243
+ async function copyFileAtomic(source, destination) {
244
+ await fsp.mkdir(path.dirname(destination), { recursive: true });
245
+ const temp = `${destination}.${process.pid}.${Date.now()}.tmp`;
246
+ try {
247
+ await fsp.copyFile(source, temp);
248
+ await fsp.rename(temp, destination);
249
+ } catch (error) {
250
+ await removeFile(temp);
251
+ throw error;
252
+ }
253
+ }
254
+
255
+ // The download gate's file checks: empty or newline-terminated, and every line one
256
+ // JSON object. Streams the file; keeps no record in memory.
257
+ function validateJsonlFile(file) {
258
+ return new Promise((resolve) => {
259
+ const stream = fs.createReadStream(file, { encoding: 'utf8' });
260
+ let rest = '';
261
+ let lines = 0;
262
+ let last = '';
263
+ let failure = null;
264
+ const checkLine = (line) => {
265
+ if (failure) return;
266
+ let value;
267
+ try {
268
+ value = JSON.parse(line);
269
+ } catch {
270
+ failure = 'a line does not parse as JSON';
271
+ return;
272
+ }
273
+ if (!value || typeof value !== 'object' || Array.isArray(value)) failure = 'a line is not a JSON object';
274
+ else lines += 1;
275
+ };
276
+ stream.on('data', (chunk) => {
277
+ if (failure) return;
278
+ last = chunk[chunk.length - 1];
279
+ rest += chunk;
280
+ let at = rest.indexOf('\n');
281
+ while (at !== -1 && !failure) {
282
+ checkLine(rest.slice(0, at));
283
+ rest = rest.slice(at + 1);
284
+ at = rest.indexOf('\n');
285
+ }
286
+ });
287
+ stream.on('error', (error) => resolve({ ok: false, reason: `the file could not be read: ${error.message}` }));
288
+ stream.on('end', () => {
289
+ if (!failure && rest.length) failure = 'the file does not end with a newline';
290
+ if (failure) resolve({ ok: false, reason: failure });
291
+ else resolve({ ok: true, lines, endsWithNewline: last === '\n' || last === '' });
292
+ });
293
+ });
294
+ }
295
+
296
+ // Node 22.12 ships node:sqlite behind --experimental-sqlite. Keep the documented adapter
297
+ // invocation flag-free: on that one supported boundary runtime, only the disk-backed transform
298
+ // runs in a child with the built-in module enabled. Node 22.13+ stays in-process. The worker gets
299
+ // only paths and the public query shape, never credentials or record values over the command line.
300
+ function loadDatabaseSync() {
301
+ try {
302
+ return require('node:sqlite').DatabaseSync;
303
+ } catch (error) {
304
+ if (error && error.code === 'ERR_UNKNOWN_BUILTIN_MODULE') return null;
305
+ throw error;
306
+ }
307
+ }
308
+
309
+ function sqliteWorkerError(payload) {
310
+ const error = new Error(payload && payload.message ? payload.message : 'the SQLite worker failed');
311
+ if (payload && payload.name) error.name = payload.name;
312
+ for (const field of ['code', 'errno', 'syscall', 'path']) {
313
+ if (payload && payload[field] !== undefined) error[field] = payload[field];
314
+ }
315
+ if (payload && payload.stack) error.stack = payload.stack;
316
+ return error;
317
+ }
318
+
319
+ function runSqliteWorker(operation, payload) {
320
+ return new Promise((resolve, reject) => {
321
+ // Preserve explicit memory ceilings used to prove the bounded-memory contract. Other Node
322
+ // entry-point/debug flags belong to the parent, not to this internal helper.
323
+ const memoryArgs = process.execArgv.filter((arg) => /^--(?:max-old-space-size|max-semi-space-size|stack-size)=/.test(arg));
324
+ const child = fork(SQLITE_WORKER, [], {
325
+ execArgv: [...memoryArgs, '--no-warnings', '--experimental-sqlite'],
326
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
327
+ });
328
+ let settled = false;
329
+ const fail = (error) => {
330
+ if (settled) return;
331
+ settled = true;
332
+ reject(error);
333
+ };
334
+ child.once('error', fail);
335
+ child.once('exit', (code, signal) => {
336
+ if (!settled) fail(new Error(`the SQLite worker exited before replying (${signal || `code ${code}`})`));
337
+ });
338
+ child.once('message', (message) => {
339
+ if (settled) return;
340
+ settled = true;
341
+ if (child.connected) child.disconnect();
342
+ if (message && message.ok) resolve(message.result);
343
+ else reject(sqliteWorkerError(message && message.error));
344
+ });
345
+ child.send({ operation, payload }, (error) => {
346
+ if (error) fail(error);
347
+ });
348
+ });
349
+ }
350
+
351
+ // Shopify leaves `groupObjects` false, so children may precede their parents. Index child rows in
352
+ // a temporary SQLite database, then stream roots in source order and attach only that root's tree.
353
+ // Memory is therefore bounded by the largest assembled root, not by the full store export.
354
+ async function foldBulkJsonl(file, shape, { outputFile } = {}) {
355
+ if (!outputFile) throw new Error('foldBulkJsonl requires outputFile');
356
+ const DatabaseSync = loadDatabaseSync();
357
+ if (!DatabaseSync) return runSqliteWorker('foldBulkJsonl', { file, shape, outputFile });
358
+ await fsp.mkdir(path.dirname(outputFile), { recursive: true });
359
+ const work = `${outputFile}.${process.pid}.${Date.now()}.fold.tmp`;
360
+ const outputTemp = `${outputFile}.${process.pid}.${Date.now()}.tmp`;
361
+ const db = new DatabaseSync(work);
362
+ let output = null;
363
+ let lines = 0;
364
+ try {
365
+ db.exec(`
366
+ PRAGMA journal_mode = OFF;
367
+ PRAGMA synchronous = OFF;
368
+ PRAGMA temp_store = FILE;
369
+ CREATE TABLE roots (seq INTEGER PRIMARY KEY, json TEXT NOT NULL);
370
+ CREATE TABLE children (
371
+ seq INTEGER PRIMARY KEY,
372
+ parent_id TEXT NOT NULL,
373
+ child_id TEXT,
374
+ child_type TEXT,
375
+ json TEXT NOT NULL,
376
+ attached INTEGER NOT NULL DEFAULT 0,
377
+ orphan_reason TEXT
378
+ );
379
+ `);
380
+ const addRoot = db.prepare('INSERT INTO roots(seq, json) VALUES (?, ?)');
381
+ const addChild = db.prepare('INSERT INTO children(seq, parent_id, child_id, child_type, json) VALUES (?, ?, ?, ?, ?)');
382
+ db.exec('BEGIN');
383
+ let inTransaction = true;
384
+ try {
385
+ for await (const line of readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity })) {
386
+ if (!line.length) continue;
387
+ const row = JSON.parse(line);
388
+ lines += 1;
389
+ if (row.__parentId === undefined) addRoot.run(lines, line);
390
+ else addChild.run(lines, String(row.__parentId), typeof row.id === 'string' ? row.id : null, typeof row.__typename === 'string' ? row.__typename : null, line);
391
+ }
392
+ db.exec('COMMIT');
393
+ inTransaction = false;
394
+ db.exec('CREATE INDEX children_parent ON children(parent_id, seq)');
395
+ } catch (error) {
396
+ if (inTransaction) db.exec('ROLLBACK');
397
+ throw error;
398
+ }
399
+
400
+ const childrenFor = db.prepare('SELECT seq, json, child_type FROM children WHERE parent_id = ? AND attached = 0 ORDER BY seq');
401
+ const markAttached = db.prepare('UPDATE children SET attached = 1 WHERE seq = ?');
402
+ const markOrphan = db.prepare('UPDATE children SET orphan_reason = ? WHERE seq = ?');
403
+ // Node 22.12's flag-gated StatementSync has no iterate(). Walk the integer primary key with
404
+ // get() instead: one root is resident at a time and later runtimes follow the identical path.
405
+ const nextRoot = db.prepare('SELECT seq, json FROM roots WHERE seq > ? ORDER BY seq LIMIT 1');
406
+ const nestedParentTypes = new Set(Object.keys(shape.childFields || {}));
407
+ output = fs.createWriteStream(outputTemp, { encoding: 'utf8' });
408
+ let recordCount = 0;
409
+ let rootSeq = 0;
410
+
411
+ for (let stored = nextRoot.get(rootSeq); stored; stored = nextRoot.get(rootSeq)) {
412
+ rootSeq = Number(stored.seq);
413
+ const root = JSON.parse(stored.json);
414
+ const seen = new Set();
415
+ for (const field of shape.rootFields || []) if (!Array.isArray(root[field])) root[field] = [];
416
+ for (const [field, nested] of Object.entries(shape.inline || {})) {
417
+ for (const element of Array.isArray(root[field]) ? root[field] : []) {
418
+ if (element && typeof element === 'object') for (const nestedField of nested) if (!Array.isArray(element[nestedField])) element[nestedField] = [];
419
+ }
420
+ }
421
+
422
+ const attachChildren = (value, mayHaveChildren) => {
423
+ if (!value || typeof value !== 'object') return;
424
+ if (mayHaveChildren && typeof value.id === 'string' && !seen.has(value.id)) {
425
+ seen.add(value.id);
426
+ for (const storedChild of childrenFor.all(value.id)) {
427
+ const rule = shape.children[storedChild.child_type];
428
+ if (!rule) { markOrphan.run('unrecognised_child_type', storedChild.seq); continue; }
429
+ const holder = rule.into ? (value[rule.into] && typeof value[rule.into] === 'object' ? value[rule.into] : null) : value;
430
+ if (!holder) { markOrphan.run('parent_not_found', storedChild.seq); continue; }
431
+ const child = JSON.parse(storedChild.json);
432
+ delete child.__parentId;
433
+ if (!Array.isArray(holder[rule.field])) holder[rule.field] = [];
434
+ holder[rule.field].push(child);
435
+ markAttached.run(storedChild.seq);
436
+ attachChildren(child, nestedParentTypes.has(child.__typename));
437
+ }
438
+ }
439
+ };
440
+ attachChildren(root, true);
441
+ for (const field of Object.keys(shape.inline || {})) {
442
+ for (const element of Array.isArray(root[field]) ? root[field] : []) attachChildren(element, true);
443
+ }
444
+
445
+ const initialiseTree = (value) => {
446
+ if (Array.isArray(value)) { for (const item of value) initialiseTree(item); return; }
447
+ if (!value || typeof value !== 'object') return;
448
+ const initialise = shape.childFields && shape.childFields[value.__typename];
449
+ if (initialise) for (const field of initialise) if (!Array.isArray(value[field])) value[field] = [];
450
+ for (const nested of Object.values(value)) initialiseTree(nested);
451
+ };
452
+ initialiseTree(root);
453
+ if (!output.write(`${JSON.stringify(root)}\n`)) await new Promise((resolve) => output.once('drain', resolve));
454
+ recordCount += 1;
455
+ }
456
+ output.end();
457
+ await finished(output);
458
+ output = null;
459
+
460
+ const orphanCount = Number(db.prepare('SELECT COUNT(*) AS count FROM children WHERE attached = 0').get().count);
461
+ if (orphanCount) {
462
+ const orphans = db.prepare('SELECT parent_id, child_id, child_type, orphan_reason FROM children WHERE attached = 0 ORDER BY seq LIMIT 20').all().map((row) => ({
463
+ reason: row.orphan_reason || 'parent_not_found',
464
+ parentId: row.parent_id,
465
+ id: row.child_id || null,
466
+ type: row.child_type || null,
467
+ }));
468
+ await removeFile(outputTemp);
469
+ return { orphans, orphanCount, lines };
470
+ }
471
+ await fsp.rename(outputTemp, outputFile);
472
+ return { outputFile, recordCount, lines };
473
+ } finally {
474
+ if (output) output.destroy();
475
+ db.close();
476
+ await removeFile(outputTemp);
477
+ await removeFile(work);
478
+ }
479
+ }
480
+
481
+ // Join the three order datasets without loading any of them as a whole. Supplemental rows live
482
+ // in a temporary SQLite table; core orders stream through one at a time in their original order.
483
+ async function joinOrderFiles({ coreFile, refundsFile, fulfillmentsFile, outputFile, workDir = path.dirname(outputFile) }) {
484
+ const DatabaseSync = loadDatabaseSync();
485
+ if (!DatabaseSync) return runSqliteWorker('joinOrderFiles', { coreFile, refundsFile, fulfillmentsFile, outputFile, workDir });
486
+ const work = path.join(workDir, `${path.basename(outputFile)}.${process.pid}.${Date.now()}.orders.tmp`);
487
+ const outputTemp = path.join(workDir, `${path.basename(outputFile)}.${process.pid}.${Date.now()}.tmp`);
488
+ const db = new DatabaseSync(work);
489
+ let output = null;
490
+ try {
491
+ db.exec(`
492
+ PRAGMA journal_mode = OFF;
493
+ PRAGMA synchronous = OFF;
494
+ PRAGMA temp_store = FILE;
495
+ CREATE TABLE supplements (
496
+ query_name TEXT NOT NULL,
497
+ order_id TEXT NOT NULL,
498
+ value TEXT NOT NULL,
499
+ used INTEGER NOT NULL DEFAULT 0,
500
+ PRIMARY KEY(query_name, order_id)
501
+ );
502
+ CREATE INDEX supplements_order ON supplements(order_id);
503
+ `);
504
+ const add = db.prepare('INSERT OR REPLACE INTO supplements(query_name, order_id, value) VALUES (?, ?, ?)');
505
+ db.exec('BEGIN');
506
+ try {
507
+ for (const [query, field, file] of [['orders-refunds', 'refunds', refundsFile], ['orders-fulfillments', 'fulfillments', fulfillmentsFile]]) {
508
+ if (!file) continue; // this run does not carry that query
509
+ // A `done` supplement always has its staged file, empty when the dataset is. A missing one
510
+ // is lost input, never an empty dataset: fail loudly rather than write empty arrays.
511
+ try {
512
+ await fsp.access(file);
513
+ } catch (error) {
514
+ if (error.code === 'ENOENT') throw new Error(`the staged ${query} file is missing: ${path.basename(file)}`);
515
+ throw error;
516
+ }
517
+ for await (const row of iterateNdjson(file)) add.run(query, String(row.id), JSON.stringify(Array.isArray(row[field]) ? row[field] : []));
518
+ }
519
+ db.exec('COMMIT');
520
+ } catch (error) {
521
+ db.exec('ROLLBACK');
522
+ throw error;
523
+ }
524
+ const find = db.prepare('SELECT query_name, value FROM supplements WHERE order_id = ?');
525
+ const markUsed = db.prepare('UPDATE supplements SET used = 1 WHERE order_id = ?');
526
+ output = fs.createWriteStream(outputTemp, { encoding: 'utf8' });
527
+ for await (const order of iterateNdjson(coreFile)) {
528
+ const joined = { ...order, refunds: [], fulfillments: [] };
529
+ for (const row of find.all(String(order.id))) joined[row.query_name === 'orders-refunds' ? 'refunds' : 'fulfillments'] = JSON.parse(row.value);
530
+ markUsed.run(String(order.id));
531
+ if (!output.write(`${JSON.stringify(joined)}\n`)) await new Promise((resolve) => output.once('drain', resolve));
532
+ }
533
+ output.end();
534
+ await finished(output);
535
+ output = null;
536
+ await fsp.rename(outputTemp, outputFile);
537
+ const droppedByQuery = Object.fromEntries(['orders-refunds', 'orders-fulfillments'].map((query) => [query, Number(db.prepare('SELECT COUNT(*) AS count FROM supplements WHERE query_name = ? AND used = 0').get(query).count)]));
538
+ return { droppedOrphans: droppedByQuery['orders-refunds'] + droppedByQuery['orders-fulfillments'], droppedByQuery };
539
+ } finally {
540
+ if (output) output.destroy();
541
+ db.close();
542
+ await removeFile(outputTemp);
543
+ await removeFile(work);
544
+ }
545
+ }
546
+
547
+ // The default file host download: plain http(s), no content decoding (identity only), bytes
548
+ // counted as they arrive. It reports what happened; the gate decides what it means.
549
+ function defaultDownload(url, destination) {
550
+ return new Promise((resolve) => {
551
+ let client;
552
+ try {
553
+ client = String(url).startsWith('http:') ? http : https;
554
+ } catch {
555
+ client = https;
556
+ }
557
+ const request = client.get(url, { headers: { 'accept-encoding': 'identity' } }, (response) => {
558
+ if (response.statusCode !== 200) {
559
+ response.resume();
560
+ response.on('end', () => resolve({ status: response.statusCode, bytes: 0 }));
561
+ response.on('error', (error) => resolve({ status: response.statusCode, bytes: 0, error: error.message }));
562
+ return;
563
+ }
564
+ const out = fs.createWriteStream(destination);
565
+ let bytes = 0;
566
+ let failed = null;
567
+ response.on('data', (chunk) => { bytes += chunk.length; });
568
+ response.on('error', (error) => { failed = error.message; out.end(); });
569
+ response.on('aborted', () => { failed = failed || 'the connection was cut'; });
570
+ response.pipe(out);
571
+ out.on('finish', () => resolve({ status: 200, bytes, ...(failed || !response.complete ? { error: failed || 'the response did not complete' } : {}) }));
572
+ out.on('error', (error) => resolve({ status: 200, bytes, error: error.message }));
573
+ });
574
+ request.on('error', (error) => resolve({ status: null, bytes: 0, error: error.message }));
575
+ });
576
+ }
577
+
578
+ // ---------------------------------------------------------------------------------------------
579
+ // The runner
580
+ // ---------------------------------------------------------------------------------------------
581
+
582
+ function newManifest({ caller, store, snapshotTime, queries, previousSidecars, now }) {
583
+ const manifest = {
584
+ schemaVersion: MANIFEST_SCHEMA_VERSION,
585
+ caller,
586
+ store,
587
+ snapshotTime,
588
+ startedAt: iso(now()),
589
+ status: 'running',
590
+ order: queries.map((query) => query.name),
591
+ queries: Object.fromEntries(queries.map((query) => [query.name, {
592
+ state: 'pending',
593
+ entity: query.entity || entityOf(query.name),
594
+ text: query.text,
595
+ attempts: 0,
596
+ reapproved: false,
597
+ downloadTries: 0,
598
+ linkReruns: 0,
599
+ }])),
600
+ };
601
+ if (previousSidecars.length) manifest.previousSidecars = [...new Set(previousSidecars)].sort();
602
+ return manifest;
603
+ }
604
+
605
+ const OPERATION_FIELDS = ['operationId', 'runningAt', 'deadlineAt', 'overdueRound', 'overdueActionId', 'url', 'fileSize', 'objectCount', 'rootObjectCount', 'createdAt', 'completedAt', 'startedAt'];
606
+
607
+ // The shopify extract adapters plug into the runner here and add no runner logic of their own: a denial
608
+ // handler, a `failed` handler per query (`failed.byQuery`), a reassembly hook per query, the
609
+ // `denied` reset, and `project` (the projection applied to the customer and order query text).
610
+ // Everything a handler registers must be idempotent. Options passed to createBulkRunner
611
+ // override what is registered.
612
+ const registered = { handlers: {}, deniedReset: null, project: null };
613
+
614
+ function registerHandlers({ denied, failed, reassemble, deniedReset, project } = {}) {
615
+ if (denied) registered.handlers.denied = denied;
616
+ if (failed) registered.handlers.failed = { ...(registered.handlers.failed || {}), ...failed, byQuery: { ...((registered.handlers.failed || {}).byQuery || {}), ...(failed.byQuery || {}) } };
617
+ if (reassemble) registered.handlers.reassemble = { ...(registered.handlers.reassemble || {}), ...reassemble };
618
+ if (deniedReset) registered.deniedReset = deniedReset;
619
+ if (project) registered.project = project;
620
+ }
621
+
622
+ function clearRegisteredHandlers() {
623
+ registered.handlers = {};
624
+ registered.deniedReset = null;
625
+ registered.project = null;
626
+ }
627
+
628
+ function mergeHandlers(extra = {}) {
629
+ const base = registered.handlers;
630
+ return {
631
+ denied: extra.denied || base.denied,
632
+ failed: { ...(base.failed || {}), ...(extra.failed || {}), byQuery: { ...((base.failed || {}).byQuery || {}), ...((extra.failed || {}).byQuery || {}) } },
633
+ reassemble: { ...(base.reassemble || {}), ...(extra.reassemble || {}) },
634
+ };
635
+ }
636
+
637
+ function createBulkRunner(options = {}) {
638
+ const {
639
+ projectDir,
640
+ store,
641
+ caller,
642
+ manifestPath,
643
+ stagingDir,
644
+ queries = null,
645
+ snapshotTime = null,
646
+ execute,
647
+ handlers: handlerOptions = {},
648
+ deniedReset = registered.deniedReset,
649
+ retryFailed = false,
650
+ previousSidecars = [],
651
+ sessionCheck = null,
652
+ download = defaultDownload,
653
+ outputDir = null,
654
+ now = () => Date.now(),
655
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
656
+ progress = () => {},
657
+ onPersist = null,
658
+ overdueMs = OVERDUE_MS,
659
+ } = options;
660
+ if (caller !== 'extract' && caller !== 'census') throw new Error('caller must be extract or census');
661
+ if (!projectDir || !manifestPath || !stagingDir) throw new Error('projectDir, manifestPath and stagingDir are required');
662
+ if (typeof execute !== 'function' || typeof execute.startBulkOperation !== 'function') throw new Error('execute (a store executor with startBulkOperation) is required');
663
+ if (caller === 'extract' && !outputDir) throw new Error('an extract needs outputDir');
664
+ const stage = caller === 'extract' ? 'execution' : 'discovery';
665
+ const extract = caller === 'extract';
666
+ const normalizedStore = session.normalizeDomain(store);
667
+ const handlers = mergeHandlers(handlerOptions);
668
+ let manifest = null;
669
+
670
+ // -------------------------------------------------------------------------------------------
671
+ // Manifest
672
+ // -------------------------------------------------------------------------------------------
673
+
674
+ async function save(label, query = null) {
675
+ await writeJsonAtomic(manifestPath, manifest);
676
+ if (typeof onPersist === 'function') await onPersist({ label, query, state: query ? manifest.queries[query].state : null, manifest });
677
+ }
678
+
679
+ async function readManifest() {
680
+ try {
681
+ return JSON.parse(await fsp.readFile(manifestPath, 'utf8'));
682
+ } catch (error) {
683
+ if (error.code === 'ENOENT') return null;
684
+ throw error;
685
+ }
686
+ }
687
+
688
+ const entry = (name) => manifest.queries[name];
689
+
690
+ async function setState(name, state, fields = {}, dropFields = []) {
691
+ const target = entry(name);
692
+ target.state = state;
693
+ Object.assign(target, fields);
694
+ for (const field of dropFields) delete target[field];
695
+ await save(`${name}:${state}`, name);
696
+ }
697
+
698
+ function dropOperation(name) {
699
+ const target = entry(name);
700
+ for (const field of OPERATION_FIELDS) delete target[field];
701
+ }
702
+
703
+ // -------------------------------------------------------------------------------------------
704
+ // Handlers
705
+ // -------------------------------------------------------------------------------------------
706
+
707
+ function coverageRowFor(name, { artifact, pointer, recoveryAction }) {
708
+ const entity = entityOf(name);
709
+ const [row] = buildShopifyCoverageRows({
710
+ captureFailures: [{ entity, artifact, reads: [name], errors: [{ code: 'shopify_bulk' }] }],
711
+ rawDir: RAW_EXTRACT_DIR,
712
+ });
713
+ return { ...row, evidence: { artifact, pointer }, recoveryAction };
714
+ }
715
+
716
+ function failureEvidence(name, target) {
717
+ const parts = [`queries.${name}`, `state ${target.outcome || target.state}`, `errorCode ${target.errorCode || 'unknown'}`];
718
+ if (target.error && target.error.message) parts.push(String(target.error.message).slice(0, 300));
719
+ return parts.join('; ');
720
+ }
721
+
722
+ // The default `failed` handler. Extract: the capture-failed row, upserted by coverageId.
723
+ // Census: the same row, carried in the entry's handlerOutcome for the discovery coverage step
724
+ // (the raw coverage file does not exist until discovery's last step, so nothing is upserted).
725
+ async function defaultFailedHandler({ name, entry: target }) {
726
+ const recoveryAction = extract
727
+ ? `Fix the cause named in the stop message, then run shopify-extract.js --retry-failed for ${entityOf(name)}.`
728
+ : `Fix the cause, then run Shopify discovery again for ${entityOf(name)} (the extract's gated read also covers it).`;
729
+ const row = coverageRowFor(name, {
730
+ artifact: extract ? `${RAW_EXTRACT_DIR}/${EXTRACT_MANIFEST_FILE}` : path.relative(projectDir, manifestPath).split(path.sep).join('/'),
731
+ pointer: failureEvidence(name, target),
732
+ recoveryAction,
733
+ });
734
+ if (extract) await upsertAdapterCoverageRows(projectDir, { adapter: 'shopify', rows: [row] });
735
+ return { handlerOutcome: { coverageId: row.coverageId, ...(extract ? {} : { row }) } };
736
+ }
737
+
738
+ // The fail-closed denial fallback, used only when the caller registers no denial handler (the
739
+ // customer-and-order adapter registers its own): the denial is unattributed, so the dataset is treated like a failed one.
740
+ async function defaultDeniedHandler(context) {
741
+ const result = await defaultFailedHandler(context);
742
+ return { handlerOutcome: { attribution: 'unattributed', ...result.handlerOutcome }, stop: { code: STOPPING_FAILED_CODE, message: `Shopify denied the ${context.name} export and the denial could not be attributed to a withheld detail.` } };
743
+ }
744
+
745
+ function failedHandlerFor(name) {
746
+ const byQuery = (handlers.failed && handlers.failed.byQuery) || {};
747
+ return byQuery[name] || (handlers.failed && handlers.failed.default) || defaultFailedHandler;
748
+ }
749
+
750
+ function handlerContext(name) {
751
+ return { name, query: name, entity: entityOf(name), entry: entry(name), manifest, caller, stage, projectDir, store, execute, stagingDir, outputDir, manifestPath, now, sleep };
752
+ }
753
+
754
+ // -------------------------------------------------------------------------------------------
755
+ // Settling
756
+ // -------------------------------------------------------------------------------------------
757
+
758
+ async function beginSettling(name, outcome, { errorCode, error }) {
759
+ await setState(name, 'settling', { outcome, errorCode, error, settlingAt: iso(now()) });
760
+ }
761
+
762
+ // `later` is a start that finds an already-terminal stopping entry: it stops with the generic
763
+ // `shopify_bulk_failed`; the first settle stops with the entry's own code.
764
+ function stopFor(name, target, handlerStop, { later = false } = {}) {
765
+ const entity = entityOf(name);
766
+ if (handlerStop) {
767
+ return new BulkStop(handlerStop.code, handlerStop.message || `Shopify ${caller} stopped (${handlerStop.code}) at ${name}.`, { details: { query: name, entity, ...(handlerStop.details || {}) } });
768
+ }
769
+ const specific = target.errorCode && target.state === 'failed' ? target.errorCode : STOPPING_FAILED_CODE;
770
+ const code = later ? STOPPING_FAILED_CODE : specific;
771
+ const cause = target.error && target.error.message ? `: ${String(target.error.message).slice(0, 300)}` : '';
772
+ return new BulkStop(code, `Shopify dataset ${entity} could not be read (${specific})${cause}. Requires Import Operator: fix the cause named here, run \`shopify-extract.js --retry-failed\`, and when the extract completes record the coverage decision \`provided\` for \`shopify:${entity}\`; otherwise show the merchant the row at mapping.`, { details: { query: name, entity, errorCode: target.errorCode || null, coverageId: target.handlerOutcome ? target.handlerOutcome.coverageId : null } });
773
+ }
774
+
775
+ // Runs the outcome's handler for a `settling` entry, writes the terminal state, and returns the
776
+ // stop the entry causes, or null.
777
+ async function finishSettling(name) {
778
+ const target = entry(name);
779
+ const context = handlerContext(name);
780
+ let result;
781
+ if (target.outcome === 'failed') {
782
+ result = await failedHandlerFor(name)({ ...context, outcome: 'failed' });
783
+ } else {
784
+ result = await (handlers.denied || defaultDeniedHandler)({ ...context, outcome: 'denied' });
785
+ }
786
+ const terminal = { handlerOutcome: (result && result.handlerOutcome) || {} };
787
+ if (target.outcome === 'denied') terminal.deniedAt = iso(now());
788
+ await setState(name, target.outcome, terminal);
789
+ const handlerStop = result && result.stop ? result.stop : null;
790
+ if (handlerStop) return stopFor(name, entry(name), handlerStop);
791
+ if (isStopping(entry(name), caller)) return stopFor(name, entry(name), null);
792
+ return null;
793
+ }
794
+
795
+ async function settle(name, outcome, details) {
796
+ await beginSettling(name, outcome, details);
797
+ const stop = await finishSettling(name);
798
+ if (stop) throw stop;
799
+ }
800
+
801
+ async function settleAll() {
802
+ for (const name of manifest.order) {
803
+ if (entry(name).state === 'settling') {
804
+ const stop = await finishSettling(name);
805
+ if (stop) throw stop;
806
+ }
807
+ }
808
+ }
809
+
810
+ // -------------------------------------------------------------------------------------------
811
+ // Session expiry, denial
812
+ // -------------------------------------------------------------------------------------------
813
+
814
+ async function authExpiredStop(extraMessage = '') {
815
+ const action = await session.recordAuthExpired(projectDir, { stage, store });
816
+ return new BulkStop('source_auth_expired', `the Shopify connection for ${store} expired during the ${caller}${extraMessage}. Re-approval request ${action.requestId} is pending: run the Shopify session check (with --connect if asked), answer it, then run the same step again. Finished reads are not repeated.`, { details: { requestId: action.requestId } });
817
+ }
818
+
819
+ async function runSessionCheck() {
820
+ if (typeof sessionCheck !== 'function') return { ok: true };
821
+ return sessionCheck();
822
+ }
823
+
824
+ async function handleDenial(name, evidence) {
825
+ const target = entry(name);
826
+ const check = await runSessionCheck();
827
+ if (!check.ok && !target.reapproved) {
828
+ dropOperation(name);
829
+ await setState(name, 'pending', { reapproved: true });
830
+ throw await authExpiredStop(` (Shopify denied the ${name} export and the session check failed)`);
831
+ }
832
+ const verbatim = { message: 'Shopify refused the bulk export with ACCESS_DENIED', ...evidence };
833
+ if (DENIAL_ATTRIBUTED_QUERIES.includes(name)) {
834
+ await settle(name, 'denied', { errorCode: 'ACCESS_DENIED', error: verbatim });
835
+ } else {
836
+ await settle(name, 'failed', { errorCode: STOPPING_FAILED_CODE, error: { ...verbatim, message: 'Shopify refused the bulk export with ACCESS_DENIED' } });
837
+ }
838
+ }
839
+
840
+ // -------------------------------------------------------------------------------------------
841
+ // Per query
842
+ // -------------------------------------------------------------------------------------------
843
+
844
+ const hasCode = (errors, code) => (errors || []).some((error) => error && error.extensions && error.extensions.code === code);
845
+
846
+ async function startQuery(name) {
847
+ const target = entry(name);
848
+ await setState(name, 'starting', { startedAt: iso(now()) });
849
+ progress('Starting Shopify bulk export', { query: name });
850
+ const result = await execute.startBulkOperation(target.text);
851
+ if (result.errors && result.errors.length) {
852
+ if (hasCode(result.errors, 'ACCESS_DENIED')) { await handleDenial(name, { graphqlErrors: result.errors }); return; }
853
+ await settle(name, 'failed', { errorCode: STOPPING_FAILED_CODE, error: { message: 'Shopify answered the bulk start with GraphQL errors', graphqlErrors: result.errors } });
854
+ return;
855
+ }
856
+ const payload = result.data && result.data.bulkOperationRunQuery;
857
+ if (!payload) {
858
+ await settle(name, 'failed', { errorCode: STOPPING_FAILED_CODE, error: { message: 'Shopify answered the bulk start with no bulkOperationRunQuery result' } });
859
+ return;
860
+ }
861
+ if (Array.isArray(payload.userErrors) && payload.userErrors.length) {
862
+ await settle(name, 'failed', { errorCode: STOPPING_FAILED_CODE, error: { message: 'Shopify refused the bulk start', userErrors: payload.userErrors } });
863
+ return;
864
+ }
865
+ const operation = payload.bulkOperation;
866
+ if (!operation || typeof operation.id !== 'string') {
867
+ await settle(name, 'failed', { errorCode: STOPPING_FAILED_CODE, error: { message: 'Shopify answered the bulk start with no operation id' } });
868
+ return;
869
+ }
870
+ const runningAt = now();
871
+ await setState(name, 'running', { operationId: operation.id, runningAt: iso(runningAt), deadlineAt: iso(runningAt + overdueMs), overdueRound: 1 });
872
+ }
873
+
874
+ function overdueRequestId(name, round) {
875
+ return session.sequencedRequestId(OVERDUE_NAMESPACE, `${caller}\0${name}\0${entry(name).operationId}`, round);
876
+ }
877
+
878
+ async function readActionIfAny(requestId) {
879
+ try {
880
+ return await readUserAction(projectDir, requestId);
881
+ } catch (error) {
882
+ if (error.code === 'ENOENT') return null;
883
+ throw error;
884
+ }
885
+ }
886
+
887
+ async function raiseOverdue(name) {
888
+ const target = entry(name);
889
+ const round = target.overdueRound || 1;
890
+ const requestId = overdueRequestId(name, round);
891
+ let action = await readActionIfAny(requestId);
892
+ if (!action) {
893
+ action = await createUserAction(projectDir, {
894
+ requestId,
895
+ kind: 'question',
896
+ stage,
897
+ title: `Shopify export overdue: ${name} (shopify_bulk_overdue)`,
898
+ prompt: `Shopify has been preparing the \`${name}\` export (operation ${target.operationId}) for over ${round * 4} hours. Wait another 4 hours, or abort this dataset?`,
899
+ response: { mode: 'choice' },
900
+ choices: [
901
+ { id: 'wait', label: 'Wait another 4 hours' },
902
+ { id: 'abort', label: 'Abort this dataset' },
903
+ ],
904
+ });
905
+ }
906
+ await setState(name, 'running', { overdueActionId: action.requestId });
907
+ throw new BulkStop('shopify_bulk_overdue', `Shopify has been preparing the ${name} export for over ${round * 4} hours. Answer request ${action.requestId} (wait or abort), then run the same step again.`, { status: 'awaiting_user_action', details: { query: name, operationId: target.operationId, round, requestIds: [action.requestId] } });
908
+ }
909
+
910
+ // Applies an answered overdue action, or stops while it is unanswered. Returns 'waited' | 'aborted'.
911
+ async function applyOverdue(name) {
912
+ const target = entry(name);
913
+ const action = await readActionIfAny(target.overdueActionId);
914
+ if (!action || action.status !== 'answered') {
915
+ throw new BulkStop('shopify_bulk_overdue', `The ${name} export is overdue and request ${target.overdueActionId} is unanswered; nothing was polled or started.`, { status: 'awaiting_user_action', details: { query: name, operationId: target.operationId, round: target.overdueRound || 1, requestIds: [target.overdueActionId] } });
916
+ }
917
+ if (action.answer && action.answer.choice === 'abort') {
918
+ await settle(name, 'failed', { errorCode: 'shopify_bulk_overdue_aborted', error: { message: `The ${name} export was aborted after it ran over ${(target.overdueRound || 1) * 4} hours; Shopify's operation ${target.operationId} was not cancelled and its result was never downloaded`, operationId: target.operationId, requestId: action.requestId } });
919
+ return 'aborted';
920
+ }
921
+ const answeredAt = Date.parse(action.answer && action.answer.answeredAt);
922
+ const base = Number.isFinite(answeredAt) ? answeredAt : now();
923
+ await setState(name, 'running', { deadlineAt: iso(base + overdueMs), overdueRound: (target.overdueRound || 1) + 1 }, ['overdueActionId']);
924
+ return 'waited';
925
+ }
926
+
927
+ function classifyOperation(operation) {
928
+ if (!operation) return 'failed';
929
+ if (operation.partialDataUrl) return 'failed';
930
+ if (operation.status === 'COMPLETED') return 'completed';
931
+ if (operation.status === 'FAILED' && operation.errorCode === 'ACCESS_DENIED') return 'denied';
932
+ if (['FAILED', 'CANCELED', 'EXPIRED'].includes(operation.status)) return 'failed';
933
+ return 'running';
934
+ }
935
+
936
+ async function failedResult(name, { errorCode = STOPPING_FAILED_CODE, message, evidence = {} }) {
937
+ const target = entry(name);
938
+ if (target.attempts < MAX_ATTEMPTS) {
939
+ dropOperation(name);
940
+ await setState(name, 'pending', { attempts: target.attempts + 1, downloadTries: 0 });
941
+ return;
942
+ }
943
+ await settle(name, 'failed', { errorCode, error: { message, ...evidence } });
944
+ }
945
+
946
+ async function pollOperation(name) {
947
+ const result = await execute(STATUS_QUERY, { id: entry(name).operationId });
948
+ if (result.errors && result.errors.length) {
949
+ return { errors: result.errors };
950
+ }
951
+ return { operation: result.data && result.data.node ? result.data.node : null };
952
+ }
953
+
954
+ async function processRunning(name) {
955
+ if (entry(name).overdueActionId) {
956
+ const outcome = await applyOverdue(name);
957
+ if (outcome === 'aborted') return;
958
+ }
959
+ let wait = POLL_START_MS;
960
+ for (;;) {
961
+ const polled = await pollOperation(name);
962
+ if (polled.errors) {
963
+ if (hasCode(polled.errors, 'ACCESS_DENIED')) { await handleDenial(name, { graphqlErrors: polled.errors }); return; }
964
+ await settle(name, 'failed', { errorCode: STOPPING_FAILED_CODE, error: { message: 'Shopify answered the status poll with GraphQL errors', graphqlErrors: polled.errors } });
965
+ return;
966
+ }
967
+ const operation = polled.operation;
968
+ const kind = classifyOperation(operation);
969
+ if (kind === 'running') {
970
+ if (now() >= Date.parse(entry(name).deadlineAt)) await raiseOverdue(name);
971
+ await sleep(wait);
972
+ wait = Math.min(wait * 2, POLL_CAP_MS);
973
+ continue;
974
+ }
975
+ if (kind === 'denied') { await handleDenial(name, { operation: operationEvidence(operation) }); return; }
976
+ if (kind === 'failed') {
977
+ await failedResult(name, { message: operation ? `Shopify's bulk operation ended ${operation.status}${operation.errorCode ? ` (${operation.errorCode})` : ''}${operation.partialDataUrl ? ' with only partial data' : ''}` : 'Shopify no longer knows the bulk operation', evidence: { operation: operationEvidence(operation) } });
978
+ return;
979
+ }
980
+ await setState(name, 'running', {
981
+ url: operation.url || null,
982
+ fileSize: operation.fileSize === undefined ? null : operation.fileSize,
983
+ objectCount: operation.objectCount,
984
+ rootObjectCount: operation.rootObjectCount,
985
+ createdAt: operation.createdAt,
986
+ completedAt: operation.completedAt,
987
+ });
988
+ await downloadGate(name);
989
+ return;
990
+ }
991
+ }
992
+
993
+ function operationEvidence(operation) {
994
+ if (!operation) return null;
995
+ return { id: operation.id, status: operation.status, errorCode: operation.errorCode || null, partialDataUrl: operation.partialDataUrl || null, objectCount: operation.objectCount, fileSize: operation.fileSize === undefined ? null : operation.fileSize };
996
+ }
997
+
998
+ // Marks the entry `downloaded` only when the whole gate holds.
999
+ async function downloadGate(name) {
1000
+ const jsonl = path.join(stagingDir, `${name}.jsonl`);
1001
+ const partial = `${jsonl}.partial`;
1002
+ await fsp.mkdir(stagingDir, { recursive: true });
1003
+ for (;;) {
1004
+ const target = entry(name);
1005
+ if (!target.url) {
1006
+ if (String(target.objectCount) === '0') {
1007
+ await writeTextAtomic(jsonl, '');
1008
+ await setState(name, 'downloaded', { bytes: 0, lines: 0 });
1009
+ return;
1010
+ }
1011
+ await failedResult(name, { message: `Shopify completed the ${name} export with no file for ${target.objectCount} objects`, evidence: { operation: { objectCount: target.objectCount } } });
1012
+ return;
1013
+ }
1014
+ progress('Downloading Shopify bulk file', { query: name });
1015
+ await removeFile(partial);
1016
+ const result = await download(target.url, partial);
1017
+ const written = result && Number.isFinite(result.bytes) ? result.bytes : 0;
1018
+ if (result && (result.status === 400 || result.status === 403)) {
1019
+ await removeFile(partial);
1020
+ if (target.linkReruns >= MAX_LINK_RERUNS) {
1021
+ await settle(name, 'failed', { errorCode: 'shopify_bulk_download_failed', error: { message: `The ${name} export's download link expired ${target.linkReruns + 1} times (HTTP ${result.status})`, httpStatus: result.status } });
1022
+ return;
1023
+ }
1024
+ dropOperation(name);
1025
+ await setState(name, 'pending', { linkReruns: target.linkReruns + 1, downloadTries: 0 });
1026
+ return;
1027
+ }
1028
+ let reason = null;
1029
+ if (!result || result.status !== 200) reason = `the download answered ${result && result.status !== null && result.status !== undefined ? `HTTP ${result.status}` : 'no HTTP response'}${result && result.error ? ` (${result.error})` : ''}`;
1030
+ else if (result.error) reason = `the download failed: ${result.error}`;
1031
+ else if (target.fileSize === null || target.fileSize === undefined || String(written) !== String(target.fileSize)) reason = `the download was ${written} bytes, Shopify reported ${target.fileSize === null || target.fileSize === undefined ? 'no size' : target.fileSize}`;
1032
+ let checked = null;
1033
+ if (!reason) {
1034
+ checked = await validateJsonlFile(partial);
1035
+ if (!checked.ok) reason = checked.reason;
1036
+ }
1037
+ if (!reason) {
1038
+ await fsp.rename(partial, jsonl);
1039
+ await setState(name, 'downloaded', { bytes: written, lines: checked.lines });
1040
+ return;
1041
+ }
1042
+ await removeFile(partial);
1043
+ const tries = target.downloadTries + 1;
1044
+ await setState(name, 'running', { downloadTries: tries });
1045
+ if (tries < MAX_DOWNLOAD_TRIES) continue;
1046
+ await failedResult(name, { errorCode: 'shopify_bulk_download_failed', message: `The ${name} export could not be downloaded whole after ${tries} tries: ${reason}`, evidence: { reason } });
1047
+ return;
1048
+ }
1049
+ }
1050
+
1051
+ async function reassemble(name) {
1052
+ const target = entry(name);
1053
+ const catalog = catalogEntry(name);
1054
+ const jsonl = path.join(stagingDir, `${name}.jsonl`);
1055
+ if (!fs.existsSync(jsonl)) {
1056
+ // `downloaded` promises a complete local file. If it is gone (staging cleared by hand), the
1057
+ // dataset is simply read again: no attempt is spent, nothing is guessed.
1058
+ dropOperation(name);
1059
+ await setState(name, 'pending', { downloadTries: 0 }, ['bytes', 'lines']);
1060
+ return;
1061
+ }
1062
+ const foldedFile = path.join(stagingDir, `${name}.folded.tmp`);
1063
+ const folded = await foldBulkJsonl(jsonl, catalog, { outputFile: foldedFile });
1064
+ if (folded.orphans) {
1065
+ await settle(name, 'failed', { errorCode: 'shopify_bulk_orphan_child', error: { message: `${folded.orphanCount} child row(s) of ${name} match no parent row`, orphans: folded.orphans } });
1066
+ return;
1067
+ }
1068
+ const hook = handlers.reassemble && handlers.reassemble[name];
1069
+ let records = null;
1070
+ let recordsFile = null;
1071
+ let recordCount = folded.recordCount;
1072
+ let outputs = {};
1073
+ let sidecarFiles = {};
1074
+ let result = {};
1075
+ let outputFile = null;
1076
+ let entryFields = {};
1077
+ let hookStop = null;
1078
+ if (hook) {
1079
+ const hooked = await hook({ ...handlerContext(name), records: iterateNdjson(foldedFile), recordsFile: foldedFile, recordCount, lines: folded.lines });
1080
+ if (hooked && hooked.ok === false) {
1081
+ await removeFile(foldedFile);
1082
+ await settle(name, 'failed', { errorCode: hooked.errorCode || STOPPING_FAILED_CODE, error: { message: hooked.message || `The ${name} recheck failed (${hooked.errorCode || STOPPING_FAILED_CODE})`, ...(hooked.evidence ? { evidence: hooked.evidence } : {}) } });
1083
+ return;
1084
+ }
1085
+ if (hooked && hooked.records) records = hooked.records;
1086
+ if (hooked && hooked.recordsFile) recordsFile = hooked.recordsFile;
1087
+ if (hooked && Number.isInteger(hooked.recordCount)) recordCount = hooked.recordCount;
1088
+ if (hooked && hooked.sidecars) outputs = hooked.sidecars;
1089
+ if (hooked && hooked.sidecarFiles) sidecarFiles = hooked.sidecarFiles;
1090
+ if (hooked && hooked.manifest) Object.assign(manifest, hooked.manifest);
1091
+ if (hooked && hooked.result) result = hooked.result;
1092
+ if (hooked && hooked.outputFile) outputFile = hooked.outputFile;
1093
+ if (hooked && hooked.entry) entryFields = hooked.entry;
1094
+ if (hooked && hooked.stop) hookStop = hooked.stop;
1095
+ }
1096
+ const readAt = { createdAt: target.createdAt || null, completedAt: target.completedAt || null };
1097
+ const durationMs = Number.isFinite(Date.parse(target.completedAt)) && Number.isFinite(Date.parse(target.createdAt)) ? Date.parse(target.completedAt) - Date.parse(target.createdAt) : null;
1098
+ if (extract) {
1099
+ const stagedName = outputFile || `${name}.ndjson`;
1100
+ const staged = path.join(stagingDir, stagedName);
1101
+ if (recordsFile) {
1102
+ await removeFile(staged);
1103
+ await fsp.rename(recordsFile, staged);
1104
+ await removeFile(foldedFile);
1105
+ } else if (records) {
1106
+ recordCount = await writeNdjsonAtomic(staged, records);
1107
+ await removeFile(foldedFile);
1108
+ } else {
1109
+ await fsp.rename(foldedFile, staged);
1110
+ }
1111
+ const sidecarNames = [...new Set([...Object.keys(outputs), ...Object.keys(sidecarFiles)])].sort();
1112
+ const oldSidecars = Array.isArray(target.sidecars) ? target.sidecars : [];
1113
+ for (const sidecar of oldSidecars.filter((sidecar) => !sidecarNames.includes(sidecar))) {
1114
+ await removeFile(path.join(stagingDir, `sidecar-${sidecar}.ndjson`));
1115
+ manifest.obsoleteSidecars = [...new Set([...(manifest.obsoleteSidecars || []), sidecar])].sort();
1116
+ }
1117
+ for (const sidecar of sidecarNames) {
1118
+ const destination = path.join(stagingDir, `sidecar-${sidecar}.ndjson`);
1119
+ if (sidecarFiles[sidecar]) {
1120
+ await removeFile(destination);
1121
+ await fsp.rename(sidecarFiles[sidecar], destination);
1122
+ } else {
1123
+ await writeNdjsonAtomic(destination, outputs[sidecar]);
1124
+ }
1125
+ }
1126
+ manifest.sidecars = [...new Set(manifest.order.flatMap((query) => query === name ? sidecarNames : (entry(query).sidecars || [])))].sort();
1127
+ await setState(name, 'done', { readAt, durationMs, records: recordCount, sidecars: sidecarNames, ...(outputFile ? { outputFile } : {}), ...entryFields }, ['url']);
1128
+ } else {
1129
+ await removeFile(foldedFile);
1130
+ await setState(name, 'done', { readAt, durationMs, result: { records: recordCount, ...result }, ...entryFields }, ['url']);
1131
+ }
1132
+ await removeFile(jsonl);
1133
+ if (hookStop) throw new BulkStop(hookStop.code, hookStop.message || `Shopify extract stopped (${hookStop.code}) at ${name}.`, { details: { query: name, entity: entityOf(name), ...(hookStop.details || {}) } });
1134
+ }
1135
+
1136
+ async function processQuery(name) {
1137
+ for (;;) {
1138
+ const target = entry(name);
1139
+ switch (target.state) {
1140
+ case 'done':
1141
+ return;
1142
+ case 'denied':
1143
+ if (isStopping(target, caller)) throw stopFor(name, target, null, { later: true });
1144
+ return;
1145
+ case 'failed':
1146
+ if (extract) throw stopFor(name, target, null, { later: true });
1147
+ return;
1148
+ case 'settling': {
1149
+ const stop = await finishSettling(name);
1150
+ if (stop) throw stop;
1151
+ break;
1152
+ }
1153
+ case 'starting':
1154
+ dropOperation(name);
1155
+ await setState(name, 'pending');
1156
+ break;
1157
+ case 'pending':
1158
+ await startQuery(name);
1159
+ break;
1160
+ case 'running':
1161
+ await processRunning(name);
1162
+ break;
1163
+ case 'downloaded':
1164
+ await reassemble(name);
1165
+ break;
1166
+ default:
1167
+ throw new Error(`unknown query state ${target.state} for ${name}`);
1168
+ }
1169
+ }
1170
+ }
1171
+
1172
+ // -------------------------------------------------------------------------------------------
1173
+ // Resume resets
1174
+ // -------------------------------------------------------------------------------------------
1175
+
1176
+ async function cleanLeftovers() {
1177
+ let names = [];
1178
+ try {
1179
+ names = await fsp.readdir(stagingDir);
1180
+ } catch (error) {
1181
+ if (error.code !== 'ENOENT') throw error;
1182
+ }
1183
+ for (const leftover of names.filter((file) => file.endsWith('.partial') || file.endsWith('.tmp'))) await removeFile(path.join(stagingDir, leftover));
1184
+ // A crash between the `done` write and the JSONL delete leaves the file behind.
1185
+ for (const name of manifest.order) if (entry(name).state === 'done') await removeFile(path.join(stagingDir, `${name}.jsonl`));
1186
+ }
1187
+
1188
+ function resetEntry(name, fields = {}) {
1189
+ const target = entry(name);
1190
+ dropOperation(name);
1191
+ for (const field of ['outcome', 'errorCode', 'error', 'settlingAt', 'handlerOutcome', 'deniedAt', 'readAt', 'durationMs', 'records', 'result', 'bytes', 'lines']) delete target[field];
1192
+ Object.assign(target, { state: 'pending', attempts: 0, downloadTries: 0, linkReruns: 0, reapproved: false }, fields);
1193
+ }
1194
+
1195
+ async function applyResets() {
1196
+ if (!extract) return;
1197
+ let changed = false;
1198
+ if (typeof deniedReset === 'function') {
1199
+ for (const reset of (await deniedReset({ manifest, projectDir })) || []) {
1200
+ resetEntry(reset.name, { text: reset.text });
1201
+ changed = true;
1202
+ }
1203
+ }
1204
+ if (retryFailed) {
1205
+ for (const name of manifest.order) {
1206
+ if (isStopping(entry(name), caller)) { resetEntry(name); changed = true; }
1207
+ }
1208
+ if (manifest.countFailure && manifest.countFailure.entities) {
1209
+ for (const failedEntity of manifest.countFailure.entities) {
1210
+ for (const name of manifest.order.filter((candidate) => entityOf(candidate) === failedEntity)) {
1211
+ await removeFile(path.join(stagingDir, `${name}.ndjson`));
1212
+ resetEntry(name);
1213
+ }
1214
+ }
1215
+ delete manifest.countFailure;
1216
+ changed = true;
1217
+ }
1218
+ }
1219
+ // A `done` extract entry promises its staged output, and a resume never reads a
1220
+ // finished query again. When that output is gone before the final join, read the query again
1221
+ // without spending an attempt instead of joining the hole as an empty dataset.
1222
+ for (const name of manifest.order) {
1223
+ const target = entry(name);
1224
+ if (target.state !== 'done') continue;
1225
+ const files = [target.outputFile || `${name}.ndjson`, ...(target.sidecars || []).map((sidecar) => `sidecar-${sidecar}.ndjson`)].map((file) => path.join(stagingDir, file));
1226
+ const present = await Promise.all(files.map((file) => fsp.access(file).then(() => true, (error) => { if (error.code === 'ENOENT') return false; throw error; })));
1227
+ if (present.every(Boolean)) continue;
1228
+ for (const file of files) await removeFile(file);
1229
+ resetEntry(name);
1230
+ changed = true;
1231
+ }
1232
+ if (changed) await save('resets');
1233
+ }
1234
+
1235
+ // -------------------------------------------------------------------------------------------
1236
+ // Extract: the final join and the count check
1237
+ // -------------------------------------------------------------------------------------------
1238
+
1239
+ function expectedFinalFiles() {
1240
+ const entities = [...new Set(manifest.order.map(entityOf))];
1241
+ return [
1242
+ ...entities.map((entity) => {
1243
+ const first = manifest.order.find((name) => entityOf(name) === entity);
1244
+ return (first && entry(first).outputFile) || `${entity}.ndjson`;
1245
+ }),
1246
+ ...(manifest.sidecars || []).map((entity) => `${entity}.ndjson`),
1247
+ ];
1248
+ }
1249
+
1250
+ async function joinFinalFiles() {
1251
+ await fsp.mkdir(outputDir, { recursive: true });
1252
+ const staged = (name) => path.join(stagingDir, `${name}.ndjson`);
1253
+ let droppedOrphans = 0;
1254
+ const droppedByQuery = {};
1255
+ for (const entity of [...new Set(manifest.order.map(entityOf))]) {
1256
+ const members = manifest.order.filter((name) => entityOf(name) === entity);
1257
+ if (entity !== 'orders') {
1258
+ const outputFile = entry(members[0]).outputFile || `${entity}.ndjson`;
1259
+ const stagedFile = entry(members[0]).outputFile || `${members[0]}.ndjson`;
1260
+ await copyFileAtomic(path.join(stagingDir, stagedFile), path.join(outputDir, outputFile));
1261
+ continue;
1262
+ }
1263
+ const joined = await joinOrderFiles({
1264
+ coreFile: staged('orders-core'),
1265
+ refundsFile: members.includes('orders-refunds') ? staged('orders-refunds') : null,
1266
+ fulfillmentsFile: members.includes('orders-fulfillments') ? staged('orders-fulfillments') : null,
1267
+ outputFile: path.join(outputDir, 'orders.ndjson'),
1268
+ workDir: stagingDir,
1269
+ });
1270
+ droppedOrphans += joined.droppedOrphans;
1271
+ Object.assign(droppedByQuery, joined.droppedByQuery);
1272
+ }
1273
+ for (const sidecar of manifest.sidecars || []) await copyFileAtomic(path.join(stagingDir, `sidecar-${sidecar}.ndjson`), path.join(outputDir, `${sidecar}.ndjson`));
1274
+ const currentSidecars = new Set(manifest.sidecars || []);
1275
+ for (const sidecar of new Set([...(manifest.previousSidecars || []), ...(manifest.obsoleteSidecars || [])])) {
1276
+ if (!currentSidecars.has(sidecar)) await removeFile(path.join(outputDir, `${sidecar}.ndjson`));
1277
+ }
1278
+ manifest.droppedOrphans = droppedOrphans;
1279
+ manifest.droppedOrphansByQuery = droppedByQuery;
1280
+ }
1281
+
1282
+ const COUNT_QUERIES = {
1283
+ customers: (snapshot) => `query RpExtractCustomersCount { customersCount(query: "created_at:<='${snapshot}'", limit: null) { count precision } }`,
1284
+ orders: (snapshot) => `query RpExtractOrdersCount { ordersCount(query: "created_at:<='${snapshot}'", limit: null) { count precision } }`,
1285
+ };
1286
+
1287
+ async function readExactCount(entity) {
1288
+ const root = entity === 'customers' ? 'customersCount' : 'ordersCount';
1289
+ let result;
1290
+ try {
1291
+ result = await execute(COUNT_QUERIES[entity](manifest.snapshotTime));
1292
+ } catch (error) {
1293
+ if (error instanceof ShopifyCliError && error.code === 'shopify_throttled') return { error: { code: 'shopify_throttled', message: error.message } };
1294
+ throw error;
1295
+ }
1296
+ if (result.errors && result.errors.length) return { error: { code: 'GRAPHQL_ERROR', message: result.errors.map((error) => error && error.message).filter(Boolean).join('; ').slice(0, 300) } };
1297
+ const counted = result.data && result.data[root];
1298
+ if (!counted || !Number.isInteger(counted.count)) return { error: { code: 'COUNT_MISSING', message: 'the count read returned no count' } };
1299
+ return { count: counted.count, precision: counted.precision || null };
1300
+ }
1301
+
1302
+ async function countCheck() {
1303
+ const customersReceived = (await countLines(path.join(outputDir, 'customers.ndjson'))) || 0;
1304
+ const withheld = (manifest.sidecars || []).includes('customers-withheld-identity') ? ((await countLines(path.join(outputDir, 'customers-withheld-identity.ndjson'))) || 0) : 0;
1305
+ const received = { customers: customersReceived + withheld, orders: (await countLines(path.join(outputDir, 'orders.ndjson'))) || 0 };
1306
+ manifest.counts = {};
1307
+ const rows = [];
1308
+ const stopCodes = [];
1309
+ for (const entity of ['customers', 'orders']) {
1310
+ const expected = await readExactCount(entity);
1311
+ const record = { received: received[entity], ...(entity === 'customers' ? { withheldIdentity: withheld } : {}) };
1312
+ let outcome;
1313
+ if (expected.error) {
1314
+ outcome = 'inexact';
1315
+ Object.assign(record, { error: expected.error });
1316
+ } else if (expected.precision !== 'EXACT') {
1317
+ outcome = 'inexact';
1318
+ Object.assign(record, { expected: expected.count, precision: expected.precision });
1319
+ } else if (received[entity] < expected.count) {
1320
+ outcome = 'short';
1321
+ Object.assign(record, { expected: expected.count, precision: expected.precision });
1322
+ } else {
1323
+ outcome = 'pass';
1324
+ Object.assign(record, { expected: expected.count, precision: expected.precision });
1325
+ }
1326
+ record.outcome = outcome;
1327
+ manifest.counts[entity] = record;
1328
+ if (outcome === 'pass') continue;
1329
+ const code = outcome === 'short' ? 'shopify_extract_count_short' : 'shopify_extract_count_inexact';
1330
+ const pointer = outcome === 'short'
1331
+ ? `counts.${entity}: received ${record.received} < Shopify's exact count ${record.expected} (precision ${record.precision})`
1332
+ : `counts.${entity}: Shopify's count is not exact (${record.error ? `${record.error.code}: ${record.error.message}` : `precision ${record.precision}`}); received ${record.received}`;
1333
+ rows.push(coverageRowFor(orderQueryOf(entity), { artifact: `${RAW_EXTRACT_DIR}/${EXTRACT_MANIFEST_FILE}`, pointer, recoveryAction: `Run shopify-extract.js --retry-failed to read ${entity} again, or decide the shortfall at mapping.` }));
1334
+ stopCodes.push({ code, entity });
1335
+ }
1336
+ if (!stopCodes.length) { await save('counts'); return; }
1337
+ manifest.countFailure = { entities: stopCodes.map((stop) => stop.entity), codes: stopCodes.map((stop) => stop.code) };
1338
+ await save('counts');
1339
+ const result = await upsertAdapterCoverageRows(projectDir, { adapter: 'shopify', rows });
1340
+ throw new ShopifyExtractStop(stopCodes[0].code, `Shopify extract stopped (${stopCodes[0].code}): ${rows.map((row) => row.coverageId).join(', ')} recorded as source-coverage row(s) for the merchant's decision at mapping. Counts: ${JSON.stringify(manifest.counts)}. Requires Import Operator: after any cause is fixed, run \`shopify-extract.js --retry-failed\` to read the dataset again; when the extract completes, record the coverage decision \`provided\` for each row, otherwise show the merchant the row at mapping.`, { coverageIds: rows.map((row) => row.coverageId), ...result });
1341
+ }
1342
+
1343
+ function orderQueryOf(entity) {
1344
+ return entity === 'customers' ? 'customers' : 'orders-core';
1345
+ }
1346
+
1347
+ async function finishExtract() {
1348
+ if (!manifest.order.every((name) => entry(name).state === 'done')) {
1349
+ const open = manifest.order.filter((name) => entry(name).state !== 'done');
1350
+ throw new BulkStop(STOPPING_FAILED_CODE, `The extract cannot finish: ${open.join(', ')} ${open.length === 1 ? 'is' : 'are'} not read (${open.map((name) => `${name} ${entry(name).state}`).join(', ')}). Nothing was marked complete.`, { details: { open } });
1351
+ }
1352
+ await joinFinalFiles();
1353
+ await save('joined');
1354
+ await countCheck();
1355
+ manifest.status = 'complete';
1356
+ manifest.completedAt = iso(now());
1357
+ delete manifest.countFailure;
1358
+ await save('complete');
1359
+ await fsp.rm(stagingDir, { recursive: true, force: true });
1360
+ }
1361
+
1362
+ // -------------------------------------------------------------------------------------------
1363
+ // run()
1364
+ // -------------------------------------------------------------------------------------------
1365
+
1366
+ async function filesPresent() {
1367
+ for (const file of expectedFinalFiles()) {
1368
+ try {
1369
+ await fsp.access(path.join(outputDir, file));
1370
+ } catch {
1371
+ return false;
1372
+ }
1373
+ }
1374
+ return true;
1375
+ }
1376
+
1377
+ async function runInner() {
1378
+ manifest = await readManifest();
1379
+ let storeMatches = !manifest;
1380
+ if (manifest && manifest.store) {
1381
+ try {
1382
+ storeMatches = session.normalizeDomain(manifest.store) === normalizedStore;
1383
+ } catch {
1384
+ storeMatches = false;
1385
+ }
1386
+ }
1387
+ if (manifest && !storeMatches) {
1388
+ const recorded = manifest.store || null;
1389
+ manifest = null;
1390
+ throw new BulkStop('shopify_extract_store_mismatch', `${path.basename(manifestPath)} was read from ${recorded || 'an unrecorded store'}, not ${normalizedStore}. Nothing was read or changed.`, { details: { recorded, store: normalizedStore } });
1391
+ }
1392
+ if (!manifest) {
1393
+ if (!Array.isArray(queries) || !queries.length) throw new Error('queries are required to start a new manifest');
1394
+ manifest = newManifest({ caller, store: normalizedStore, snapshotTime: extract ? snapshotTime : null, queries, previousSidecars, now });
1395
+ await save('created');
1396
+ }
1397
+ if (extract && manifest.status === 'complete') {
1398
+ if (!(await filesPresent())) {
1399
+ throw new BulkStop('shopify_extract_files_missing', `The extract manifest says complete but its final files are missing from ${path.relative(projectDir, outputDir)}. Run shopify-extract.js --catch-up to read the store again.`);
1400
+ }
1401
+ await fsp.rm(stagingDir, { recursive: true, force: true });
1402
+ return { status: 'complete', skipped: true };
1403
+ }
1404
+ if (manifest.lastStop) { delete manifest.lastStop; await save('cleared-stop'); }
1405
+ await settleAll();
1406
+ await cleanLeftovers();
1407
+ await applyResets();
1408
+ for (const name of manifest.order) {
1409
+ if (isStopping(entry(name), caller)) throw stopFor(name, entry(name), null, { later: true });
1410
+ }
1411
+ for (const name of manifest.order) await processQuery(name);
1412
+ if (extract) await finishExtract();
1413
+ else { manifest.status = 'complete'; manifest.completedAt = iso(now()); await save('complete'); }
1414
+ return { status: 'complete' };
1415
+ }
1416
+
1417
+ async function run() {
1418
+ let stop = null;
1419
+ try {
1420
+ const outcome = await runInner();
1421
+ return { ...outcome, manifest };
1422
+ } catch (error) {
1423
+ if (error instanceof BulkStop) stop = error;
1424
+ else if (error instanceof ShopifyExtractStop) stop = new BulkStop(error.code, error.message, { details: error.details });
1425
+ else if (error instanceof ShopifyCliError && error.code === 'source_auth_expired') stop = await authExpiredStop();
1426
+ else if (error instanceof ShopifyCliError) stop = new BulkStop(error.code, error.message, { details: { cli: true } });
1427
+ else throw error;
1428
+ }
1429
+ if (manifest) {
1430
+ manifest.lastStop = { code: stop.code, message: stop.message, status: stop.status, at: iso(now()) };
1431
+ await save('stopped');
1432
+ }
1433
+ return { status: stop.status, code: stop.code, message: stop.message, details: stop.details, manifest };
1434
+ }
1435
+
1436
+ return { run, get manifest() { return manifest; } };
1437
+ }
1438
+
1439
+ module.exports = {
1440
+ QUERIES_DIR,
1441
+ QUERY_CATALOG,
1442
+ QUERY_NAMES,
1443
+ CUSTOMER_QUERIES,
1444
+ ORDER_QUERIES,
1445
+ DENIAL_ATTRIBUTED_QUERIES,
1446
+ MANIFEST_SCHEMA_VERSION,
1447
+ EXTRACT_MANIFEST_FILE,
1448
+ RAW_EXTRACT_DIR,
1449
+ SNAPSHOT_PLACEHOLDER,
1450
+ STATUS_QUERY,
1451
+ POLL_START_MS,
1452
+ POLL_CAP_MS,
1453
+ OVERDUE_MS,
1454
+ MAX_DOWNLOAD_TRIES,
1455
+ MAX_LINK_RERUNS,
1456
+ BulkStop,
1457
+ catalogEntry,
1458
+ entityOf,
1459
+ readQueryFile,
1460
+ generateQueryText,
1461
+ connectionShape,
1462
+ validateJsonlFile,
1463
+ foldBulkJsonl,
1464
+ joinOrderFiles,
1465
+ defaultDownload,
1466
+ registerHandlers,
1467
+ clearRegisteredHandlers,
1468
+ registeredProjection: () => registered.project,
1469
+ createBulkRunner,
1470
+ };