@ecomiq/storefront 2.1.3 → 3.0.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 (317) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -123
  3. package/dist/account-Dx4e3syi.js +258 -0
  4. package/dist/account-forms-AVk71ko7.js +39 -0
  5. package/dist/account-forms.d.ts +13 -0
  6. package/dist/account.d.ts +240 -0
  7. package/dist/address-defaults-BqjRhS82.js +14 -0
  8. package/dist/address-defaults.d.ts +11 -0
  9. package/dist/analytics/analytics-CG1Qagwl.js +148 -0
  10. package/dist/analytics/analytics.d.ts +1 -0
  11. package/dist/analytics/config-DJr-GRhs.js +62 -0
  12. package/dist/analytics/config.d.ts +22 -0
  13. package/dist/analytics/consent-B13rBpBs.js +57 -0
  14. package/dist/analytics/consent-banner-9QvRRy8v.js +239 -0
  15. package/dist/analytics/consent-banner.d.ts +20 -0
  16. package/dist/analytics/cookies-pLozllyB.js +100 -0
  17. package/dist/analytics/cookies.d.ts +6 -0
  18. package/dist/analytics/destinations-iECrlLIr.js +144 -0
  19. package/dist/analytics/events-Dt81tIp1.js +102 -0
  20. package/dist/analytics/events.d.ts +51 -0
  21. package/dist/analytics/tracker-p4yaoOyk.js +51 -0
  22. package/dist/api-cache-DsuIn5hX.js +159 -0
  23. package/dist/bank-accounts-DlEczQQ5.js +81 -0
  24. package/dist/bank-accounts.d.ts +4 -0
  25. package/dist/captcha-DAqaIx8m.js +117 -0
  26. package/dist/captcha.d.ts +34 -0
  27. package/dist/cart-D7DxZ2lD.js +30 -0
  28. package/dist/cart-actions-Bsub_FFG.js +116 -0
  29. package/dist/cart-actions.d.ts +15 -0
  30. package/dist/cart-drawer-B7PPsR69.js +22 -0
  31. package/dist/cart-drawer.d.ts +9 -0
  32. package/dist/cart-form-y9P1r_EX.js +81 -0
  33. package/dist/cart-form.d.ts +24 -0
  34. package/dist/cart-summary-ur2VWKr-.js +89 -0
  35. package/dist/cart-summary.d.ts +31 -0
  36. package/dist/cart.d.ts +4 -0
  37. package/dist/catalog-7gJ-l5hW.js +67 -0
  38. package/dist/catalog-hooks-B7ZP4wYY.js +312 -0
  39. package/dist/catalog-hooks.d.ts +111 -0
  40. package/dist/catalog.d.ts +5 -0
  41. package/dist/checkout-DVWSXANi.js +474 -0
  42. package/dist/checkout-form-CbOIdENC.js +131 -0
  43. package/dist/checkout-form.d.ts +20 -0
  44. package/dist/checkout.d.ts +86 -0
  45. package/dist/complaint-book-BvwLvfx0.js +117 -0
  46. package/dist/complaint-book.d.ts +62 -0
  47. package/dist/culqi-authentication-BGr20vAJ.js +204 -0
  48. package/dist/culqi-authentication.d.ts +15 -0
  49. package/dist/culqi-checkout-CTXpKgp_.js +55 -0
  50. package/dist/culqi-three-ds-HP3mfrvV.js +33 -0
  51. package/dist/culqi-three-ds.d.ts +29 -0
  52. package/dist/customer-avatar-CJXSDroK.js +12 -0
  53. package/dist/customer-avatar.d.ts +5 -0
  54. package/dist/customer-cookies-DHOgFAMV.js +45 -0
  55. package/dist/customer-csrf-C1oDX-Py.js +17 -0
  56. package/dist/customer-csrf.d.ts +3 -0
  57. package/dist/customer-document-fields-C1K-_DAD.js +70 -0
  58. package/dist/customer-document-fields.d.ts +9 -0
  59. package/dist/customer-login-form-C7AC6vXd.js +144 -0
  60. package/dist/customer-login-form.d.ts +17 -0
  61. package/dist/customer-registration-form-BEm_NEfP.js +93 -0
  62. package/dist/customer-registration-form.d.ts +8 -0
  63. package/dist/document-url-CGsAl5Tf.js +9 -0
  64. package/dist/documents-T1mzc_j8.js +38 -0
  65. package/dist/documents.d.ts +16 -0
  66. package/dist/entries/account.d.ts +11 -0
  67. package/dist/entries/account.js +10 -0
  68. package/dist/entries/analytics.d.ts +6 -0
  69. package/dist/entries/analytics.js +5 -0
  70. package/dist/entries/cart.d.ts +8 -0
  71. package/dist/entries/cart.js +7 -0
  72. package/dist/entries/checkout.d.ts +12 -0
  73. package/dist/entries/checkout.js +11 -0
  74. package/dist/entries/order.d.ts +11 -0
  75. package/dist/entries/order.js +11 -0
  76. package/dist/favicon-YpyhVJ9H.js +28 -0
  77. package/dist/favicon.d.ts +4 -0
  78. package/dist/form-BtQcbXlJ.js +18 -0
  79. package/dist/form-contracts-BNpHaTGJ.js +166 -0
  80. package/dist/form-contracts.d.ts +42 -0
  81. package/dist/form.d.ts +3 -0
  82. package/dist/hidden-CCWtOWKR.js +3 -0
  83. package/dist/hidden.d.ts +4 -0
  84. package/dist/index.d.ts +50 -0
  85. package/dist/index.js +50 -0
  86. package/dist/invoice-fields-BG0HjL6T.js +103 -0
  87. package/dist/invoice-fields.d.ts +39 -0
  88. package/dist/links-kFxBZfdb.js +96 -0
  89. package/dist/links.d.ts +21 -0
  90. package/dist/mercadopago-checkout-DC7RXa8k.js +27 -0
  91. package/dist/mercadopago-dialog-UTQev0MG.js +180 -0
  92. package/dist/mercadopago-dialog.d.ts +21 -0
  93. package/dist/money-DtGOtDri.js +32 -0
  94. package/dist/money.d.ts +1 -0
  95. package/dist/optimistic-cart-BveVOHuh.js +53 -0
  96. package/dist/optimistic-cart.d.ts +16 -0
  97. package/dist/order-display-DTt5WBbc.js +112 -0
  98. package/dist/order-display.d.ts +20 -0
  99. package/dist/order-draft-DxV1Uhm3.js +38 -0
  100. package/dist/order-draft.d.ts +16 -0
  101. package/dist/order-pages-Dm6l5m0m.js +38 -0
  102. package/dist/order-pages.d.ts +12 -0
  103. package/dist/order-payment-continuation-D_d5PGA4.js +212 -0
  104. package/dist/order-payment-continuation.d.ts +10 -0
  105. package/dist/order-payment-in-review-x4gdLFHZ.js +65 -0
  106. package/dist/order-payment-in-review.d.ts +5 -0
  107. package/dist/order-status-BJXLJwxq.js +162 -0
  108. package/dist/order-status.d.ts +89 -0
  109. package/dist/order-view-9IlBg5AF.js +62 -0
  110. package/dist/order-view.d.ts +12 -0
  111. package/dist/page-action-Ctkf4xC6.js +7 -0
  112. package/dist/page-seo-a5FJl8x5.js +262 -0
  113. package/dist/page-seo.d.ts +34 -0
  114. package/dist/pages-Ca_Gt6mq.js +150 -0
  115. package/dist/pages.d.ts +45 -0
  116. package/dist/payment-dialog-frame-B-Q_xQ94.js +57 -0
  117. package/dist/payment-logo-BoPaGJc_.js +46 -0
  118. package/dist/payment-logo-svgs-By9lDTLK.js +20 -0
  119. package/dist/payment-logo.d.ts +11 -0
  120. package/dist/payment-logos-BYvdwYyJ.js +23 -0
  121. package/dist/payment-methods-B8ocTgFZ.js +73 -0
  122. package/dist/payment-methods.d.ts +58 -0
  123. package/dist/payment-return-5cjypwIw.js +7 -0
  124. package/dist/place-CmW4hBWY.js +13 -0
  125. package/dist/place.d.ts +4 -0
  126. package/dist/preview-BiIBif3C.js +427 -0
  127. package/dist/preview-address-Cf0sJ-9p.js +21 -0
  128. package/dist/preview-cart-Dg2CVktS.js +376 -0
  129. package/dist/product-preview-BspMAecJ.js +51 -0
  130. package/dist/product-preview.d.ts +5 -0
  131. package/dist/product-variants-BNDHvs1y.js +46 -0
  132. package/dist/product-variants.d.ts +12 -0
  133. package/dist/public-pages-XtwlaLwt.js +194 -0
  134. package/dist/public-pages.d.ts +67 -0
  135. package/dist/registration-CpDcv8ql.js +91 -0
  136. package/dist/registration.d.ts +12 -0
  137. package/dist/request-security-CRsRMgwj.js +76 -0
  138. package/dist/rich-text-M-Ju8RL4.js +9 -0
  139. package/dist/rich-text.d.ts +5 -0
  140. package/dist/route-text-DcJw2SsK.js +9 -0
  141. package/dist/route-text.d.ts +4 -0
  142. package/dist/section-preview-CmsMl3yu.js +83 -0
  143. package/dist/section-preview.d.ts +12 -0
  144. package/dist/sections/account-addresses.d.ts +18 -0
  145. package/dist/sections/account-addresses.js +375 -0
  146. package/dist/sections/account-order.d.ts +12 -0
  147. package/dist/sections/account-order.js +592 -0
  148. package/dist/sections/account-orders.d.ts +8 -0
  149. package/dist/sections/account-orders.js +359 -0
  150. package/dist/sections/account-profile.d.ts +16 -0
  151. package/dist/sections/account-profile.js +123 -0
  152. package/dist/sections/checkout.d.ts +24 -0
  153. package/dist/sections/checkout.js +963 -0
  154. package/dist/sections/complaint-book.d.ts +8 -0
  155. package/dist/sections/complaint-book.js +538 -0
  156. package/dist/sections/design-system.d.ts +1 -0
  157. package/dist/sections/design-system.js +310 -0
  158. package/dist/sections/draft-invoice.d.ts +20 -0
  159. package/dist/sections/draft-invoice.js +158 -0
  160. package/dist/sections/order-tracking.d.ts +19 -0
  161. package/dist/sections/order-tracking.js +141 -0
  162. package/dist/sections-CNUMWTF_.js +77 -0
  163. package/dist/sections.d.ts +19 -0
  164. package/dist/seo-GpDRhAAA.js +78 -0
  165. package/dist/session-CKvmFJyg.js +379 -0
  166. package/dist/session.d.ts +24 -0
  167. package/dist/settings-B0NO2A6Y.js +78 -0
  168. package/dist/settings.d.ts +51 -0
  169. package/dist/source-marker-DhqSkW7n.js +4 -0
  170. package/dist/sources-B-3JFJfb.js +46 -0
  171. package/dist/sources.d.ts +7 -0
  172. package/dist/store-8Q-_LFrQ.js +152 -0
  173. package/dist/store-contact--hY6CoFb.js +19 -0
  174. package/dist/store-contact.d.ts +6 -0
  175. package/dist/store.d.ts +17 -0
  176. package/dist/storefront-language-DrMjVbmk.js +29 -0
  177. package/dist/storefront-language.d.ts +14 -0
  178. package/dist/storefront-text-D25ae1qf.js +11 -0
  179. package/dist/storefront-text-en-ljjjSS4q.js +1030 -0
  180. package/dist/storefront-text-pt-BtHaJLcp.js +1030 -0
  181. package/dist/storefront-text.d.ts +4 -0
  182. package/dist/stripe-dialog-Ev9s3Z62.js +396 -0
  183. package/dist/stripe-dialog.d.ts +30 -0
  184. package/dist/telemetry-HuZXWBPi.js +114 -0
  185. package/dist/telemetry.d.ts +10 -0
  186. package/dist/templates-CAqoNyTW.js +40 -0
  187. package/dist/templates.d.ts +15 -0
  188. package/dist/urls-CpGQPxvf.js +71 -0
  189. package/dist/urls.d.ts +18 -0
  190. package/dist/use-checkout-CZcxXJXi.js +42 -0
  191. package/dist/use-checkout-payment-9R-zacrJ.js +80 -0
  192. package/dist/use-checkout-payment.d.ts +18 -0
  193. package/dist/use-checkout.d.ts +36 -0
  194. package/dist/use-culqi-checkout-CrjLAipU.js +109 -0
  195. package/dist/use-order-payment-BKIz_IO0.js +45 -0
  196. package/dist/use-order-payment.d.ts +18 -0
  197. package/dist/use-payment-token-CErx-tN-.js +105 -0
  198. package/dist/vite-payment-logos-kziu7wKb.js +27 -0
  199. package/dist/vite-payment-logos.d.ts +24 -0
  200. package/dist/vite-public-assets-DW2fgtVb.js +209 -0
  201. package/dist/vite-public-assets.d.ts +29 -0
  202. package/dist/vite-sections-DTBr0-Kg.js +464 -0
  203. package/dist/vite-sections.d.ts +21 -0
  204. package/dist/vite-theme-ui-BMO-CDi3.js +41 -0
  205. package/dist/vite-theme-ui.d.ts +10 -0
  206. package/dist/vite.d.ts +36 -0
  207. package/dist/vite.js +127 -0
  208. package/dist/voucher-payment-CVFDZ1L8.js +66 -0
  209. package/dist/worker-CNi-gzCu.js +86 -0
  210. package/dist/worker.d.ts +27 -0
  211. package/package.json +100 -81
  212. package/src/sections/account-addresses.tsx +215 -0
  213. package/src/sections/account-order.tsx +424 -0
  214. package/src/sections/account-orders.tsx +259 -0
  215. package/src/sections/account-profile.tsx +70 -0
  216. package/src/sections/checkout.tsx +586 -0
  217. package/src/sections/complaint-book.tsx +325 -0
  218. package/src/sections/design-system.tsx +146 -0
  219. package/src/sections/draft-invoice.tsx +105 -0
  220. package/src/sections/order-tracking.tsx +81 -0
  221. package/src/vite-client.d.ts +4 -0
  222. package/bin/ecomiq.mjs +0 -179
  223. package/public/design-bridge.js +0 -318
  224. package/src/api-proxy.ts +0 -194
  225. package/src/auth/create-storefront-auth.ts +0 -94
  226. package/src/auth/ecomiq-oauth-password-client.ts +0 -26
  227. package/src/auth/ecomiq-oauth-password-constants.ts +0 -24
  228. package/src/auth/ecomiq-oauth-password-plugin.ts +0 -294
  229. package/src/auth/ecomiq-oauth-password-types.ts +0 -24
  230. package/src/auth/ecomiq-storefront-sign-in.ts +0 -44
  231. package/src/auth/env.ts +0 -7
  232. package/src/auth/secure-cookies.ts +0 -23
  233. package/src/auth/storefront-auth-base-url.ts +0 -117
  234. package/src/auth/storefront-auth.ts +0 -7
  235. package/src/cart-session.ts +0 -239
  236. package/src/client.ts +0 -48
  237. package/src/cloud-runtime-client.ts +0 -378
  238. package/src/codegen.mjs +0 -789
  239. package/src/components/account/customer-addresses-panel.tsx +0 -678
  240. package/src/components/account/customer-order-detail-panel.tsx +0 -285
  241. package/src/components/account/customer-orders-panel.tsx +0 -192
  242. package/src/components/account/customer-profile-panel.tsx +0 -379
  243. package/src/components/checkout/cart-sync.ts +0 -143
  244. package/src/components/checkout/checkout-contact-section.tsx +0 -76
  245. package/src/components/checkout/checkout-external-update-banner.tsx +0 -15
  246. package/src/components/checkout/checkout-form-controls.tsx +0 -139
  247. package/src/components/checkout/checkout-line-items.tsx +0 -43
  248. package/src/components/checkout/checkout-order-summary.tsx +0 -165
  249. package/src/components/checkout/checkout-payment-section.tsx +0 -212
  250. package/src/components/checkout/checkout-session-view.tsx +0 -564
  251. package/src/components/checkout/checkout-shipping-address-section.tsx +0 -400
  252. package/src/components/checkout/checkout-shipping-section.tsx +0 -98
  253. package/src/components/checkout/checkout-states.tsx +0 -73
  254. package/src/components/checkout/checkout-step-card.tsx +0 -101
  255. package/src/components/checkout/checkout-steps.ts +0 -111
  256. package/src/components/checkout/form-schema.ts +0 -281
  257. package/src/components/checkout/format.ts +0 -15
  258. package/src/components/checkout/index.ts +0 -5
  259. package/src/components/checkout/map-customer-to-checkout.ts +0 -188
  260. package/src/components/checkout/types.ts +0 -41
  261. package/src/components/checkout/use-checkout-customer-prefill.ts +0 -409
  262. package/src/components/checkout/use-checkout-geo.ts +0 -50
  263. package/src/components/checkout/use-checkout-session.ts +0 -640
  264. package/src/components/hero.tsx +0 -291
  265. package/src/config.d.ts +0 -94
  266. package/src/config.mjs +0 -146
  267. package/src/format-money.ts +0 -31
  268. package/src/health.ts +0 -90
  269. package/src/hooks/index.ts +0 -9
  270. package/src/hooks/recently-viewed.ts +0 -125
  271. package/src/index.ts +0 -354
  272. package/src/link.tsx +0 -2
  273. package/src/pages/account/account-page-skeleton.tsx +0 -69
  274. package/src/pages/account/account-page-view.tsx +0 -270
  275. package/src/pages/account/account-shell.tsx +0 -101
  276. package/src/pages/account/parse-account-route.ts +0 -36
  277. package/src/pages/account.tsx +0 -16
  278. package/src/pages/api.$.ts +0 -20
  279. package/src/pages/api.auth.$.ts +0 -16
  280. package/src/pages/checkout.$checkoutId.tsx +0 -60
  281. package/src/pages/checkout.tsx +0 -31
  282. package/src/pages/pages.$pageSlug.tsx +0 -111
  283. package/src/pages/thank-you.tsx +0 -53
  284. package/src/providers/auth.tsx +0 -96
  285. package/src/providers/cart.tsx +0 -275
  286. package/src/providers/ecomiq.ts +0 -137
  287. package/src/providers/index.ts +0 -26
  288. package/src/proxy-api.ts +0 -20
  289. package/src/public-config.ts +0 -24
  290. package/src/review-submission.ts +0 -89
  291. package/src/runtime/context.ts +0 -2
  292. package/src/runtime/default-layout.tsx +0 -64
  293. package/src/runtime/head.ts +0 -149
  294. package/src/runtime/page.tsx +0 -143
  295. package/src/runtime/postcss-browser-stub.mjs +0 -5
  296. package/src/server-config-store.ts +0 -35
  297. package/src/server.ts +0 -301
  298. package/src/storefront-definition/contract.ts +0 -1
  299. package/src/storefront-definition/data.ts +0 -188
  300. package/src/storefront-definition/index.ts +0 -2
  301. package/src/storefront-definition/renderer.tsx +0 -1481
  302. package/src/storefront-layout.ts +0 -59
  303. package/src/storefront-runtime.ts +0 -173
  304. package/src/styles.css +0 -97
  305. package/src/ui/badge.tsx +0 -32
  306. package/src/ui/button.tsx +0 -31
  307. package/src/ui/card.tsx +0 -31
  308. package/src/ui/carousel.tsx +0 -218
  309. package/src/ui/cn.ts +0 -6
  310. package/src/ui/index.ts +0 -8
  311. package/src/ui/separator.tsx +0 -6
  312. package/src/ui/skeleton.tsx +0 -6
  313. package/src/ui/storefront-error.tsx +0 -49
  314. package/src/utils.ts +0 -36
  315. package/src/vite-inline.mjs +0 -263
  316. package/templates/__root.tsx +0 -83
  317. package/templates/router.tsx +0 -19
package/src/codegen.mjs DELETED
@@ -1,789 +0,0 @@
1
- /**
2
- * Codegen de Ecomiq.
3
- *
4
- * Lee `pages/` y `ecomiq.config.js` del proyecto del usuario y genera una app
5
- * interna en `.ecomiq/` que sigue las convenciones de TanStack Start
6
- * (routes con createFileRoute, router.tsx, vite.config.ts). El usuario nunca
7
- * ve ni edita estos archivos: son un artefacto de build, como `.next/`.
8
- *
9
- * Convención de páginas:
10
- * pages/index.tsx → /
11
- * pages/products.$productId.tsx → /products/:productId
12
- * pages/products.index.tsx → /products
13
- * pages/api/$.ts → /api/$ (server route / proxy)
14
- *
15
- * Páginas cerradas del framework (siempre generadas, no overrideables):
16
- * /checkout/ ← redirect a /cart (checkout.index, sin layout padre)
17
- * /checkout/$checkoutId ← flujo de checkout
18
- * /thank-you ← post-compra
19
- * /account/* ← área de cuenta (login/register en template: /login, /register)
20
- * /api/$ ← proxy BFF same-origin
21
- * /api/auth/$ ← Better Auth (handlers del framework)
22
- */
23
- import {
24
- mkdirSync,
25
- readdirSync,
26
- readFileSync,
27
- rmSync,
28
- watch as watchFileSystem,
29
- writeFileSync,
30
- existsSync,
31
- symlinkSync,
32
- lstatSync,
33
- readlinkSync,
34
- unlinkSync,
35
- statSync,
36
- realpathSync,
37
- } from 'node:fs'
38
- import { createRequire } from 'node:module'
39
- import { resolve, join, relative, dirname, isAbsolute, sep } from 'node:path'
40
-
41
- const HEADER = '/* Generado por Ecomiq — no editar. */\n'
42
- const ROUTE_MANIFEST_FILE = 'generated-routes.json'
43
-
44
- /** Rutas reservadas que viven solo en el package (templates no pueden overridear). */
45
- const FRAMEWORK_LOCKED_PAGES = [
46
- {
47
- // index (no `checkout.tsx`): evita que TanStack anide $checkoutId bajo un layout
48
- // que redirige a /cart.
49
- rel: 'checkout.index.tsx',
50
- routeId: '/checkout/',
51
- importFrom: '@ecomiq/storefront/internal/checkout',
52
- },
53
- {
54
- rel: 'checkout.$checkoutId.tsx',
55
- routeId: '/checkout/$checkoutId',
56
- importFrom: '@ecomiq/storefront/internal/checkout-session',
57
- },
58
- {
59
- rel: 'thank-you.tsx',
60
- routeId: '/thank-you',
61
- importFrom: '@ecomiq/storefront/internal/thank-you',
62
- },
63
- {
64
- rel: 'pages.$pageSlug.tsx',
65
- routeId: '/pages/$pageSlug',
66
- importFrom: '@ecomiq/storefront/internal/cms-page',
67
- },
68
- {
69
- rel: 'account.index.tsx',
70
- routeId: '/account/',
71
- importFrom: '@ecomiq/storefront/internal/account',
72
- },
73
- {
74
- rel: 'account.addresses.tsx',
75
- routeId: '/account/addresses',
76
- importFrom: '@ecomiq/storefront/internal/account',
77
- },
78
- {
79
- rel: 'account.orders.tsx',
80
- routeId: '/account/orders',
81
- importFrom: '@ecomiq/storefront/internal/account',
82
- },
83
- {
84
- rel: 'account.orders.$orderId.tsx',
85
- routeId: '/account/orders/$orderId',
86
- importFrom: '@ecomiq/storefront/internal/account',
87
- },
88
- {
89
- rel: 'account.devices.tsx',
90
- routeId: '/account/devices',
91
- importFrom: '@ecomiq/storefront/internal/account',
92
- },
93
- ]
94
-
95
- /** Server routes cerradas del framework (proxy BFF, Better Auth, etc.). */
96
- const FRAMEWORK_LOCKED_API_ROUTES = [
97
- {
98
- rel: 'api/$.ts',
99
- routeId: '/api/$',
100
- importFrom: '@ecomiq/storefront/internal/api-proxy',
101
- },
102
- {
103
- rel: 'api/auth.$.ts',
104
- routeId: '/api/auth/$',
105
- importFrom: '@ecomiq/storefront/internal/auth-api',
106
- },
107
- ]
108
-
109
- export async function generateApp({ cwd, appDir, frameworkRoot, config }) {
110
- const pagesDir = resolve(cwd, 'pages')
111
- if (!existsSync(pagesDir)) {
112
- throw new Error('No existe la carpeta pages/. Crea al menos pages/index.tsx')
113
- }
114
-
115
- const srcDir = join(appDir, 'src')
116
- const routesDir = join(srcDir, 'routes')
117
- mkdirSync(routesDir, { recursive: true })
118
-
119
- // ── 1. dependencias internas resolubles desde .ecomiq (soporta npm, pnpm y monorepos) ──
120
- linkFrameworkDependencies(appDir, frameworkRoot, cwd)
121
-
122
- // ── 2. package.json interno (type: module para que Vite resuelva bien) ──
123
- writeGeneratedFile(
124
- join(appDir, 'package.json'),
125
- JSON.stringify({ name: 'ecomiq-app', private: true, type: 'module' }, null, 2),
126
- )
127
-
128
- // ── 3. tsconfig interno ──
129
- writeGeneratedFile(
130
- join(appDir, 'tsconfig.json'),
131
- JSON.stringify(
132
- {
133
- compilerOptions: {
134
- jsx: 'react-jsx',
135
- module: 'ESNext',
136
- moduleResolution: 'Bundler',
137
- target: 'ES2022',
138
- strict: true,
139
- skipLibCheck: true,
140
- verbatimModuleSyntax: true,
141
- types: ['vite/client'],
142
- },
143
- include: ['src', '../pages', '../lib'],
144
- },
145
- null,
146
- 2,
147
- ),
148
- )
149
-
150
- const publicConfig = {
151
- domain: config.domain,
152
- }
153
- if (config.theme !== undefined) publicConfig.theme = config.theme
154
-
155
- for (const serverOnlyKey of ['api', 'cloud', 'dev', 'deploy', 'env']) {
156
- if (Object.hasOwn(publicConfig, serverOnlyKey)) {
157
- throw new Error(`La clave server-only \`${serverOnlyKey}\` no puede serializarse en app-config.ts`)
158
- }
159
- }
160
-
161
- writeGeneratedFile(
162
- join(srcDir, 'app-config.ts'),
163
- HEADER +
164
- `import type { PublicEcomiqConfig } from '@ecomiq/storefront'\n\n` +
165
- `const config = ${JSON.stringify(publicConfig, null, 2)} satisfies PublicEcomiqConfig\n` +
166
- `export default config\n`,
167
- )
168
-
169
- writeGeneratedFile(
170
- join(srcDir, 'server.ts'),
171
- HEADER +
172
- `import startServer, { createServerEntry } from '@tanstack/react-start/server-entry'\n` +
173
- `import config from '../../ecomiq.config.js'\n` +
174
- `import { registerServerConfig } from '@ecomiq/storefront/internal/server-config'\n` +
175
- `import { handleEcomiqHealth } from '@ecomiq/storefront/internal/health'\n\n` +
176
- `export default createServerEntry({\n` +
177
- ` async fetch(request, ...rest) {\n` +
178
- ` let api = config.api\n` +
179
- ` if (import.meta.env.DEV && config.dev?.apiBaseUrl) {\n` +
180
- ` api = { ...api, baseUrl: config.dev.apiBaseUrl }\n` +
181
- ` }\n` +
182
- ` let cloud = config.cloud\n` +
183
- ` if (import.meta.env.DEV && !cloud?.baseUrl) {\n` +
184
- ` cloud = {\n` +
185
- ` timeoutMs: cloud?.timeoutMs ?? 3_000,\n` +
186
- ` cacheTtlMs: cloud?.cacheTtlMs ?? 15_000,\n` +
187
- ` ...cloud,\n` +
188
- ` baseUrl: 'http://127.0.0.1:8020',\n` +
189
- ` }\n` +
190
- ` }\n` +
191
- ` registerServerConfig({ domain: config.domain, api, cloud })\n` +
192
- ` const health = await handleEcomiqHealth(request)\n` +
193
- ` if (health) return health\n` +
194
- ` return startServer.fetch(request, ...rest)\n` +
195
- ` },\n` +
196
- `})\n`,
197
- )
198
-
199
- // ── 5. styles.css: tokens del framework + fuentes de contenido del usuario ──
200
- const themeOverrides = buildThemeOverrides(config)
201
- writeGeneratedFile(
202
- join(srcDir, 'styles.css'),
203
- HEADER.replace('/*', '/*!') +
204
- `@import '@ecomiq/storefront/styles.css';\n` +
205
- `@source '../../pages';\n` +
206
- `@source '../../components';\n` +
207
- `@source '../../lib';\n` +
208
- `@source '../../layout.tsx';\n` +
209
- (themeOverrides ? `\n${themeOverrides}\n` : ''),
210
- )
211
-
212
- // ── 6. router.tsx ──
213
- writeTemplate(frameworkRoot, srcDir, 'router.tsx')
214
-
215
- // ── 7. __root.tsx (shell HTML + providers) ──
216
- writeTemplate(frameworkRoot, routesDir, '__root.tsx')
217
-
218
- // ── 7b. user-layout.tsx: layout.tsx del usuario si existe, si no el default ──
219
- const hasCustomLayout = existsSync(resolve(cwd, 'layout.tsx')) || existsSync(resolve(cwd, 'layout.jsx'))
220
- writeGeneratedFile(
221
- join(srcDir, 'user-layout.tsx'),
222
- HEADER +
223
- (hasCustomLayout
224
- ? `export { default } from '../../layout'\n`
225
- : `export { default } from '@ecomiq/storefront/internal/default-layout'\n`),
226
- )
227
-
228
- // ── 8. rutas generadas desde pages/ (páginas UI + API server routes) ──
229
- const entries = listPageEntries(pagesDir)
230
- const pageEntries = entries.filter((e) => e.kind === 'page')
231
- const apiEntries = entries.filter((e) => e.kind === 'api')
232
- if (pageEntries.length === 0) {
233
- throw new Error('pages/ está vacío. Crea al menos pages/index.tsx')
234
- }
235
-
236
- assertNoFrameworkPageOverrides(pageEntries)
237
- assertNoFrameworkApiOverrides(apiEntries)
238
-
239
- const desiredRoutes = [
240
- ...pageEntries.map((entry) => entry.rel.replace(/\.jsx$/, '.tsx')),
241
- ...apiEntries.map((entry) => entry.rel),
242
- ...FRAMEWORK_LOCKED_PAGES.map((page) => page.rel),
243
- ...FRAMEWORK_LOCKED_API_ROUTES.map((route) => route.rel),
244
- ].sort()
245
-
246
- for (const entry of pageEntries) {
247
- const routeId = fileToRouteId(entry.rel)
248
- const outFile = join(routesDir, entry.rel.replace(/\.jsx$/, '.tsx'))
249
- mkdirSync(dirname(outFile), { recursive: true })
250
- const importPath = relative(dirname(outFile), join(pagesDir, entry.rel))
251
- .replace(/\\/g, '/')
252
- .replace(/\.(tsx|jsx)$/, '')
253
- writeGeneratedFile(outFile, routeFileSource(routeId, importPath, entry.rel))
254
- }
255
-
256
- for (const entry of apiEntries) {
257
- const routeId = fileToRouteId(entry.rel)
258
- const outFile = join(routesDir, entry.rel)
259
- mkdirSync(dirname(outFile), { recursive: true })
260
- // Extensión explícita: archivos como `$.ts` no resuelven bien sin ella.
261
- const importPath = relative(dirname(outFile), join(pagesDir, entry.rel)).replace(/\\/g, '/')
262
- writeGeneratedFile(outFile, apiRouteFileSource(routeId, importPath))
263
- }
264
-
265
- for (const locked of FRAMEWORK_LOCKED_PAGES) {
266
- const outFile = join(routesDir, locked.rel)
267
- mkdirSync(dirname(outFile), { recursive: true })
268
- writeGeneratedFile(
269
- outFile,
270
- frameworkLockedPageRouteSource(locked.routeId, locked.importFrom, locked.rel),
271
- )
272
- }
273
-
274
- for (const locked of FRAMEWORK_LOCKED_API_ROUTES) {
275
- const outFile = join(routesDir, locked.rel)
276
- mkdirSync(dirname(outFile), { recursive: true })
277
- writeGeneratedFile(
278
- outFile,
279
- apiRouteFileSource(locked.routeId, locked.importFrom),
280
- )
281
- }
282
-
283
- reconcileGeneratedRoutes(appDir, routesDir, desiredRoutes)
284
-
285
- // ── 9. wrangler.jsonc para deploy en Cloudflare Workers ──
286
- const workerName = config.deploy?.name ?? slugify(config.domain ?? 'ecomiq-store')
287
- writeGeneratedFile(
288
- join(appDir, 'wrangler.jsonc'),
289
- JSON.stringify(
290
- {
291
- $schema: 'node_modules/wrangler/config-schema.json',
292
- name: workerName,
293
- main: 'src/server.ts',
294
- compatibility_date: '2026-01-01',
295
- compatibility_flags: ['nodejs_compat'],
296
- observability: {
297
- enabled: false,
298
- head_sampling_rate: 1,
299
- logs: {
300
- enabled: true,
301
- head_sampling_rate: 1,
302
- persist: true,
303
- invocation_logs: true,
304
- },
305
- traces: {
306
- enabled: false,
307
- persist: true,
308
- head_sampling_rate: 1,
309
- },
310
- },
311
- ...(config.deploy?.routes ? { routes: config.deploy.routes } : {}),
312
- vars: {...(config.env ?? {}), BETTER_AUTH_TRUSTED_HOSTS: "localhost,localhost:*,127.0.0.1,127.0.0.1:*,*.ecomiq.app,ecomiq.app,*.juanpablocs.workers.dev,*.aecca.workers.dev"},
313
- },
314
- null,
315
- 2,
316
- ),
317
- )
318
-
319
- // ── 10. .gitignore para que .ecomiq no se versione dentro de sí mismo ──
320
- writeGeneratedFile(join(appDir, '.gitignore'), '*\n')
321
- }
322
-
323
- export function watchPages({
324
- cwd,
325
- appDir,
326
- frameworkRoot,
327
- config,
328
- debounceMs = 75,
329
- /** Intervalo de polling (ms) como respaldo cuando `fs.watch` no emite eventos (p. ej. sandbox). */
330
- pollMs = 0,
331
- onGenerate = () => {},
332
- onError = () => {},
333
- }) {
334
- const pagesDir = resolve(cwd, 'pages')
335
- if (!existsSync(pagesDir)) {
336
- throw new Error('No existe la carpeta pages/. Crea al menos pages/index.tsx')
337
- }
338
-
339
- let closed = false
340
- let dirty = false
341
- let running = false
342
- let timer
343
- let lastPagesSignature = pagesDirSignature(pagesDir)
344
-
345
- async function flush() {
346
- if (running || closed) return
347
- running = true
348
-
349
- while (dirty && !closed) {
350
- dirty = false
351
- try {
352
- await generateApp({ cwd, appDir, frameworkRoot, config })
353
- lastPagesSignature = pagesDirSignature(pagesDir)
354
- onGenerate()
355
- } catch (error) {
356
- onError(error instanceof Error ? error : new Error(String(error)))
357
- }
358
- }
359
-
360
- running = false
361
- }
362
-
363
- function schedule() {
364
- if (closed) return
365
- if (timer) clearTimeout(timer)
366
- timer = setTimeout(() => {
367
- timer = undefined
368
- dirty = true
369
- void flush()
370
- }, debounceMs)
371
- }
372
-
373
- const watcher = watchFileSystem(pagesDir, { recursive: true }, schedule)
374
- watcher.on('error', (error) => onError(error))
375
-
376
- let pollTimer
377
- if (pollMs > 0) {
378
- pollTimer = setInterval(() => {
379
- if (closed) return
380
- const next = pagesDirSignature(pagesDir)
381
- if (next !== lastPagesSignature) {
382
- lastPagesSignature = next
383
- schedule()
384
- }
385
- }, pollMs)
386
- }
387
-
388
- return {
389
- close() {
390
- closed = true
391
- dirty = false
392
- if (timer) clearTimeout(timer)
393
- if (pollTimer) clearInterval(pollTimer)
394
- watcher.close()
395
- },
396
- }
397
- }
398
-
399
- /** Firma ligera de `pages/` para detectar altas/bajas/renombres sin depender de `fs.watch`. */
400
- function pagesDirSignature(pagesDir) {
401
- const parts = []
402
- for (const entry of listPageEntries(pagesDir)) {
403
- const full = join(pagesDir, entry.rel)
404
- parts.push(`${entry.rel}:${statSync(full).mtimeMs}`)
405
- }
406
- return parts.sort().join('|')
407
- }
408
-
409
- /** Lista pages UI (.tsx/.jsx) y API server routes (.ts) de forma recursiva. */
410
- function listPageEntries(pagesDir, prefix = '') {
411
- const entries = []
412
- const dir = prefix ? join(pagesDir, prefix) : pagesDir
413
- for (const name of readdirSync(dir).sort()) {
414
- if (
415
- name.startsWith('.') ||
416
- name === '__tests__' ||
417
- /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(name)
418
- ) continue
419
- const rel = prefix ? `${prefix}/${name}` : name
420
- const full = join(pagesDir, rel)
421
- if (statSync(full).isDirectory()) {
422
- entries.push(...listPageEntries(pagesDir, rel))
423
- continue
424
- }
425
- if (/\.(tsx|jsx)$/.test(name)) entries.push({ kind: 'page', rel })
426
- else if (/\.ts$/.test(name) && !name.endsWith('.d.ts')) entries.push({ kind: 'api', rel })
427
- }
428
- return entries
429
- }
430
-
431
- function reconcileGeneratedRoutes(appDir, routesDir, desiredRoutes) {
432
- const manifestPath = join(appDir, ROUTE_MANIFEST_FILE)
433
- const previousRoutes = readRouteManifest(manifestPath)
434
- const desired = new Set(desiredRoutes)
435
-
436
- for (const relativePath of previousRoutes) {
437
- if (desired.has(relativePath)) continue
438
- const outputPath = ownedRoutePath(routesDir, relativePath)
439
- if (outputPath) rmSync(outputPath, { force: true })
440
- }
441
-
442
- writeGeneratedFile(
443
- manifestPath,
444
- JSON.stringify({ version: 1, routes: desiredRoutes }, null, 2) + '\n',
445
- )
446
- }
447
-
448
- function readRouteManifest(manifestPath) {
449
- if (!existsSync(manifestPath)) return []
450
-
451
- try {
452
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
453
- if (manifest?.version !== 1 || !Array.isArray(manifest.routes)) return []
454
- return manifest.routes.filter((route) => typeof route === 'string')
455
- } catch {
456
- return []
457
- }
458
- }
459
-
460
- function ownedRoutePath(routesDir, relativePath) {
461
- if (
462
- relativePath.length === 0 ||
463
- isAbsolute(relativePath) ||
464
- relativePath.split('/').includes('..')
465
- ) {
466
- return null
467
- }
468
- const outputPath = resolve(routesDir, relativePath)
469
- if (!outputPath.startsWith(resolve(routesDir) + sep)) return null
470
- return outputPath
471
- }
472
-
473
- /**
474
- * 'products.$productId.tsx' → '/products/$productId'
475
- * 'api/$.ts' → '/api/$'
476
- * 'index.tsx' → '/'
477
- */
478
- function fileToRouteId(relPath) {
479
- const withoutExt = relPath.replace(/\.(tsx|jsx|ts)$/, '')
480
- if (withoutExt === 'index') return '/'
481
-
482
- const segments = []
483
- for (const part of withoutExt.split('/')) {
484
- const bits = part.split('.').map((s) => (s === 'index' ? '' : s))
485
- segments.push(...bits.filter(Boolean))
486
- }
487
- return '/' + segments.join('/') + (withoutExt.endsWith('.index') ? '/' : '')
488
- }
489
-
490
- /** Relativo desde routes/<rel> hasta src/app-config. */
491
- function appConfigImportFrom(relPath) {
492
- const nestDepth = relPath.split('/').length - 1
493
- return '../'.repeat(nestDepth + 1) + 'app-config'
494
- }
495
-
496
- /** Código de una ruta interna que envuelve la página del usuario. */
497
- function routeFileSource(routeId, importPath, relPath) {
498
- const appConfigImport = appConfigImportFrom(relPath)
499
-
500
- return (
501
- HEADER +
502
- `import { createFileRoute } from '@tanstack/react-router'\n` +
503
- `import appConfig from '${appConfigImport}'\n` +
504
- `import pageModule from '${importPath}'\n` +
505
- `import { pageToRouteOptions, PageBoundary } from '@ecomiq/storefront/internal/page'\n\n` +
506
- `export const Route = createFileRoute('${routeId}')({\n` +
507
- ` ...pageToRouteOptions(pageModule, appConfig),\n` +
508
- ` component: PageComponent,\n` +
509
- `})\n\n` +
510
- `function PageComponent() {\n` +
511
- ` const data = Route.useLoaderData()\n` +
512
- ` const params = Route.useParams()\n` +
513
- ` const search = Route.useSearch()\n` +
514
- ` return <PageBoundary page={pageModule} data={data} params={params} search={search} />\n` +
515
- `}\n`
516
- )
517
- }
518
-
519
- /** Página cerrada del framework (import desde package, no desde pages/ del usuario). */
520
- function frameworkLockedPageRouteSource(routeId, importFrom, relPath) {
521
- const appConfigImport = appConfigImportFrom(relPath)
522
-
523
- return (
524
- HEADER +
525
- `import { createFileRoute } from '@tanstack/react-router'\n` +
526
- `import appConfig from '${appConfigImport}'\n` +
527
- `import pageModule from '${importFrom}'\n` +
528
- `import { pageToRouteOptions, PageBoundary } from '@ecomiq/storefront/internal/page'\n\n` +
529
- `export const Route = createFileRoute('${routeId}')({\n` +
530
- ` ...pageToRouteOptions(pageModule, appConfig),\n` +
531
- ` component: PageComponent,\n` +
532
- `})\n\n` +
533
- `function PageComponent() {\n` +
534
- ` const data = Route.useLoaderData()\n` +
535
- ` const params = Route.useParams()\n` +
536
- ` const search = Route.useSearch()\n` +
537
- ` return <PageBoundary page={pageModule} data={data} params={params} search={search} />\n` +
538
- `}\n`
539
- )
540
- }
541
-
542
- function assertNoFrameworkPageOverrides(pageEntries) {
543
- const reserved = new Map(
544
- FRAMEWORK_LOCKED_PAGES.map((page) => [page.routeId, page.rel]),
545
- )
546
- // Overrides / alias legados
547
- reserved.set('/checkout', 'checkout.tsx')
548
-
549
- for (const entry of pageEntries) {
550
- const routeId = fileToRouteId(entry.rel)
551
- if (!reserved.has(routeId)) continue
552
- throw new Error(
553
- `La ruta ${routeId} es reservada por Ecomiq (página cerrada). ` +
554
- `Elimina pages/${entry.rel}; vive en @ecomiq/storefront (checkout, thank-you, CMS).`,
555
- )
556
- }
557
- }
558
-
559
- function assertNoFrameworkApiOverrides(apiEntries) {
560
- const reserved = new Map(
561
- FRAMEWORK_LOCKED_API_ROUTES.map((route) => [route.routeId, route.rel]),
562
- )
563
-
564
- for (const entry of apiEntries) {
565
- const routeId = fileToRouteId(entry.rel)
566
- if (!reserved.has(routeId)) continue
567
- throw new Error(
568
- `La ruta ${routeId} es reservada por Ecomiq. ` +
569
- `Elimina pages/${entry.rel}; ya la genera @ecomiq/storefront ` +
570
- `(proxy BFF /api/$ y Better Auth /api/auth/$). ` +
571
- `Puedes añadir otras rutas en pages/api/.`,
572
- )
573
- }
574
- }
575
-
576
- /** Server route: reexporta GET/POST/... del módulo del usuario. */
577
- function apiRouteFileSource(routeId, importPath) {
578
- return (
579
- HEADER +
580
- `import { createFileRoute } from '@tanstack/react-router'\n` +
581
- `import * as api from '${importPath}'\n\n` +
582
- `export const Route = createFileRoute('${routeId}')({\n` +
583
- ` server: {\n` +
584
- ` handlers: {\n` +
585
- ` ...(api.GET ? { GET: api.GET } : {}),\n` +
586
- ` ...(api.POST ? { POST: api.POST } : {}),\n` +
587
- ` ...(api.PUT ? { PUT: api.PUT } : {}),\n` +
588
- ` ...(api.PATCH ? { PATCH: api.PATCH } : {}),\n` +
589
- ` ...(api.DELETE ? { DELETE: api.DELETE } : {}),\n` +
590
- ` },\n` +
591
- ` },\n` +
592
- `})\n`
593
- )
594
- }
595
-
596
- function buildThemeOverrides(config) {
597
- const theme = config.theme ?? {}
598
- const map = {
599
- primary: '--primary',
600
- primaryForeground: '--primary-foreground',
601
- radius: '--radius',
602
- background: '--background',
603
- foreground: '--foreground',
604
- accent: '--accent',
605
- }
606
- const lines = Object.entries(map)
607
- .filter(([key]) => theme[key])
608
- .map(([key, cssVar]) => ` ${cssVar}: ${theme[key]};`)
609
- if (lines.length === 0) return ''
610
- return `:root {\n${lines.join('\n')}\n}`
611
- }
612
-
613
- function writeTemplate(frameworkRoot, targetDir, name) {
614
- const src = resolve(frameworkRoot, 'templates', name)
615
- writeGeneratedFile(join(targetDir, name), readFileSync(src, 'utf8'))
616
- }
617
-
618
- function writeGeneratedFile(path, contents) {
619
- if (existsSync(path) && readFileSync(path, 'utf8') === contents) return
620
- mkdirSync(dirname(path), { recursive: true })
621
- writeFileSync(path, contents)
622
- }
623
-
624
- /**
625
- * Crea `.ecomiq/node_modules` con symlinks a las dependencias del framework.
626
- *
627
- * Workerd (Cloudflare Vite plugin) resuelve desde la raíz `.ecomiq`, así que
628
- * no basta con el hoisting del proyecto: hay que materializar los packages
629
- * ahí. En installs npm/pnpm/yarn las deps suelen vivir en el node_modules del
630
- * proyecto (o en el store de pnpm), no bajo `@ecomiq/storefront/node_modules`.
631
- */
632
- function linkFrameworkDependencies(appDir, frameworkRoot, projectRoot = dirname(appDir)) {
633
- const target = join(appDir, 'node_modules')
634
- mkdirSync(target, { recursive: true })
635
-
636
- linkInto(join(target, '@ecomiq'), 'storefront', frameworkRoot)
637
- const legacyFramework = join(target, '@ecomiq', 'framework')
638
- try {
639
- if (lstatSync(legacyFramework).isSymbolicLink()) unlinkSync(legacyFramework)
640
- } catch {
641
- /* no existía */
642
- }
643
-
644
- const resolveFrom = [
645
- join(frameworkRoot, 'package.json'),
646
- join(projectRoot, 'package.json'),
647
- join(frameworkRoot, 'src', 'codegen.mjs'),
648
- ]
649
-
650
- const manifestPath = join(frameworkRoot, 'package.json')
651
- let depNames = []
652
- try {
653
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
654
- depNames = [
655
- ...Object.keys(manifest.dependencies ?? {}),
656
- ...Object.keys(manifest.peerDependencies ?? {}),
657
- ]
658
- } catch {
659
- depNames = []
660
- }
661
-
662
- // Transitive crítico que Vite/TanStack piden explícitamente en SSR.
663
- for (const extra of ['@tanstack/react-store', '@tanstack/history', '@tanstack/router-core']) {
664
- if (!depNames.includes(extra)) depNames.push(extra)
665
- }
666
-
667
- for (const name of depNames) {
668
- const pkgDir = resolvePackageDir(name, resolveFrom)
669
- if (!pkgDir) continue
670
- linkPackage(target, name, pkgDir)
671
- }
672
-
673
- // Fallback: mirror de node_modules locales (monorepo / nested installs).
674
- for (const source of [join(frameworkRoot, 'node_modules'), join(projectRoot, 'node_modules')]) {
675
- linkNodeModulesTree(source, target)
676
- }
677
- }
678
-
679
- function linkPackage(targetRoot, packageName, packageDir) {
680
- if (packageName.startsWith('@')) {
681
- const [scope, name] = packageName.split('/')
682
- if (!scope || !name) return
683
- linkInto(join(targetRoot, scope), name, packageDir)
684
- return
685
- }
686
- linkInto(targetRoot, packageName, packageDir)
687
- }
688
-
689
- function linkNodeModulesTree(source, target) {
690
- if (!existsSync(source)) return
691
- for (const entry of readdirSync(source)) {
692
- if (entry === '.bin' || entry.startsWith('.')) continue
693
- if (entry.startsWith('@')) {
694
- const scopeDir = join(source, entry)
695
- if (!statSync(scopeDir).isDirectory()) continue
696
- for (const scoped of readdirSync(scopeDir)) {
697
- linkInto(join(target, entry), scoped, join(scopeDir, scoped))
698
- }
699
- } else {
700
- linkInto(target, entry, join(source, entry))
701
- }
702
- }
703
- }
704
-
705
- /**
706
- * Resuelve el directorio raíz de un package usando la resolución de Node
707
- * (funciona con hoisting npm/yarn y el store de pnpm).
708
- */
709
- function resolvePackageDir(packageName, fromFiles) {
710
- for (const fromFile of fromFiles) {
711
- if (!existsSync(fromFile)) continue
712
- try {
713
- const require = createRequire(fromFile)
714
- try {
715
- return dirname(require.resolve(`${packageName}/package.json`))
716
- } catch {
717
- const entry = require.resolve(packageName)
718
- return findPackageRoot(entry, packageName)
719
- }
720
- } catch {
721
- /* probar siguiente origen */
722
- }
723
- }
724
- return null
725
- }
726
-
727
- function findPackageRoot(startPath, packageName) {
728
- let dir = dirname(startPath)
729
- while (true) {
730
- const pkgPath = join(dir, 'package.json')
731
- if (existsSync(pkgPath)) {
732
- try {
733
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))
734
- if (pkg.name === packageName) return dir
735
- } catch {
736
- /* ignore */
737
- }
738
- }
739
- const parent = dirname(dir)
740
- if (parent === dir) return null
741
- dir = parent
742
- }
743
- }
744
-
745
- function linkInto(dir, name, targetPath) {
746
- mkdirSync(dir, { recursive: true })
747
- const linkPath = join(dir, name)
748
-
749
- // Target absoluto y ya resuelto: los symlinks relativos se rompen cuando un
750
- // directorio padre es a su vez un symlink (p. ej. /var → /private/var en macOS).
751
- let destination
752
- try {
753
- destination = realpathSync(targetPath)
754
- } catch {
755
- destination = resolve(targetPath)
756
- }
757
-
758
- try {
759
- const current = lstatSync(linkPath)
760
- if (current.isSymbolicLink()) {
761
- let resolved
762
- try {
763
- resolved = realpathSync(linkPath)
764
- } catch {
765
- resolved = resolve(dir, readlinkSync(linkPath))
766
- }
767
- if (resolved === destination) return
768
- unlinkSync(linkPath)
769
- } else if (current.isDirectory() || current.isFile()) {
770
- return
771
- }
772
- } catch {
773
- /* no existe aún */
774
- }
775
- try {
776
- symlinkSync(destination, linkPath, 'junction')
777
- } catch {
778
- /* FS sin symlinks: la resolución cae al hoisting */
779
- }
780
- }
781
-
782
- function slugify(s) {
783
- return s
784
- .toLowerCase()
785
- .normalize('NFD')
786
- .replace(/[\u0300-\u036f]/g, '')
787
- .replace(/[^a-z0-9]+/g, '-')
788
- .replace(/^-|-$/g, '')
789
- }