@farm.js/core 0.1.0-beta.1 → 0.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-runtime.d.mts +1 -1
  3. package/dist/agent-runtime.d.ts +1 -1
  4. package/dist/api/route-manager.cjs +97 -5
  5. package/dist/api/route-manager.cjs.map +1 -1
  6. package/dist/api/route-manager.d.mts +3 -2
  7. package/dist/api/route-manager.d.ts +3 -2
  8. package/dist/api/route-manager.mjs +8 -8
  9. package/dist/api/runtime.cjs +441 -5
  10. package/dist/api/runtime.cjs.map +1 -1
  11. package/dist/api/runtime.d.mts +2 -16
  12. package/dist/api/runtime.d.ts +2 -16
  13. package/dist/api/runtime.mjs +7 -1
  14. package/dist/api.cjs +579 -263
  15. package/dist/api.cjs.map +1 -1
  16. package/dist/api.d.mts +4 -147
  17. package/dist/api.d.ts +4 -147
  18. package/dist/api.mjs +30 -20
  19. package/dist/{app-BiX4qb-d.d.mts → app-BB3Iu3xh.d.mts} +2 -2
  20. package/dist/{app-CFRNJXP1.d.ts → app-DOKxo-LH.d.ts} +2 -2
  21. package/dist/app-markdown.cjs +1 -1
  22. package/dist/app-markdown.cjs.map +1 -1
  23. package/dist/app-markdown.d.mts +1 -1
  24. package/dist/app-markdown.d.ts +1 -1
  25. package/dist/app-markdown.mjs +1 -1
  26. package/dist/cache.cjs +19 -0
  27. package/dist/cache.cjs.map +1 -1
  28. package/dist/cache.d.mts +21 -1
  29. package/dist/cache.d.ts +21 -1
  30. package/dist/cache.mjs +5 -3
  31. package/dist/{chunk-QF4PHCMA.mjs → chunk-2ED5Q2GH.mjs} +3 -3
  32. package/dist/chunk-2ED5Q2GH.mjs.map +1 -0
  33. package/dist/{chunk-GZP5W4K3.mjs → chunk-32W4QEJP.mjs} +1 -1
  34. package/dist/chunk-32W4QEJP.mjs.map +1 -0
  35. package/dist/{chunk-AGS7UJ52.mjs → chunk-45LKHSHJ.mjs} +2 -2
  36. package/dist/{chunk-TU4YJICB.mjs → chunk-5FW6PQ3J.mjs} +1 -1
  37. package/dist/{chunk-TU4YJICB.mjs.map → chunk-5FW6PQ3J.mjs.map} +1 -1
  38. package/dist/{chunk-TRORP7E4.mjs → chunk-5QH4IKY3.mjs} +2 -2
  39. package/dist/{chunk-RKI6TN3A.mjs → chunk-6VS6CKAV.mjs} +2 -2
  40. package/dist/chunk-6VS6CKAV.mjs.map +1 -0
  41. package/dist/{chunk-25D7G34K.mjs → chunk-6WXJ54TC.mjs} +4 -4
  42. package/dist/{chunk-3QJO55ZF.mjs → chunk-BIOIOWXZ.mjs} +5 -3
  43. package/dist/{chunk-3QJO55ZF.mjs.map → chunk-BIOIOWXZ.mjs.map} +1 -1
  44. package/dist/{chunk-QFQRHRZS.mjs → chunk-C33RALN7.mjs} +75 -11
  45. package/dist/chunk-C33RALN7.mjs.map +1 -0
  46. package/dist/{chunk-B6N4ZB2H.mjs → chunk-CSU4KJJF.mjs} +3 -3
  47. package/dist/{chunk-JN3UU635.mjs → chunk-EJ7T4TPB.mjs} +2 -2
  48. package/dist/chunk-EJ7T4TPB.mjs.map +1 -0
  49. package/dist/{chunk-ZJQNATYV.mjs → chunk-FRPWCMMG.mjs} +3 -3
  50. package/dist/chunk-FRPWCMMG.mjs.map +1 -0
  51. package/dist/{chunk-PRNYWD7K.mjs → chunk-G5I34UA6.mjs} +67 -239
  52. package/dist/chunk-G5I34UA6.mjs.map +1 -0
  53. package/dist/{chunk-QM6VV26B.mjs → chunk-GQVGIUSN.mjs} +3 -3
  54. package/dist/{chunk-QM6VV26B.mjs.map → chunk-GQVGIUSN.mjs.map} +1 -1
  55. package/dist/{chunk-UREJA4GZ.mjs → chunk-GXASWWJU.mjs} +1 -1
  56. package/dist/{chunk-UREJA4GZ.mjs.map → chunk-GXASWWJU.mjs.map} +1 -1
  57. package/dist/{chunk-4PTK6KT4.mjs → chunk-GZWT6VI5.mjs} +22 -4
  58. package/dist/chunk-GZWT6VI5.mjs.map +1 -0
  59. package/dist/{chunk-JLWMCADZ.mjs → chunk-HZYXGV4K.mjs} +2 -2
  60. package/dist/chunk-JNYVN7YP.mjs +10 -0
  61. package/dist/chunk-JNYVN7YP.mjs.map +1 -0
  62. package/dist/{chunk-YHU7SS6L.mjs → chunk-LG3YINQN.mjs} +11 -11
  63. package/dist/chunk-LWMGIEJA.mjs +593 -0
  64. package/dist/chunk-LWMGIEJA.mjs.map +1 -0
  65. package/dist/{chunk-HXP3ZSPC.mjs → chunk-MH6FKW2I.mjs} +3 -3
  66. package/dist/{chunk-O3HADRW6.mjs → chunk-MIUW47JX.mjs} +2 -2
  67. package/dist/{chunk-O3HADRW6.mjs.map → chunk-MIUW47JX.mjs.map} +1 -1
  68. package/dist/{chunk-6XDUHOEM.mjs → chunk-NRRFGX45.mjs} +3 -3
  69. package/dist/{chunk-G3B5BRDY.mjs → chunk-OHC6VCDI.mjs} +24 -25
  70. package/dist/{chunk-G3B5BRDY.mjs.map → chunk-OHC6VCDI.mjs.map} +1 -1
  71. package/dist/{chunk-S2XHZS7W.mjs → chunk-QGQX7SFC.mjs} +2 -2
  72. package/dist/chunk-QGQX7SFC.mjs.map +1 -0
  73. package/dist/{chunk-TXCFGOHW.mjs → chunk-SHRJG6OG.mjs} +25 -1
  74. package/dist/chunk-SHRJG6OG.mjs.map +1 -0
  75. package/dist/{chunk-UHE2TTLK.mjs → chunk-T543TMFY.mjs} +8 -8
  76. package/dist/chunk-T543TMFY.mjs.map +1 -0
  77. package/dist/{chunk-SXZTEK3V.mjs → chunk-UXUAWNO5.mjs} +2 -2
  78. package/dist/{chunk-Y2OJJD7R.mjs → chunk-XIVV5IWN.mjs} +7 -9
  79. package/dist/chunk-XIVV5IWN.mjs.map +1 -0
  80. package/dist/{chunk-CHFHNEMO.mjs → chunk-XJSHJN4M.mjs} +41 -42
  81. package/dist/chunk-XJSHJN4M.mjs.map +1 -0
  82. package/dist/{chunk-Y7A27276.mjs → chunk-XUBZ7JI4.mjs} +178 -15
  83. package/dist/chunk-XUBZ7JI4.mjs.map +1 -0
  84. package/dist/{chunk-OYXO65LI.mjs → chunk-YW7OBE6Q.mjs} +4 -4
  85. package/dist/chunk-YW7OBE6Q.mjs.map +1 -0
  86. package/dist/{chunk-SOU3Q3ZA.mjs → chunk-ZZ57EH5Z.mjs} +1 -1
  87. package/dist/chunk-ZZ57EH5Z.mjs.map +1 -0
  88. package/dist/{client-D_yUjVhe.d.mts → client-DiViK9yK.d.mts} +33 -7
  89. package/dist/{client-Dkc03WP8.d.ts → client-DpEBJbts.d.ts} +33 -7
  90. package/dist/{client-plugins-BZnpeTGA.d.ts → client-plugins-CTnsZz_A.d.ts} +1 -0
  91. package/dist/{client-plugins-g4bzuCmo.d.mts → client-plugins-Cnr0D3kk.d.mts} +1 -0
  92. package/dist/client-plugins.d.mts +1 -1
  93. package/dist/client-plugins.d.ts +1 -1
  94. package/dist/client.cjs +302 -54
  95. package/dist/client.cjs.map +1 -1
  96. package/dist/client.d.mts +54 -2
  97. package/dist/client.d.ts +54 -2
  98. package/dist/client.mjs +20 -16
  99. package/dist/config.d.mts +1 -1
  100. package/dist/config.d.ts +1 -1
  101. package/dist/cron.cjs.map +1 -1
  102. package/dist/cron.mjs +1 -1
  103. package/dist/{devtools-AE4RVXCM.mjs → devtools-HE4FTUDN.mjs} +10 -10
  104. package/dist/{devtools-client-6WPY2AQU.mjs → devtools-client-3XRTBND5.mjs} +2 -11
  105. package/dist/devtools-client-3XRTBND5.mjs.map +1 -0
  106. package/dist/docs.cjs +3 -1
  107. package/dist/docs.cjs.map +1 -1
  108. package/dist/docs.mjs +10 -10
  109. package/dist/i18n/server.cjs +2 -2
  110. package/dist/i18n/server.cjs.map +1 -1
  111. package/dist/i18n/server.mjs +1 -1
  112. package/dist/index.cjs +791 -317
  113. package/dist/index.cjs.map +1 -1
  114. package/dist/index.d.mts +11 -11
  115. package/dist/index.d.ts +11 -11
  116. package/dist/index.mjs +125 -110
  117. package/dist/index.mjs.map +1 -1
  118. package/dist/integrations.d.mts +1 -1
  119. package/dist/integrations.d.ts +1 -1
  120. package/dist/internal/build-runtime.cjs +162 -60
  121. package/dist/internal/build-runtime.cjs.map +1 -1
  122. package/dist/internal/build-runtime.d.mts +3 -3
  123. package/dist/internal/build-runtime.d.ts +3 -3
  124. package/dist/internal/build-runtime.mjs +26 -25
  125. package/dist/internal/client-runtime.cjs.map +1 -1
  126. package/dist/internal/client-runtime.mjs +1 -1
  127. package/dist/internal/config-runtime.cjs +1 -1
  128. package/dist/internal/config-runtime.cjs.map +1 -1
  129. package/dist/internal/config-runtime.d.mts +2 -2
  130. package/dist/internal/config-runtime.d.ts +2 -2
  131. package/dist/internal/config-runtime.mjs +9 -9
  132. package/dist/internal/production-runtime.cjs +3 -3
  133. package/dist/internal/production-runtime.cjs.map +1 -1
  134. package/dist/internal/production-runtime.d.mts +3 -3
  135. package/dist/internal/production-runtime.d.ts +3 -3
  136. package/dist/internal/production-runtime.mjs +8 -8
  137. package/dist/{metadata-C9NZxMDW.d.mts → metadata-Dp8AdvsB.d.mts} +1 -1
  138. package/dist/{metadata-DAXRaOHx.d.ts → metadata-eoVmHoyv.d.ts} +1 -1
  139. package/dist/middleware.cjs +2 -2
  140. package/dist/middleware.cjs.map +1 -1
  141. package/dist/middleware.d.mts +3 -3
  142. package/dist/middleware.d.ts +3 -3
  143. package/dist/middleware.mjs +3 -3
  144. package/dist/navigation.cjs.map +1 -1
  145. package/dist/navigation.mjs +3 -3
  146. package/dist/{nitro-KME62MWG.mjs → nitro-QO5LV6QK.mjs} +11 -13
  147. package/dist/{nitro-KME62MWG.mjs.map → nitro-QO5LV6QK.mjs.map} +1 -1
  148. package/dist/plugin.cjs +119 -39
  149. package/dist/plugin.cjs.map +1 -1
  150. package/dist/plugin.d.mts +1 -1
  151. package/dist/plugin.d.ts +1 -1
  152. package/dist/plugin.mjs +22 -21
  153. package/dist/{production-runtime-DRkCHUvJ.d.ts → production-runtime-BqTnUTai.d.ts} +1 -1
  154. package/dist/{production-runtime-flrjp_nC.d.mts → production-runtime-DtDdG9fc.d.mts} +1 -1
  155. package/dist/routes.cjs.map +1 -1
  156. package/dist/routes.d.mts +1 -1
  157. package/dist/routes.d.ts +1 -1
  158. package/dist/routes.mjs +4 -4
  159. package/dist/runtime-C1B7pSGT.d.mts +207 -0
  160. package/dist/runtime-CdPHt0bv.d.ts +207 -0
  161. package/dist/server-action-security.cjs.map +1 -1
  162. package/dist/server-action-security.mjs +2 -2
  163. package/dist/server-fn-client.cjs.map +1 -1
  164. package/dist/server-fn-client.mjs +1 -1
  165. package/dist/server-fn.cjs.map +1 -1
  166. package/dist/server-fn.mjs +3 -3
  167. package/dist/server-plugins.d.mts +2 -2
  168. package/dist/server-plugins.d.ts +2 -2
  169. package/dist/server-query-client.cjs.map +1 -1
  170. package/dist/server-query-client.mjs +4 -4
  171. package/dist/server-query.cjs.map +1 -1
  172. package/dist/server-query.mjs +5 -5
  173. package/dist/server.cjs +148 -43
  174. package/dist/server.cjs.map +1 -1
  175. package/dist/server.d.mts +6 -6
  176. package/dist/server.d.ts +6 -6
  177. package/dist/server.mjs +36 -31
  178. package/dist/server.mjs.map +1 -1
  179. package/dist/testing.cjs +95 -5
  180. package/dist/testing.cjs.map +1 -1
  181. package/dist/testing.d.mts +3 -3
  182. package/dist/testing.d.ts +3 -3
  183. package/dist/testing.mjs +18 -18
  184. package/dist/{utils-DOXXivjL.d.mts → utils-8USa5BiY.d.mts} +1 -1
  185. package/dist/{utils-DA1yo54_.d.ts → utils-DKJb6K6G.d.ts} +1 -1
  186. package/dist/version.cjs +36 -0
  187. package/dist/version.cjs.map +1 -0
  188. package/dist/version.d.mts +3 -0
  189. package/dist/version.d.ts +3 -0
  190. package/dist/version.mjs +8 -0
  191. package/dist/version.mjs.map +1 -0
  192. package/dist/vite.cjs +126 -40
  193. package/dist/vite.cjs.map +1 -1
  194. package/dist/vite.d.mts +1 -1
  195. package/dist/vite.d.ts +1 -1
  196. package/dist/vite.mjs +22 -21
  197. package/dist/workflows.cjs +6 -8
  198. package/dist/workflows.cjs.map +1 -1
  199. package/dist/workflows.mjs +1 -1
  200. package/package.json +12 -5
  201. package/types/client.d.ts +136 -13
  202. package/dist/chunk-4PTK6KT4.mjs.map +0 -1
  203. package/dist/chunk-CHFHNEMO.mjs.map +0 -1
  204. package/dist/chunk-EVGBEZDF.mjs +0 -215
  205. package/dist/chunk-EVGBEZDF.mjs.map +0 -1
  206. package/dist/chunk-GZP5W4K3.mjs.map +0 -1
  207. package/dist/chunk-JN3UU635.mjs.map +0 -1
  208. package/dist/chunk-OYXO65LI.mjs.map +0 -1
  209. package/dist/chunk-PRNYWD7K.mjs.map +0 -1
  210. package/dist/chunk-QF4PHCMA.mjs.map +0 -1
  211. package/dist/chunk-QFQRHRZS.mjs.map +0 -1
  212. package/dist/chunk-RKI6TN3A.mjs.map +0 -1
  213. package/dist/chunk-S2XHZS7W.mjs.map +0 -1
  214. package/dist/chunk-SOU3Q3ZA.mjs.map +0 -1
  215. package/dist/chunk-TXCFGOHW.mjs.map +0 -1
  216. package/dist/chunk-UHE2TTLK.mjs.map +0 -1
  217. package/dist/chunk-Y2OJJD7R.mjs.map +0 -1
  218. package/dist/chunk-Y7A27276.mjs.map +0 -1
  219. package/dist/chunk-ZJQNATYV.mjs.map +0 -1
  220. package/dist/devtools-client-6WPY2AQU.mjs.map +0 -1
  221. /package/dist/{chunk-AGS7UJ52.mjs.map → chunk-45LKHSHJ.mjs.map} +0 -0
  222. /package/dist/{chunk-TRORP7E4.mjs.map → chunk-5QH4IKY3.mjs.map} +0 -0
  223. /package/dist/{chunk-25D7G34K.mjs.map → chunk-6WXJ54TC.mjs.map} +0 -0
  224. /package/dist/{chunk-B6N4ZB2H.mjs.map → chunk-CSU4KJJF.mjs.map} +0 -0
  225. /package/dist/{chunk-JLWMCADZ.mjs.map → chunk-HZYXGV4K.mjs.map} +0 -0
  226. /package/dist/{chunk-YHU7SS6L.mjs.map → chunk-LG3YINQN.mjs.map} +0 -0
  227. /package/dist/{chunk-HXP3ZSPC.mjs.map → chunk-MH6FKW2I.mjs.map} +0 -0
  228. /package/dist/{chunk-6XDUHOEM.mjs.map → chunk-NRRFGX45.mjs.map} +0 -0
  229. /package/dist/{chunk-SXZTEK3V.mjs.map → chunk-UXUAWNO5.mjs.map} +0 -0
  230. /package/dist/{devtools-AE4RVXCM.mjs.map → devtools-HE4FTUDN.mjs.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/integration-client.ts","../src/api/client.ts"],"sourcesContent":["import type {\n FarmIntegrationAPI,\n FarmIntegrationAPIBodyFormat,\n FarmIntegrationAPIOperation,\n} from \"./integration-api\";\nimport type { FarmIntegration as FarmIntegrationDefinition } from \"./integrations\";\n\n/**\n * Small per-call integration metadata. When sent from a browser, values are\n * client-controlled and should be validated before authorization decisions.\n */\nexport type IntegrationClientData = Record<string, unknown>;\n\nexport type IntegrationClientOptions = {\n baseURL?: string;\n headers?: Record<string, string>;\n credentials?: RequestCredentials;\n data?: IntegrationClientData;\n isServer?: false | undefined;\n};\n\ntype IntegrationRequestOptionsBase = {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n credentials?: RequestCredentials;\n data?: IntegrationClientData;\n};\n\nexport type IntegrationClientRequestOptions = IntegrationRequestOptionsBase;\n\nexport type IntegrationServerRequestLike =\n | Request\n | {\n url?: string;\n headers?: HeadersInit;\n };\n\nexport type IntegrationServerClientOptions = Omit<IntegrationClientOptions, \"isServer\"> & {\n isServer: true;\n request?: IntegrationServerRequestLike;\n forwardHeaders?: boolean | readonly string[];\n};\n\nexport type IntegrationServerClientRequestOptions = IntegrationRequestOptionsBase & {\n baseURL?: string;\n request?: IntegrationServerRequestLike;\n forwardHeaders?: boolean | readonly string[];\n};\n\nexport class IntegrationClientError<TData = unknown> extends Error {\n readonly status: number;\n readonly response: Response;\n readonly data: TData | undefined;\n\n constructor(message: string, response: Response, data?: TData) {\n super(message);\n this.name = \"IntegrationClientError\";\n this.status = response.status;\n this.response = response;\n this.data = data;\n }\n}\n\nexport type IntegrationOperationResult<\n TData = unknown,\n TError = IntegrationClientError<unknown> | Error,\n> = {\n data: TData | null;\n error: TError | null;\n};\n\ntype ExtractOperationBody<T> = T extends {\n __types?: { body: infer TBody };\n}\n ? TBody\n : never;\n\ntype ExtractOperationQuery<T> = T extends {\n __types?: { query: infer TQuery };\n}\n ? TQuery\n : never;\n\ntype ExtractOperationResponse<T> = T extends {\n __types?: { response: infer TResponse };\n}\n ? TResponse\n : unknown;\n\nexport type InferIntegrationOperationBody<T> = ExtractOperationBody<T>;\nexport type InferIntegrationOperationQuery<T> = ExtractOperationQuery<T>;\nexport type InferIntegrationOperationResponse<T> = ExtractOperationResponse<T>;\n\ntype IsNever<T> = [T] extends [never] ? true : false;\n\ntype OperationInput<T> =\n IsNever<ExtractOperationBody<T>> extends true\n ? IsNever<ExtractOperationQuery<T>> extends true\n ? {}\n : { query?: ExtractOperationQuery<T> }\n : IsNever<ExtractOperationQuery<T>> extends true\n ? { body: ExtractOperationBody<T> }\n : { body: ExtractOperationBody<T>; query?: ExtractOperationQuery<T> };\n\ntype ClientOperation<T> = (\n options?: OperationInput<T>,\n requestOptions?: IntegrationClientRequestOptions,\n) => Promise<IntegrationOperationResult<ExtractOperationResponse<T>>>;\n\ntype ServerOperation<T> = (\n options?: OperationInput<T>,\n requestOptions?: IntegrationServerClientRequestOptions,\n) => Promise<IntegrationOperationResult<ExtractOperationResponse<T>>>;\n\ntype IsUnion<T, U = T> = T extends any ? ([U] extends [T] ? false : true) : never;\n\ntype SingleKey<T> = [T] extends [never] ? never : IsUnion<T> extends true ? never : T;\n\ntype ExtractAPIFromSource<TSource> = TSource extends { api?: infer TAPI }\n ? NonNullable<TAPI> extends FarmIntegrationAPI\n ? NonNullable<TAPI>\n : never\n : TSource extends FarmIntegrationAPI\n ? TSource\n : never;\n\ntype SourceKeysWithAPI<TSources extends Record<string, any>> = {\n [K in keyof TSources]: [ExtractAPIFromSource<TSources[K]>] extends [never] ? never : K;\n}[keyof TSources];\n\ntype IsServerRegisteredOperation<T> = T extends { isServer: true } ? true : false;\n\ntype ClientOperationKeys<TAPI> = {\n [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n ? IsServerRegisteredOperation<TAPI[K]> extends true\n ? never\n : K\n : never;\n}[keyof TAPI];\n\ntype ClientNamespaceShape<TAPI> = {\n [K in keyof TAPI as TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n ? IsServerRegisteredOperation<TAPI[K]> extends true\n ? never\n : K\n : K]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n ? ClientOperation<TAPI[K]>\n : TAPI[K] extends Record<string, any>\n ? IntegrationAPIToClient<TAPI[K]>\n : never;\n};\n\ntype SingleClientOperationKey<TAPI> =\n Exclude<keyof TAPI, ClientOperationKeys<TAPI>> extends never\n ? SingleKey<ClientOperationKeys<TAPI>>\n : never;\n\ntype IntegrationAPIToClient<TAPI> =\n TAPI extends FarmIntegrationAPIOperation<any, any, any, any>\n ? ClientOperation<TAPI>\n : TAPI extends Record<string, any>\n ? [SingleClientOperationKey<TAPI>] extends [never]\n ? ClientNamespaceShape<TAPI>\n : SingleClientOperationKey<TAPI> extends keyof TAPI\n ? ClientOperation<TAPI[SingleClientOperationKey<TAPI>]> & ClientNamespaceShape<TAPI>\n : ClientNamespaceShape<TAPI>\n : never;\n\nexport type IntegrationClient<TSources extends Record<string, any>> = {\n [K in SourceKeysWithAPI<TSources>]: IntegrationAPIToClient<ExtractAPIFromSource<TSources[K]>>;\n};\n\nexport type IntegrationClientRoot<TSources extends Record<string, any>> = {\n integrations: IntegrationClient<TSources>;\n};\n\ntype ServerOperationKeys<TAPI> = {\n [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any> ? K : never;\n}[keyof TAPI];\n\ntype ServerNamespaceShape<TAPI> = {\n [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any>\n ? ServerOperation<TAPI[K]>\n : TAPI[K] extends Record<string, any>\n ? IntegrationAPIToServerClient<TAPI[K]>\n : never;\n};\n\ntype SingleServerOperationKey<TAPI> =\n Exclude<keyof TAPI, ServerOperationKeys<TAPI>> extends never\n ? SingleKey<ServerOperationKeys<TAPI>>\n : never;\n\ntype IntegrationAPIToServerClient<TAPI> =\n TAPI extends FarmIntegrationAPIOperation<any, any, any>\n ? ServerOperation<TAPI>\n : TAPI extends Record<string, any>\n ? [SingleServerOperationKey<TAPI>] extends [never]\n ? ServerNamespaceShape<TAPI>\n : SingleServerOperationKey<TAPI> extends keyof TAPI\n ? ServerOperation<TAPI[SingleServerOperationKey<TAPI>]> & ServerNamespaceShape<TAPI>\n : ServerNamespaceShape<TAPI>\n : never;\n\nexport type IntegrationServerClient<TSources extends Record<string, any>> = {\n [K in SourceKeysWithAPI<TSources>]: IntegrationAPIToServerClient<\n ExtractAPIFromSource<TSources[K]>\n >;\n};\n\nexport type IntegrationServerClientRoot<TSources extends Record<string, any>> = {\n integrations: IntegrationServerClient<TSources>;\n};\n\nexport type IntegrationClientAliases<TSources extends Record<string, any>> =\n IntegrationClient<TSources> & {\n integrations: IntegrationClient<TSources>;\n };\n\nexport type IntegrationServerClientAliases<TSources extends Record<string, any>> =\n IntegrationServerClient<TSources> & {\n integrations: IntegrationServerClient<TSources>;\n };\n\nexport type IntegrationAPI<TSources extends Record<string, any>> =\n IntegrationClientAliases<TSources> & {\n server: (\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n ) => IntegrationServerClientAliases<TSources>;\n };\n\nexport type IntegrationClients<TSources extends Record<string, any>> = {\n api: IntegrationServerClientAliases<TSources>;\n apiClient: IntegrationClientAliases<TSources>;\n};\n\ntype ResolvedIntegrationNamespace = readonly [\n string,\n FarmIntegrationAPI,\n FarmIntegrationDefinition | FarmIntegrationAPI,\n];\n\ntype RegisteredIntegrationRuntime = {\n integration: FarmIntegrationDefinition;\n config: unknown;\n isDev: boolean;\n isProd: boolean;\n};\n\nconst INTEGRATION_RUNTIME_REGISTRY_KEY = Symbol.for(\"farm.integrationRuntimeRegistry\");\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\nconst INTEGRATION_REQUEST_DISPATCHER_KEY = Symbol.for(\"farm.integrationRequestDispatcher\");\n\ntype IntegrationRequestDispatcher = (\n runtime: RegisteredIntegrationRuntime,\n request: Request,\n options?: { currentRequest?: Request; data?: IntegrationClientData; internal?: boolean },\n) => Promise<Response | null>;\n\ntype GlobalWithIntegrationRuntimeRegistry = typeof globalThis & {\n [INTEGRATION_RUNTIME_REGISTRY_KEY]?: Map<string, RegisteredIntegrationRuntime>;\n [CURRENT_REQUEST_RESOLVER_KEY]?: () => Request | undefined;\n [INTEGRATION_REQUEST_DISPATCHER_KEY]?: IntegrationRequestDispatcher;\n};\n\ntype GlobalWithIntegrationAPIManifest = typeof globalThis & {\n __FARM_INTEGRATION_API_MANIFEST__?: Record<string, FarmIntegrationAPI>;\n window?: {\n __FARM_INTEGRATION_API_MANIFEST__?: Record<string, FarmIntegrationAPI>;\n };\n};\n\nfunction isOperation(value: unknown): value is FarmIntegrationAPIOperation<any, any, any, any> {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as FarmIntegrationAPIOperation<any, any, any, any>).kind ===\n \"farm-integration-api-operation\"\n );\n}\n\nfunction resolveSourceAPI(\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n): FarmIntegrationAPI {\n if (\"kind\" in source && source.kind === \"farm-integration\") {\n if (!source.api) {\n throw new Error(`Integration \"${source.type}\" does not expose a client API definition.`);\n }\n\n return source.api as FarmIntegrationAPI;\n }\n\n return source as FarmIntegrationAPI;\n}\n\nfunction tryResolveSourceAPI(\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n): FarmIntegrationAPI | null {\n if (\"kind\" in source && source.kind === \"farm-integration\") {\n if (!source.api) {\n return null;\n }\n\n return source.api as FarmIntegrationAPI;\n }\n\n return source as FarmIntegrationAPI;\n}\n\nfunction getIntegrationRuntimeRegistry() {\n const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n return (\n globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] || new Map<string, RegisteredIntegrationRuntime>()\n );\n}\n\nfunction getRegisteredIntegrationRuntimeLocal(\n key: string,\n): RegisteredIntegrationRuntime | undefined {\n return getIntegrationRuntimeRegistry().get(key);\n}\n\nfunction getRegisteredIntegrationsLocal(): Record<string, FarmIntegrationDefinition> {\n return Object.fromEntries(\n Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [\n key,\n runtime.integration,\n ]),\n );\n}\n\nfunction resolveCurrentRequestLocal(): Request | undefined {\n const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n return globalState[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n\nfunction resolveIntegrationRequestDispatcherLocal(): IntegrationRequestDispatcher | undefined {\n const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n return globalState[INTEGRATION_REQUEST_DISPATCHER_KEY];\n}\n\nconst INTEGRATION_DATA_HEADER = \"x-farm-integration-data\";\nconst INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;\nconst BLOCKED_INTEGRATION_DATA_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isIntegrationClientData(value: unknown): value is IntegrationClientData {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isPlainIntegrationDataObject(value: unknown): value is Record<string, unknown> {\n if (!isIntegrationClientData(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction sanitizeIntegrationClientDataValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeIntegrationClientDataValue(item));\n }\n\n if (!isPlainIntegrationDataObject(value)) {\n return value;\n }\n\n const sanitized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {\n continue;\n }\n\n sanitized[key] = sanitizeIntegrationClientDataValue(item);\n }\n\n return sanitized;\n}\n\nfunction normalizeIntegrationClientData(\n value: IntegrationClientData | undefined,\n): IntegrationClientData | undefined {\n if (!isIntegrationClientData(value)) {\n return undefined;\n }\n\n const sanitized = sanitizeIntegrationClientDataValue(value);\n return isIntegrationClientData(sanitized) && Object.keys(sanitized).length > 0\n ? sanitized\n : undefined;\n}\n\nfunction getIntegrationDataHeaderByteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength;\n}\n\nfunction mergeIntegrationClientData(\n ...values: Array<IntegrationClientData | undefined>\n): IntegrationClientData | undefined {\n let merged: IntegrationClientData | undefined;\n\n for (const value of values) {\n const data = normalizeIntegrationClientData(value);\n if (!data) {\n continue;\n }\n\n merged = {\n ...(merged || {}),\n ...data,\n };\n }\n\n return merged && Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nfunction serializeIntegrationClientData(data: IntegrationClientData): string {\n const serialized = JSON.stringify(data);\n if (getIntegrationDataHeaderByteLength(serialized) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {\n throw new Error(\n `Integration client data must be smaller than ${INTEGRATION_DATA_HEADER_MAX_LENGTH} bytes when sent over HTTP headers.`,\n );\n }\n\n return serialized;\n}\n\nfunction appendIntegrationClientDataHeader(\n headers: Headers,\n data: IntegrationClientData | undefined,\n) {\n if (!data) {\n return;\n }\n\n headers.set(INTEGRATION_DATA_HEADER, serializeIntegrationClientData(data));\n}\n\nfunction resolveAutomaticClientNamespaces(): ResolvedIntegrationNamespace[] {\n const globalState = globalThis as GlobalWithIntegrationAPIManifest;\n const manifest =\n globalState.window?.__FARM_INTEGRATION_API_MANIFEST__ ||\n globalState.__FARM_INTEGRATION_API_MANIFEST__ ||\n {};\n\n return Object.entries(manifest).map(([key, api]) => [key, api, api] as const);\n}\n\nfunction resolveAutomaticServerNamespaces(): ResolvedIntegrationNamespace[] {\n return Object.entries(getRegisteredIntegrationsLocal()).flatMap(([key, source]) => {\n const api = tryResolveSourceAPI(source);\n return api ? [[key, api, source] as ResolvedIntegrationNamespace] : [];\n });\n}\n\nfunction appendQuery(url: URL, query: Record<string, unknown> | undefined) {\n if (!query) {\n return;\n }\n\n for (const [key, value] of Object.entries(query)) {\n if (value == null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item != null) {\n url.searchParams.append(key, String(item));\n }\n }\n continue;\n }\n\n url.searchParams.set(key, String(value));\n }\n}\n\nfunction appendHeaders(target: Headers, source: HeadersInit | undefined) {\n if (!source) {\n return;\n }\n\n const headers = new Headers(source);\n headers.forEach((value, key) => {\n target.set(key, value);\n });\n}\n\nconst DEFAULT_FORWARDED_HEADERS = [\n \"authorization\",\n \"cookie\",\n \"x-client-ip\",\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n \"x-real-ip\",\n] as const;\n\nfunction resolveRequestLike(request: IntegrationServerRequestLike | undefined) {\n if (!request) {\n return undefined;\n }\n\n if (request instanceof Request) {\n return {\n url: request.url,\n headers: request.headers,\n };\n }\n\n return {\n url: request.url,\n headers: request.headers ? new Headers(request.headers) : undefined,\n };\n}\n\nfunction resolveServerBaseURL(\n explicitBaseURL: string | undefined,\n request: ReturnType<typeof resolveRequestLike>,\n) {\n if (explicitBaseURL) {\n return explicitBaseURL;\n }\n\n if (request?.url) {\n try {\n return new URL(request.url).origin;\n } catch {\n // Fall back to forwarded headers below.\n }\n }\n\n const headers = request?.headers;\n const host = headers?.get(\"x-forwarded-host\") || headers?.get(\"host\");\n if (host) {\n const proto = headers?.get(\"x-forwarded-proto\") || \"http\";\n return `${proto}://${host}`;\n }\n\n return \"http://localhost:3000\";\n}\n\nfunction resolveForwardHeaders(\n request: ReturnType<typeof resolveRequestLike>,\n forwardHeaders: boolean | readonly string[] | undefined,\n) {\n if (!request?.headers || forwardHeaders === false) {\n return new Headers();\n }\n\n const allowed =\n Array.isArray(forwardHeaders) && forwardHeaders.length > 0\n ? new Set(forwardHeaders.map((item) => item.toLowerCase()))\n : new Set<string>(DEFAULT_FORWARDED_HEADERS);\n\n const headers = new Headers();\n request.headers.forEach((value, key) => {\n if (allowed.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n return headers;\n}\n\nfunction createBody(\n format: FarmIntegrationAPIBodyFormat | undefined,\n body: unknown,\n headers: Headers,\n): BodyInit | undefined {\n if (body == null || format === \"none\") {\n return undefined;\n }\n\n if (format === \"form\") {\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n const form = new URLSearchParams();\n for (const [key, value] of Object.entries(body as Record<string, unknown>)) {\n if (value == null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item != null) {\n form.append(key, String(item));\n }\n }\n continue;\n }\n\n form.set(key, String(value));\n }\n\n headers.set(\"content-type\", \"application/x-www-form-urlencoded;charset=UTF-8\");\n return form;\n }\n\n headers.set(\"content-type\", \"application/json\");\n return JSON.stringify(body);\n}\n\nasync function parseResponseData(response: Response): Promise<unknown> {\n if (response.status === 204 || response.status === 205) {\n return undefined;\n }\n\n const contentType = response.headers.get(\"content-type\") || \"\";\n\n if (contentType.includes(\"application/json\")) {\n return await response.json();\n }\n\n return await response.text();\n}\n\nasync function safeParseResponseData(response: Response): Promise<unknown> {\n try {\n return await parseResponseData(response);\n } catch {\n return undefined;\n }\n}\n\nfunction createResponseError(response: Response, errorData: unknown) {\n const message =\n typeof errorData === \"string\"\n ? errorData\n : typeof errorData === \"object\" && errorData\n ? String(\n (errorData as { error?: string; message?: string }).error ||\n (errorData as { error?: string; message?: string }).message ||\n response.statusText,\n )\n : response.statusText || \"Integration request failed.\";\n\n return new IntegrationClientError(message, response, errorData);\n}\n\nfunction normalizeExecutionError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n\n if (typeof error === \"string\" && error.length > 0) {\n return new Error(error);\n }\n\n return new Error(\"Integration request failed.\");\n}\n\nasync function finalizeOperationResponse(\n operation: FarmIntegrationAPIOperation<any, any, any>,\n response: Response,\n) {\n if (!response.ok) {\n const errorData = await safeParseResponseData(response);\n return {\n data: null,\n error: createResponseError(response, errorData),\n };\n }\n\n if (operation.responseFormat === \"response\") {\n return {\n data: response,\n error: null,\n };\n }\n\n return {\n data: (await parseResponseData(response)) as unknown,\n error: null,\n };\n}\n\nasync function executeClientOperation(\n operation: FarmIntegrationAPIOperation<any, any, any>,\n input: Record<string, unknown>,\n options: Pick<IntegrationClientOptions, \"baseURL\" | \"headers\" | \"credentials\" | \"data\">,\n requestOptions?: IntegrationClientRequestOptions,\n) {\n try {\n if (!operation.path) {\n return {\n data: null,\n error: new Error(\n \"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... }).\",\n ),\n };\n }\n\n const baseURL =\n options.baseURL ||\n (typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\");\n const url = new URL(operation.path, baseURL);\n appendQuery(url, input.query as Record<string, unknown> | undefined);\n\n const headers = new Headers({\n \"x-farm-integration-client\": \"1\",\n ...options.headers,\n ...operation.headers,\n ...requestOptions?.headers,\n });\n\n if (operation.responseFormat !== \"response\") {\n headers.set(\"accept\", \"application/json\");\n }\n\n appendIntegrationClientDataHeader(\n headers,\n mergeIntegrationClientData(options.data, requestOptions?.data),\n );\n\n const response = await fetch(url.toString(), {\n method: operation.method,\n headers,\n body: createBody(operation.bodyFormat, input.body, headers),\n credentials:\n requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? \"include\",\n signal: requestOptions?.signal,\n });\n\n if (!response.ok) {\n const errorData = await safeParseResponseData(response);\n return {\n data: null,\n error: createResponseError(response, errorData),\n };\n }\n\n if (operation.responseFormat === \"response\") {\n return {\n data: response,\n error: null,\n };\n }\n\n return {\n data: (await parseResponseData(response)) as unknown,\n error: null,\n };\n } catch (error) {\n return {\n data: null,\n error: normalizeExecutionError(error),\n };\n }\n}\n\nasync function executeServerOperation(\n operation: FarmIntegrationAPIOperation<any, any, any>,\n input: Record<string, unknown>,\n options: Pick<\n IntegrationServerClientOptions,\n \"baseURL\" | \"headers\" | \"credentials\" | \"data\" | \"request\" | \"forwardHeaders\"\n >,\n requestOptions?: IntegrationServerClientRequestOptions,\n integrationKey?: string,\n source?: FarmIntegrationDefinition | FarmIntegrationAPI,\n) {\n try {\n if (!operation.path) {\n return {\n data: null,\n error: new Error(\n \"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... }).\",\n ),\n };\n }\n\n const serverRequestOptions =\n requestOptions &&\n (\"request\" in requestOptions ||\n \"baseURL\" in requestOptions ||\n \"forwardHeaders\" in requestOptions)\n ? requestOptions\n : undefined;\n const currentRequest =\n serverRequestOptions?.request instanceof Request\n ? serverRequestOptions.request\n : options.request instanceof Request\n ? options.request\n : resolveCurrentRequestLocal();\n const request = resolveRequestLike(\n serverRequestOptions?.request ?? options.request ?? currentRequest,\n );\n const baseURL = resolveServerBaseURL(serverRequestOptions?.baseURL ?? options.baseURL, request);\n const url = new URL(operation.path, baseURL);\n appendQuery(url, input.query as Record<string, unknown> | undefined);\n\n const headers = new Headers();\n appendHeaders(\n headers,\n resolveForwardHeaders(\n request,\n serverRequestOptions?.forwardHeaders ?? options.forwardHeaders,\n ),\n );\n appendHeaders(headers, options.headers);\n appendHeaders(headers, operation.headers);\n appendHeaders(headers, requestOptions?.headers);\n headers.set(\"x-farm-integration-client\", \"1\");\n\n if (operation.responseFormat !== \"response\") {\n headers.set(\"accept\", \"application/json\");\n }\n\n const data = mergeIntegrationClientData(options.data, requestOptions?.data);\n\n if (integrationKey) {\n const runtime =\n \"kind\" in (source || {}) &&\n (source as FarmIntegrationDefinition).kind === \"farm-integration\"\n ? getRegisteredIntegrationRuntimeLocal(integrationKey) || {\n integration: source as FarmIntegrationDefinition,\n config: {},\n isDev: process.env.NODE_ENV !== \"production\",\n isProd: process.env.NODE_ENV === \"production\",\n }\n : getRegisteredIntegrationRuntimeLocal(integrationKey);\n\n if (runtime) {\n const dispatchIntegrationRequest = resolveIntegrationRequestDispatcherLocal();\n const directResponse = dispatchIntegrationRequest\n ? await dispatchIntegrationRequest(\n runtime,\n new Request(url.toString(), {\n method: operation.method,\n headers,\n body: createBody(operation.bodyFormat, input.body, headers),\n }),\n {\n currentRequest,\n data,\n internal: true,\n },\n )\n : null;\n\n if (directResponse) {\n return await finalizeOperationResponse(operation, directResponse);\n }\n }\n }\n\n appendIntegrationClientDataHeader(headers, data);\n\n const response = await fetch(url.toString(), {\n method: operation.method,\n headers,\n body: createBody(operation.bodyFormat, input.body, headers),\n credentials:\n requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? \"include\",\n signal: requestOptions?.signal,\n });\n\n return await finalizeOperationResponse(operation, response);\n } catch (error) {\n return {\n data: null,\n error: normalizeExecutionError(error),\n };\n }\n}\n\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options: IntegrationServerClientOptions,\n): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options?: IntegrationClientOptions,\n): IntegrationClientAliases<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: TSources,\n options: IntegrationServerClientOptions,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: TSources,\n options?: IntegrationClientOptions,\n): IntegrationClient<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: TSources | { integrations: TSources },\n options: IntegrationClientOptions | IntegrationServerClientOptions = {},\n):\n | IntegrationClient<TSources>\n | IntegrationClientAliases<TSources>\n | IntegrationServerClient<TSources>\n | IntegrationServerClientAliases<TSources> {\n const rawSources = \"integrations\" in sources ? sources.integrations : sources;\n const isServer = options.isServer === true;\n\n const namespaces = Object.entries(rawSources)\n .map(([key, source]) => {\n const api = tryResolveSourceAPI(source as FarmIntegrationDefinition | FarmIntegrationAPI);\n if (!api) {\n return null;\n }\n return [key, api, source as FarmIntegrationDefinition | FarmIntegrationAPI] as const;\n })\n .filter(\n (\n value,\n ): value is readonly [\n string,\n FarmIntegrationAPI,\n FarmIntegrationDefinition | FarmIntegrationAPI,\n ] => value !== null,\n );\n\n const cache = new Map<string, any>();\n\n const integrationNamespaces = new Proxy(\n {},\n {\n get(target, property) {\n if (typeof property !== \"string\") {\n return undefined;\n }\n\n if (Reflect.has(target, property)) {\n return Reflect.get(target, property);\n }\n\n if (cache.has(property)) {\n return cache.get(property);\n }\n\n const match = namespaces.find(([key]) => key === property);\n if (!match) {\n return undefined;\n }\n\n const namespace = isServer\n ? createServerNamespaceProxy(\n match[0],\n match[2],\n match[1],\n options as IntegrationServerClientOptions,\n )\n : createNamespaceProxy(match[1], options);\n cache.set(property, namespace);\n return namespace;\n },\n },\n ) as\n | IntegrationClient<TSources>\n | IntegrationClientAliases<TSources>\n | IntegrationServerClient<TSources>\n | IntegrationServerClientAliases<TSources>;\n\n if (\"integrations\" in sources) {\n Object.defineProperty(integrationNamespaces, \"integrations\", {\n value: integrationNamespaces,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return integrationNamespaces as\n | IntegrationClientAliases<TSources>\n | IntegrationServerClientAliases<TSources>;\n }\n\n return integrationNamespaces as IntegrationClient<TSources> | IntegrationServerClient<TSources>;\n}\n\nfunction createAutomaticIntegrationAliases<TSources extends Record<string, any>>(\n isServer: boolean,\n options: IntegrationClientOptions | IntegrationServerClientOptions = {},\n): IntegrationClientAliases<TSources> | IntegrationServerClientAliases<TSources> {\n const cache = isServer ? new Map<string, any>() : null;\n\n const integrationNamespaces = new Proxy(\n {},\n {\n get(_target, property) {\n if (typeof property !== \"string\") {\n return undefined;\n }\n\n if (property === \"integrations\") {\n return integrationNamespaces;\n }\n\n if (cache?.has(property)) {\n return cache.get(property);\n }\n\n const namespaces = isServer\n ? resolveAutomaticServerNamespaces()\n : resolveAutomaticClientNamespaces();\n const match = namespaces.find(([key]) => key === property);\n if (!match) {\n return undefined;\n }\n\n const namespace = isServer\n ? createServerNamespaceProxy(\n match[0],\n match[2],\n match[1],\n options as IntegrationServerClientOptions,\n )\n : createNamespaceProxy(match[1], options as IntegrationClientOptions);\n\n cache?.set(property, namespace);\n return namespace;\n },\n },\n ) as IntegrationClientAliases<TSources> | IntegrationServerClientAliases<TSources>;\n\n Object.defineProperty(integrationNamespaces, \"integrations\", {\n value: integrationNamespaces,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return integrationNamespaces;\n}\n\nexport function integrationsClient<\n TSources extends Record<string, any>,\n>(): IntegrationClientAliases<TSources>;\nexport function integrationsClient<TSources extends Record<string, any>>(\n options: IntegrationClientOptions,\n): IntegrationClientAliases<TSources>;\nexport function integrationsClient<TSources extends Record<string, any>>(\n options: IntegrationClientOptions = {},\n): IntegrationClientAliases<TSources> {\n return createAutomaticIntegrationAliases<TSources>(\n false,\n options,\n ) as IntegrationClientAliases<TSources>;\n}\n\nexport function integrationsServer<\n TSources extends Record<string, any>,\n>(): IntegrationServerClientAliases<TSources>;\nexport function integrationsServer<TSources extends Record<string, any>>(\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClientAliases<TSources>;\nexport function integrationsServer<TSources extends Record<string, any>>(\n options: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): IntegrationServerClientAliases<TSources> {\n return createAutomaticIntegrationAliases<TSources>(true, {\n ...options,\n isServer: true,\n }) as IntegrationServerClientAliases<TSources>;\n}\n\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(sources: {\n integrations: TSources;\n}): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: TSources,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: TSources,\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: TSources | { integrations: TSources },\n options: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): IntegrationServerClient<TSources> | IntegrationServerClientAliases<TSources> {\n return createIntegrationClient(sources, {\n ...options,\n isServer: true,\n }) as IntegrationServerClient<TSources> | IntegrationServerClientAliases<TSources>;\n}\n\nexport function createIntegrationApi<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options: IntegrationClientOptions = {},\n): IntegrationAPI<TSources> {\n const client = createIntegrationClient(sources, options);\n\n return {\n ...client,\n server(serverOptions = {}) {\n return createIntegrationServerClient(sources, {\n ...options,\n ...serverOptions,\n });\n },\n };\n}\n\nfunction isIntegrationClientOptionsInput(value: unknown): value is IntegrationClientOptions {\n return (\n !!value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n (\"baseURL\" in value ||\n \"headers\" in value ||\n \"credentials\" in value ||\n \"data\" in value ||\n \"isServer\" in value)\n );\n}\n\nfunction resolveIntegrationServerOptions(\n clientOptions: IntegrationClientOptions = {},\n serverOptions: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): Omit<IntegrationServerClientOptions, \"isServer\"> {\n const data = mergeIntegrationClientData(clientOptions.data, serverOptions.data);\n\n return {\n baseURL: clientOptions.baseURL,\n headers: clientOptions.headers,\n credentials: clientOptions.credentials,\n ...serverOptions,\n ...(data ? { data } : {}),\n };\n}\n\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n sources: TSources,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n sources?: TSources | { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n if (arguments.length === 0 || isIntegrationClientOptionsInput(sources)) {\n const automaticClientOptions = isIntegrationClientOptionsInput(sources) ? sources : {};\n const automaticServerOptions = arguments.length > 1 ? clientOptions : undefined;\n\n return {\n api: integrationsServer<TSources>(\n resolveIntegrationServerOptions(\n automaticClientOptions,\n automaticServerOptions as Omit<IntegrationServerClientOptions, \"isServer\"> | undefined,\n ),\n ),\n apiClient: integrationsClient<TSources>(automaticClientOptions),\n };\n }\n\n const explicitSources =\n sources && \"integrations\" in sources ? sources.integrations : (sources as TSources);\n\n return {\n api: createIntegrationServerClient(\n {\n integrations: explicitSources,\n },\n resolveIntegrationServerOptions(clientOptions, serverOptions),\n ) as IntegrationServerClientAliases<TSources>,\n apiClient: createIntegrationClient(\n {\n integrations: explicitSources,\n },\n clientOptions,\n ) as IntegrationClientAliases<TSources>,\n };\n}\n\nexport function createIntegrations<TSources extends Record<string, any>>(\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n sources: TSources,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n sources?: TSources | { integrations: TSources } | IntegrationClientOptions,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n if (arguments.length === 0) {\n return createIntegrationClients<TSources>();\n }\n\n return createIntegrationClients<TSources>(\n sources as TSources,\n clientOptions,\n serverOptions,\n ) as IntegrationClients<TSources>;\n}\n\nfunction createClientSafeIntegrationAPI(\n api: FarmIntegrationAPI | undefined,\n): FarmIntegrationAPI | undefined {\n if (!api) {\n return undefined;\n }\n\n const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n if (isOperation(value)) {\n return [\n key,\n {\n kind: value.kind,\n path: value.path,\n method: value.method,\n bodyFormat: value.bodyFormat,\n responseFormat: value.responseFormat,\n credentials: value.credentials,\n isServer: value.isServer,\n __pathless: value.__pathless,\n },\n ];\n }\n\n if (value && typeof value === \"object\") {\n return [key, createClientSafeIntegrationAPI(value as FarmIntegrationAPI)];\n }\n\n return [key, value];\n });\n\n return Object.fromEntries(entries) as FarmIntegrationAPI;\n}\n\nexport function getIntegrationAPIManifest(): Record<string, FarmIntegrationAPI> {\n const manifestEntries = Object.entries(getRegisteredIntegrationsLocal())\n .map(([key, integration]) => {\n const api = createClientSafeIntegrationAPI(integration.api);\n return api ? ([key, api] as const) : null;\n })\n .filter((value): value is readonly [string, FarmIntegrationAPI] => value !== null);\n\n return Object.fromEntries(manifestEntries);\n}\n\nexport function integrationClients<TSources extends Record<string, any>>(\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n sources: TSources,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n sources?: TSources | { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n if (arguments.length === 0) {\n return createIntegrationClients<TSources>();\n }\n\n return createIntegrationClients<TSources>(\n sources as TSources,\n clientOptions,\n serverOptions,\n ) as IntegrationClients<TSources>;\n}\n\nfunction resolveSingleNamespaceOperation(api: FarmIntegrationAPI) {\n const entries = Object.entries(api as Record<string, unknown>);\n if (entries.length !== 1) {\n return null;\n }\n\n const [, value] = entries[0]!;\n return isOperation(value) ? value : null;\n}\n\nfunction createClientOperationCaller(\n operation: FarmIntegrationAPIOperation<any, any, any, any>,\n property: string,\n options: IntegrationClientOptions,\n) {\n if (operation.isServer === true) {\n return async () => {\n throw new Error(\n `Integration method \"${property}\" is registered with isServer: true and is only available from a server integration client.`,\n );\n };\n }\n\n return async (\n input: Record<string, unknown> = {},\n requestOptions?: IntegrationClientRequestOptions,\n ) => {\n if (typeof window === \"undefined\") {\n throw new Error(\n \"Client integration API cannot be called on the server. Pass { isServer: true } to createIntegrationClient(...) during server rendering, or provide { isServer: true, request } outside it.\",\n );\n }\n\n return executeClientOperation(operation, input, options, requestOptions);\n };\n}\n\nfunction createServerOperationCaller(\n operation: FarmIntegrationAPIOperation<any, any, any, any>,\n options: IntegrationServerClientOptions,\n integrationKey: string,\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n) {\n return async (\n input: Record<string, unknown> = {},\n requestOptions?: IntegrationServerClientRequestOptions,\n ) => {\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"Server integration API cannot be called in the browser. Remove { isServer: true } and create a client integration API instead.\",\n );\n }\n\n return executeServerOperation(\n operation,\n input,\n options,\n requestOptions,\n integrationKey,\n source,\n );\n };\n}\n\nfunction createNamespaceProxy(api: FarmIntegrationAPI, options: IntegrationClientOptions) {\n const cache = new Map<string, any>();\n const directOperation = resolveSingleNamespaceOperation(api);\n const target = directOperation\n ? createClientOperationCaller(directOperation, directOperation.method.toLowerCase(), options)\n : {};\n\n return new Proxy(target, {\n get(targetObject, property, receiver) {\n if (typeof property !== \"string\") {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (cache.has(property)) {\n return cache.get(property);\n }\n\n const value = (api as Record<string, unknown>)[property];\n if (!value) {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (isOperation(value)) {\n const caller = createClientOperationCaller(value, property, options);\n cache.set(property, caller);\n return caller;\n }\n\n const namespace = createNamespaceProxy(value as FarmIntegrationAPI, options);\n cache.set(property, namespace);\n return namespace;\n },\n });\n}\n\nfunction createServerNamespaceProxy(\n integrationKey: string,\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n api: FarmIntegrationAPI,\n options: IntegrationServerClientOptions,\n) {\n const cache = new Map<string, any>();\n const directOperation = resolveSingleNamespaceOperation(api);\n const target = directOperation\n ? createServerOperationCaller(directOperation, options, integrationKey, source)\n : {};\n\n return new Proxy(target, {\n get(targetObject, property, receiver) {\n if (typeof property !== \"string\") {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (cache.has(property)) {\n return cache.get(property);\n }\n\n const value = (api as Record<string, unknown>)[property];\n if (!value) {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (isOperation(value)) {\n const caller = createServerOperationCaller(value, options, integrationKey, source);\n cache.set(property, caller);\n return caller;\n }\n\n const namespace = createServerNamespaceProxy(\n integrationKey,\n source,\n value as FarmIntegrationAPI,\n options,\n );\n cache.set(property, namespace);\n return namespace;\n },\n });\n}\n","import {\n integrationsClient,\n integrationsServer,\n type IntegrationClientOptions,\n type IntegrationClientRoot,\n type IntegrationServerClientOptions,\n type IntegrationServerClientRoot,\n} from \"../integration-client\";\nimport {\n getFarmClientDataCache,\n normalizeFarmClientCacheKey,\n type FarmClientCacheEntry,\n type FarmClientCacheKey,\n type FarmClientDataCache,\n} from \"../client-cache\";\n\nexport type APIClientOptions = {\n baseURL?: string;\n headers?: Record<string, string>;\n credentials?: RequestCredentials;\n cacheDefaults?: CacheOptions;\n integrations?: IntegrationClientOptions;\n};\n\nexport type APIClientWithoutIntegrationsOptions = Omit<APIClientOptions, \"integrations\"> & {\n integrations: false;\n};\n\nexport type ServerAPIClientOptions = {\n integrations?: Omit<IntegrationServerClientOptions, \"isServer\">;\n};\n\nexport type ServerAPIClientWithoutIntegrationsOptions = Omit<\n ServerAPIClientOptions,\n \"integrations\"\n> & {\n integrations: false;\n};\n\nexport type StatusPhase = \"idle\" | \"pending\" | \"success\" | \"error\" | \"revalidating\" | \"invalidated\";\n\nexport type StatusEvent<TData = unknown, TError = unknown> = {\n phase: StatusPhase;\n requestId: string;\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\" | \"HEAD\";\n key: string;\n input?: unknown;\n data?: TData;\n error?: TError;\n isBackground?: boolean;\n timestamp: number;\n};\n\nexport type CacheKey<TData = unknown> = string & {\n readonly __farmCacheData?: TData;\n};\n\nexport type APIResult<TData = unknown, TError = Error> = {\n data: TData | undefined;\n error: TError | null;\n key: CacheKey<TData>;\n};\n\nexport type RequestEvent = {\n requestId: string;\n method: StatusEvent[\"method\"];\n key: string;\n path: string;\n input?: unknown;\n attempt: number;\n timestamp: number;\n};\n\nexport type ResponseEvent<TData = unknown, TError = Error> = {\n requestId: string;\n method: StatusEvent[\"method\"];\n key: string;\n path: string;\n input?: unknown;\n attempt: number;\n timestamp: number;\n response?: Response;\n data?: TData;\n error?: TError;\n ok?: boolean;\n status?: number;\n};\n\nexport type CachePolicy = \"cache-first\" | \"network-only\" | \"stale-while-revalidate\";\n\nexport type CacheOptions = {\n key?: FarmClientCacheKey;\n policy?: CachePolicy;\n staleTime?: number;\n gcTime?: number;\n dedupeMs?: number;\n};\n\nexport type RetryOptions = {\n count?: number;\n delay?: number | ((attempt: number) => number);\n};\n\nexport type InvalidateTarget =\n | string\n | {\n key: FarmClientCacheKey;\n }\n | {\n path: string;\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\" | \"HEAD\";\n input?: unknown;\n }\n | [CallableRouteRef<any>, unknown?];\n\nexport type InvalidateOptions =\n | InvalidateTarget[]\n | {\n targets: InvalidateTarget[];\n refetch?: boolean;\n };\n\nexport type OptimisticUpdate =\n | [CallableRouteRef<any>, unknown, (prev: any) => any]\n | [CacheKey<any> | string, (prev: any) => any];\n\nexport type OptimisticOptions<TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]> = {\n update: TUpdates & NormalizeOptimisticUpdates<TUpdates>;\n rollbackOnError?: boolean;\n};\n\nexport type ClientOptions<\n TData = unknown,\n TError = unknown,\n TUpdates extends readonly unknown[] = readonly OptimisticUpdate[],\n> = {\n key?: CacheKey<TData> | FarmClientCacheKey;\n cache?: CacheOptions;\n retry?: RetryOptions;\n invalidate?: InvalidateOptions;\n optimistic?: OptimisticOptions<TUpdates>;\n onRequest?: (event: RequestEvent) => void;\n onResponse?: (\n data: TData | undefined,\n error: TError | null,\n event: ResponseEvent<TData, TError>,\n ) => void;\n onSuccess?: (data: TData) => void;\n onError?: (err: TError) => void;\n onSettled?: (data?: TData, err?: TError | null) => void;\n onStatus?: (event: StatusEvent<TData, TError>) => void;\n};\n\ntype AnyRouteRef = (...args: any[]) => any;\ntype RouteRef<TData = any, TInput = any> = {\n readonly __farmRouteInput: TInput;\n readonly __farmRouteData: TData;\n};\ntype CallableRouteRef<TData = any, TInput = any> = AnyRouteRef & RouteRef<TData, TInput>;\n\ntype InferRouteInput<TRoute> = TRoute extends { readonly __farmRouteInput: infer TInput }\n ? TInput\n : never;\ntype InferRouteData<TRoute> = TRoute extends { readonly __farmRouteData: infer TData }\n ? TData\n : never;\n\ntype NormalizeOptimisticUpdate<TUpdate> = TUpdate extends readonly [\n infer TRoute,\n unknown,\n (prev: any) => any,\n]\n ? TRoute extends RouteRef<any, any>\n ? [\n TRoute,\n InferRouteInput<TRoute> | undefined,\n (prev: InferRouteData<TRoute> | undefined) => InferRouteData<TRoute>,\n ]\n : never\n : TUpdate extends readonly [infer TKey, (prev: any) => any]\n ? TKey extends CacheKey<infer TData>\n ? [TKey, (prev: TData | undefined) => TData]\n : TKey extends string\n ? [TKey, (prev: unknown) => unknown]\n : never\n : never;\n\ntype NormalizeOptimisticUpdates<TUpdates extends readonly unknown[]> = {\n [K in keyof TUpdates]: NormalizeOptimisticUpdate<TUpdates[K]>;\n};\n\ntype TypedEndpointLike = {\n __types: {\n body: any;\n query: any;\n response: any;\n };\n};\n\ntype Simplify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\ntype IsNever<T> = [T] extends [never] ? true : false;\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype RequiredKeys<T> = T extends object\n ? {\n [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n }[keyof T]\n : never;\n\ntype BodyInputProp<TValue> =\n IsNever<TValue> extends true\n ? {}\n : IsAny<TValue> extends true\n ? { body?: TValue }\n : undefined extends TValue\n ? { body?: TValue }\n : { body: TValue };\n\ntype QueryInputProp<TValue> =\n IsNever<TValue> extends true\n ? {}\n : IsAny<TValue> extends true\n ? { query?: TValue }\n : undefined extends TValue\n ? { query?: TValue }\n : RequiredKeys<TValue> extends never\n ? { query?: TValue }\n : { query: TValue };\n\ntype HasRequiredKeys<T> = RequiredKeys<T> extends never ? false : true;\n\n// Type utilities to extract endpoint input/output types from TypedEndpoint\ntype InferEndpointInput<T> = T extends {\n __types: {\n body: infer TBody;\n query: infer TQuery;\n };\n}\n ? Simplify<BodyInputProp<TBody> & QueryInputProp<TQuery>>\n : {};\n\ntype InferEndpointOutput<T> = T extends {\n __types: {\n response: infer R;\n };\n}\n ? R\n : any;\n\n// Type for a single endpoint method\ntype EndpointMethod<T = any> = (<TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]>(\n ...args: HasRequiredKeys<InferEndpointInput<T>> extends true\n ? [\n options: InferEndpointInput<T>,\n clientOptions?: ClientOptions<InferEndpointOutput<T>, Error, TUpdates>,\n ]\n : [\n options?: InferEndpointInput<T>,\n clientOptions?: ClientOptions<InferEndpointOutput<T>, Error, TUpdates>,\n ]\n) => Promise<APIResult<InferEndpointOutput<T>, Error>>) &\n RouteRef<InferEndpointOutput<T>, InferEndpointInput<T>>;\n\n// Type for converting router structure to client structure\ntype RouterToClient<T> = {\n [K in keyof T]: T[K] extends TypedEndpointLike\n ? EndpointMethod<T[K]>\n : T[K] extends Record<string, any>\n ? RouterToClient<T[K]> // Recurssive handling of the multi level api routes\n : EndpointMethod<T[K]>;\n};\n\nexport type RouteAPIClient<TRouter extends Record<string, any>> = RouterToClient<TRouter>;\n\nexport type APIClient<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n> = RouteAPIClient<TRouter> & IntegrationClientRoot<TIntegrations>;\n\nexport type ServerAPIClient<\n TEndpoints extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n> = TEndpoints & IntegrationServerClientRoot<TIntegrations>;\n\n/**\n * Create a typed RPC client for Farm.js API routes\n *\n * Returns a nested proxy that supports:\n * - api.hello.get({ query: { name: 'World' } })\n * - api['auth/login'].post({ body: { email: '...', password: '...' } })\n * - api.users.get({ query: { limit: '10' } })\n * - api.integrations.billing.checkout({ body: { priceId: 'price_...' } })\n *\n * @example\n * ```typescript\n * import { createAPIClient } from 'farm/client';\n * import type { APIRouter } from '@/api';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createAPIClient<APIRouter, AppIntegrations>();\n *\n * // Use it (nested property access)\n * const result = await api.hello.get({ query: { name: 'World' } });\n * if (result.error) console.error(result.error);\n * else console.log(result.data);\n *\n * // Or with string keys for nested paths\n * const result = await api['auth/login'].post({\n * body: { email: 'test@example.com', password: 'pass123' }\n * });\n *\n * // Integration APIs live under a reserved namespace.\n * const checkout = await api.integrations.billing.checkout({\n * body: { priceId: 'price_123' }\n * });\n * ```\n */\nexport function createAPIClient<TRouter extends Record<string, any>>(\n options: APIClientWithoutIntegrationsOptions,\n): RouteAPIClient<TRouter>;\nexport function createAPIClient<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(options?: APIClientOptions): APIClient<TRouter, TIntegrations>;\nexport function createAPIClient<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n): RouteAPIClient<TRouter> | APIClient<TRouter, TIntegrations> {\n options ??= {};\n // Auto-detect baseURL\n const baseURL =\n options.baseURL ||\n (typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\");\n const integrationOptions =\n options.integrations === false\n ? false\n : {\n baseURL: options.baseURL,\n headers: options.headers,\n credentials: options.credentials,\n ...(typeof options.integrations === \"object\" ? options.integrations : {}),\n };\n const rootAliases =\n integrationOptions === false\n ? undefined\n : {\n integrations: integrationsClient<TIntegrations>(integrationOptions),\n };\n\n const cacheState = getFarmClientDataCache();\n const inflightState = new Map<string, InflightEntry>();\n const routeMeta = new WeakMap<AnyRouteRef, RouteMeta>();\n let requestCounter = 0;\n\n // Create a simple fetch-based client (browser compatible)\n const fetchClient = async (path: string, requestOptions: any = {}) => {\n const url = new URL(path, baseURL);\n\n // Handle query parameters\n if (requestOptions.query) {\n Object.entries(requestOptions.query).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n url.searchParams.set(key, String(value));\n }\n });\n }\n\n // Prepare fetch options\n const fetchOptions: RequestInit = {\n method: requestOptions.method || \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n ...requestOptions.headers,\n },\n };\n\n // Handle body\n if (requestOptions.body) {\n fetchOptions.body = JSON.stringify(requestOptions.body);\n }\n\n const response = await fetch(url.toString(), fetchOptions);\n let data: any = undefined;\n if (response.status !== 204 && response.status !== 205) {\n data = await response.json();\n }\n\n return { response, data };\n };\n\n const request = async (\n path: string,\n method: string,\n input: any = {},\n clientOptions?: ClientOptions<any, any>,\n ): Promise<APIResult<any, Error>> => {\n const methodUpper = method.toUpperCase() as StatusEvent[\"method\"];\n const requestId = `${Date.now()}-${++requestCounter}`;\n const cacheOptions = clientOptions?.cache\n ? {\n ...options.cacheDefaults,\n ...clientOptions.cache,\n }\n : undefined;\n const configuredCacheKey = clientOptions?.key ?? cacheOptions?.key;\n const cacheKey = normalizeFarmClientCacheKey(\n configuredCacheKey ?? buildCacheKey(methodUpper, path, input, baseURL),\n ) as CacheKey<any>;\n const now = Date.now();\n\n const emitStatus = (phase: StatusPhase, payload?: Partial<StatusEvent>) => {\n clientOptions?.onStatus?.({\n phase,\n requestId,\n method: methodUpper,\n key: cacheKey,\n input,\n timestamp: Date.now(),\n ...payload,\n });\n };\n\n const entry = getValidCacheEntry(cacheState, cacheKey, now);\n const policy = cacheOptions?.policy ?? (cacheOptions ? \"cache-first\" : \"network-only\");\n const staleTime = cacheOptions?.staleTime ?? 0;\n const isCacheEnabled = Boolean(cacheOptions) && methodUpper === \"GET\";\n const isStale = entry ? isEntryStale(entry, now) : true;\n\n const applyOptimisticUpdates = () => {\n if (!clientOptions?.optimistic?.update?.length) return [] as OptimisticSnapshot[];\n\n const snapshots: OptimisticSnapshot[] = [];\n for (const update of clientOptions.optimistic.update) {\n const [target, targetInput, updater] =\n update.length === 2\n ? [update[0], undefined, update[1]]\n : [update[0], update[1], update[2]];\n const targetKey = resolveTargetKey(routeMeta, target, targetInput, baseURL);\n if (!targetKey) continue;\n\n const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n const previousEntry = targetEntry ? { ...targetEntry } : undefined;\n const previousData = targetEntry?.data;\n const nextData = updater(previousData);\n cacheState.set(targetKey, {\n data: nextData,\n updatedAt: now,\n staleAt:\n targetEntry?.staleAt ??\n now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),\n gcAt:\n targetEntry?.gcAt ??\n getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime),\n invalidatedAt: targetEntry?.invalidatedAt,\n });\n\n snapshots.push({ key: targetKey, entry: previousEntry });\n }\n\n return snapshots;\n };\n\n const rollbackOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n if (!clientOptions?.optimistic?.rollbackOnError) return;\n\n for (const snapshot of snapshots) {\n if (!snapshot.entry) {\n cacheState.delete(snapshot.key);\n continue;\n }\n\n cacheState.set(snapshot.key, { ...snapshot.entry });\n }\n };\n\n const executeNetwork = async (opts?: { isBackground?: boolean; callCallbacks?: boolean }) => {\n const dedupeMs = cacheOptions?.dedupeMs ?? 0;\n const inflight = inflightState.get(cacheKey);\n const allowDedupe = isCacheEnabled && dedupeMs > 0;\n\n if (allowDedupe && inflight && now - inflight.startedAt < dedupeMs) {\n emitStatus(\"pending\", { isBackground: opts?.isBackground, data: entry?.data });\n const result = await inflight.promise;\n\n if (result.error) {\n emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n if (opts?.callCallbacks !== false) {\n clientOptions?.onError?.(result.error);\n }\n } else {\n emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n if (opts?.callCallbacks !== false) {\n clientOptions?.onSuccess?.(result.data as any);\n }\n }\n\n return result;\n }\n\n emitStatus(opts?.isBackground ? \"revalidating\" : \"pending\", {\n isBackground: opts?.isBackground,\n });\n\n const promise = (async () => {\n const maxRetries = Math.max(0, clientOptions?.retry?.count ?? 0);\n let attempt = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n clientOptions?.onRequest?.({\n requestId,\n method: methodUpper,\n key: cacheKey,\n path,\n input,\n attempt,\n timestamp: Date.now(),\n });\n\n try {\n const { response, data } = await fetchClient(path, {\n ...input,\n method: methodUpper,\n });\n\n const error = response.ok ? null : createResponseError(response, data);\n\n const responseEvent: ResponseEvent<any, Error> = {\n requestId,\n method: methodUpper,\n key: cacheKey,\n path,\n input,\n attempt,\n timestamp: Date.now(),\n response,\n data: response.ok ? data : undefined,\n error: error ?? undefined,\n ok: response.ok,\n status: response.status,\n };\n\n clientOptions?.onResponse?.(response.ok ? data : undefined, error, responseEvent);\n\n if (!error) {\n return { data, error: null, key: cacheKey } as APIResult<any, Error>;\n }\n\n if (attempt >= maxRetries) {\n return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n }\n } catch (err: any) {\n const error = normalizeError(err);\n const responseEvent: ResponseEvent<any, Error> = {\n requestId,\n method: methodUpper,\n key: cacheKey,\n path,\n input,\n attempt,\n timestamp: Date.now(),\n error,\n ok: false,\n };\n\n clientOptions?.onResponse?.(undefined, error, responseEvent);\n\n if (attempt >= maxRetries) {\n return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n }\n }\n\n attempt += 1;\n const delay =\n typeof clientOptions?.retry?.delay === \"function\"\n ? clientOptions.retry.delay(attempt)\n : (clientOptions?.retry?.delay ?? 0);\n\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n })();\n\n inflightState.set(cacheKey, { promise, startedAt: now });\n\n try {\n const result = await promise;\n\n if (!result.error && isCacheEnabled) {\n const updatedAt = Date.now();\n cacheState.set(cacheKey, {\n data: result.data,\n updatedAt,\n staleAt: updatedAt + staleTime,\n gcAt: getGcAt(updatedAt, cacheOptions?.gcTime),\n invalidatedAt: undefined,\n });\n }\n\n if (result.error) {\n emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n if (opts?.callCallbacks !== false) {\n clientOptions?.onError?.(result.error);\n }\n } else {\n emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n if (opts?.callCallbacks !== false) {\n clientOptions?.onSuccess?.(result.data as any);\n }\n }\n\n return result;\n } finally {\n inflightState.delete(cacheKey);\n }\n };\n\n const invalidateTargets = async () => {\n if (!clientOptions?.invalidate) return;\n\n const invalidateOptions = Array.isArray(clientOptions.invalidate)\n ? { targets: clientOptions.invalidate, refetch: false }\n : {\n targets: clientOptions.invalidate.targets,\n refetch: clientOptions.invalidate.refetch ?? false,\n };\n\n for (const target of invalidateOptions.targets) {\n const targetKey = resolveTargetKey(routeMeta, target, undefined, baseURL);\n if (!targetKey) continue;\n\n const existing = cacheState.get(targetKey);\n if (existing) {\n cacheState.set(targetKey, {\n ...existing,\n staleAt: 0,\n invalidatedAt: Date.now(),\n });\n }\n\n emitStatus(\"invalidated\", { key: targetKey });\n\n if (invalidateOptions.refetch && existing && targetKey === cacheKey) {\n void executeNetwork({ isBackground: true, callCallbacks: false });\n }\n }\n };\n\n const optimisticSnapshots = applyOptimisticUpdates();\n\n if (isCacheEnabled) {\n if (entry && !isStale && policy !== \"network-only\") {\n emitStatus(\"success\", { data: entry.data });\n clientOptions?.onSuccess?.(entry.data);\n clientOptions?.onSettled?.(entry.data, null);\n return { data: entry.data, error: null, key: cacheKey };\n }\n\n if (entry && isStale && policy === \"stale-while-revalidate\") {\n emitStatus(\"success\", { data: entry.data });\n clientOptions?.onSuccess?.(entry.data);\n clientOptions?.onSettled?.(entry.data, null);\n\n void executeNetwork({ isBackground: true, callCallbacks: false });\n return { data: entry.data, error: null, key: cacheKey };\n }\n }\n\n const result = await executeNetwork();\n if (result.error) {\n rollbackOptimisticUpdates(optimisticSnapshots);\n }\n await invalidateTargets();\n clientOptions?.onSettled?.(result.data, result.error);\n return result;\n };\n\n // Return nested proxy (starts with empty path, user adds to it)\n return createNestedProxy([], request, routeMeta, baseURL, rootAliases) as APIClient<\n TRouter,\n TIntegrations\n >;\n}\n\n/**\n * Create a nested proxy that builds up the path\n *\n * Flow:\n * 1. api.hello -> Proxy(['hello'])\n * 2. api.hello.get -> Proxy(['hello', 'get'])\n * 3. api.hello.get({ query: {...} })\n * -> fetch('/api/hello', { method: 'GET', ... })\n *\n * For routes with single method:\n * 1. api.hello -> Proxy(['hello'])\n * 2. api.hello({ query: {...} })\n * -> fetch('/api/hello', ...)\n */\nfunction createNestedProxy(\n path: string[],\n client: any,\n routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n baseURL: string,\n rootAliases?: Record<string, unknown>,\n): any {\n const target = () => {};\n const proxy = new Proxy(target, {\n // When accessing a property (api.hello)\n get(_target, prop: string) {\n if (path.length === 0 && typeof prop === \"string\" && rootAliases && prop in rootAliases) {\n return rootAliases[prop];\n }\n\n // Add prop to path and return new proxy\n return createNestedProxy([...path, prop], client, routeMeta, baseURL, rootAliases);\n },\n\n // When calling as a function\n apply(_target, _thisArg, args) {\n // Check if the last part is an HTTP method\n const lastPart = path[path.length - 1];\n const httpMethods = [\"get\", \"post\", \"put\", \"delete\", \"patch\", \"options\", \"head\"];\n\n if (httpMethods.includes(lastPart)) {\n // Method is explicitly called: api.users.get() or api['auth/login'].post()\n // Remove the method from path and use it as the HTTP method\n const routePath = \"/api/\" + path.slice(0, -1).join(\"/\");\n const method = lastPart.toUpperCase();\n\n // Extract options from arguments\n const [options, clientOptions] = args;\n\n // Call fetch client with explicit method\n return client(routePath, method, options, clientOptions);\n } else {\n // Direct call without method: api.hello()\n // Use the full path and let the server determine the method (usually GET)\n const routePath = \"/api/\" + path.join(\"/\");\n\n // Extract options from arguments\n const [options, clientOptions] = args;\n\n // Call fetch client (default method will be GET)\n return client(routePath, options?.method || \"GET\", options, clientOptions);\n }\n },\n });\n\n routeMeta.set(proxy, { path: [...path], baseURL });\n return proxy;\n}\n\n/**\n * Server-side API client that calls endpoints directly as functions\n * No HTTP overhead for app endpoints, and registered integration routes can be exposed at\n * api.integrations.* where Farm can dispatch them directly to the integration handler.\n *\n * @example\n * ```typescript\n * import { createServerAPIClient } from 'farm/client';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createServerAPIClient<{}, AppIntegrations>({});\n *\n * const result = await api.integrations.billing.status();\n * ```\n */\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n endpoints: TEndpoints,\n): TEndpoints;\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n endpoints: TEndpoints,\n options: ServerAPIClientWithoutIntegrationsOptions,\n): TEndpoints;\nexport function createServerAPIClient<\n TEndpoints extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n endpoints: TEndpoints,\n options?: ServerAPIClientOptions,\n): ServerAPIClient<TEndpoints, TIntegrations>;\nexport function createServerAPIClient<\n TEndpoints extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n endpoints: TEndpoints,\n options: ServerAPIClientOptions | ServerAPIClientWithoutIntegrationsOptions = {},\n): TEndpoints | ServerAPIClient<TEndpoints, TIntegrations> {\n if (\n options.integrations === false ||\n Object.prototype.hasOwnProperty.call(endpoints, \"integrations\")\n ) {\n return endpoints;\n }\n\n Object.defineProperty(endpoints, \"integrations\", {\n get() {\n return integrationsServer<TIntegrations>(\n typeof options.integrations === \"object\" ? options.integrations : {},\n );\n },\n enumerable: false,\n configurable: true,\n });\n\n return endpoints as ServerAPIClient<TEndpoints, TIntegrations>;\n}\n\ntype CacheEntry = FarmClientCacheEntry<any>;\n\ntype InflightEntry = {\n promise: Promise<APIResult<any, Error>>;\n startedAt: number;\n};\n\ntype RouteMeta = {\n path: string[];\n baseURL: string;\n};\n\ntype OptimisticSnapshot = {\n key: string;\n entry?: CacheEntry;\n};\n\nfunction buildCacheKey(method: string, path: string, input: any, baseURL: string): string {\n const keyInput =\n input && typeof input === \"object\" ? { query: input.query, body: input.body } : input;\n const url = new URL(path, baseURL);\n return `${method}:${url.origin}${url.pathname}:${stableStringify(keyInput ?? {})}`;\n}\n\nfunction stableStringify(value: any): string {\n if (value === null || value === undefined) return String(value);\n if (value instanceof Date) return value.toISOString();\n if (typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n\n const keys = Object.keys(value).sort();\n const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);\n return `{${entries.join(\",\")}}`;\n}\n\nfunction getGcAt(now: number, gcTime?: number): number | undefined {\n if (gcTime === undefined) return undefined;\n if (!Number.isFinite(gcTime) || gcTime <= 0) return now;\n return now + gcTime;\n}\n\nfunction getValidCacheEntry(\n cacheState: FarmClientDataCache,\n key: string,\n now: number,\n): CacheEntry | undefined {\n const entry = cacheState.get(key);\n if (!entry) return undefined;\n\n if (entry.gcAt !== undefined && now >= entry.gcAt) {\n cacheState.delete(key);\n return undefined;\n }\n\n return entry;\n}\n\nfunction isEntryStale(entry: CacheEntry, now: number): boolean {\n if (entry.invalidatedAt !== undefined) return true;\n return now >= entry.staleAt;\n}\n\nfunction resolveTargetKey(\n routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n target: InvalidateTarget | AnyRouteRef,\n input?: unknown,\n baseURL = \"http://localhost:3000\",\n): string | null {\n if (!target) return null;\n\n if (typeof target === \"string\") return target;\n\n if (typeof target === \"function\") {\n const meta = routeMeta.get(target);\n if (!meta) return null;\n\n const { method, routePath } = resolveRouteMeta(meta);\n return buildCacheKey(method, routePath, input ?? {}, meta.baseURL);\n }\n\n if (Array.isArray(target)) {\n const [route, routeInput] = target;\n return resolveTargetKey(routeMeta, route, routeInput, baseURL);\n }\n\n if (\"key\" in target) return normalizeFarmClientCacheKey(target.key);\n\n if (\"path\" in target) {\n const method = target.method ?? \"GET\";\n return buildCacheKey(method, target.path, target.input ?? {}, baseURL);\n }\n\n return null;\n}\n\nfunction resolveRouteMeta(meta: RouteMeta): { routePath: string; method: string } {\n const httpMethods = [\"get\", \"post\", \"put\", \"delete\", \"patch\", \"options\", \"head\"];\n const lastPart = meta.path[meta.path.length - 1];\n if (lastPart && httpMethods.includes(lastPart)) {\n return {\n routePath: \"/api/\" + meta.path.slice(0, -1).join(\"/\"),\n method: lastPart.toUpperCase(),\n };\n }\n\n return {\n routePath: \"/api/\" + meta.path.join(\"/\"),\n method: \"GET\",\n };\n}\n\nfunction normalizeError(error: unknown): Error {\n if (error instanceof Error) return error;\n return new Error(typeof error === \"string\" ? error : \"Unknown error\");\n}\n\nfunction createResponseError(response: Response, data: any): Error {\n const error = new Error(`HTTP ${response.status}: ${response.statusText}`);\n (error as any).status = response.status;\n (error as any).response = response;\n (error as any).data = data;\n return error;\n}\n"],"mappings":";;;;;;;;;AAiDO,IAAM,0BAAN,MAAM,gCAAgD,MAAM;AAAA,EAKjE,YAAY,SAAiB,UAAoB,MAAc;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AM,GAAG,EAAE,EAAE,KAAK,GAAG;AAAA,MACpD,QAAQ,SAAS,YAAY;AAAA,IAC/B;AAAA,EACF;AAEA,SAAO;AAAA,IACL,WAAW,UAAU,KAAK,KAAK,KAAK,GAAG;AAAA,IACvC,QAAQ;AAAA,EACV;AACF;AAdS;AAgBT,SAAS,eAAe,OAAuB;AAC7C,MAAI,iBAAiB,MAAO,QAAO;AACnC,SAAO,IAAI,MAAM,OAAO,UAAU,WAAW,QAAQ,eAAe;AACtE;AAHS;AAKT,SAASC,qBAAoB,UAAoB,MAAkB;AACjE,QAAM,QAAQ,IAAI,MAAM,QAAQ,SAAS,MAAM,KAAK,SAAS,UAAU,EAAE;AACzE,EAAC,MAAc,SAAS,SAAS;AACjC,EAAC,MAAc,WAAW;AAC1B,EAAC,MAAc,OAAO;AACtB,SAAO;AACT;AANS,OAAAA,sBAAA;","names":["result","createResponseError"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/vite-config.ts"],"sourcesContent":["import type { UserConfig as ViteUserConfig } from \"vite\";\n\ntype ViteNoExternal = NonNullable<NonNullable<ViteUserConfig[\"ssr\"]>[\"noExternal\"]>;\n\nfunction mergeNoExternal(\n farmValue: ViteNoExternal | undefined,\n userValue: ViteNoExternal | undefined,\n): ViteNoExternal {\n if (farmValue === true || userValue === true) return true;\n\n const normalize = (value: ViteNoExternal | undefined) =>\n value == null ? [] : Array.isArray(value) ? value : [value];\n\n return Array.from(new Set([...normalize(farmValue), ...normalize(userValue)]));\n}\n\nexport function mergeFarmViteConfig(\n farmConfig: ViteUserConfig,\n userConfig: ViteUserConfig = {},\n): ViteUserConfig {\n return {\n ...farmConfig,\n ...userConfig,\n plugins: [...(farmConfig.plugins || []), ...(userConfig.plugins || [])],\n server: {\n ...farmConfig.server,\n ...userConfig.server,\n },\n optimizeDeps: {\n ...farmConfig.optimizeDeps,\n ...userConfig.optimizeDeps,\n include: Array.from(\n new Set([\n ...(farmConfig.optimizeDeps?.include || []),\n ...(userConfig.optimizeDeps?.include || []),\n ]),\n ),\n exclude: Array.from(\n new Set([\n ...(farmConfig.optimizeDeps?.exclude || []),\n ...(userConfig.optimizeDeps?.exclude || []),\n ]),\n ),\n },\n ssr: {\n ...farmConfig.ssr,\n ...userConfig.ssr,\n noExternal: mergeNoExternal(farmConfig.ssr?.noExternal, userConfig.ssr?.noExternal),\n },\n };\n}\n"],"mappings":";;;;;AAIA,SAAS,gBACP,WACA,WACgB;AAChB,MAAI,cAAc,QAAQ,cAAc,KAAM,QAAO;AAErD,QAAM,YAAY,wBAAC,UACjB,SAAS,OAAO,CAAC,IAAI,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GAD1C;AAGlB,SAAO,MAAM,KAAK,oBAAI,IAAI,CAAC,GAAG,UAAU,SAAS,GAAG,GAAG,UAAU,SAAS,CAAC,CAAC,CAAC;AAC/E;AAVS;AAYF,SAAS,oBACd,YACA,aAA6B,CAAC,GACd;AAChB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,IACH,SAAS,CAAC,GAAI,WAAW,WAAW,CAAC,GAAI,GAAI,WAAW,WAAW,CAAC,CAAE;AAAA,IACtE,QAAQ;AAAA,MACN,GAAG,WAAW;AAAA,MACd,GAAG,WAAW;AAAA,IAChB;AAAA,IACA,cAAc;AAAA,MACZ,GAAG,WAAW;AAAA,MACd,GAAG,WAAW;AAAA,MACd,SAAS,MAAM;AAAA,QACb,oBAAI,IAAI;AAAA,UACN,GAAI,WAAW,cAAc,WAAW,CAAC;AAAA,UACzC,GAAI,WAAW,cAAc,WAAW,CAAC;AAAA,QAC3C,CAAC;AAAA,MACH;AAAA,MACA,SAAS,MAAM;AAAA,QACb,oBAAI,IAAI;AAAA,UACN,GAAI,WAAW,cAAc,WAAW,CAAC;AAAA,UACzC,GAAI,WAAW,cAAc,WAAW,CAAC;AAAA,QAC3C,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,GAAG,WAAW;AAAA,MACd,GAAG,WAAW;AAAA,MACd,YAAY,gBAAgB,WAAW,KAAK,YAAY,WAAW,KAAK,UAAU;AAAA,IACpF;AAAA,EACF;AACF;AAlCgB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/app-markdown.ts"],"sourcesContent":["import React from \"react\";\nimport { readFile } from \"fs/promises\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport type { Metadata, RouteModule } from \"./types\";\n\nexport type FarmMdxComponent = React.ComponentType<any> | keyof React.JSX.IntrinsicElements;\nexport type FarmMdxComponents = Record<string, FarmMdxComponent>;\n\nexport interface FarmMdxUserConfig {\n /**\n * Component map or module path that exports `components` or a default component map.\n * Relative paths resolve from the project root.\n */\n components?: string | FarmMdxComponents;\n /**\n * Serve source-authored markdown pages at `/route.md`.\n * Enabled by default for `page.md` and `page.mdx`.\n */\n markdownRoutes?: boolean;\n /**\n * Class name used for the wrapper around rendered markdown content.\n */\n className?: string;\n}\n\nexport interface FarmMdxResolvedConfig {\n components?: string | FarmMdxComponents;\n markdownRoutes: boolean;\n className: string;\n}\n\nexport interface FarmMarkdownPageSource {\n source: string;\n filePath: string;\n}\n\nexport interface FarmMarkdownPageModuleInput extends FarmMarkdownPageSource {\n components?: FarmMdxComponents;\n config?: FarmMdxResolvedConfig;\n}\n\nexport function resolveMdxConfig(config: FarmMdxUserConfig | undefined): FarmMdxResolvedConfig {\n return {\n components: config?.components,\n markdownRoutes: config?.markdownRoutes ?? true,\n className: config?.className ?? \"farm-markdown\",\n };\n}\n\nexport function isFarmMarkdownPageFile(filePath: string): boolean {\n return /(^|[/\\\\])page\\.mdx?$/i.test(filePath);\n}\n\nexport function normalizeFarmMarkdownRoutePath(pathname: string): string {\n const withoutExtension = pathname.replace(/\\.md$/i, \"\");\n const normalized = withoutExtension.startsWith(\"/\") ? withoutExtension : `/${withoutExtension}`;\n return normalized === \"/index\" ? \"/\" : normalized.replace(/\\/+$/g, \"\") || \"/\";\n}\n\nexport function parseMarkdownFrontmatter(source: string): {\n frontmatter: Record<string, string>;\n body: string;\n} {\n if (!source.startsWith(\"---\")) {\n return { frontmatter: {}, body: source };\n }\n\n const endIndex = source.indexOf(\"\\n---\", 3);\n if (endIndex === -1) {\n return { frontmatter: {}, body: source };\n }\n\n const frontmatterSource = source.slice(3, endIndex).trim();\n const closingFenceEnd = endIndex + \"\\n---\".length;\n const bodyStart =\n source.slice(closingFenceEnd, closingFenceEnd + 2) === \"\\r\\n\"\n ? closingFenceEnd + 2\n : source[closingFenceEnd] === \"\\n\"\n ? closingFenceEnd + 1\n : closingFenceEnd;\n const body = source.slice(bodyStart);\n const frontmatter: Record<string, string> = {};\n\n for (const line of frontmatterSource.split(/\\r?\\n/)) {\n const separator = line.indexOf(\":\");\n if (separator === -1) continue;\n const key = line.slice(0, separator).trim();\n const value = line\n .slice(separator + 1)\n .trim()\n .replace(/^[\"']|[\"']$/g, \"\");\n if (key && value) frontmatter[key] = value;\n }\n\n return { frontmatter, body };\n}\n\nexport function titleFromMarkdown(body: string, fallback?: string): string | undefined {\n return body.match(/^#\\s+(.+)$/m)?.[1]?.trim() || fallback;\n}\n\nexport function createMarkdownMetadata(\n source: string,\n filePath: string,\n): (Metadata & Record<string, any>) | undefined {\n const { frontmatter, body } = parseMarkdownFrontmatter(source);\n const routeTitle = titleFromMarkdown(body);\n const title = frontmatter.title || routeTitle;\n const description = frontmatter.description;\n\n if (!title && !description) {\n return undefined;\n }\n\n return {\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n source: filePath,\n };\n}\n\nasync function evaluateMdxSource(source: string, filePath: string) {\n const [{ evaluate }, runtime, remarkGfmModule] = await Promise.all([\n import(\"@mdx-js/mdx\"),\n import(\"react/jsx-runtime\"),\n import(\"remark-gfm\"),\n ]);\n const remarkGfm = remarkGfmModule.default;\n\n return evaluate(source, {\n ...runtime,\n baseUrl: pathToFileURL(filePath),\n remarkPlugins: [remarkGfm],\n });\n}\n\nexport function createFarmMarkdownRouteModule(\n input: FarmMarkdownPageModuleInput,\n): RouteModule & { source: string } {\n const { body } = parseMarkdownFrontmatter(input.source);\n const components = input.components || {};\n const className = input.config?.className || \"farm-markdown\";\n let evaluatedPromise: Promise<{ default: React.ComponentType<any> }> | undefined;\n\n const loadContent = async () => {\n evaluatedPromise ??= evaluateMdxSource(body, input.filePath) as Promise<{\n default: React.ComponentType<any>;\n }>;\n return evaluatedPromise;\n };\n\n async function FarmMarkdownPage(props: any) {\n const evaluated = await loadContent();\n const MDXContent = evaluated.default;\n return React.createElement(\n \"article\",\n { className, \"data-farm-markdown-page\": \"\" },\n React.createElement(MDXContent, {\n ...props,\n components: {\n ...components,\n ...(props?.components || {}),\n },\n }),\n );\n }\n\n return {\n default: FarmMarkdownPage as unknown as RouteModule[\"default\"],\n metadata: createMarkdownMetadata(input.source, input.filePath),\n source: input.source,\n };\n}\n\nexport async function createFarmMarkdownRouteModuleFromFile(\n filePath: string,\n options: {\n components?: FarmMdxComponents;\n config?: FarmMdxResolvedConfig;\n } = {},\n) {\n const source = await readFile(filePath, \"utf8\");\n return createFarmMarkdownRouteModule({\n source,\n filePath,\n components: options.components,\n config: options.config,\n });\n}\n\nexport async function loadFarmMdxComponents(\n config: FarmMdxResolvedConfig | undefined,\n options: {\n root: string;\n loadModule?: (modulePath: string) => Promise<unknown>;\n },\n): Promise<FarmMdxComponents> {\n const configured = config?.components;\n if (!configured) {\n return {};\n }\n\n if (typeof configured !== \"string\") {\n return configured;\n }\n\n const modulePath = path.isAbsolute(configured) ? configured : path.join(options.root, configured);\n const mod = options.loadModule\n ? await options.loadModule(modulePath)\n : await import(pathToFileURL(modulePath).href);\n const maybeModule = mod as {\n components?: FarmMdxComponents;\n default?: FarmMdxComponents;\n };\n\n return maybeModule.components || maybeModule.default || {};\n}\n\nexport async function createFarmMarkdownSourceResponse(options: {\n request: Request;\n config?: FarmMdxResolvedConfig;\n resolveSource: (\n pathname: string,\n ) => Promise<FarmMarkdownPageSource | null> | FarmMarkdownPageSource | null;\n}): Promise<Response | null> {\n if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n return null;\n }\n if (options.config?.markdownRoutes === false) {\n return null;\n }\n\n const url = new URL(options.request.url);\n if (!url.pathname.endsWith(\".md\")) {\n return null;\n }\n\n const targetPathname = normalizeFarmMarkdownRoutePath(url.pathname);\n const source = await options.resolveSource(targetPathname);\n if (!source) {\n return null;\n }\n\n return new Response(options.request.method === \"HEAD\" ? null : source.source, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/markdown; charset=utf-8\",\n \"Cache-Control\": \"public, s-maxage=60, stale-while-revalidate=300\",\n \"X-Farm-Markdown-Route\": targetPathname,\n \"X-Farm-Markdown-Source\": source.filePath,\n },\n });\n}\n"],"mappings":";;;;;AAAA,OAAO,WAAW;AAClB,SAAS,gBAAgB;AACzB,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAuCvB,SAAS,iBAAiB,QAA8D;AAC7F,SAAO;AAAA,IACL,YAAY,QAAQ;AAAA,IACpB,gBAAgB,QAAQ,kBAAkB;AAAA,IAC1C,WAAW,QAAQ,aAAa;AAAA,EAClC;AACF;AANgB;AAQT,SAAS,uBAAuB,UAA2B;AAChE,SAAO,wBAAwB,KAAK,QAAQ;AAC9C;AAFgB;AAIT,SAAS,+BAA+B,UAA0B;AACvE,QAAM,mBAAmB,SAAS,QAAQ,UAAU,EAAE;AACtD,QAAM,aAAa,iBAAiB,WAAW,GAAG,IAAI,mBAAmB,IAAI,gBAAgB;AAC7F,SAAO,eAAe,WAAW,MAAM,WAAW,QAAQ,SAAS,EAAE,KAAK;AAC5E;AAJgB;AAMT,SAAS,yBAAyB,QAGvC;AACA,MAAI,CAAC,OAAO,WAAW,KAAK,GAAG;AAC7B,WAAO,EAAE,aAAa,CAAC,GAAG,MAAM,OAAO;AAAA,EACzC;AAEA,QAAM,WAAW,OAAO,QAAQ,SAAS,CAAC;AAC1C,MAAI,aAAa,IAAI;AACnB,WAAO,EAAE,aAAa,CAAC,GAAG,MAA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,QAAM,aAAa,QAAQ;AAC3B,MAAI,CAAC,YAAY;AACf,WAAO,CAAC;AAAA,EACV;AAEA,MAAI,OAAO,eAAe,UAAU;AAClC,WAAO;AAAA,EACT;AAEA,QAAM,aAAa,KAAK,WAAW,UAAU,IAAI,aAAa,KAAK,KAAK,QAAQ,MAAM,UAAU;AAChG,QAAM,MAAM,QAAQ,aAChB,MAAM,QAAQ,WAAW,UAAU,IACnC,MAAM,OAAO,cAAc,UAAU,EAAE;AAC3C,QAAM,cAAc;AAKpB,SAAO,YAAY,cAAc,YAAY,WAAW,CAAC;AAC3D;AA1BsB;AA4BtB,eAAsB,iCAAiC,SAM1B;AAC3B,MAAI,QAAQ,QAAQ,WAAW,SAAS,QAAQ,QAAQ,WAAW,QAAQ;AACzE,WAAO;AAAA,EACT;AACA,MAAI,QAAQ,QAAQ,mBAAmB,OAAO;AAC5C,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,IAAI,IAAI,QAAQ,QAAQ,GAAG;AACvC,MAAI,CAAC,IAAI,SAAS,SAAS,KAAK,GAAG;AACjC,WAAO;AAAA,EACT;AAEA,QAAM,iBAAiB,+BAA+B,IAAI,QAAQ;AAClE,QAAM,SAAS,MAAM,QAAQ,cAAc,cAAc;AACzD,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,SAAO,IAAI,SAAS,QAAQ,QAAQ,WAAW,SAAS,OAAO,OAAO,QAAQ;AAAA,IAC5E,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,MACjB,yBAAyB;AAAA,MACzB,0BAA0B,OAAO;AAAA,IACnC;AAAA,EACF,CAAC;AACH;AAlCsB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/client/chunk-recovery.ts"],"sourcesContent":["\"use client\";\n\nexport interface FarmChunkRecoveryOptions {\n /**\n * How long a page is considered already recovered before another chunk\n * failure may trigger a reload. Defaults to 30 seconds.\n */\n maxAgeMs?: number;\n /**\n * Override the storage key. Mostly useful for tests and embedded runtimes.\n */\n storageKey?: string;\n /**\n * Called right before Farm reloads the page.\n */\n onRecover?: (error: unknown) => void;\n /**\n * Test hooks for browser globals.\n */\n reload?: () => void;\n storage?: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | null;\n location?: Pick<Location, \"pathname\" | \"search\" | \"reload\">;\n now?: () => number;\n}\n\nconst DEFAULT_MAX_AGE_MS = 30_000;\nconst STORAGE_KEY_PREFIX = \"farm:chunk-recovery:\";\nconst CHUNK_ERROR_PATTERNS = [\n /ChunkLoadError/i,\n /Loading chunk [\\w-]+ failed/i,\n /Loading CSS chunk [\\w-]+ failed/i,\n /CSS_CHUNK_LOAD_FAILED/i,\n /failed to fetch dynamically imported module/i,\n /error loading dynamically imported module/i,\n /importing a module script failed/i,\n /unable to preload CSS/i,\n /module script failed/i,\n];\n\nexport function isChunkLoadError(errorLike: unknown): boolean {\n const values = collectErrorText(errorLike);\n if (values.some((value) => CHUNK_ERROR_PATTERNS.some((pattern) => pattern.test(value)))) {\n return true;\n }\n\n const targetUrl = getEventTargetAssetUrl(errorLike);\n return Boolean(targetUrl && /\\.(?:m?js|css)(?:[?#].*)?$/i.test(targetUrl));\n}\n\nexport function installChunkErrorRecovery(\n options: FarmChunkRecoveryOptions = {},\n): () => void {\n if (typeof window === \"undefined\") {\n return () => {};\n }\n\n const recover = (errorLike: unknown) => {\n if (!isChunkLoadError(errorLike)) {\n return;\n }\n if (!markRecovered(options)) {\n return;\n }\n\n options.onRecover?.(errorLike);\n getReload(options)();\n };\n\n const onError = (event: Event | ErrorEvent) => {\n recover(getErrorEventPayload(event));\n };\n const onUnhandledRejection = (event: PromiseRejectionEvent) => {\n recover(event.reason);\n };\n\n window.addEventListener(\"error\", onError, true);\n window.addEventListener(\"unhandledrejection\", onUnhandledRejection);\n\n return () => {\n window.removeEventListener(\"error\", onError, true);\n window.removeEventListener(\"unhandledrejection\", onUnhandledRejection);\n };\n}\n\nfunction markRecovered(options: FarmChunkRecoveryOptions): boolean {\n const now = getNow(options);\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n const storage = getStorage(options);\n const key = getStorageKey(options);\n\n if (!storage) {\n return true;\n }\n\n try {\n const previous = Number(storage.getItem(key));\n if (Number.isFinite(previous) && previous > 0 && now - previous < maxAgeMs) {\n return false;\n }\n storage.setItem(key, String(now));\n return true;\n } catch {\n return true;\n }\n}\n\nfunction getErrorEventPayload(event: Event | ErrorEvent): unknown {\n if (\"error\" in event && event.error) {\n return event.error;\n }\n if (\"message\" in event && event.message) {\n return event.message;\n }\n return event;\n}\n\nfunction collectErrorText(value: unknown, seen = new Set<unknown>()): string[] {\n if (value == null || seen.has(value)) {\n return [];\n }\n seen.add(value);\n\n if (typeof value === \"string\") {\n return [value];\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return [String(value)];\n }\n if (typeof value !== \"object\") {\n return [];\n }\n\n const record = value as Record<string, unknown>;\n const output: string[] = [];\n\n for (const key of [\"name\", \"message\", \"code\", \"type\", \"request\", \"src\", \"href\"]) {\n const candidate = record[key];\n if (typeof candidate === \"string\") {\n output.push(candidate);\n }\n }\n\n if (\"reason\" in record) {\n output.push(...collectErrorText(record.reason, seen));\n }\n if (\"error\" in record) {\n output.push(...collectErrorText(record.error, seen));\n }\n\n return output;\n}\n\nfunction getEventTargetAssetUrl(value: unknown): string | undefined {\n if (!value || typeof value !== \"object\") {\n return undefined;\n }\n\n const target = (value as Event).target as\n | (EventTarget & { src?: string; href?: string; tagName?: string })\n | null\n | undefined;\n if (!target || typeof target !== \"object\") {\n return undefined;\n }\n\n const tagName = typeof target.tagName === \"string\" ? target.tagName.toLowerCase() : \"\";\n if (tagName !== \"script\" && tagName !== \"link\") {\n return undefined;\n }\n\n return typeof target.src === \"string\" && target.src\n ? target.src\n : typeof target.href === \"string\" && target.href\n ? target.href\n : undefined;\n}\n\nfunction getStorage(options: FarmChunkRecoveryOptions) {\n if (\"storage\" in options) {\n return options.storage;\n }\n\n try {\n return window.sessionStorage;\n } catch {\n return null;\n }\n}\n\nfunction getStorageKey(options: FarmChunkRecoveryOptions): string {\n if (options.storageKey) {\n return options.storageKey;\n }\n\n const location = getLocation(options);\n return `${STORAGE_KEY_PREFIX}${location.pathname}${location.search}`;\n}\n\nfunction getLocation(options: FarmChunkRecoveryOptions) {\n return options.location ?? window.location;\n}\n\nfunction getReload(options: FarmChunkRecoveryOptions): () => void {\n if (options.reload) {\n return options.reload;\n }\n\n const location = getLocation(options);\n return () => location.reload();\n}\n\nfunction getNow(options: FarmChunkRecoveryOptions): number {\n return options.now ? options.now() : Date.now();\n}\n"],"mappings":";;;;;AAyBA,IAAM,qBAAqB;AAC3B,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,iBAAiB,WAA6B;AAC5D,QAAM,SAAS,iBAAiB,SAAS;AACzC,MAAI,OAAO,KAAK,CAAC,UAAU,qBAAqB,KAAK,CAAC,YAAY,QAAQ,KAAK,KAAK,CAAC,CAAC,GAAG;AACvF,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,uBAAuB,SAAS;AAClD,SAAO,QAAQ,aAAa,8BAA8B,KAAK,SAAS,CAAC;AAC3E;AARgB;AAUT,SAAS,0BACd,UAAoC,CAAC,GACzB;AACZ,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,MAAM;AAAA,IAAC;AAAA,EAChB;AAEA,QAAM,UAAU,wBAAC,cAAuB;AACtC,QAAI,CAAC,iBAAiB,SAAS,GAAG;AAChC;AAAA,IACF;AACA,QAAI,CAAC,cAAc,OAAO,GAAG;AAC3B;AAAA,IACF;AAEA,YAAQ,YAAY,SAAS;AAC7B,cAAU,OAAO,EAAE;AAAA,EACrB,GAVgB;AAYhB,QAAM,UAAU,wBAAC,UAA8B;A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EA,QAAM,WAAW,YAAY,OAAO;AACpC,SAAO,GAAG,kBAAkB,GAAG,SAAS,QAAQ,GAAG,SAAS,MAAM;AACpE;AAPS;AAST,SAAS,YAAY,SAAmC;AACtD,SAAO,QAAQ,YAAY,OAAO;AACpC;AAFS;AAIT,SAAS,UAAU,SAA+C;AAChE,MAAI,QAAQ,QAAQ;AAClB,WAAO,QAAQ;AAAA,EACjB;AAEA,QAAM,WAAW,YAAY,OAAO;AACpC,SAAO,MAAM,SAAS,OAAO;AAC/B;AAPS;AAST,SAAS,OAAO,SAA2C;AACzD,SAAO,QAAQ,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI;AAChD;AAFS;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cache-invalidation.ts"],"sourcesContent":["export type FarmCacheInvalidationListener = (key: string) => void;\n\ntype FarmCacheInvalidationState = {\n listeners: Set<FarmCacheInvalidationListener>;\n};\n\nconst FARM_CACHE_INVALIDATION_STATE = Symbol.for(\"farm.cacheInvalidationState\");\nconst globalState = globalThis as typeof globalThis & {\n [FARM_CACHE_INVALIDATION_STATE]?: FarmCacheInvalidationState;\n};\n\nfunction getFarmCacheInvalidationState(): FarmCacheInvalidationState {\n return (globalState[FARM_CACHE_INVALIDATION_STATE] ??= {\n listeners: new Set(),\n });\n}\n\nexport function notifyFarmCacheInvalidation(key: string): void {\n if (typeof key !== \"string\" || key.length === 0) return;\n\n for (const listener of getFarmCacheInvalidationState().listeners) {\n listener(key);\n }\n}\n\nexport function applyFarmCacheInvalidations(keys: unknown): void {\n if (!Array.isArray(keys)) return;\n\n for (const key of keys) {\n if (typeof key === \"string\") {\n notifyFarmCacheInvalidation(key);\n }\n }\n}\n\nexport function subscribeFarmCacheInvalidation(\n listener: FarmCacheInvalidationListener,\n): () => void {\n const state = getFarmCacheInvalidationState();\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n"],"mappings":";;;;;AAMA,IAAM,gCAAgC,uBAAO,IAAI,6BAA6B;AAC9E,IAAM,cAAc;AAIpB,SAAS,gCAA4D;AACnE,SAAQ,4FAA+C;AAAA,IACrD,WAAW,oBAAI,IAAI;AAAA,EACrB;AACF;AAJS;AAMF,SAAS,4BAA4B,KAAmB;AAC7D,MAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,EAAG;AAEjD,aAAW,YAAY,8BAA8B,EAAE,WAAW;AAChE,aAAS,GAAG;AAAA,EACd;AACF;AANgB;AAQT,SAAS,4BAA4B,MAAqB;AAC/D,MAAI,CAAC,MAAM,QAAQ,IAAI,EAAG;AAE1B,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,QAAQ,UAAU;AAC3B,kCAA4B,GAAG;AAAA,IACjC;AAAA,EACF;AACF;AARgB;AAUT,SAAS,+BACd,UACY;AACZ,QAAM,QAAQ,8BAA8B;AAC5C,QAAM,UAAU,IAAI,QAAQ;AAC5B,SAAO,MAAM,MAAM,UAAU,OAAO,QAAQ;AAC9C;AANgB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/config.ts"],"sourcesContent":["import type {\n FarmConfig as BaseFarmConfig,\n FarmMigrationCommand,\n FarmMigrationsConfig,\n FarmMigrationsUserConfig,\n ResolvedFarmMigrationsConfig,\n} from \"./types\";\nimport type { DocsConfig } from \"@farming-labs/docs\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./docs/types\";\nimport type { FarmIntegrationsUserConfig } from \"./integrations\";\nimport type { FarmMarkdownResolvedConfig, FarmMarkdownUserConfig } from \"./markdown\";\nimport type { FarmObservabilityUserConfig } from \"./observability\";\nimport type { FarmMiddlewareConfig } from \"./middleware/types\";\nimport type { FarmPlugin } from \"./plugin\";\nimport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nimport type { FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nimport type { FarmEnvConfig, ResolvedFarmEnv } from \"./env\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport { resolveIntegrationPlugins } from \"./integrations\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig } from \"./workflows\";\nimport { resolveCronConfig } from \"./cron\";\nimport { resolveEnv, setEnv } from \"./env\";\nimport {\n resolveMdxConfig,\n type FarmMdxResolvedConfig,\n type FarmMdxUserConfig,\n} from \"./app-markdown\";\nimport {\n normalizeRouteRules,\n routeRulesToHeaders,\n routeRulesToRedirects,\n type FarmRouteRules,\n} from \"./route-rules\";\nimport {\n resolveServerActionsConfig,\n type FarmServerActionsConfig,\n type ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nimport {\n loadFarmConfigFile,\n resolveFarmLayers,\n type FarmLayerEntry,\n type ResolvedFarmLayer,\n} from \"./layers\";\nimport path from \"path\";\nimport { normalizeFarmDeploymentId } from \"./deployment\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n resolveFarmImageConfig,\n type FarmImageConfig,\n type ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport type { FarmI18nUserConfig, ResolvedFarmI18nConfig } from \"./i18n/types\";\n\nconst FARM_RESOLVED_CUSTOM_CONTEXT = Symbol.for(\"farm.resolvedCustomContext\");\n\nexport type {\n FarmDocsConfigInput,\n FarmDocsNavigationConfig,\n FarmDocsResolvedConfig,\n FarmDocsSidebarItem,\n FarmDocsUserConfig,\n} from \"./docs/types\";\nexport type {\n FarmMarkdownResolvedConfig,\n FarmMarkdownRouteInput,\n FarmMarkdownUserConfig,\n} from \"./markdown\";\nexport type { FarmMdxComponents, FarmMdxResolvedConfig, FarmMdxUserConfig } from \"./app-markdown\";\nexport type {\n FarmMigrationCommand,\n FarmMigrationsConfig,\n FarmMigrationsUserConfig,\n ResolvedFarmMigrationsConfig,\n} from \"./types\";\nexport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nexport type { FarmCronJobConfig, FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nexport type {\n FarmRouteRule,\n FarmRouteRuleCors,\n FarmRouteRuleRedirect,\n FarmRouteRuleRenderMode,\n FarmRouteRules,\n} from \"./route-rules\";\nexport type {\n FarmServerActionsConfig,\n ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nexport type { FarmLayerEntry, ResolvedFarmLayer } from \"./layers\";\nexport type {\n FarmDevtoolsConfig,\n FarmDevtoolsUserConfig,\n ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\nexport type {\n FarmImageConfig,\n FarmImageFormat,\n FarmImageLocalPattern,\n FarmImageProvider,\n FarmImageRemotePattern,\n ResolvedFarmImageConfig,\n} from \"./image-config\";\nexport type {\n FarmI18nCookieConfig,\n FarmI18nDetectionSignal,\n FarmI18nDirection,\n FarmI18nRouting,\n FarmI18nUserConfig,\n ResolvedFarmI18nConfig,\n} from \"./i18n/types\";\n\nexport interface RedirectConfig {\n source: string;\n destination: string;\n permanent?: boolean;\n statusCode?: number;\n}\n\nexport interface HeaderConfig {\n source: string;\n headers: Array<{\n key: string;\n value: string;\n }>;\n}\n\nexport interface RewriteConfig {\n source: string;\n destination: string;\n}\n\n/** @deprecated Use FarmImageConfig. */\nexport type ImageConfig = FarmImageConfig;\n\n/** @deprecated Use FarmI18nUserConfig. */\nexport type I18nConfig = FarmI18nUserConfig;\n\nexport interface OpenAPIConfig {\n enabled?: boolean;\n route?: string;\n title?: string;\n description?: string;\n version?: string;\n servers?: Array<{\n url: string;\n description?: string;\n }>;\n contact?: {\n name?: string;\n email?: string;\n url?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n}\n\nexport type MiddlewareConfig = FarmMiddlewareConfig;\n\nexport interface NotFoundConfig {\n /** Path to a custom 404 page component (e.g., \"./src/app/not-found.tsx\") */\n component?: string;\n}\n\nexport type FarmDeployTarget = \"vercel\" | \"cloudflare\" | \"netlify\" | \"node\" | string;\n\nexport interface FarmDeployConfig {\n /**\n * Deployment platform. When present, Farm picks the matching Nitro preset and\n * output directory unless explicitly overridden.\n */\n target?: FarmDeployTarget;\n /** Nitro preset override. Usually inferred from target. */\n preset?: BaseFarmConfig[\"preset\"];\n /** Deployable output directory, relative to project root unless absolute. */\n outputDir?: string;\n /** Alias for outputDir for terser config. */\n output?: string;\n /** Cloudflare Pages project name used by `farm deploy --cloudflare`. */\n projectName?: string;\n vercel?: {\n outputDirectory?: string;\n buildCommand?: string;\n installCommand?: string;\n framework?: string | null;\n };\n cloudflare?: {\n outputDir?: string;\n projectName?: string;\n };\n netlify?: {\n outputDir?: string;\n site?: string;\n };\n}\n\nexport interface ResolvedFarmDeployConfig extends Omit<FarmDeployConfig, \"output\"> {\n target?: FarmDeployTarget;\n preset: BaseFarmConfig[\"preset\"];\n outputDir: string;\n}\n\nexport interface FarmUserConfig extends Omit<BaseFarmConfig, \"vite\" | \"docs\" | \"env\" | \"layers\"> {\n /** Reusable Farm directories or installed packages, applied from left to right. */\n extends?: readonly FarmLayerEntry[];\n plugins?: FarmPlugin[];\n integrations?: FarmIntegrationsUserConfig;\n migrations?: FarmMigrationsUserConfig;\n /** Map portable cron schedules to ordinary GET API routes. */\n cron?: FarmCronUserConfig | FarmCronResolvedConfig | false;\n workflows?: FarmWorkflowsUserConfig | boolean;\n preset?: BaseFarmConfig[\"preset\"];\n deploy?: FarmDeployConfig;\n docs?: FarmDocsUserConfig;\n md?: FarmMarkdownUserConfig | boolean;\n mdx?: FarmMdxUserConfig;\n observability?: FarmObservabilityUserConfig;\n\n trailingSlash?: boolean;\n redirects?: () => Promise<RedirectConfig[]> | RedirectConfig[];\n rewrites?: () => Promise<RewriteConfig[]> | RewriteConfig[];\n headers?: () => Promise<HeaderConfig[]> | HeaderConfig[];\n\n images?: ImageConfig;\n publicDir?: string;\n\n i18n?: FarmI18nUserConfig | false;\n openapi?: OpenAPIConfig;\n\n middleware?: FarmMiddlewareConfig;\n routeRules?: FarmRouteRules;\n context?: BaseFarmConfig[\"context\"];\n serverActions?: FarmServerActionsConfig;\n /** Build identifier used to detect and recover from deployment version skew. */\n deploymentId?: string;\n\n notFound?: NotFoundConfig;\n\n output?: \"standalone\" | \"static\" | \"export\";\n distDir?: string;\n generateBuildId?: () => string | Promise<string>;\n compress?: boolean;\n\n devIndicators?: {\n buildActivity?: boolean;\n buildActivityPosition?: \"bottom-right\" | \"bottom-left\" | \"top-right\" | \"top-left\";\n };\n\n serverRuntimeConfig?: Record<string, any>;\n publicRuntimeConfig?: Record<string, any>;\n\n env?: FarmEnvConfig<any, any>;\n\n typescript?: {\n tsconfigPath?: string;\n ignoreBuildErrors?: boolean;\n };\n\n vite?: ViteUserConfig | ((config: ViteUserConfig) => ViteUserConfig);\n\n [key: string]: any;\n}\n\nexport interface ResolvedFarmConfig extends Required<\n Omit<\n FarmUserConfig,\n | \"extends\"\n | \"plugins\"\n | \"vite\"\n | \"deploy\"\n | \"docs\"\n | \"md\"\n | \"mdx\"\n | \"migrations\"\n | \"cron\"\n | \"workflows\"\n | \"env\"\n | \"serverActions\"\n | \"devtools\"\n | \"images\"\n | \"i18n\"\n >\n> {\n /** @internal Tracks whether `context` came from user/layer config instead of the default noop. */\n [FARM_RESOLVED_CUSTOM_CONTEXT]?: boolean;\n extends: readonly FarmLayerEntry[];\n layers: ResolvedFarmLayer[];\n plugins: FarmPlugin[];\n vite: ViteUserConfig;\n deploy: ResolvedFarmDeployConfig;\n docs: FarmDocsResolvedConfig;\n md: FarmMarkdownResolvedConfig;\n mdx: FarmMdxResolvedConfig;\n migrations: ResolvedFarmMigrationsConfig;\n cron: FarmCronResolvedConfig;\n workflows: FarmWorkflowsResolvedConfig;\n env: ResolvedFarmEnv;\n serverActions: ResolvedFarmServerActionsConfig;\n devtools: ResolvedFarmDevtoolsConfig;\n images: ResolvedFarmImageConfig;\n i18n: ResolvedFarmI18nConfig;\n}\n\nexport function hasCustomFarmRouteContext(config: ResolvedFarmConfig): boolean {\n return config[FARM_RESOLVED_CUSTOM_CONTEXT] === true;\n}\n\nexport type FarmLayerConfig = Omit<\n FarmUserConfig,\n | \"root\"\n | \"outDir\"\n | \"distDir\"\n | \"deploy\"\n | \"output\"\n | \"preset\"\n | \"publicDir\"\n | \"generateBuildId\"\n | \"deploymentId\"\n>;\n\nexport { defineConfig, defineFarmConfig } from \"./config-entry\";\n\nexport function normalizeDeployTarget(target?: FarmDeployTarget): FarmDeployTarget | undefined {\n if (!target) return undefined;\n if (target === \"cloudflare-pages\" || target === \"cloudflare_pages\") return \"cloudflare\";\n if (target === \"node-server\" || target === \"nitro\") return \"node\";\n return target;\n}\n\nexport function getPresetForDeployTarget(\n target?: FarmDeployTarget,\n): BaseFarmConfig[\"preset\"] | undefined {\n switch (normalizeDeployTarget(target)) {\n case \"vercel\":\n return \"vercel\";\n case \"cloudflare\":\n return \"cloudflare-pages\";\n case \"netlify\":\n return \"netlify\";\n case \"node\":\n return \"node-server\";\n default:\n return undefined;\n }\n}\n\nexport function getDeployTargetForPreset(preset?: string): FarmDeployTarget | undefined {\n if (!preset) return undefined;\n if (preset === \"vercel\" || preset === \"vercel-edge\") return \"vercel\";\n if (preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\") {\n return \"cloudflare\";\n }\n if (preset === \"netlify\" || preset === \"netlify-edge\") return \"netlify\";\n if (preset === \"node-server\") return \"node\";\n return undefined;\n}\n\nexport function getDefaultDeployOutputDir(\n target: FarmDeployTarget | undefined,\n preset: string | undefined,\n distDir: string,\n): string {\n const normalizedTarget = normalizeDeployTarget(target) || getDeployTargetForPreset(preset);\n if (normalizedTarget === \"vercel\") return \".vercel/output\";\n return `${distDir}/.output`;\n}\n\nexport function resolveDeployOutputPath(root: string, outputDir: string): string {\n return path.isAbsolute(outputDir) ? outputDir : path.join(root, outputDir);\n}\n\nexport function resolveDeployConfig(\n config: Pick<FarmUserConfig, \"deploy\" | \"preset\" | \"distDir\">,\n overrides: {\n target?: FarmDeployTarget;\n preset?: BaseFarmConfig[\"preset\"];\n outputDir?: string;\n } = {},\n): ResolvedFarmDeployConfig {\n const deploy = config.deploy || {};\n const distDir = config.distDir || \".farm\";\n const target = normalizeDeployTarget(overrides.target || deploy.target);\n const preset =\n overrides.preset ||\n deploy.preset ||\n config.preset ||\n getPresetForDeployTarget(target) ||\n \"node-server\";\n const resolvedTarget = target || getDeployTargetForPreset(preset);\n const platformOutput =\n resolvedTarget === \"vercel\"\n ? deploy.vercel?.outputDirectory\n : resolvedTarget === \"cloudflare\"\n ? deploy.cloudflare?.outputDir\n : resolvedTarget === \"netlify\"\n ? deploy.netlify?.outputDir\n : undefined;\n const outputDir =\n overrides.outputDir ||\n deploy.outputDir ||\n deploy.output ||\n platformOutput ||\n getDefaultDeployOutputDir(resolvedTarget, preset, distDir);\n\n return {\n ...deploy,\n target: resolvedTarget,\n preset,\n outputDir,\n };\n}\n\nexport function resolveMigrationsConfig(\n migrations: FarmMigrationsUserConfig | undefined,\n): ResolvedFarmMigrationsConfig {\n if (!migrations) return { commands: [] };\n if (Array.isArray(migrations)) return { commands: migrations };\n return { commands: migrations.commands || [] };\n}\n\nexport const DOCS_CONFIG_FILENAMES = [\n \"docs.config.ts\",\n \"docs.config.tsx\",\n \"docs.config.mts\",\n \"docs.config.cts\",\n \"docs.config.js\",\n \"docs.config.jsx\",\n \"docs.config.mjs\",\n \"docs.config.cjs\",\n \"docs.json\",\n];\n\nfunction normalizeDocsRoute(value: string | undefined, fallback = \"/docs\"): string {\n const raw = (value || fallback).trim();\n if (!raw || raw === \"/\") return \"/\";\n const normalized = raw\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/^\\/?/, \"/\")\n .replace(/\\/+$/, \"\");\n return normalized || \"/\";\n}\n\nfunction docsRouteToEntry(route: string): string {\n const entry = route.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return entry || \"docs\";\n}\n\nfunction normalizeDocsContentDir(value: string | undefined): string | undefined {\n if (!value) return undefined;\n const normalized = value.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized || undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction cloneSerializable(value: unknown, seen = new WeakSet<object>()): any {\n if (value === null) return null;\n\n const valueType = typeof value;\n if (valueType === \"string\" || valueType === \"number\" || valueType === \"boolean\") {\n return value;\n }\n if (valueType === \"undefined\" || valueType === \"function\" || valueType === \"symbol\") {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map((item) => cloneSerializable(item, seen)).filter((item) => item !== undefined);\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (isRecord(value)) {\n if (seen.has(value)) return undefined;\n seen.add(value);\n\n const output: Record<string, any> = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n const clonedValue = cloneSerializable(nestedValue, seen);\n if (clonedValue !== undefined) {\n output[key] = clonedValue;\n }\n }\n return output;\n }\n\n return undefined;\n}\n\nfunction sanitizeDocsConfig(config: Partial<DocsConfig>): Partial<DocsConfig> {\n return cloneSerializable(config) || {};\n}\n\nexport async function findDocsConfigPath(\n rootDir: string,\n configPath?: string,\n): Promise<string | undefined> {\n const { existsSync } = await import(\"fs\");\n const root = path.resolve(rootDir || process.cwd());\n\n if (configPath) {\n const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n if (!existsSync(resolvedPath)) {\n throw new Error(`Could not find docs config at ${configPath}.`);\n }\n return path.resolve(resolvedPath);\n }\n\n for (const filename of DOCS_CONFIG_FILENAMES) {\n const resolvedPath = path.join(root, filename);\n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n }\n\n return undefined;\n}\n\nexport async function loadDocsConfig(\n rootDir: string,\n configPath?: string,\n): Promise<{ config: Partial<DocsConfig>; configPath: string } | undefined> {\n const fs = await import(\"fs/promises\");\n const { pathToFileURL } = await import(\"url\");\n const root = path.resolve(rootDir || process.cwd());\n const resolvedPath = await findDocsConfigPath(root, configPath);\n\n if (!resolvedPath) return undefined;\n\n try {\n if (resolvedPath.endsWith(\".json\")) {\n const content = await fs.readFile(resolvedPath, \"utf8\");\n return { config: JSON.parse(content), configPath: resolvedPath };\n }\n\n const { build } = await import(\"esbuild\");\n const configCacheDir = path.join(root, \".farm\", \".config-loader\");\n await fs.mkdir(configCacheDir, { recursive: true });\n const modulePath = path.join(\n configCacheDir,\n `docs-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n await build({\n absWorkingDir: root,\n entryPoints: [resolvedPath],\n outfile: modulePath,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: `node${process.versions.node.split(\".\")[0]}`,\n packages: \"external\",\n jsx: \"automatic\",\n logLevel: \"silent\",\n sourcemap: \"inline\",\n });\n\n const moduleUrl = pathToFileURL(modulePath).href + `?t=${Date.now()}`;\n let importedConfig: any;\n\n try {\n importedConfig = await import(/* @vite-ignore */ moduleUrl);\n } finally {\n await fs.unlink(modulePath).catch(() => undefined);\n }\n\n return {\n config: importedConfig.default || importedConfig,\n configPath: resolvedPath,\n };\n } catch (error: any) {\n const relativePath = path.relative(root, resolvedPath) || resolvedPath;\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load docs config from ${relativePath}: ${message}`);\n }\n}\n\nexport async function resolveDocsConfig(\n userDocs: FarmDocsUserConfig | undefined,\n options: {\n root?: string;\n srcDir?: string;\n } = {},\n): Promise<FarmDocsResolvedConfig> {\n const root = options.root || process.cwd();\n\n if (userDocs === false) {\n return {\n enabled: false,\n entry: \"/docs\",\n config: { entry: \"docs\", docsPath: \"/docs\" },\n };\n }\n\n const docsOptions = isRecord(userDocs) ? userDocs : {};\n if (docsOptions.enabled === false) {\n return {\n enabled: false,\n entry: \"/docs\",\n config: { entry: \"docs\", docsPath: \"/docs\" },\n };\n }\n\n const loadedConfig = await loadDocsConfig(root, docsOptions.configPath);\n const hasExplicitDocsConfig = userDocs === true || isRecord(userDocs);\n\n if (!hasExplicitDocsConfig && !loadedConfig) {\n return {\n enabled: false,\n entry: \"/docs\",\n config: { entry: \"docs\", docsPath: \"/docs\" },\n };\n }\n\n const inlineDocsConfig = sanitizeDocsConfig(docsOptions.config || {});\n const directDocsConfig = sanitizeDocsConfig({\n ...docsOptions,\n enabled: undefined,\n config: undefined,\n configPath: undefined,\n } as Partial<DocsConfig>);\n const loadedDocsConfig = sanitizeDocsConfig(loadedConfig?.config || {});\n const mergedDocsConfig: Partial<DocsConfig> = {\n ...loadedDocsConfig,\n ...inlineDocsConfig,\n ...directDocsConfig,\n };\n\n const explicitRoute = typeof docsOptions.entry === \"string\" ? docsOptions.entry : undefined;\n const configuredDocsPath =\n typeof mergedDocsConfig.docsPath === \"string\" ? mergedDocsConfig.docsPath : undefined;\n const configuredEntry =\n typeof mergedDocsConfig.entry === \"string\" ? mergedDocsConfig.entry : undefined;\n const entryRoute = normalizeDocsRoute(\n configuredDocsPath || explicitRoute || (configuredEntry ? `/${configuredEntry}` : undefined),\n );\n const docsEntry =\n explicitRoute && explicitRoute.startsWith(\"/\")\n ? docsRouteToEntry(explicitRoute)\n : docsRouteToEntry(configuredEntry || entryRoute);\n const contentDir = normalizeDocsContentDir(docsOptions.contentDir || mergedDocsConfig.contentDir);\n\n return {\n enabled: true,\n entry: entryRoute,\n contentDir,\n configPath: loadedConfig?.configPath,\n config: {\n ...mergedDocsConfig,\n entry: docsEntry,\n docsPath: entryRoute,\n ...(contentDir ? { contentDir } : {}),\n },\n };\n}\n\nexport async function resolveConfig(\n userConfig: FarmUserConfig,\n mode: \"development\" | \"production\",\n): Promise<ResolvedFarmConfig> {\n const projectRoot = userConfig.root || process.cwd();\n const layerResolution = await resolveFarmLayers(userConfig, {\n root: projectRoot,\n mode,\n });\n userConfig = layerResolution.config;\n\n const redirects =\n typeof userConfig.redirects === \"function\"\n ? await userConfig.redirects()\n : userConfig.redirects || [];\n\n const rewrites =\n typeof userConfig.rewrites === \"function\"\n ? await userConfig.rewrites()\n : userConfig.rewrites || [];\n\n const headers =\n typeof userConfig.headers === \"function\"\n ? await userConfig.headers()\n : userConfig.headers || [];\n const routeRules = normalizeRouteRules(userConfig.routeRules);\n const routeRuleRedirects = routeRulesToRedirects(routeRules);\n const routeRuleHeaders = routeRulesToHeaders(routeRules);\n\n const deploy = resolveDeployConfig(userConfig);\n const root = userConfig.root || process.cwd();\n const srcDir = userConfig.srcDir || \"src\";\n const docs = await resolveDocsConfig(userConfig.docs, { root, srcDir });\n const md = resolveMarkdownConfig(userConfig.md);\n const mdx = resolveMdxConfig(userConfig.mdx);\n const env = resolveEnv(userConfig.env, process.env);\n setEnv(env);\n const generateBuildId = userConfig.generateBuildId || (() => `build-${Date.now()}`);\n const deploymentId = normalizeFarmDeploymentId(\n userConfig.deploymentId ||\n process.env.FARM_DEPLOYMENT_ID ||\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.CF_PAGES_COMMIT_SHA ||\n (mode === \"production\" ? await generateBuildId() : \"development\"),\n );\n\n const resolved: ResolvedFarmConfig = {\n [FARM_RESOLVED_CUSTOM_CONTEXT]: typeof userConfig.context === \"function\",\n root,\n srcDir,\n extends: userConfig.extends || [],\n layers: layerResolution.layers,\n outDir: userConfig.outDir || \"dist\",\n basePath: userConfig.basePath || \"/\",\n preset: deploy.preset || \"node-server\",\n deploy,\n docs,\n md,\n mdx,\n migrations: resolveMigrationsConfig(userConfig.migrations),\n cron: resolveCronConfig(userConfig.cron),\n workflows: resolveWorkflowsConfig(userConfig.workflows),\n observability: userConfig.observability ?? false,\n devtools: resolveFarmDevtoolsConfig(userConfig.devtools, mode),\n storage: userConfig.storage || {},\n suppressLintOnLink: userConfig.suppressLintOnLink ?? false,\n experimental: {\n serverComponents: false,\n serverActions: false,\n ...userConfig.experimental,\n },\n plugins: [...resolveIntegrationPlugins(userConfig.integrations), ...(userConfig.plugins || [])],\n integrations: userConfig.integrations || {},\n trailingSlash: userConfig.trailingSlash ?? false,\n redirects: () => [...redirects, ...routeRuleRedirects],\n rewrites: () => rewrites,\n headers: () => [...headers, ...routeRuleHeaders],\n routeRules,\n images: resolveFarmImageConfig(userConfig.images),\n publicDir: userConfig.publicDir || \"public\",\n i18n: resolveFarmI18nConfig(userConfig.i18n, { root, mode }),\n openapi: {\n enabled: false,\n route: \"/docs/reference\",\n title: \"API Documentation\",\n description: \"Auto-generated API documentation\",\n version: \"1.0.0\",\n servers: [{ url: \"http://localhost:3000\", description: \"Development server\" }],\n ...userConfig.openapi,\n },\n middleware: userConfig.middleware || {},\n notFound: userConfig.notFound || {},\n context: userConfig.context || (() => undefined),\n serverActions: resolveServerActionsConfig(userConfig.serverActions),\n deploymentId,\n output: userConfig.output || \"standalone\",\n distDir: userConfig.distDir || \".farm\",\n generateBuildId,\n compress: userConfig.compress ?? true,\n devIndicators: {\n buildActivity: true,\n buildActivityPosition: \"bottom-right\",\n ...userConfig.devIndicators,\n },\n serverRuntimeConfig: userConfig.serverRuntimeConfig || {},\n publicRuntimeConfig: userConfig.publicRuntimeConfig || {},\n env,\n typescript: {\n tsconfigPath: \"tsconfig.json\",\n ignoreBuildErrors: false,\n ...userConfig.typescript,\n },\n vite: typeof userConfig.vite === \"function\" ? userConfig.vite({}) : userConfig.vite || {},\n };\n\n return resolved;\n}\n\nexport async function loadConfig(\n rootDir?: string,\n configPath?: string,\n mode = process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n loadEnvironment?: (typeof import(\"vite\"))[\"loadEnv\"],\n): Promise<FarmUserConfig | undefined> {\n const { existsSync } = await import(\"fs\");\n const loadEnv = loadEnvironment || (await import(\"vite\")).loadEnv;\n\n const root = rootDir || process.cwd();\n const loadedEnv = loadEnv(mode, root, \"\");\n for (const [key, value] of Object.entries(loadedEnv)) {\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n const searchPaths = [\n configPath,\n \"farm.config.ts\",\n \"farm.config.mts\",\n \"farm.config.js\",\n \"farm.config.mjs\",\n \"config.ts\",\n \"config.mts\",\n \"config.js\",\n \"config.mjs\",\n ].filter(Boolean) as string[];\n\n for (const relativePath of searchPaths) {\n try {\n // Use path.join for proper path construction\n const absolutePath = relativePath.startsWith(\"/\")\n ? relativePath\n : path.join(root, relativePath);\n\n // Normalize the path to handle any issues\n const normalizedPath = path.resolve(absolutePath);\n\n // Check if file exists before trying to import\n if (!existsSync(normalizedPath)) {\n continue;\n }\n\n const loadedConfig = await loadFarmConfigFile<FarmUserConfig>(normalizedPath, { root });\n return loadedConfig.root === undefined ? { ...loadedConfig, root } : loadedConfig;\n } catch (error: any) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load config from ${relativePath}: ${message}`);\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,OAAO,UAAU;AAWjB,IAAM,+BAA+B,uBAAO,IAAI,4BAA4B;AA0PrE,SAAS,0BAA0B,QAAqC;AAC7E,SAAO,OAAO,4BAA4B,MAAM;AAClD;AAFgB;AAmBT,SAAS,sBAAsB,QAAyD;AAC7F,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,WAAW,sBAAsB,WAAW,mBAAoB,QAAO;AAC3E,MAAI,WAAW,iBAAiB,WAAW,QAAS,QAAO;AAC3D,SAAO;AACT;AALgB;AAOT,SAAS,yBACd,QACsC;AACtC,UAAQ,sBAAsB,MAAM,GAAG;AAAA,IACrC,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAfgB;AAiBT,SAAS,yBAAyB,QAA+C;AACtF,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,WAAW,YAAY,WAAW,cAAe,QAAO;AAC5D,MAAI,WAAW,gBAAgB,WAAW,sBAAsB,WAAW,qBAAqB;AAC9F,WAAO;AAAA,EACT;AACA,MAAI,WAAW,aAAa,WAAW,eAAgB,QAAO;AAC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AC,KAAK,KAAK,KAAK,OAAO,QAAQ,SAAS,GAAG;AACpD,QAAI,QAAQ,IAAI,GAAG,MAAM,QAAW;AAClC,cAAQ,IAAI,GAAG,IAAI;AAAA,IACrB;AAAA,EACF;AACA,QAAM,cAAc;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,OAAO,OAAO;AAEhB,aAAW,gBAAgB,aAAa;AACtC,QAAI;AAEF,YAAM,eAAe,aAAa,WAAW,GAAG,IAC5C,eACA,KAAK,KAAK,MAAM,YAAY;AAGhC,YAAM,iBAAiB,KAAK,QAAQ,YAAY;AAGhD,UAAI,CAAC,WAAW,cAAc,GAAG;AAC/B;AAAA,MACF;AAEA,YAAM,eAAe,MAAM,mBAAmC,gBAAgB,EAAE,KAAK,CAAC;AACtF,aAAO,aAAa,SAAS,SAAY,EAAE,GAAG,cAAc,KAAK,IAAI;AAAA,IACvE,SAAS,OAAY;AACnB,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,YAAM,IAAI,MAAM,8BAA8B,YAAY,KAAK,OAAO,EAAE;AAAA,IAC1E;AAAA,EACF;AACA,SAAO;AACT;AAnDsB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/workflows.ts"],"sourcesContent":["export type FarmWorkflowSchedule = string | string[];\n\nexport interface FarmWorkflowsUserConfig {\n /** Enable or disable Farm workflow discovery. Enabled by default. */\n enabled?: boolean;\n /** Directory or directories to scan for workflow modules. */\n dir?: string | string[];\n /** Alias for dir. */\n dirs?: string[];\n /** HTTP route used for manual and URL-based cron invocation. */\n route?: string;\n /** Environment variable that stores the optional runner secret. */\n secretEnv?: string;\n /** Inline runner secret. Prefer secretEnv for deployed apps. */\n secret?: string;\n}\n\nexport interface FarmWorkflowsResolvedConfig {\n enabled: boolean;\n dirs: string[];\n route: string;\n secretEnv: string;\n secret?: string;\n}\n\nexport interface FarmWorkflowLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n}\n\nexport interface FarmWorkflowRunContext<TPayload = unknown> {\n id: string;\n name: string;\n payload: TPayload;\n scheduledTime?: number | string;\n request?: Request;\n event?: unknown;\n env: Record<string, string | undefined>;\n data: Map<string, unknown>;\n log: FarmWorkflowLogger;\n}\n\nexport interface FarmWorkflowDefinition<TPayload = unknown, TResult = unknown> {\n kind?: \"farm-workflow\";\n id?: string;\n description?: string;\n schedule?: FarmWorkflowSchedule;\n timezone?: string;\n run: (ctx: FarmWorkflowRunContext<TPayload>) => TResult | Promise<TResult>;\n}\n\nexport interface FarmCronDefinition<TPayload = unknown, TResult = unknown>\n extends FarmWorkflowDefinition<TPayload, TResult> {\n schedule: FarmWorkflowSchedule;\n}\n\nexport interface FarmDiscoveredWorkflow {\n id: string;\n filePath: string;\n description?: string;\n schedule: string[];\n timezone?: string;\n routePath: string;\n}\n\nexport interface PreparedFarmWorkflows {\n workflows: FarmDiscoveredWorkflow[];\n tasks: Record<string, { handler: string; description: string }>;\n scheduledTasks: Record<string, string | string[]>;\n handlerPath?: string;\n manifestPath?: string;\n}\n\nexport interface FarmWorkflowHTTPHandlerOptions {\n workflows: FarmDiscoveredWorkflow[];\n config: FarmWorkflowsResolvedConfig;\n loadModule: (workflow: FarmDiscoveredWorkflow) => Promise<Record<string, any>>;\n}\n\nexport const DEFAULT_FARM_WORKFLOW_DIRS = [\"src/jobs\", \"src/workflows\", \"src/cron\"];\nexport const DEFAULT_FARM_WORKFLOW_ROUTE = \"/api/_farm/workflows\";\nexport const DEFAULT_FARM_WORKFLOW_SECRET_ENV = \"CRON_SECRET\";\n\nexport function defineWorkflow<const TPayload = unknown, TResult = unknown>(\n definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n return {\n ...definition,\n kind: \"farm-workflow\",\n };\n}\n\nexport function defineTask<const TPayload = unknown, TResult = unknown>(\n definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n return defineWorkflow(definition);\n}\n\n/**\n * @deprecated Configure `cron` in `farm.config.ts` and point it at an API route.\n */\nexport function defineCron<const TPayload = unknown, TResult = unknown>(\n definition: FarmCronDefinition<TPayload, TResult>,\n): FarmCronDefinition<TPayload, TResult> {\n return {\n ...definition,\n kind: \"farm-workflow\",\n };\n}\n\nexport function resolveWorkflowsConfig(\n workflows: FarmWorkflowsUserConfig | boolean | undefined,\n): FarmWorkflowsResolvedConfig {\n if (workflows === false) {\n return {\n enabled: false,\n dirs: [...DEFAULT_FARM_WORKFLOW_DIRS],\n route: DEFAULT_FARM_WORKFLOW_ROUTE,\n secretEnv: DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n };\n }\n\n const options = workflows && typeof workflows === \"object\" ? workflows : {};\n const dirs = normalizeWorkflowDirs(options);\n\n return {\n enabled: options.enabled ?? true,\n dirs,\n route: normalizeWorkflowRoute(options.route || DEFAULT_FARM_WORKFLOW_ROUTE),\n secretEnv: options.secretEnv || DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n secret: options.secret,\n };\n}\n\nexport async function discoverFarmWorkflows(\n config: { root?: string; workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean },\n options: {\n loadModule?: (filePath: string) => Promise<Record<string, any>>;\n } = {},\n): Promise<FarmDiscoveredWorkflow[]> {\n const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n ? config.workflows\n : resolveWorkflowsConfig(config.workflows);\n if (!workflowConfig.enabled) return [];\n\n const root = config.root || process.cwd();\n const files = await findWorkflowFiles(root, workflowConfig.dirs);\n const workflows: FarmDiscoveredWorkflow[] = [];\n const seenIds = new Map<string, string>();\n\n for (const filePath of files) {\n const module = options.loadModule\n ? await options.loadModule(filePath)\n : await loadWorkflowModule(filePath, root);\n const definition = resolveWorkflowDefinition(module);\n if (!definition) continue;\n\n const id = normalizeWorkflowId(definition.id || workflowIdFromFile(root, filePath));\n const previousPath = seenIds.get(id);\n if (previousPath) {\n throw new Error(\n `Duplicate Farm workflow id \"${id}\" found in ${relativePath(root, previousPath)} and ${relativePath(root, filePath)}.`,\n );\n }\n seenIds.set(id, filePath);\n\n workflows.push({\n id,\n filePath,\n description: definition.description,\n schedule: normalizeSchedule(definition.schedule),\n timezone: definition.timezone,\n routePath: joinRoute(workflowConfig.route, encodeURIComponent(id)),\n });\n }\n\n return workflows;\n}\n\nexport function createFarmWorkflowRequestHandler(options: FarmWorkflowHTTPHandlerOptions) {\n const workflowsById = new Map(options.workflows.map((workflow) => [workflow.id, workflow]));\n\n return async function handleFarmWorkflowRequest(request: Request): Promise<Response | null> {\n const url = new URL(request.url);\n const route = normalizeWorkflowRoute(options.config.route);\n if (url.pathname !== route && !url.pathname.startsWith(`${route}/`)) {\n return null;\n }\n\n if (url.pathname === route) {\n const secretError = verifyWorkflowSecret(request, options.config);\n if (secretError) return secretError;\n\n return Response.json({\n workflows: options.workflows.map(toWorkflowMetadata),\n });\n }\n\n const id = decodeURIComponent(url.pathname.slice(route.length + 1));\n const workflow = workflowsById.get(id);\n if (!workflow) {\n return Response.json({ error: `Workflow \"${id}\" was not found.` }, { status: 404 });\n }\n\n const secretError = verifyWorkflowSecret(request, options.config);\n if (secretError) return secretError;\n\n const payload = await readWorkflowPayload(request);\n const module = await options.loadModule(workflow);\n const result = await runFarmWorkflowModule(module, {\n id: workflow.id,\n name: workflow.id,\n payload,\n request,\n scheduledTime: readScheduledTime(payload),\n });\n\n return Response.json({\n id: workflow.id,\n ok: true,\n result: result ?? null,\n });\n };\n}\n\nexport async function runFarmWorkflowModule(\n module: Record<string, any>,\n context: {\n id: string;\n name?: string;\n payload?: unknown;\n scheduledTime?: number | string;\n request?: Request;\n event?: unknown;\n env?: Record<string, string | undefined>;\n },\n): Promise<unknown> {\n const definition = resolveWorkflowDefinition(module);\n if (!definition) {\n throw new Error(`Farm workflow \"${context.id}\" does not export a workflow definition.`);\n }\n\n return await definition.run({\n id: context.id,\n name: context.name || context.id,\n payload: context.payload,\n scheduledTime: context.scheduledTime,\n request: context.request,\n event: context.event,\n env: context.env || process.env,\n data: new Map<string, unknown>(),\n log: console,\n });\n}\n\nexport async function prepareFarmWorkflowsForNitro(\n config: { root?: string; distDir?: string; workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean },\n): Promise<PreparedFarmWorkflows> {\n const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n ? config.workflows\n : resolveWorkflowsConfig(config.workflows);\n const workflows = await discoverFarmWorkflows({\n root: config.root,\n workflows: workflowConfig,\n });\n\n if (workflows.length === 0) {\n return {\n workflows,\n tasks: {},\n scheduledTasks: {},\n };\n }\n\n const root = config.root || process.cwd();\n const distDir = config.distDir || \".farm\";\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const generatedDir = path.join(root, distDir, \".nitro\", \"farm-workflows\");\n await fs.mkdir(generatedDir, { recursive: true });\n\n const tasks: PreparedFarmWorkflows[\"tasks\"] = {};\n const scheduledTasks = createScheduledTasks(workflows);\n\n for (const workflow of workflows) {\n const wrapperPath = path.join(generatedDir, `${safeFileName(workflow.id)}.mjs`);\n await fs.writeFile(wrapperPath, createNitroTaskWrapper(workflow), \"utf8\");\n tasks[workflow.id] = {\n handler: wrapperPath,\n description: workflow.description || `Farm workflow ${workflow.id}`,\n };\n }\n\n const handlerPath = path.join(generatedDir, \"http-handler.mjs\");\n await fs.writeFile(handlerPath, createNitroWorkflowHTTPHandler(workflowConfig, workflows), \"utf8\");\n\n const manifestPath = path.join(generatedDir, \"manifest.json\");\n await fs.writeFile(\n manifestPath,\n JSON.stringify(\n {\n route: workflowConfig.route,\n secretEnv: workflowConfig.secretEnv,\n trigger: {\n method: \"GET\",\n authorization: `Bearer $${workflowConfig.secretEnv}`,\n },\n workflows: workflows.map(toWorkflowMetadata),\n },\n null,\n 2,\n ),\n \"utf8\",\n );\n\n return {\n workflows,\n tasks,\n scheduledTasks,\n handlerPath,\n manifestPath,\n };\n}\n\nexport function createFarmWorkflowVercelCrons(\n workflows: FarmDiscoveredWorkflow[],\n): Array<{ path: string; schedule: string }> {\n return workflows.flatMap((workflow) =>\n workflow.schedule.map((schedule) => ({\n path: workflow.routePath,\n schedule,\n })),\n );\n}\n\nexport function applyFarmWorkflowVercelCrons(\n vercelConfig: Record<string, any>,\n workflows: FarmDiscoveredWorkflow[],\n): Record<string, any> {\n const crons = createFarmWorkflowVercelCrons(workflows);\n if (crons.length === 0) return vercelConfig;\n\n const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n const nextCrons = [...existingCrons];\n for (const cron of crons) {\n const key = `${cron.path}:${cron.schedule}`;\n if (seen.has(key)) continue;\n seen.add(key);\n nextCrons.push(cron);\n }\n return {\n ...vercelConfig,\n crons: nextCrons,\n };\n}\n\nfunction isResolvedWorkflowConfig(value: unknown): value is FarmWorkflowsResolvedConfig {\n return (\n !!value &&\n typeof value === \"object\" &&\n \"dirs\" in value &&\n Array.isArray((value as FarmWorkflowsResolvedConfig).dirs) &&\n typeof (value as FarmWorkflowsResolvedConfig).route === \"string\"\n );\n}\n\nfunction normalizeWorkflowDirs(options: FarmWorkflowsUserConfig): string[] {\n const rawDirs = options.dirs || (Array.isArray(options.dir) ? options.dir : options.dir ? [options.dir] : undefined);\n const dirs = rawDirs && rawDirs.length > 0 ? rawDirs : DEFAULT_FARM_WORKFLOW_DIRS;\n return [...new Set(dirs.map((dir) => trimSlashes(dir)).filter(Boolean))];\n}\n\nfunction normalizeWorkflowRoute(route: string): string {\n const trimmed = route.trim();\n if (!trimmed || trimmed === \"/\") return DEFAULT_FARM_WORKFLOW_ROUTE;\n return `/${trimSlashes(trimmed)}`;\n}\n\nfunction normalizeWorkflowId(id: string): string {\n const normalized = id\n .replace(/\\\\/g, \"/\")\n .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\")\n .replace(/\\/index$/, \"\")\n .replace(/[^a-zA-Z0-9._/-]+/g, \"-\")\n .replace(/^\\/+|\\/+$/g, \"\")\n .replace(/\\/+/g, \"/\");\n return normalized || \"workflow\";\n}\n\nfunction normalizeSchedule(schedule: FarmWorkflowSchedule | undefined): string[] {\n if (!schedule) return [];\n return (Array.isArray(schedule) ? schedule : [schedule]).map((value) => value.trim()).filter(Boolean);\n}\n\nfunction resolveWorkflowDefinition(\n module: Record<string, any>,\n): FarmWorkflowDefinition | FarmCronDefinition | null {\n const candidates = [\n module.default,\n module.workflow,\n module.cron,\n module.task,\n module.job,\n ];\n for (const candidate of candidates) {\n if (candidate && typeof candidate === \"object\" && typeof candidate.run === \"function\") {\n return candidate as FarmWorkflowDefinition;\n }\n }\n return null;\n}\n\nasync function findWorkflowFiles(root: string, dirs: string[]): Promise<string[]> {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const files: string[] = [];\n\n for (const dir of dirs) {\n const absoluteDir = path.isAbsolute(dir) ? dir : path.join(root, dir);\n if (!(await pathExists(absoluteDir))) continue;\n await walkWorkflowDir(absoluteDir, files);\n }\n\n return files.sort();\n}\n\nasync function walkWorkflowDir(dir: string, files: string[]): Promise<void> {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const filePath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n await walkWorkflowDir(filePath, files);\n continue;\n }\n if (isWorkflowFile(entry.name)) {\n files.push(filePath);\n }\n }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n const fs = await import(\"fs/promises\");\n return fs\n .access(filePath)\n .then(() => true)\n .catch(() => false);\n}\n\nfunction isWorkflowFile(fileName: string): boolean {\n return /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(fileName) && !/\\.d\\.[cm]?ts$/.test(fileName);\n}\n\nasync function loadWorkflowModule(filePath: string, root: string): Promise<Record<string, any>> {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const { pathToFileURL } = await import(\"url\");\n const { build } = await import(\"esbuild\");\n const outDir = path.join(root, \".farm\", \".workflow-loader\");\n await fs.mkdir(outDir, { recursive: true });\n const outfile = path.join(\n outDir,\n `workflow-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n await build({\n absWorkingDir: root,\n entryPoints: [filePath],\n outfile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: `node${process.versions.node.split(\".\")[0]}`,\n packages: \"external\",\n external: [\"@farm.js/core\", \"@farm.js/core/*\", \"nitro\", \"nitro/*\"],\n jsx: \"automatic\",\n logLevel: \"silent\",\n sourcemap: \"inline\",\n });\n\n try {\n return await import(/* @vite-ignore */ `${pathToFileURL(outfile).href}?t=${Date.now()}`);\n } finally {\n await fs.unlink(outfile).catch(() => undefined);\n }\n}\n\nfunction workflowIdFromFile(root: string, filePath: string): string {\n const normalizedRoot = root.replace(/\\\\/g, \"/\");\n const normalizedFile = filePath.replace(/\\\\/g, \"/\");\n const relative = normalizedFile.startsWith(`${normalizedRoot}/`)\n ? normalizedFile.slice(normalizedRoot.length + 1)\n : normalizedFile;\n return normalizeWorkflowId(\n relative\n .replace(/^src\\/(?:jobs|workflows|cron)\\//, \"\")\n .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\"),\n );\n}\n\nfunction createScheduledTasks(workflows: FarmDiscoveredWorkflow[]): Record<string, string | string[]> {\n const scheduleMap = new Map<string, string[]>();\n for (const workflow of workflows) {\n for (const schedule of workflow.schedule) {\n const taskIds = scheduleMap.get(schedule) || [];\n taskIds.push(workflow.id);\n scheduleMap.set(schedule, taskIds);\n }\n }\n\n return Object.fromEntries(\n [...scheduleMap.entries()].map(([schedule, taskIds]) => [\n schedule,\n taskIds.length === 1 ? taskIds[0] : taskIds,\n ]),\n );\n}\n\nfunction createNitroTaskWrapper(workflow: FarmDiscoveredWorkflow): string {\n const normalizedPath = workflow.filePath.replace(/\\\\/g, \"/\");\n return `\nimport { defineTask } from \"nitro/runtime\";\nimport { runFarmWorkflowModule } from \"@farm.js/core/workflows\";\nimport * as workflowModule from ${JSON.stringify(normalizedPath)};\n\nexport default defineTask({\n meta: {\n description: ${JSON.stringify(workflow.description || `Farm workflow ${workflow.id}`)}\n },\n async run(event) {\n const payload = event?.payload || {};\n const env = event?.context?.cloudflare?.env || event?.context?.env || process.env;\n return await runFarmWorkflowModule(workflowModule, {\n id: ${JSON.stringify(workflow.id)},\n name: event?.name || ${JSON.stringify(workflow.id)},\n payload,\n scheduledTime: payload.scheduledTime,\n request: event?.context?.request,\n event,\n env\n });\n }\n});\n`.trim();\n}\n\nfunction createNitroWorkflowHTTPHandler(\n config: FarmWorkflowsResolvedConfig,\n workflows: FarmDiscoveredWorkflow[],\n): string {\n return `\nimport { H3 } from \"h3\";\nimport { runTask } from \"nitro/runtime\";\n\nconst route = ${JSON.stringify(config.route)};\nconst secretEnv = ${JSON.stringify(config.secretEnv)};\nconst inlineSecret = ${JSON.stringify(config.secret || \"\")};\nconst workflows = ${JSON.stringify(workflows.map(toWorkflowMetadata))};\nconst workflowIds = new Set(workflows.map((workflow) => workflow.id));\n\nfunction json(value, status = 200) {\n return new Response(JSON.stringify(value), {\n status,\n headers: { \"content-type\": \"application/json\" }\n });\n}\n\nfunction getHeader(event, name) {\n return event.req.headers.get(name);\n}\n\nfunction getSecret() {\n return inlineSecret || process.env[secretEnv] || \"\";\n}\n\nfunction verifySecret(event) {\n const secret = getSecret();\n if (!secret) return null;\n const authorization = getHeader(event, \"authorization\") || \"\";\n const headerSecret = getHeader(event, \"x-farm-workflow-secret\") || \"\";\n const querySecret = event.url.searchParams.get(\"secret\") || \"\";\n const bearer = authorization.startsWith(\"Bearer \") ? authorization.slice(7) : \"\";\n if (headerSecret === secret || querySecret === secret || bearer === secret) return null;\n return json({ error: \"Unauthorized workflow request.\" }, 401);\n}\n\nasync function readPayload(event) {\n if (event.req.method === \"GET\" || event.req.method === \"HEAD\") {\n const payload = Object.fromEntries(event.url.searchParams.entries());\n delete payload.secret;\n return payload;\n }\n return await event.req.json().catch(() => ({}));\n}\n\nexport default new H3()\n .get(route, (event) => {\n const unauthorized = verifySecret(event);\n if (unauthorized) return unauthorized;\n return { workflows };\n })\n .all(route + \"/:id\", async (event) => {\n const id = decodeURIComponent(event.context.params?.id || \"\");\n if (!workflowIds.has(id)) {\n return json({ error: \"Workflow \" + id + \" was not found.\" }, 404);\n }\n\n const unauthorized = verifySecret(event);\n if (unauthorized) return unauthorized;\n\n const payload = await readPayload(event);\n const result = await runTask(id, {\n payload,\n context: {\n source: \"http\",\n request: event.req,\n route,\n url: event.url.href,\n method: event.req.method\n }\n });\n return {\n id,\n ok: true,\n result: result ?? null\n };\n });\n`.trim();\n}\n\nfunction toWorkflowMetadata(workflow: FarmDiscoveredWorkflow) {\n return {\n id: workflow.id,\n description: workflow.description || null,\n schedule: workflow.schedule,\n timezone: workflow.timezone || null,\n path: workflow.routePath,\n };\n}\n\nasync function readWorkflowPayload(request: Request): Promise<unknown> {\n const url = new URL(request.url);\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n const payload = Object.fromEntries(url.searchParams.entries());\n delete payload.secret;\n return payload;\n }\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"application/json\")) {\n return await request.json().catch(() => ({}));\n }\n\n const text = await request.text().catch(() => \"\");\n return text ? { text } : {};\n}\n\nfunction readScheduledTime(payload: unknown): number | string | undefined {\n return payload && typeof payload === \"object\" && \"scheduledTime\" in payload\n ? (payload as { scheduledTime?: number | string }).scheduledTime\n : undefined;\n}\n\nfunction verifyWorkflowSecret(\n request: Request,\n config: FarmWorkflowsResolvedConfig,\n): Response | null {\n const secret = config.secret || process.env[config.secretEnv] || \"\";\n if (!secret) return null;\n\n const url = new URL(request.url);\n const authorization = request.headers.get(\"authorization\") || \"\";\n const bearer = authorization.startsWith(\"Bearer \") ? authorization.slice(7) : \"\";\n const headerSecret = request.headers.get(\"x-farm-workflow-secret\") || \"\";\n const querySecret = url.searchParams.get(\"secret\") || \"\";\n if (bearer === secret || headerSecret === secret || querySecret === secret) return null;\n\n return Response.json({ error: \"Unauthorized workflow request.\" }, { status: 401 });\n}\n\nfunction joinRoute(...parts: string[]): string {\n return `/${parts.map((part) => trimSlashes(part)).filter(Boolean).join(\"/\")}`;\n}\n\nfunction trimSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction safeFileName(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"workflow\";\n}\n\nfunction relativePath(root: string, filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\").replace(`${root.replace(/\\\\/g, \"/\")}/`, \"\");\n}\n"],"mappings":";;;;;AAgFO,IAAM,6BAA6B,CAAC,YAAY,iBAAiB,UAAU;AAC3E,IAAM,8BAA8B;AACpC,IAAM,mCAAmC;AAEzC,SAAS,eACd,YAC2C;AAC3C,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM;AAAA,EACR;AACF;AAPgB;AAST,SAAS,WACd,YAC2C;AAC3C,SAAO,eAAe,UAAU;AAClC;AAJgB;AAST,SAAS,WACd,YACuC;AACvC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM;AAAA,EACR;AACF;AAPgB;AAST,SAAS,uBACd,WAC6B;AAC7B,MAAI,cAAc,OAAO;AACvB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,MAAM,CAAC,GAAG,0BAA0B;AAAA,MACpC,OAAO;AAAA,MACP,WAAW;AAAA,IACb;AAAA,EACF;AAEA,QAAM,UAAU,aAAa,OAAO,cAAc,WAAW,YAAY,CAAC;AAC1E,QAAM,OAAO,sBAAsB,OAAO;AAE1C,SAAO;AAAA,IACL,SAAS,QAAQ,WAAW;AAAA,IAC5B;AAAA,IACA,OAAO,uBAAuB,QAAQ,SAAS,2BAA2B;A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