expo-router 4.0.0-preview.9 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/assets/error.png +0 -0
  2. package/assets/file.png +0 -0
  3. package/assets/forward.png +0 -0
  4. package/assets/logotype.png +0 -0
  5. package/assets/pkg.png +0 -0
  6. package/assets/sitemap.png +0 -0
  7. package/build/ExpoRoot.js +2 -2
  8. package/build/ExpoRoot.js.map +1 -1
  9. package/build/doctor/index.d.ts +16 -0
  10. package/build/doctor/index.d.ts.map +1 -0
  11. package/build/doctor/index.js +66 -0
  12. package/build/doctor/index.js.map +1 -0
  13. package/build/exports.d.ts +1 -1
  14. package/build/exports.d.ts.map +1 -1
  15. package/build/exports.js +24 -2
  16. package/build/exports.js.map +1 -1
  17. package/build/fast-refresh.d.ts.map +1 -1
  18. package/build/fast-refresh.js.map +1 -1
  19. package/build/getRoutesCore.d.ts +1 -0
  20. package/build/getRoutesCore.d.ts.map +1 -1
  21. package/build/getRoutesCore.js +3 -1
  22. package/build/getRoutesCore.js.map +1 -1
  23. package/build/global-state/router-store.d.ts.map +1 -1
  24. package/build/global-state/router-store.js +1 -2
  25. package/build/global-state/router-store.js.map +1 -1
  26. package/build/global-state/routing.d.ts.map +1 -1
  27. package/build/global-state/routing.js +4 -0
  28. package/build/global-state/routing.js.map +1 -1
  29. package/build/head/url.d.ts +1 -0
  30. package/build/head/url.d.ts.map +1 -1
  31. package/build/head/url.js +21 -4
  32. package/build/head/url.js.map +1 -1
  33. package/build/hooks.d.ts +90 -38
  34. package/build/hooks.d.ts.map +1 -1
  35. package/build/hooks.js +46 -39
  36. package/build/hooks.js.map +1 -1
  37. package/build/imperative-api.d.ts +58 -15
  38. package/build/imperative-api.d.ts.map +1 -1
  39. package/build/imperative-api.js.map +1 -1
  40. package/build/layouts/Drawer.d.ts +2 -142
  41. package/build/layouts/Drawer.d.ts.map +1 -1
  42. package/build/layouts/Drawer.js +8 -5
  43. package/build/layouts/Drawer.js.map +1 -1
  44. package/build/layouts/DrawerClient.d.ts +144 -0
  45. package/build/layouts/DrawerClient.d.ts.map +1 -0
  46. package/build/layouts/DrawerClient.js +10 -0
  47. package/build/layouts/DrawerClient.js.map +1 -0
  48. package/build/layouts/Stack.d.ts +2 -126
  49. package/build/layouts/Stack.d.ts.map +1 -1
  50. package/build/layouts/Stack.js +8 -6
  51. package/build/layouts/Stack.js.map +1 -1
  52. package/build/layouts/StackClient.d.ts +128 -0
  53. package/build/layouts/StackClient.d.ts.map +1 -0
  54. package/build/layouts/StackClient.js +10 -0
  55. package/build/layouts/StackClient.js.map +1 -0
  56. package/build/layouts/Tabs.d.ts +2 -134
  57. package/build/layouts/Tabs.d.ts.map +1 -1
  58. package/build/layouts/Tabs.js +5 -37
  59. package/build/layouts/Tabs.js.map +1 -1
  60. package/build/layouts/TabsClient.d.ts +136 -0
  61. package/build/layouts/TabsClient.d.ts.map +1 -0
  62. package/build/layouts/TabsClient.js +44 -0
  63. package/build/layouts/TabsClient.js.map +1 -0
  64. package/build/layouts/withLayoutContext.d.ts +4 -1
  65. package/build/layouts/withLayoutContext.d.ts.map +1 -1
  66. package/build/layouts/withLayoutContext.js +4 -1
  67. package/build/layouts/withLayoutContext.js.map +1 -1
  68. package/build/link/Link.d.ts +48 -4
  69. package/build/link/Link.d.ts.map +1 -1
  70. package/build/link/Link.js +47 -3
  71. package/build/link/Link.js.map +1 -1
  72. package/build/link/href.d.ts +1 -1
  73. package/build/link/href.d.ts.map +1 -1
  74. package/build/link/href.js.map +1 -1
  75. package/build/link/useLinkHooks.d.ts +122 -29
  76. package/build/link/useLinkHooks.d.ts.map +1 -1
  77. package/build/link/useLinkHooks.js.map +1 -1
  78. package/build/onboard/Tutorial.d.ts.map +1 -1
  79. package/build/onboard/Tutorial.js +140 -86
  80. package/build/onboard/Tutorial.js.map +1 -1
  81. package/build/renderRootComponent.d.ts.map +1 -1
  82. package/build/renderRootComponent.js +1 -2
  83. package/build/renderRootComponent.js.map +1 -1
  84. package/build/rsc/exports.d.ts +3 -1
  85. package/build/rsc/exports.d.ts.map +1 -1
  86. package/build/rsc/exports.js +3 -1
  87. package/build/rsc/exports.js.map +1 -1
  88. package/build/rsc/middleware.d.ts +1 -1
  89. package/build/rsc/middleware.d.ts.map +1 -1
  90. package/build/rsc/middleware.js +2 -1
  91. package/build/rsc/middleware.js.map +1 -1
  92. package/build/rsc/router/client.d.ts +2 -2
  93. package/build/rsc/router/client.d.ts.map +1 -1
  94. package/build/rsc/router/client.js.map +1 -1
  95. package/build/rsc/router/host.d.ts.map +1 -1
  96. package/build/rsc/router/host.js +20 -15
  97. package/build/rsc/router/host.js.map +1 -1
  98. package/build/rsc/rsc-renderer.d.ts +1 -1
  99. package/build/rsc/rsc-renderer.d.ts.map +1 -1
  100. package/build/rsc/rsc-renderer.js +1 -1
  101. package/build/rsc/rsc-renderer.js.map +1 -1
  102. package/build/rsc/server.d.ts +3 -0
  103. package/build/rsc/server.d.ts.map +1 -1
  104. package/build/rsc/server.js +19 -1
  105. package/build/rsc/server.js.map +1 -1
  106. package/build/testing-library/context-stubs.d.ts.map +1 -1
  107. package/build/testing-library/context-stubs.js +3 -1
  108. package/build/testing-library/context-stubs.js.map +1 -1
  109. package/build/testing-library/mocks.js +14 -13
  110. package/build/testing-library/mocks.js.map +1 -1
  111. package/build/typed-routes/generate.d.ts +5 -1
  112. package/build/typed-routes/generate.d.ts.map +1 -1
  113. package/build/typed-routes/generate.js +129 -64
  114. package/build/typed-routes/generate.js.map +1 -1
  115. package/build/typed-routes/index.d.ts +5 -0
  116. package/build/typed-routes/index.d.ts.map +1 -1
  117. package/build/typed-routes/index.js +8 -3
  118. package/build/typed-routes/index.js.map +1 -1
  119. package/build/typed-routes/testSetup.d.ts +1 -1
  120. package/build/typed-routes/testSetup.d.ts.map +1 -1
  121. package/build/typed-routes/testSetup.js +29 -17
  122. package/build/typed-routes/testSetup.js.map +1 -1
  123. package/build/typed-routes/types.d.ts +43 -145
  124. package/build/typed-routes/types.d.ts.map +1 -1
  125. package/build/typed-routes/types.js.map +1 -1
  126. package/build/types.d.ts +33 -0
  127. package/build/types.d.ts.map +1 -1
  128. package/build/types.js.map +1 -1
  129. package/build/ui/TabContext.d.ts +158 -1
  130. package/build/ui/TabContext.d.ts.map +1 -1
  131. package/build/ui/TabContext.js +25 -1
  132. package/build/ui/TabContext.js.map +1 -1
  133. package/build/ui/TabList.d.ts +17 -1
  134. package/build/ui/TabList.d.ts.map +1 -1
  135. package/build/ui/TabList.js +16 -0
  136. package/build/ui/TabList.js.map +1 -1
  137. package/build/ui/TabSlot.d.ts +55 -5
  138. package/build/ui/TabSlot.d.ts.map +1 -1
  139. package/build/ui/TabSlot.js +38 -14
  140. package/build/ui/TabSlot.js.map +1 -1
  141. package/build/ui/TabTrigger.d.ts +65 -70
  142. package/build/ui/TabTrigger.d.ts.map +1 -1
  143. package/build/ui/TabTrigger.js +25 -1
  144. package/build/ui/TabTrigger.js.map +1 -1
  145. package/build/ui/Tabs.d.ts +89 -132
  146. package/build/ui/Tabs.d.ts.map +1 -1
  147. package/build/ui/Tabs.js +53 -8
  148. package/build/ui/Tabs.js.map +1 -1
  149. package/build/ui/common.d.ts +3 -3
  150. package/build/ui/common.d.ts.map +1 -1
  151. package/build/ui/common.js.map +1 -1
  152. package/build/useFocusEffect.d.ts +15 -6
  153. package/build/useFocusEffect.d.ts.map +1 -1
  154. package/build/useFocusEffect.js +15 -6
  155. package/build/useFocusEffect.js.map +1 -1
  156. package/build/useNavigation.d.ts +11 -5
  157. package/build/useNavigation.d.ts.map +1 -1
  158. package/build/useNavigation.js +11 -5
  159. package/build/useNavigation.js.map +1 -1
  160. package/build/utils/splash.d.ts +6 -0
  161. package/build/utils/splash.d.ts.map +1 -0
  162. package/build/utils/splash.js +51 -0
  163. package/build/utils/splash.js.map +1 -0
  164. package/build/utils/url.js +2 -2
  165. package/build/utils/url.js.map +1 -1
  166. package/build/views/Navigator.d.ts +6 -5
  167. package/build/views/Navigator.d.ts.map +1 -1
  168. package/build/views/Navigator.js +6 -5
  169. package/build/views/Navigator.js.map +1 -1
  170. package/build/views/Sitemap.d.ts.map +1 -1
  171. package/build/views/Sitemap.js +93 -46
  172. package/build/views/Sitemap.js.map +1 -1
  173. package/build/views/Splash.d.ts +1 -1
  174. package/build/views/Splash.d.ts.map +1 -1
  175. package/build/views/Splash.js +3 -13
  176. package/build/views/Splash.js.map +1 -1
  177. package/build/views/Try.d.ts +1 -1
  178. package/build/views/Try.d.ts.map +1 -1
  179. package/build/views/Try.js +1 -1
  180. package/build/views/Try.js.map +1 -1
  181. package/doctor.js +1 -0
  182. package/entry-classic.js +0 -6
  183. package/package.json +23 -24
  184. package/plugin/build/index.d.ts +2 -0
  185. package/plugin/options.json +74 -73
  186. package/plugin/src/index.ts +64 -0
  187. package/rsc/entry.js +0 -6
  188. package/rsc/headers.d.ts +3 -0
  189. package/rsc/headers.js +5 -0
  190. package/build/rsc/runtime.d.ts +0 -9
  191. package/build/rsc/runtime.d.ts.map +0 -1
  192. package/build/rsc/runtime.js +0 -36
  193. package/build/rsc/runtime.js.map +0 -1
  194. package/virtual-client-boundaries.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"rsc-renderer.js","sourceRoot":"","sources":["../../src/rsc/rsc-renderer.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAEH,kEAAkE;AAElE,iGAAiG;AACjG,qBAAmB;AAGnB,4DAAsF;AAEtF,iCAA2C;AAC3C,0CAAgD;AAChD,qCAAgF;AAqCzE,KAAK,UAAU,SAAS,CAAC,IAAmB,EAAE,IAAmB;IACtE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC5D,MAAM,EAAE,kBAAkB,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAE7C,MAAM,EACJ,OAAO,EAAE,EAAE,aAAa,EAAE;IAC1B,mBAAm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IAAI,EAAE;IACvB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACvB,CAAC,CAAC","sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n * Copyright © 2024 dai-shi.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * From waku https://github.com/dai-shi/waku/blob/32d52242c1450b5f5965860e671ff73c42da8bd0/packages/waku/src/lib/renderers/rsc-renderer.ts\n */\n\n// This file must remain platform agnostic for production exports.\n\n// Import the runtime to support polyfills for webpack to load modules in the server using Metro.\nimport './runtime';\n\nimport type { ReactNode } from 'react';\nimport { renderToReadableStream, decodeReply } from 'react-server-dom-webpack/server';\n\nimport { fileURLToFilePath } from './path';\nimport { decodeActionId } from './router/utils';\nimport { runWithRenderStore, type EntriesDev, type EntriesPrd } from './server';\n\nexport interface RenderContext<T = unknown> {\n rerender: (input: string, searchParams?: URLSearchParams) => void;\n context: T;\n}\n\ntype ResolvedConfig = any;\n\nexport type RenderRscArgs = {\n // TODO:\n config: ResolvedConfig;\n\n // Done\n input: string;\n context: Record<string, unknown> | undefined;\n body?: ReadableStream | undefined;\n contentType?: string | undefined;\n decodedBody?: unknown;\n moduleIdCallback?: (module: {\n id: string;\n chunks: string[];\n name: string;\n async: boolean;\n }) => void;\n onError?: (err: unknown) => void;\n};\n\ntype ResolveClientEntry = (id: string, server: boolean) => { id: string; chunks: string[] };\n\ntype RenderRscOpts = {\n isExporting: boolean;\n entries: EntriesDev;\n resolveClientEntry: ResolveClientEntry;\n loadServerModuleRsc: (url: string) => Promise<any>;\n};\n\nexport async function renderRsc(args: RenderRscArgs, opts: RenderRscOpts): Promise<ReadableStream> {\n const { input, body, contentType, context, onError } = args;\n const { resolveClientEntry, entries } = opts;\n\n const {\n default: { renderEntries },\n // @ts-expect-error\n buildConfig,\n } = entries as (EntriesDev & { loadModule: never; buildConfig: never }) | EntriesPrd;\n\n function resolveRequest(isServer: boolean, encodedId: string) {\n const [\n // File is the on-disk location of the module, this is injected during the \"use client\" transformation (babel).\n file,\n // The name of the import (e.g. \"default\" or \"\")\n // This will be empty when using `module.exports = ` and `require('...')`.\n name = '',\n ] = encodedId.split('#') as [string, string];\n\n const filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;\n\n args.moduleIdCallback?.({\n id: filePath,\n chunks: [\n // TODO: Add a lookup later which reads from the SSR manifest to get the correct chunk.\n // NOTE(EvanBacon): This is a placeholder since we need to render RSC to get the client boundaries, which we then inject later.\n 'chunk:' + filePath,\n ],\n name,\n async: true,\n });\n // We'll augment the file path with the incoming RSC request which will forward the metro props required to make a cache hit, e.g. platform=web&...\n // This is similar to how we handle lazy bundling.\n const resolved = resolveClientEntry(filePath, isServer);\n return { id: resolved.id, chunks: resolved.chunks, name, async: true };\n }\n\n const bundlerConfig = new Proxy(\n {},\n {\n get(_target, encodedId: string) {\n return resolveRequest(false, encodedId);\n },\n }\n );\n\n const serverConfig = new Proxy(\n {},\n {\n get(_target, encodedId: string) {\n return resolveRequest(true, encodedId);\n },\n }\n );\n\n // @ts-ignore: Not part of global types. This is added to support server actions loading more actions.\n global[`${__METRO_GLOBAL_PREFIX__}__loadBundleAsync`] = opts.loadServerModuleRsc;\n\n const renderWithContext = async (\n context: Record<string, unknown> | undefined,\n input: string,\n params: unknown\n ) => {\n const renderStore = {\n context: context || {},\n rerender: () => {\n throw new Error('Cannot rerender');\n },\n };\n return runWithRenderStore(renderStore, async () => {\n const elements = await renderEntries(input, {\n params,\n buildConfig,\n });\n if (elements === null) {\n const err = new Error('No function component found at: ' + input);\n (err as any).statusCode = 404;\n throw err;\n }\n if (Object.keys(elements).some((key) => key.startsWith('_'))) {\n throw new Error('\"_\" prefix is reserved');\n }\n return renderToReadableStream(elements, bundlerConfig, {\n onError,\n });\n });\n };\n\n const renderWithContextWithAction = async (\n context: Record<string, unknown> | undefined,\n actionFn: (...args: unknown[]) => unknown,\n actionArgs: unknown[]\n ) => {\n let elementsPromise: Promise<Record<string, ReactNode>> = Promise.resolve({});\n let rendered = false;\n const renderStore = {\n context: context || {},\n rerender: async (input: string, params?: unknown) => {\n if (rendered) {\n throw new Error('already rendered');\n }\n elementsPromise = Promise.all([\n elementsPromise,\n renderEntries(input, { params, buildConfig }),\n ]).then(([oldElements, newElements]) => ({\n ...oldElements,\n // FIXME we should actually check if newElements is null and send an error\n ...newElements,\n }));\n },\n };\n return runWithRenderStore(renderStore, async () => {\n const actionValue = await actionFn(...actionArgs);\n const elements = await elementsPromise;\n rendered = true;\n if (Object.keys(elements).some((key) => key.startsWith('_'))) {\n throw new Error('\"_\" prefix is reserved');\n }\n return renderToReadableStream({ ...elements, _value: actionValue }, bundlerConfig, {\n onError,\n });\n });\n };\n\n let decodedBody: unknown | undefined = args.decodedBody;\n if (body) {\n const bodyStr = await streamToString(body);\n if (typeof contentType === 'string' && contentType.startsWith('multipart/form-data')) {\n // XXX This doesn't support streaming unlike busboy\n const formData = parseFormData(bodyStr, contentType);\n decodedBody = await decodeReply(formData, serverConfig);\n } else if (bodyStr) {\n decodedBody = await decodeReply(bodyStr, serverConfig);\n }\n }\n\n const actionId = decodeActionId(input);\n if (actionId) {\n if (\n !opts.isExporting &&\n // @ts-ignore\n !process.env.EXPO_UNSTABLE_SERVER_ACTIONS\n ) {\n throw new Error('Experimental support for React Server Actions is not enabled');\n }\n\n const args = Array.isArray(decodedBody) ? decodedBody : [];\n\n const chunkInfo = serverConfig[actionId];\n\n // Load module into memory.\n await Promise.all(chunkInfo.chunks.map((chunk) => globalThis.__webpack_chunk_load__(chunk)));\n\n // Import module.\n const mod: any = globalThis.__webpack_require__(chunkInfo.id);\n const fn = chunkInfo.name === '*' ? chunkInfo.name : mod[chunkInfo.name] || mod;\n\n if (!fn) {\n throw new Error(\n `Could not find server action: ${actionId}. Module: ${JSON.stringify(chunkInfo, null, 2)}`\n );\n }\n\n return renderWithContextWithAction(context, fn, args);\n }\n\n // method === 'GET'\n return renderWithContext(context, input, decodedBody);\n}\n\n// TODO is this correct? better to use a library?\nconst parseFormData = (body: string, contentType: string) => {\n const boundary = contentType.split('boundary=')[1];\n const parts = body.split(`--${boundary}`);\n const formData = new FormData();\n for (const part of parts) {\n if (part.trim() === '' || part === '--') continue;\n const [rawHeaders, content] = part.split('\\r\\n\\r\\n', 2);\n const headers = rawHeaders!.split('\\r\\n').reduce(\n (acc, currentHeader) => {\n const [key, value] = currentHeader.split(': ');\n acc[key!.toLowerCase()] = value!;\n return acc;\n },\n {} as Record<string, string>\n );\n const contentDisposition = headers['content-disposition'];\n const nameMatch = /name=\"([^\"]+)\"/.exec(contentDisposition!);\n const filenameMatch = /filename=\"([^\"]+)\"/.exec(contentDisposition!);\n if (nameMatch) {\n const name = nameMatch[1];\n if (filenameMatch) {\n const filename = filenameMatch[1];\n const type = headers['content-type'] || 'application/octet-stream';\n const blob = new Blob([content!], { type });\n formData.append(name!, blob, filename);\n } else {\n formData.append(name!, content!.trim());\n }\n }\n }\n return formData;\n};\n\nconst streamToString = async (stream: ReadableStream): Promise<string> => {\n const decoder = new TextDecoder();\n const reader = stream.getReader();\n const outs: string[] = [];\n let result: ReadableStreamReadResult<unknown>;\n do {\n result = await reader.read();\n if (result.value) {\n if (!(result.value instanceof Uint8Array)) {\n throw new Error('Unexepected buffer type');\n }\n outs.push(decoder.decode(result.value, { stream: true }));\n }\n } while (!result.done);\n outs.push(decoder.decode());\n return outs.join('');\n};\n"]}
1
+ {"version":3,"file":"rsc-renderer.js","sourceRoot":"","sources":["../../src/rsc/rsc-renderer.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAEH,kEAAkE;AAElE,iGAAiG;AACjG,2CAAyC;AAGzC,4DAAsF;AAEtF,iCAA2C;AAC3C,0CAAgD;AAChD,qCAAgF;AAqCzE,KAAK,UAAU,SAAS,CAAC,IAAmB,EAAE,IAAmB;IACtE,MAAM,EAAE,KAAK,EAAE,IAAI,EA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B,CAAC,CAAC;aAC5C;YACD,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;SAC3D;KACF,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE;IACvB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACvB,CAAC,CAAC","sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n * Copyright © 2024 dai-shi.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * From waku https://github.com/dai-shi/waku/blob/32d52242c1450b5f5965860e671ff73c42da8bd0/packages/waku/src/lib/renderers/rsc-renderer.ts\n */\n\n// This file must remain platform agnostic for production exports.\n\n// Import the runtime to support polyfills for webpack to load modules in the server using Metro.\nimport '@expo/metro-runtime/rsc/runtime';\n\nimport type { ReactNode } from 'react';\nimport { renderToReadableStream, decodeReply } from 'react-server-dom-webpack/server';\n\nimport { fileURLToFilePath } from './path';\nimport { decodeActionId } from './router/utils';\nimport { runWithRenderStore, type EntriesDev, type EntriesPrd } from './server';\n\nexport interface RenderContext<T = unknown> {\n rerender: (input: string, searchParams?: URLSearchParams) => void;\n context: T;\n}\n\ntype ResolvedConfig = any;\n\nexport type RenderRscArgs = {\n // TODO:\n config: ResolvedConfig;\n\n // Done\n input: string;\n context: Record<string, unknown> | undefined;\n body?: ReadableStream | undefined;\n contentType?: string | undefined;\n decodedBody?: unknown;\n moduleIdCallback?: (module: {\n id: string;\n chunks: string[];\n name: string;\n async: boolean;\n }) => void;\n onError?: (err: unknown) => void;\n};\n\ntype ResolveClientEntry = (id: string, server: boolean) => { id: string; chunks: string[] };\n\ntype RenderRscOpts = {\n isExporting: boolean;\n entries: EntriesDev;\n resolveClientEntry: ResolveClientEntry;\n loadServerModuleRsc: (url: string) => Promise<any>;\n};\n\nexport async function renderRsc(args: RenderRscArgs, opts: RenderRscOpts): Promise<ReadableStream> {\n const { input, body, contentType, context, onError } = args;\n const { resolveClientEntry, entries } = opts;\n\n const {\n default: { renderEntries },\n // @ts-expect-error\n buildConfig,\n } = entries as (EntriesDev & { loadModule: never; buildConfig: never }) | EntriesPrd;\n\n function resolveRequest(isServer: boolean, encodedId: string) {\n const [\n // File is the on-disk location of the module, this is injected during the \"use client\" transformation (babel).\n file,\n // The name of the import (e.g. \"default\" or \"\")\n // This will be empty when using `module.exports = ` and `require('...')`.\n name = '',\n ] = encodedId.split('#') as [string, string];\n\n const filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;\n\n args.moduleIdCallback?.({\n id: filePath,\n chunks: [\n // TODO: Add a lookup later which reads from the SSR manifest to get the correct chunk.\n // NOTE(EvanBacon): This is a placeholder since we need to render RSC to get the client boundaries, which we then inject later.\n 'chunk:' + filePath,\n ],\n name,\n async: true,\n });\n // We'll augment the file path with the incoming RSC request which will forward the metro props required to make a cache hit, e.g. platform=web&...\n // This is similar to how we handle lazy bundling.\n const resolved = resolveClientEntry(filePath, isServer);\n return { id: resolved.id, chunks: resolved.chunks, name, async: true };\n }\n\n const bundlerConfig = new Proxy(\n {},\n {\n get(_target, encodedId: string) {\n return resolveRequest(false, encodedId);\n },\n }\n );\n\n const serverConfig = new Proxy(\n {},\n {\n get(_target, encodedId: string) {\n return resolveRequest(true, encodedId);\n },\n }\n );\n\n // @ts-ignore: Not part of global types. This is added to support server actions loading more actions.\n global[`${__METRO_GLOBAL_PREFIX__}__loadBundleAsync`] = opts.loadServerModuleRsc;\n\n const renderWithContext = async (\n context: Record<string, unknown> | undefined,\n input: string,\n params: unknown\n ) => {\n const renderStore = {\n context: context || {},\n rerender: () => {\n throw new Error('Cannot rerender');\n },\n };\n return runWithRenderStore(renderStore, async () => {\n const elements = await renderEntries(input, {\n params,\n buildConfig,\n });\n if (elements === null) {\n const err = new Error('No function component found at: ' + input);\n (err as any).statusCode = 404;\n throw err;\n }\n if (Object.keys(elements).some((key) => key.startsWith('_'))) {\n throw new Error('\"_\" prefix is reserved');\n }\n return renderToReadableStream(elements, bundlerConfig, {\n onError,\n });\n });\n };\n\n const renderWithContextWithAction = async (\n context: Record<string, unknown> | undefined,\n actionFn: (...args: unknown[]) => unknown,\n actionArgs: unknown[]\n ) => {\n let elementsPromise: Promise<Record<string, ReactNode>> = Promise.resolve({});\n let rendered = false;\n const renderStore = {\n context: context || {},\n rerender: async (input: string, params?: unknown) => {\n if (rendered) {\n throw new Error('already rendered');\n }\n elementsPromise = Promise.all([\n elementsPromise,\n renderEntries(input, { params, buildConfig }),\n ]).then(([oldElements, newElements]) => ({\n ...oldElements,\n // FIXME we should actually check if newElements is null and send an error\n ...newElements,\n }));\n },\n };\n return runWithRenderStore(renderStore, async () => {\n const actionValue = await actionFn(...actionArgs);\n const elements = await elementsPromise;\n rendered = true;\n if (Object.keys(elements).some((key) => key.startsWith('_'))) {\n throw new Error('\"_\" prefix is reserved');\n }\n return renderToReadableStream({ ...elements, _value: actionValue }, bundlerConfig, {\n onError,\n });\n });\n };\n\n let decodedBody: unknown | undefined = args.decodedBody;\n if (body) {\n const bodyStr = await streamToString(body);\n if (typeof contentType === 'string' && contentType.startsWith('multipart/form-data')) {\n // XXX This doesn't support streaming unlike busboy\n const formData = parseFormData(bodyStr, contentType);\n decodedBody = await decodeReply(formData, serverConfig);\n } else if (bodyStr) {\n decodedBody = await decodeReply(bodyStr, serverConfig);\n }\n }\n\n const actionId = decodeActionId(input);\n if (actionId) {\n if (\n !opts.isExporting &&\n // @ts-ignore\n !process.env.EXPO_UNSTABLE_SERVER_ACTIONS\n ) {\n throw new Error('Experimental support for React Server Actions is not enabled');\n }\n\n const args = Array.isArray(decodedBody) ? decodedBody : [];\n\n const chunkInfo = serverConfig[actionId];\n\n // Load module into memory.\n await Promise.all(chunkInfo.chunks.map((chunk) => globalThis.__webpack_chunk_load__(chunk)));\n\n // Import module.\n const mod: any = globalThis.__webpack_require__(chunkInfo.id);\n const fn = chunkInfo.name === '*' ? chunkInfo.name : mod[chunkInfo.name] || mod;\n\n if (!fn) {\n throw new Error(\n `Could not find server action: ${actionId}. Module: ${JSON.stringify(chunkInfo, null, 2)}`\n );\n }\n\n return renderWithContextWithAction(context, fn, args);\n }\n\n // method === 'GET'\n return renderWithContext(context, input, decodedBody);\n}\n\n// TODO is this correct? better to use a library?\nconst parseFormData = (body: string, contentType: string) => {\n const boundary = contentType.split('boundary=')[1];\n const parts = body.split(`--${boundary}`);\n const formData = new FormData();\n for (const part of parts) {\n if (part.trim() === '' || part === '--') continue;\n const [rawHeaders, content] = part.split('\\r\\n\\r\\n', 2);\n const headers = rawHeaders!.split('\\r\\n').reduce(\n (acc, currentHeader) => {\n const [key, value] = currentHeader.split(': ');\n acc[key!.toLowerCase()] = value!;\n return acc;\n },\n {} as Record<string, string>\n );\n const contentDisposition = headers['content-disposition'];\n const nameMatch = /name=\"([^\"]+)\"/.exec(contentDisposition!);\n const filenameMatch = /filename=\"([^\"]+)\"/.exec(contentDisposition!);\n if (nameMatch) {\n const name = nameMatch[1];\n if (filenameMatch) {\n const filename = filenameMatch[1];\n const type = headers['content-type'] || 'application/octet-stream';\n const blob = new Blob([content!], { type });\n formData.append(name!, blob, filename);\n } else {\n formData.append(name!, content!.trim());\n }\n }\n }\n return formData;\n};\n\nconst streamToString = async (stream: ReadableStream): Promise<string> => {\n const decoder = new TextDecoder();\n const reader = stream.getReader();\n const outs: string[] = [];\n let result: ReadableStreamReadResult<unknown>;\n do {\n result = await reader.read();\n if (result.value) {\n if (!(result.value instanceof Uint8Array)) {\n throw new Error('Unexepected buffer type');\n }\n outs.push(decoder.decode(result.value, { stream: true }));\n }\n } while (!result.done);\n outs.push(decoder.decode());\n return outs.join('');\n};\n"]}
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { ReactNode } from 'react';
9
9
  import type { PathSpec } from './path';
10
+ export declare const REQUEST_HEADERS = "__expo_requestHeaders";
10
11
  type Config = any;
11
12
  type Elements = Record<string, ReactNode>;
12
13
  export type BuildConfig = {
@@ -58,5 +59,7 @@ type RenderStore = {
58
59
  export declare const runWithRenderStore: <T>(renderStore: RenderStore, fn: () => T) => T;
59
60
  export declare function rerender(input: string, params?: unknown): void;
60
61
  export declare function getContext<RscContext extends Record<string, unknown> = Record<string, unknown>>(): RscContext;
62
+ /** Get the request headers used to make the server component or action request. */
63
+ export declare function unstable_headers(): Promise<Headers>;
61
64
  export {};
62
65
  //# sourceMappingURL=server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/rsc/server.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAQvC,KAAK,MAAM,GAAG,GAAG,CAAC;AAElB,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAE1C,MAAM,MAAM,WAAW,GAAG;IACxB,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC5B,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC/B,OAAO,CAAC,EAAE;QACR,KAAK,EAAE,MAAM,CAAC;QACd,YAAY,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;QACnC,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;KAChC,EAAE,CAAC;IACJ,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,EAAE,CAAC;AAEJ,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,MAAM,EACb,OAAO,EAAE;IACP,MAAM,EAAE,OAAO,GAAG,SAAS,CAA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CAAC,CAAC;CAClC,CAAC;AA4CF;;GAEG;AACH,eAAO,MAAM,kBAAkB,mBAAoB,WAAW,mBAW7D,CAAC;AAEF,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,QAMvD;AAED,wBAAgB,UAAU,CACxB,UAAU,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACjE,UAAU,CAMd;AAED,mFAAmF;AACnF,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,OAAO,CAAC,CAGzD"}
@@ -7,7 +7,8 @@
7
7
  * LICENSE file in the root directory of this source tree.
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.getContext = exports.rerender = exports.runWithRenderStore = exports.defineEntries = void 0;
10
+ exports.unstable_headers = exports.getContext = exports.rerender = exports.runWithRenderStore = exports.defineEntries = exports.REQUEST_HEADERS = void 0;
11
+ exports.REQUEST_HEADERS = '__expo_requestHeaders';
11
12
  function defineEntries(renderEntries, getBuildConfig, getSsrConfig) {
12
13
  return { renderEntries, getBuildConfig, getSsrConfig };
13
14
  }
@@ -84,4 +85,21 @@ function getContext() {
84
85
  return renderStore.context;
85
86
  }
86
87
  exports.getContext = getContext;
88
+ /** Get the request headers used to make the server component or action request. */
89
+ async function unstable_headers() {
90
+ const headers = (getContext()[exports.REQUEST_HEADERS] || {});
91
+ return new ReadonlyHeaders(headers);
92
+ }
93
+ exports.unstable_headers = unstable_headers;
94
+ class ReadonlyHeaders extends Headers {
95
+ set() {
96
+ throw new Error('Server component Headers are read-only');
97
+ }
98
+ append() {
99
+ throw new Error('Server component Headers are read-only');
100
+ }
101
+ delete() {
102
+ throw new Error('Server component Headers are read-only');
103
+ }
104
+ }
87
105
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/rsc/server.ts"],"names":[],"mappings":";AAA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industries.\n * Copyright © 2024 2023 Daishi Kato\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport { type AsyncLocalStorage } from 'node:async_hooks';\nimport type { ReactNode } from 'react';\n\nimport type { PathSpec } from './path';\n\ndeclare let globalThis: {\n __EXPO_RSC_CACHE__?: Map<string, any>;\n __webpack_chunk_load__: (id: string) => Promise<any>;\n __webpack_require__: (id: string) => any;\n};\n\ntype Config = any;\n\ntype Elements = Record<string, ReactNode>;\n\nexport type BuildConfig = {\n pathname: string | PathSpec; // TODO drop support for string?\n isStatic?: boolean | undefined;\n entries?: {\n input: string;\n skipPrefetch?: boolean | undefined;\n isStatic?: boolean | undefined;\n }[];\n context?: Record<string, unknown>;\n customCode?: string; // optional code to inject TODO hope to remove this\n customData?: unknown; // should be serializable with JSON.stringify\n}[];\n\nexport type RenderEntries = (\n input: string,\n options: {\n params: unknown | undefined;\n buildConfig: BuildConfig | undefined;\n }\n) => Promise<Elements | null>;\n\nexport type GetBuildConfig = (\n unstable_collectClientModules: (input: string) => Promise<string[]>\n) => Promise<BuildConfig>;\n\nexport type GetSsrConfig = (\n pathname: string,\n options: {\n searchParams: URLSearchParams;\n buildConfig?: BuildConfig | undefined;\n }\n) => Promise<{\n input: string;\n searchParams?: URLSearchParams;\n html: ReactNode;\n} | null>;\n\nexport function defineEntries(\n renderEntries: RenderEntries,\n getBuildConfig?: GetBuildConfig,\n getSsrConfig?: GetSsrConfig\n) {\n return { renderEntries, getBuildConfig, getSsrConfig };\n}\n\nexport type EntriesDev = {\n default: ReturnType<typeof defineEntries>;\n};\n\nexport type EntriesPrd = EntriesDev & {\n loadConfig: () => Promise<Config>;\n loadModule: (id: string) => Promise<unknown>;\n dynamicHtmlPaths: [pathSpec: PathSpec, htmlHead: string][];\n publicIndexHtml: string;\n};\n\ntype RenderStore<> = {\n rerender: (input: string, params?: unknown) => void;\n context: Record<string, unknown>;\n};\n\n// TODO(EvanBacon): This can leak between platforms and runs.\n// We need to share this module between the server action module and the renderer module, per platform, and invalidate on refreshes.\nfunction getGlobalCacheForPlatform(): Pick<AsyncLocalStorage<RenderStore>, 'getStore' | 'run'> {\n if (!globalThis.__EXPO_RSC_CACHE__) {\n globalThis.__EXPO_RSC_CACHE__ = new Map();\n }\n\n if (globalThis.__EXPO_RSC_CACHE__.has(process.env.EXPO_OS!)) {\n return globalThis.__EXPO_RSC_CACHE__.get(process.env.EXPO_OS!)!;\n }\n try {\n const { AsyncLocalStorage } = require('node:async_hooks');\n // @ts-expect-error: This is a Node.js feature.\n const serverCache = new AsyncLocalStorage<RenderStore>();\n globalThis.__EXPO_RSC_CACHE__.set(process.env.EXPO_OS!, serverCache);\n return serverCache;\n } catch (error) {\n console.log('[RSC]: Failed to create cache:', error);\n\n // Fallback to a simple in-memory cache.\n const cache = new Map();\n const serverCache = {\n getStore: () => cache.get('store'),\n run: <T>(store: RenderStore, fn: () => T) => {\n cache.set('store', store);\n try {\n return fn();\n } finally {\n cache.delete('store');\n }\n },\n };\n globalThis.__EXPO_RSC_CACHE__.set(process.env.EXPO_OS!, serverCache);\n return serverCache;\n }\n}\n\nlet previousRenderStore: RenderStore | undefined;\nlet currentRenderStore: RenderStore | undefined;\n\nconst renderStorage = getGlobalCacheForPlatform();\n\n/**\n * This is an internal function and not for public use.\n */\nexport const runWithRenderStore = <T>(renderStore: RenderStore, fn: () => T): T => {\n if (renderStorage) {\n return renderStorage.run(renderStore, fn);\n }\n previousRenderStore = currentRenderStore;\n currentRenderStore = renderStore;\n try {\n return fn();\n } finally {\n currentRenderStore = previousRenderStore;\n }\n};\n\nexport function rerender(input: string, params?: unknown) {\n const renderStore = renderStorage?.getStore() ?? currentRenderStore;\n if (!renderStore) {\n throw new Error('Render store is not available');\n }\n renderStore.rerender(input, params);\n}\n\nexport function getContext<\n RscContext extends Record<string, unknown> = Record<string, unknown>,\n>(): RscContext {\n const renderStore = renderStorage?.getStore() ?? currentRenderStore;\n if (!renderStore) {\n throw new Error('Render store is not available');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,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;KAClD;IACD,OAAO,WAAW,CAAC,OAAqB,CAAC;AAC3C,CAAC;AARD,gCAQC;AAED,mFAAmF;AAC5E,KAAK,UAAU,gBAAgB;IACpC,MAAM,OAAO,GAAG,CAAC,UAAU,EAAE,CAAC,uBAAe,CAAC,IAAI,EAAE,CAA2B,CAAC;IAChF,OAAO,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;AAHD,4CAGC;AAED,MAAM,eAAgB,SAAQ,OAAO;IACnC,GAAG;QACD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC5D,CAAC;IACD,MAAM;QACJ,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC5D,CAAC;IACD,MAAM;QACJ,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC5D,CAAC;CACF","sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n * Copyright © 2024 2023 Daishi Kato\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport { type AsyncLocalStorage } from 'node:async_hooks';\nimport type { ReactNode } from 'react';\n\nimport type { PathSpec } from './path';\n\nexport const REQUEST_HEADERS = '__expo_requestHeaders';\n\ndeclare let globalThis: {\n __EXPO_RSC_CACHE__?: Map<string, any>;\n __webpack_chunk_load__: (id: string) => Promise<any>;\n __webpack_require__: (id: string) => any;\n};\n\ntype Config = any;\n\ntype Elements = Record<string, ReactNode>;\n\nexport type BuildConfig = {\n pathname: string | PathSpec; // TODO drop support for string?\n isStatic?: boolean | undefined;\n entries?: {\n input: string;\n skipPrefetch?: boolean | undefined;\n isStatic?: boolean | undefined;\n }[];\n context?: Record<string, unknown>;\n customCode?: string; // optional code to inject TODO hope to remove this\n customData?: unknown; // should be serializable with JSON.stringify\n}[];\n\nexport type RenderEntries = (\n input: string,\n options: {\n params: unknown | undefined;\n buildConfig: BuildConfig | undefined;\n }\n) => Promise<Elements | null>;\n\nexport type GetBuildConfig = (\n unstable_collectClientModules: (input: string) => Promise<string[]>\n) => Promise<BuildConfig>;\n\nexport type GetSsrConfig = (\n pathname: string,\n options: {\n searchParams: URLSearchParams;\n buildConfig?: BuildConfig | undefined;\n }\n) => Promise<{\n input: string;\n searchParams?: URLSearchParams;\n html: ReactNode;\n} | null>;\n\nexport function defineEntries(\n renderEntries: RenderEntries,\n getBuildConfig?: GetBuildConfig,\n getSsrConfig?: GetSsrConfig\n) {\n return { renderEntries, getBuildConfig, getSsrConfig };\n}\n\nexport type EntriesDev = {\n default: ReturnType<typeof defineEntries>;\n};\n\nexport type EntriesPrd = EntriesDev & {\n loadConfig: () => Promise<Config>;\n loadModule: (id: string) => Promise<unknown>;\n dynamicHtmlPaths: [pathSpec: PathSpec, htmlHead: string][];\n publicIndexHtml: string;\n};\n\ntype RenderStore<> = {\n rerender: (input: string, params?: unknown) => void;\n context: Record<string, unknown>;\n};\n\n// TODO(EvanBacon): This can leak between platforms and runs.\n// We need to share this module between the server action module and the renderer module, per platform, and invalidate on refreshes.\nfunction getGlobalCacheForPlatform(): Pick<AsyncLocalStorage<RenderStore>, 'getStore' | 'run'> {\n if (!globalThis.__EXPO_RSC_CACHE__) {\n globalThis.__EXPO_RSC_CACHE__ = new Map();\n }\n\n if (globalThis.__EXPO_RSC_CACHE__.has(process.env.EXPO_OS!)) {\n return globalThis.__EXPO_RSC_CACHE__.get(process.env.EXPO_OS!)!;\n }\n try {\n const { AsyncLocalStorage } = require('node:async_hooks');\n // @ts-expect-error: This is a Node.js feature.\n const serverCache = new AsyncLocalStorage<RenderStore>();\n globalThis.__EXPO_RSC_CACHE__.set(process.env.EXPO_OS!, serverCache);\n return serverCache;\n } catch (error) {\n console.log('[RSC]: Failed to create cache:', error);\n\n // Fallback to a simple in-memory cache.\n const cache = new Map();\n const serverCache = {\n getStore: () => cache.get('store'),\n run: <T>(store: RenderStore, fn: () => T) => {\n cache.set('store', store);\n try {\n return fn();\n } finally {\n cache.delete('store');\n }\n },\n };\n globalThis.__EXPO_RSC_CACHE__.set(process.env.EXPO_OS!, serverCache);\n return serverCache;\n }\n}\n\nlet previousRenderStore: RenderStore | undefined;\nlet currentRenderStore: RenderStore | undefined;\n\nconst renderStorage = getGlobalCacheForPlatform();\n\n/**\n * This is an internal function and not for public use.\n */\nexport const runWithRenderStore = <T>(renderStore: RenderStore, fn: () => T): T => {\n if (renderStorage) {\n return renderStorage.run(renderStore, fn);\n }\n previousRenderStore = currentRenderStore;\n currentRenderStore = renderStore;\n try {\n return fn();\n } finally {\n currentRenderStore = previousRenderStore;\n }\n};\n\nexport function rerender(input: string, params?: unknown) {\n const renderStore = renderStorage?.getStore() ?? currentRenderStore;\n if (!renderStore) {\n throw new Error('Render store is not available');\n }\n renderStore.rerender(input, params);\n}\n\nexport function getContext<\n RscContext extends Record<string, unknown> = Record<string, unknown>,\n>(): RscContext {\n const renderStore = renderStorage?.getStore() ?? currentRenderStore;\n if (!renderStore) {\n throw new Error('Render store is not available');\n }\n return renderStore.context as RscContext;\n}\n\n/** Get the request headers used to make the server component or action request. */\nexport async function unstable_headers(): Promise<Headers> {\n const headers = (getContext()[REQUEST_HEADERS] || {}) as Record<string, string>;\n return new ReadonlyHeaders(headers);\n}\n\nclass ReadonlyHeaders extends Headers {\n set() {\n throw new Error('Server component Headers are read-only');\n }\n append() {\n throw new Error('Server component Headers are read-only');\n }\n delete() {\n throw new Error('Server component Headers are read-only');\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"context-stubs.d.ts","sourceRoot":"","sources":["../../src/testing-library/context-stubs.ts"],"names":[],"mappings":";AAEA,OAAO,cAAc,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,MAAM,MAAM,cAAc,GAAG,MAAM,KAAK,CAAC,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC;AACvE,MAAM,MAAM,gB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,CAAC,EAAE,gBAAgB,CAAC;CACrC,CAAC;AAEF,OAAO,EAAE,cAAc,EAAE,CAAC;AAI1B,wBAAgB,eAAe,CAAC,OAAO,EAAE,aAAa,SAEpC,MAAM;;;;;;mBAKH,MAAM;;;EAa1B;AAED,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,SAI/D,MAAM;;mBAUH,MAAM;;EAI1B"}
@@ -18,7 +18,9 @@ function inMemoryContext(context) {
18
18
  keys: () => Object.keys(context).map((key) => {
19
19
  const ext = path_1.default.extname(key);
20
20
  key = key.replace(/^\.\//, '');
21
- return validExtensions.includes(ext) ? `./${key}` : `./${key}.js`;
21
+ key = key.startsWith('/') ? key : `./${key}`;
22
+ key = validExtensions.includes(ext) ? key : `${key}.js`;
23
+ return key;
22
24
  }),
23
25
  });
24
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"context-stubs.js","sourceRoot":"","sources":["../../src/testing-library/context-stubs.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AAExB,0FAAwD;AAgB/C,yBAhBF,kCAAc,CAgBE;AAEvB,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAEvD,SAAgB,eAAe,CAAC,OAAsB;IACpD,OAAO,MAAM,CAAC,MAAM,CAClB,UAAU,EAAU;QAClB,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QACnD,OAAO,OAAO,OAAO,CAAC,EAAE,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IACpF,CAAC,EACD;QACE,OAAO,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,GAAG;QAC7B,EAAE,EAA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-context-ponyfill';\nimport { NativeIntent } from '../types';\n\nexport type ReactComponent = () => React.ReactElement<any, any> | null;\nexport type NativeIntentStub = NativeIntent;\nexport type FileStub =\n | (Record<string, unknown> & {\n default: ReactComponent;\n unstable_settings?: Record<string, any>;\n })\n | ReactComponent;\n\nexport type MemoryContext = Record<string, FileStub | NativeIntentStub> & {\n '+native-intent'?: NativeIntentStub;\n};\n\nexport { requireContext };\n\nconst validExtensions = ['.js', '.jsx', '.ts', '.tsx'];\n\nexport function inMemoryContext(context: MemoryContext) {\n return Object.assign(\n function (id: string) {\n id = id.replace(/^\\.\\//, '').replace(/\\.\\w*$/, '');\n return typeof context[id] === 'function' ? { default: context[id] } : context[id];\n },\n {\n resolve: (key: string) => key,\n id: '0',\n keys: () =>\n Object.keys(context).map((key) => {\n const ext = path.extname(key);\n key = key.replace(/^\\.\\//, '');\n return validExtensions.includes(ext) ? `./${key}` : `./${key}.js`;\n }),\n }\n );\n}\n\nexport function requireContextWithOverrides(dir: string, overrides: MemoryContext) {\n const existingContext = requireContext(path.resolve(process.cwd(), dir));\n\n return Object.assign(\n function (id: string) {\n if (id in overrides) {\n const route = overrides[id];\n return typeof route === 'function' ? { default: route } : route;\n } else {\n return existingContext(id);\n }\n },\n {\n keys: () => [...Object.keys(overrides), ...existingContext.keys()],\n resolve: (key: string) => key,\n id: '0',\n }\n );\n}\n"]}
1
+ {"version":3,"file":"context-stubs.js","sourceRoot":"","sources":["../../src/testing-library/context-stubs.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AAExB,0FAAwD;AAgB/C,yBAhBF,kCAAc,CAgBE;AAEvB,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAEvD,SAAgB,eAAe,CAAC,OAAsB;IACpD,OAAO,MAAM,CAAC,MAAM,CAClB,UAAU,EAAU;QAClB,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAA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U,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;SACjE;aAAM;YACL,OAAO,eAAe,CAAC,EAAE,CAAC,CAAC;SAC5B;IACH,CAAC,EACD;QACE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,eAAe,CAAC,IAAI,EAAE,CAAC;QAClE,OAAO,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,GAAG;QAC7B,EAAE,EAAE,GAAG;KACR,CACF,CAAC;AACJ,CAAC;AAlBD,kEAkBC","sourcesContent":["import path from 'path';\n\nimport requireContext from './require-context-ponyfill';\nimport { NativeIntent } from '../types';\n\nexport type ReactComponent = () => React.ReactElement<any, any> | null;\nexport type NativeIntentStub = NativeIntent;\nexport type FileStub =\n | (Record<string, unknown> & {\n default: ReactComponent;\n unstable_settings?: Record<string, any>;\n })\n | ReactComponent;\n\nexport type MemoryContext = Record<string, FileStub | NativeIntentStub> & {\n '+native-intent'?: NativeIntentStub;\n};\n\nexport { requireContext };\n\nconst validExtensions = ['.js', '.jsx', '.ts', '.tsx'];\n\nexport function inMemoryContext(context: MemoryContext) {\n return Object.assign(\n function (id: string) {\n id = id.replace(/^\\.\\//, '').replace(/\\.\\w*$/, '');\n return typeof context[id] === 'function' ? { default: context[id] } : context[id];\n },\n {\n resolve: (key: string) => key,\n id: '0',\n keys: () =>\n Object.keys(context).map((key) => {\n const ext = path.extname(key);\n key = key.replace(/^\\.\\//, '');\n key = key.startsWith('/') ? key : `./${key}`;\n key = validExtensions.includes(ext) ? key : `${key}.js`;\n\n return key;\n }),\n }\n );\n}\n\nexport function requireContextWithOverrides(dir: string, overrides: MemoryContext) {\n const existingContext = requireContext(path.resolve(process.cwd(), dir));\n\n return Object.assign(\n function (id: string) {\n if (id in overrides) {\n const route = overrides[id];\n return typeof route === 'function' ? { default: route } : route;\n } else {\n return existingContext(id);\n }\n },\n {\n keys: () => [...Object.keys(overrides), ...existingContext.keys()],\n resolve: (key: string) => key,\n id: '0',\n }\n );\n}\n"]}
@@ -9,19 +9,20 @@ try {
9
9
  require('react-native-gesture-handler/jestSetup');
10
10
  }
11
11
  catch { }
12
- // include this section and the NativeAnimatedHelper section for mocking react-native-reanimated
13
- jest.mock('react-native-reanimated', () => {
14
- try {
15
- const Reanimated = require('react-native-reanimated/mock');
16
- // The mock for `call` immediately calls the callback which is incorrect
17
- // So we override it with a no-op
18
- Reanimated.default.call = () => { };
19
- return Reanimated;
20
- }
21
- catch {
22
- return {};
23
- }
24
- });
12
+ try {
13
+ require('react-native-reanimated');
14
+ jest.mock('react-native-reanimated', () => {
15
+ try {
16
+ const Reanimated = require('react-native-reanimated/mock');
17
+ Reanimated.default.call = () => { }; // Override `call` with a no-op if needed
18
+ return Reanimated;
19
+ }
20
+ catch {
21
+ return {};
22
+ }
23
+ });
24
+ }
25
+ catch { }
25
26
  jest.mock('expo-linking', () => {
26
27
  const module = {
27
28
  ...jest.requireActual('expo-linking'),
@@ -1 +1 @@
1
- {"version":3,"file":"mocks.js","sourceRoot":"","sources":["../../src/testing-library/mocks.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,IAAI;IACF,OAAO,CAAC,4CAA4C,CAAC,CAAC;CACvD;AAAC,MAAM,GAAE;AAEV,IAAI;IACF,OAAO,CAAC,wCAAwC,CAAC,CAAC;CACnD;AAAC,MAAM,GAAE;AAEV,gGAAgG;AAChG,IAAI,CAAC,IAAI,CAAC,yBAAyB,EAAE,GAAG,EAAE;IACxC,IAAI;QACF,MAAM,UAAU,GAAG,OAAO,CAAC,8BAA8B,CAAC,CAAC;QAE3D,wEAAwE;QACxE,iCAAiC;QACjC,UAAU,CAAC,OAAO,CAAC,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC;QAEnC,OAAO,UAAU,CAAC;KACnB;IAAC,MAAM;QACN,OAAO,EAAE,CAAC;KACX;AACH,CAAC,CAAC,CAAC;AAEH,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,GAAG,EAAE;IAC7B,MAAM,MAAM,GAAkC;QAC5C,GAAG,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC;QACrC,SAAS,CAAC,IAAY;YACpB,OAAO,eAAe,GAAG,IAAI,CAAC;QAChC,CAAC;QACD,aAAa;YACX,OAAO,YAAY,CAAC;QACtB,CAAC;QACD,gBAAgB;YACd,OAAO,EAAE,MAAM,KAAI,CAAC,EAAS,CAAC;QAChC,CAAC;KACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC,CAAC","sourcesContent":["/*\n * Optionally enable @testing-library/jest-native/extend-expect. We use this internally for the `toBeOnTheScreen` matcher()\n */\ntry {\n require('@testing-library/jest-native/extend-expect');\n} catch {}\n\ntry {\n require('react-native-gesture-handler/jestSetup');\n} catch {}\n\n// include this section and the NativeAnimatedHelper section for mocking react-native-reanimated\njest.mock('react-native-reanimated', () => {\n try {\n const Reanimated = require('react-native-reanimated/mock');\n\n // The mock for `call` immediately calls the callback which is incorrect\n // So we override it with a no-op\n Reanimated.default.call = () => {};\n\n return Reanimated;\n } catch {\n return {};\n }\n});\n\njest.mock('expo-linking', () => {\n const module: typeof import('expo-linking') = {\n ...jest.requireActual('expo-linking'),\n createURL(path: string) {\n return 'yourscheme://' + path;\n },\n resolveScheme() {\n return 'yourscheme';\n },\n addEventListener() {\n return { remove() {} } as any;\n },\n };\n\n return module;\n});\n"]}
1
+ {"version":3,"file":"mocks.js","sourceRoot":"","sources":["../../src/testing-library/mocks.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,IAAI;IACF,OAAO,CAAC,4CAA4C,CAAC,CAAC;CACvD;AAAC,MAAM,GAAE;AAEV,IAAI;IACF,OAAO,CAAC,wCAAwC,CAAC,CAAC;CACnD;AAAC,MAAM,GAAE;AAEV,IAAI;IACF,OAAO,CAAC,yBAAyB,CAAC,CAAC;IACnC,IAAI,CAAC,IAAI,CAAC,yBAAyB,EAAE,GAAG,EAAE;QACxC,IAAI;YACF,MAAM,UAAU,GAAG,OAAO,CAAC,8BAA8B,CAAC,CAAC;YAC3D,UAAU,CAAC,OAAO,CAAC,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,yCAAyC;YAC7E,OAAO,UAAU,CAAC;SACnB;QAAC,MAAM;YACN,OAAO,EAAE,CAAC;SACX;IACH,CAAC,CAAC,CAAC;CACJ;AAAC,MAAM,GAAE;AAEV,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,GAAG,EAAE;IAC7B,MAAM,MAAM,GAAkC;QAC5C,GAAG,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC;QACrC,SAAS,CAAC,IAAY;YACpB,OAAO,eAAe,GAAG,IAAI,CAAC;QAChC,CAAC;QACD,aAAa;YACX,OAAO,YAAY,CAAC;QACtB,CAAC;QACD,gBAAgB;YACd,OAAO,EAAE,MAAM,KAAI,CAAC,EAAS,CAAC;QAChC,CAAC;KACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC,CAAC","sourcesContent":["/*\n * Optionally enable @testing-library/jest-native/extend-expect. We use this internally for the `toBeOnTheScreen` matcher()\n */\ntry {\n require('@testing-library/jest-native/extend-expect');\n} catch {}\n\ntry {\n require('react-native-gesture-handler/jestSetup');\n} catch {}\n\ntry {\n require('react-native-reanimated');\n jest.mock('react-native-reanimated', () => {\n try {\n const Reanimated = require('react-native-reanimated/mock');\n Reanimated.default.call = () => {}; // Override `call` with a no-op if needed\n return Reanimated;\n } catch {\n return {};\n }\n });\n} catch {}\n\njest.mock('expo-linking', () => {\n const module: typeof import('expo-linking') = {\n ...jest.requireActual('expo-linking'),\n createURL(path: string) {\n return 'yourscheme://' + path;\n },\n resolveScheme() {\n return 'yourscheme';\n },\n addEventListener() {\n return { remove() {} } as any;\n },\n };\n\n return module;\n});\n"]}
@@ -1,3 +1,7 @@
1
1
  import { RequireContext } from '../types';
2
- export declare function getTypedRoutesDeclarationFile(ctx: RequireContext): string;
2
+ export type GetTypedRoutesDeclarationFileOptions = {
3
+ partialTypedGroups?: boolean;
4
+ testIgnoreComments?: boolean;
5
+ };
6
+ export declare function getTypedRoutesDeclarationFile(ctx: RequireContext, { partialTypedGroups, testIgnoreComments, }?: GetTypedRoutesDeclarationFileOptions): string;
3
7
  //# sourceMappingURL=generate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/typed-routes/generate.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAO1C,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,cAAc,UAoChE"}
1
+ {"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/typed-routes/generate.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAS1C,MAAM,MAAM,oCAAoC,GAAG;IACjD,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,wBAAgB,6BAA6B,CAC3C,GAAG,EAAE,cAAc,EACnB,EACE,kBAA0B,EAC1B,kBAA0B,GAC3B,GAAE,oCAAyC,UA4G7C"}
@@ -7,24 +7,74 @@ const matchers_1 = require("../matchers");
7
7
  const CATCH_ALL = /\[\.\.\..+?\]/g;
8
8
  // /[param1] - Match [param1]
9
9
  const SLUG = /\[.+?\]/g;
10
- function getTypedRoutesDeclarationFile(ctx) {
11
- const staticRoutes = new Set();
12
- const dynamicRoutes = new Set();
13
- const dynamicRouteContextKeys = new Set();
10
+ // /(group)/path/(group2)/route - Match [(group), (group2)]
11
+ const GROUP = /(?:^|\/)\(.*?\)/g;
12
+ function getTypedRoutesDeclarationFile(ctx, { partialTypedGroups = false, testIgnoreComments = false, } = {}) {
14
13
  let routeNode = null;
15
14
  try {
16
15
  routeNode = (0, getRoutes_1.getRoutes)(ctx, {
16
+ ignore: [/_layout\.[tj]sx?$/],
17
17
  platformRoutes: false,
18
+ notFound: false,
18
19
  ignoreEntryPoints: true,
19
20
  ignoreRequireErrors: true,
20
- importMode: 'async',
21
+ importMode: 'async', // Don't load the file
21
22
  });
22
23
  }
23
24
  catch {
24
25
  // Ignore errors from `getRoutes`. This is also called inside the app, which has
25
26
  // a nicer UX for showing error messages
26
27
  }
27
- walkRouteNode(routeNode, '', staticRoutes, dynamicRoutes, dynamicRouteContextKeys);
28
+ const groupedNodes = groupRouteNodes(routeNode);
29
+ const staticRoutesStrings = ['Router.RelativePathString', 'Router.ExternalPathString'];
30
+ const staticRouteInputObjects = [
31
+ '{ pathname: Router.RelativePathString, params?: Router.UnknownInputParams }',
32
+ '{ pathname: Router.ExternalPathString, params?: Router.UnknownInputParams }',
33
+ ];
34
+ const staticRouteOutputObjects = [
35
+ '{ pathname: Router.RelativePathString, params?: Router.UnknownOutputParams }',
36
+ '{ pathname: Router.ExternalPathString, params?: Router.UnknownOutputParams }',
37
+ ];
38
+ for (const type of groupedNodes.static) {
39
+ staticRoutesStrings.push(contextKeyToType(type + "${`?${string}` | `#${string}` | ''}", partialTypedGroups));
40
+ staticRouteInputObjects.push(`{ pathname: ${contextKeyToType(type, partialTypedGroups)}; params?: Router.UnknownInputParams; }`);
41
+ staticRouteOutputObjects.push(`{ pathname: ${contextKeyToType(type, partialTypedGroups)}; params?: Router.UnknownOutputParams; }`);
42
+ }
43
+ const dynamicRouteStrings = [];
44
+ const dynamicRouteInputObjects = [];
45
+ const dynamicRouteOutputObjects = [];
46
+ for (const [dynamicRouteTemplate, paramsNames] of groupedNodes.dynamic) {
47
+ const inputParams = paramsNames
48
+ .map((param) => {
49
+ const key = param.startsWith('...') ? param.slice(3) : param;
50
+ const value = param.startsWith('...') ? '(string | number)[]' : 'string | number';
51
+ return `${key}: ${value};`;
52
+ })
53
+ .join('');
54
+ const outputParams = paramsNames
55
+ .map((param) => {
56
+ const key = param.startsWith('...') ? param.slice(3) : param;
57
+ const value = param.startsWith('...') ? 'string[]' : 'string';
58
+ return `${key}: ${value};`;
59
+ })
60
+ .join('');
61
+ dynamicRouteStrings.push(contextKeyToType(dynamicRouteTemplate
62
+ .replaceAll(CATCH_ALL, '${string}')
63
+ .replaceAll(SLUG, '${Router.SingleRoutePart<T>}'), partialTypedGroups));
64
+ dynamicRouteInputObjects.push(`{ pathname: ${contextKeyToType(dynamicRouteTemplate, partialTypedGroups)}, params: Router.UnknownInputParams & { ${inputParams} } }`);
65
+ dynamicRouteOutputObjects.push(`{ pathname: ${contextKeyToType(dynamicRouteTemplate, partialTypedGroups)}, params: Router.UnknownOutputParams & { ${outputParams} } }`);
66
+ }
67
+ const href = [
68
+ ...staticRoutesStrings,
69
+ ...staticRouteInputObjects,
70
+ ...dynamicRouteStrings,
71
+ ...dynamicRouteInputObjects,
72
+ ].join(' | ');
73
+ const hrefInputParams = [...staticRouteInputObjects, ...dynamicRouteInputObjects].join(' | ');
74
+ const hrefOutputParams = [...staticRouteOutputObjects, ...dynamicRouteOutputObjects].join(' | ');
75
+ const tsExpectError = testIgnoreComments
76
+ ? '// @ts-ignore-error -- During tests we need to ignore the "duplicate" declaration error, as multiple fixture declare types \n '
77
+ : '';
28
78
  return `/* eslint-disable */
29
79
  import * as Router from 'expo-router';
30
80
 
@@ -32,78 +82,93 @@ export * from 'expo-router';
32
82
 
33
83
  declare module 'expo-router' {
34
84
  export namespace ExpoRouter {
35
- export interface __routes<T extends string = string> extends Record<string, unknown> {
36
- StaticRoutes: ${setToUnionType(staticRoutes)};
37
- DynamicRoutes: ${setToUnionType(dynamicRoutes)};
38
- DynamicRouteTemplate: ${setToUnionType(dynamicRouteContextKeys)};
85
+ export interface __routes<T extends string | object = string> {
86
+ ${tsExpectError}hrefInputParams: ${hrefInputParams};
87
+ ${tsExpectError}hrefOutputParams: ${hrefOutputParams};
88
+ ${tsExpectError}href: ${href};
39
89
  }
40
90
  }
41
91
  }
42
92
  `;
43
93
  }
44
94
  exports.getTypedRoutesDeclarationFile = getTypedRoutesDeclarationFile;
45
- /**
46
- * Walks a RouteNode tree and adds the routes to the provided sets
47
- */
48
- function walkRouteNode(routeNode, parentRoutePath, staticRoutes, dynamicRoutes, dynamicRouteContextKeys) {
49
- if (!routeNode)
50
- return;
51
- addRouteNode(routeNode, parentRoutePath, staticRoutes, dynamicRoutes, dynamicRouteContextKeys);
52
- parentRoutePath = `${(0, matchers_1.removeSupportedExtensions)(`${parentRoutePath}/${routeNode.route}`).replace(/\/?index$/, '')}`; // replace /index with /
53
- for (const child of routeNode.children) {
54
- walkRouteNode(child, parentRoutePath, staticRoutes, dynamicRoutes, dynamicRouteContextKeys);
95
+ function groupRouteNodes(routeNode, groupedContextKeys = {
96
+ static: new Set(),
97
+ dynamic: new Map(),
98
+ }) {
99
+ if (!routeNode) {
100
+ return groupedContextKeys;
55
101
  }
56
- }
57
- /**
58
- * Given a RouteNode, adds the route to the correct sets
59
- * Modifies the RouteNode.route to be a typed-route string
60
- */
61
- function addRouteNode(routeNode, parentRoutePath, staticRoutes, dynamicRoutes, dynamicRouteContextKeys) {
62
- if (!routeNode?.route)
63
- return;
64
- if (!(0, matchers_1.isTypedRoute)(routeNode.route))
65
- return;
66
- let routePath = `${parentRoutePath}/${(0, matchers_1.removeSupportedExtensions)(routeNode.route).replace(/\/?index$/, '')}`; // replace /index with /
67
- if (!routePath.startsWith('/')) {
68
- routePath = `/${routePath}`;
102
+ // Skip non-route files
103
+ if (routeNode.type !== 'route') {
104
+ // Except the root layout
105
+ if (routeNode.route === '') {
106
+ for (const child of routeNode.children) {
107
+ groupRouteNodes(child, groupedContextKeys);
108
+ }
109
+ return groupedContextKeys;
110
+ }
111
+ return groupedContextKeys;
112
+ }
113
+ let routeKey;
114
+ if (routeNode.generated) {
115
+ // Some routes like the root _layout, _sitemap, +not-found are generated.
116
+ // We cannot use the contextKey, as their context key does not specify a route
117
+ routeKey = routeNode.route;
118
+ }
119
+ else {
120
+ routeKey = (0, matchers_1.removeSupportedExtensions)(routeNode.contextKey)
121
+ .replace(/\/index$/, '') // Remove any trailing /index
122
+ .replace(/^\./, ''); // Remove any leading .
123
+ }
124
+ routeKey ||= '/'; // A routeKey may be empty for contextKey '' or './index.js'
125
+ if (!routeKey.startsWith('/')) {
126
+ // Not all generated files will have the `/` prefix
127
+ routeKey = `/${routeKey}`;
69
128
  }
70
129
  if (routeNode.dynamic) {
71
- for (const path of generateCombinations(routePath)) {
72
- dynamicRouteContextKeys.add(path);
73
- dynamicRoutes.add(`${path.replaceAll(CATCH_ALL, '${string}').replaceAll(SLUG, '${Router.SingleRoutePart<T>}')}`);
74
- }
130
+ groupedContextKeys.dynamic.set(routeKey, routeKey
131
+ .split('/')
132
+ .filter((segment) => {
133
+ return segment.startsWith('[') && segment.endsWith(']');
134
+ })
135
+ .map((segment) => {
136
+ return segment.slice(1, -1);
137
+ }));
75
138
  }
76
139
  else {
77
- for (const combination of generateCombinations(routePath)) {
78
- staticRoutes.add(combination);
79
- }
140
+ groupedContextKeys.static.add(routeKey);
141
+ }
142
+ for (const child of routeNode.children) {
143
+ groupRouteNodes(child, groupedContextKeys);
80
144
  }
145
+ return groupedContextKeys;
81
146
  }
82
- /**
83
- * Converts a Set to a TypeScript union type
84
- */
85
- const setToUnionType = (set) => {
86
- return set.size > 0
87
- ? [...set]
88
- .sort()
89
- .map((s) => `\`${s}\``)
90
- .join(' | ')
91
- : 'never';
92
- };
93
- function generateCombinations(pathname) {
94
- const groups = pathname.split('/').filter((part) => part.startsWith('(') && part.endsWith(')'));
95
- const combinations = [];
96
- function generate(currentIndex, currentPath) {
97
- if (currentIndex === groups.length) {
98
- combinations.push(currentPath.replace(/\/{2,}/g, '/'));
99
- return;
147
+ function contextKeyToType(contextKey, partialTypedGroups) {
148
+ // If the route has groups, turn them into template strings
149
+ const typeWithGroups = contextKey.replaceAll(GROUP, (match) => {
150
+ const groups = match.slice(2, -1); // Remove the leading ( and the trailing )
151
+ // When `partialRoutes` is enabled, we always change a group to a template
152
+ if (groups.length > 1 || partialTypedGroups) {
153
+ // Ensure each group has the trailing slash
154
+ const groupsAsType = groups.split(',').map((group) => `'/(${group})'`);
155
+ // `partialRoutes` allow you to skip a group
156
+ if (partialTypedGroups) {
157
+ groupsAsType.push("''");
158
+ }
159
+ // Combine together into a union
160
+ return `\${${groupsAsType.join(' | ')}}`;
161
+ }
162
+ else {
163
+ return match;
100
164
  }
101
- const group = groups[currentIndex];
102
- const withoutGroup = currentPath.replace(`/${group}`, '');
103
- generate(currentIndex + 1, withoutGroup);
104
- generate(currentIndex + 1, currentPath);
165
+ });
166
+ const typeWithoutGroups = contextKey.replaceAll(GROUP, '');
167
+ if (typeWithGroups === typeWithoutGroups) {
168
+ return `\`${typeWithGroups}\``;
169
+ }
170
+ else {
171
+ return `\`${typeWithGroups}\` | \`${typeWithoutGroups}\``;
105
172
  }
106
- generate(0, pathname);
107
- return combinations;
108
173
  }
109
174
  //# sourceMappingURL=generate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.js","sourceRoot":"","sources":["../../src/typed-routes/generate.ts"],"names":[],"mappings":";;;AACA,4CAAyC;AACzC,0CAAsE;AAGtE,oCAAoC;AACpC,MAAM,SAAS,GAAG,gBAAgB,CAAC;AACnC,6BAA6B;AAC7B,MAAM,IAAI,GAAG,UAAU,CAAC;AAExB,SAAgB,6BAA6B,CAAC,GAAmB;IAC/D,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IACvC,MAAM,aAAa,GAAG,IAAI,GAAG,EAAU,CAAC;IACxC,MAAM,uBAAuB,GAAG,IAAI,GAAG,EAAU,CAAC;IAElD,IAAI,SAAS,GAAqB,IAAI,CAAC;IAEvC,IAAI;QACF,SAAS,GAAG,IAAA,qBAAS,EAAC,GAAG,EAAE;YACzB,cAAc,EAAE,KAAK;YACrB,iBAAiB,EAAE,IAAI;YACvB,mBAAmB,EAAE,IAAI;YACzB,UAAU,EAAE,OAAO;SACpB,CAAC,CAAC;KACJ;IAAC,MAAM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AAW,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC;YACvD,OAAO;SACR;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;QACnC,MAAM,YAAY,GAAG,WAAW,CAAC,OAAO,CAAC,IAAI,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;QAC1D,QAAQ,CAAC,YAAY,GAAG,CAAC,EAAE,YAAY,CAAC,CAAC;QACzC,QAAQ,CAAC,YAAY,GAAG,CAAC,EAAE,WAAW,CAAC,CAAC;IAC1C,CAAC;IAED,QAAQ,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;IACtB,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import { RouteNode } from '../Route';\nimport { getRoutes } from '../getRoutes';\nimport { isTypedRoute, removeSupportedExtensions } from '../matchers';\nimport { RequireContext } from '../types';\n\n// /[...param1]/ - Match [...param1]\nconst CATCH_ALL = /\\[\\.\\.\\..+?\\]/g;\n// /[param1] - Match [param1]\nconst SLUG = /\\[.+?\\]/g;\n\nexport function getTypedRoutesDeclarationFile(ctx: RequireContext) {\n const staticRoutes = new Set<string>();\n const dynamicRoutes = new Set<string>();\n const dynamicRouteContextKeys = new Set<string>();\n\n let routeNode: RouteNode | null = null;\n\n try {\n routeNode = getRoutes(ctx, {\n platformRoutes: false, // We don't need to generate platform specific routes\n ignoreEntryPoints: true,\n ignoreRequireErrors: true,\n importMode: 'async',\n });\n } catch {\n // Ignore errors from `getRoutes`. This is also called inside the app, which has\n // a nicer UX for showing error messages\n }\n\n walkRouteNode(routeNode, '', staticRoutes, dynamicRoutes, dynamicRouteContextKeys);\n\n return `/* eslint-disable */\nimport * as Router from 'expo-router';\n\nexport * from 'expo-router';\n\ndeclare module 'expo-router' {\n export namespace ExpoRouter {\n export interface __routes<T extends string = string> extends Record<string, unknown> {\n StaticRoutes: ${setToUnionType(staticRoutes)};\n DynamicRoutes: ${setToUnionType(dynamicRoutes)};\n DynamicRouteTemplate: ${setToUnionType(dynamicRouteContextKeys)};\n }\n }\n}\n`;\n}\n\n/**\n * Walks a RouteNode tree and adds the routes to the provided sets\n */\nfunction walkRouteNode(\n routeNode: RouteNode | null,\n parentRoutePath: string,\n staticRoutes: Set<string>,\n dynamicRoutes: Set<string>,\n dynamicRouteContextKeys: Set<string>\n) {\n if (!routeNode) return;\n\n addRouteNode(routeNode, parentRoutePath, staticRoutes, dynamicRoutes, dynamicRouteContextKeys);\n\n parentRoutePath = `${removeSupportedExtensions(`${parentRoutePath}/${routeNode.route}`).replace(/\\/?index$/, '')}`; // replace /index with /\n\n for (const child of routeNode.children) {\n walkRouteNode(child, parentRoutePath, staticRoutes, dynamicRoutes, dynamicRouteContextKeys);\n }\n}\n\n/**\n * Given a RouteNode, adds the route to the correct sets\n * Modifies the RouteNode.route to be a typed-route string\n */\nfunction addRouteNode(\n routeNode: RouteNode | null,\n parentRoutePath: string,\n staticRoutes: Set<string>,\n dynamicRoutes: Set<string>,\n dynamicRouteContextKeys: Set<string>\n) {\n if (!routeNode?.route) return;\n if (!isTypedRoute(routeNode.route)) return;\n\n let routePath = `${parentRoutePath}/${removeSupportedExtensions(routeNode.route).replace(/\\/?index$/, '')}`; // replace /index with /\n\n if (!routePath.startsWith('/')) {\n routePath = `/${routePath}`;\n }\n\n if (routeNode.dynamic) {\n for (const path of generateCombinations(routePath)) {\n dynamicRouteContextKeys.add(path);\n dynamicRoutes.add(\n `${path.replaceAll(CATCH_ALL, '${string}').replaceAll(SLUG, '${Router.SingleRoutePart<T>}')}`\n );\n }\n } else {\n for (const combination of generateCombinations(routePath)) {\n staticRoutes.add(combination);\n }\n }\n}\n\n/**\n * Converts a Set to a TypeScript union type\n */\nconst setToUnionType = <T>(set: Set<T>) => {\n return set.size > 0\n ? [...set]\n .sort()\n .map((s) => `\\`${s}\\``)\n .join(' | ')\n : 'never';\n};\n\nfunction generateCombinations(pathname) {\n const groups = pathname.split('/').filter((part) => part.startsWith('(') && part.endsWith(')'));\n const combinations: string[] = [];\n\n function generate(currentIndex, currentPath) {\n if (currentIndex === groups.length) {\n combinations.push(currentPath.replace(/\\/{2,}/g, '/'));\n return;\n }\n\n const group = groups[currentIndex];\n const withoutGroup = currentPath.replace(`/${group}`, '');\n generate(currentIndex + 1, withoutGroup);\n generate(currentIndex + 1, currentPath);\n }\n\n generate(0, pathname);\n return combinations;\n}\n"]}
1
+ {"version":3,"file":"generate.js","sourceRoot":"","sources":["../../src/typed-routes/generate.ts"],"names":[],"mappings":";;;AACA,4CAAyC;AACzC,0CAAwD;AAGxD,oCAAoC;AACpC,MAAM,SAAS,GAAG,gBAAgB,CAAC;AACnC,6BAA6B;AAC7B,MAAM,IAAI,GAAG,UAAU,CAAC;AACxB,2DAA2D;AAC3D,MAAM,KAAK,GAAG,kBAAkB,CAAC;AAOjC,SAAgB,6BAA6B,CAC3C,GAAmB,EACnB,EACE,kBAAkB,GAAG,KAAK,EAC1B,kBAAkB,GAAG,KAAK,MACc,EAAE;IAE5C,IAAI,SAAS,GAAqB,IAAI,CAAC;IAEvC,IAAI;QACF,SAAS,GAAG,IAAA,qBAAS,EAAC,GAAG,EAAE;YACzB,MAAM,EAAE,CAAC,mBAAmB,CAAC;YAC7B,cAAc,EAAE,KAAK;YACrB,QAAQ,EAAE,KAAK;YACf,iBAAiB,EAAE,IAAI;YACvB,mBAAmB,EAAE,IAAI;YACzB,UAAU,EAAE,OAAO,EAAE,sBAAsB;SAC5C,CAAC,CAAC;KACJ;IAAC,MAAM;QACN,gFAAgF;QAChF,wCAAwC;KACzC;IAED,MAAM,YAAY,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;IAChD,MAAM,mBAAmB,GAAa,CAAC,2BAA2B,EAAE,2BAA2B,CAAC,CAAC;IACjG,MAAM,uBAAuB,GAAa;QACxC,6EAA6E;QAC7E,6EAA6E;KAC9E,CAAC;IACF,MAAM,wBAAwB,GAAa;QACzC,8EAA8E;QAC9E,8EAA8E;KAC/E,CAAC;IAEF,KAAK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AE;QACxC,OAAO,KAAK,cAAc,IAAI,CAAC;KAChC;SAAM;QACL,OAAO,KAAK,cAAc,UAAU,iBAAiB,IAAI,CAAC;KAC3D;AACH,CAAC","sourcesContent":["import { RouteNode } from '../Route';\nimport { getRoutes } from '../getRoutes';\nimport { removeSupportedExtensions } from '../matchers';\nimport { RequireContext } from '../types';\n\n// /[...param1]/ - Match [...param1]\nconst CATCH_ALL = /\\[\\.\\.\\..+?\\]/g;\n// /[param1] - Match [param1]\nconst SLUG = /\\[.+?\\]/g;\n// /(group)/path/(group2)/route - Match [(group), (group2)]\nconst GROUP = /(?:^|\\/)\\(.*?\\)/g;\n\nexport type GetTypedRoutesDeclarationFileOptions = {\n partialTypedGroups?: boolean;\n testIgnoreComments?: boolean;\n};\n\nexport function getTypedRoutesDeclarationFile(\n ctx: RequireContext,\n {\n partialTypedGroups = false,\n testIgnoreComments = false,\n }: GetTypedRoutesDeclarationFileOptions = {}\n) {\n let routeNode: RouteNode | null = null;\n\n try {\n routeNode = getRoutes(ctx, {\n ignore: [/_layout\\.[tj]sx?$/], // Skip layout files\n platformRoutes: false, // We don't need to generate platform specific routes\n notFound: false, // We don't need +not-found routes either\n ignoreEntryPoints: true,\n ignoreRequireErrors: true,\n importMode: 'async', // Don't load the file\n });\n } catch {\n // Ignore errors from `getRoutes`. This is also called inside the app, which has\n // a nicer UX for showing error messages\n }\n\n const groupedNodes = groupRouteNodes(routeNode);\n const staticRoutesStrings: string[] = ['Router.RelativePathString', 'Router.ExternalPathString'];\n const staticRouteInputObjects: string[] = [\n '{ pathname: Router.RelativePathString, params?: Router.UnknownInputParams }',\n '{ pathname: Router.ExternalPathString, params?: Router.UnknownInputParams }',\n ];\n const staticRouteOutputObjects: string[] = [\n '{ pathname: Router.RelativePathString, params?: Router.UnknownOutputParams }',\n '{ pathname: Router.ExternalPathString, params?: Router.UnknownOutputParams }',\n ];\n\n for (const type of groupedNodes.static) {\n staticRoutesStrings.push(\n contextKeyToType(type + \"${`?${string}` | `#${string}` | ''}\", partialTypedGroups)\n );\n staticRouteInputObjects.push(\n `{ pathname: ${contextKeyToType(type, partialTypedGroups)}; params?: Router.UnknownInputParams; }`\n );\n staticRouteOutputObjects.push(\n `{ pathname: ${contextKeyToType(type, partialTypedGroups)}; params?: Router.UnknownOutputParams; }`\n );\n }\n\n const dynamicRouteStrings: string[] = [];\n const dynamicRouteInputObjects: string[] = [];\n const dynamicRouteOutputObjects: string[] = [];\n\n for (const [dynamicRouteTemplate, paramsNames] of groupedNodes.dynamic) {\n const inputParams = paramsNames\n .map((param) => {\n const key = param.startsWith('...') ? param.slice(3) : param;\n const value = param.startsWith('...') ? '(string | number)[]' : 'string | number';\n return `${key}: ${value};`;\n })\n .join('');\n\n const outputParams = paramsNames\n .map((param) => {\n const key = param.startsWith('...') ? param.slice(3) : param;\n const value = param.startsWith('...') ? 'string[]' : 'string';\n return `${key}: ${value};`;\n })\n .join('');\n\n dynamicRouteStrings.push(\n contextKeyToType(\n dynamicRouteTemplate\n .replaceAll(CATCH_ALL, '${string}')\n .replaceAll(SLUG, '${Router.SingleRoutePart<T>}'),\n partialTypedGroups\n )\n );\n\n dynamicRouteInputObjects.push(\n `{ pathname: ${contextKeyToType(dynamicRouteTemplate, partialTypedGroups)}, params: Router.UnknownInputParams & { ${inputParams} } }`\n );\n dynamicRouteOutputObjects.push(\n `{ pathname: ${contextKeyToType(dynamicRouteTemplate, partialTypedGroups)}, params: Router.UnknownOutputParams & { ${outputParams} } }`\n );\n }\n\n const href = [\n ...staticRoutesStrings,\n ...staticRouteInputObjects,\n ...dynamicRouteStrings,\n ...dynamicRouteInputObjects,\n ].join(' | ');\n\n const hrefInputParams = [...staticRouteInputObjects, ...dynamicRouteInputObjects].join(' | ');\n const hrefOutputParams = [...staticRouteOutputObjects, ...dynamicRouteOutputObjects].join(' | ');\n\n const tsExpectError = testIgnoreComments\n ? '// @ts-ignore-error -- During tests we need to ignore the \"duplicate\" declaration error, as multiple fixture declare types \\n '\n : '';\n\n return `/* eslint-disable */\nimport * as Router from 'expo-router';\n\nexport * from 'expo-router';\n\ndeclare module 'expo-router' {\n export namespace ExpoRouter {\n export interface __routes<T extends string | object = string> {\n ${tsExpectError}hrefInputParams: ${hrefInputParams};\n ${tsExpectError}hrefOutputParams: ${hrefOutputParams};\n ${tsExpectError}href: ${href};\n }\n }\n}\n`;\n}\n\nfunction groupRouteNodes(\n routeNode: RouteNode | null,\n groupedContextKeys = {\n static: new Set<string>(),\n dynamic: new Map<string, string[]>(),\n }\n) {\n if (!routeNode) {\n return groupedContextKeys;\n }\n\n // Skip non-route files\n if (routeNode.type !== 'route') {\n // Except the root layout\n if (routeNode.route === '') {\n for (const child of routeNode.children) {\n groupRouteNodes(child, groupedContextKeys);\n }\n return groupedContextKeys;\n }\n\n return groupedContextKeys;\n }\n\n let routeKey: string;\n\n if (routeNode.generated) {\n // Some routes like the root _layout, _sitemap, +not-found are generated.\n // We cannot use the contextKey, as their context key does not specify a route\n routeKey = routeNode.route;\n } else {\n routeKey = removeSupportedExtensions(routeNode.contextKey)\n .replace(/\\/index$/, '') // Remove any trailing /index\n .replace(/^\\./, ''); // Remove any leading .\n }\n\n routeKey ||= '/'; // A routeKey may be empty for contextKey '' or './index.js'\n\n if (!routeKey.startsWith('/')) {\n // Not all generated files will have the `/` prefix\n routeKey = `/${routeKey}`;\n }\n\n if (routeNode.dynamic) {\n groupedContextKeys.dynamic.set(\n routeKey,\n routeKey\n .split('/')\n .filter((segment) => {\n return segment.startsWith('[') && segment.endsWith(']');\n })\n .map((segment) => {\n return segment.slice(1, -1);\n })\n );\n } else {\n groupedContextKeys.static.add(routeKey);\n }\n\n for (const child of routeNode.children) {\n groupRouteNodes(child, groupedContextKeys);\n }\n\n return groupedContextKeys;\n}\n\nfunction contextKeyToType(contextKey: string, partialTypedGroups: boolean) {\n // If the route has groups, turn them into template strings\n const typeWithGroups = contextKey.replaceAll(GROUP, (match) => {\n const groups = match.slice(2, -1); // Remove the leading ( and the trailing )\n // When `partialRoutes` is enabled, we always change a group to a template\n if (groups.length > 1 || partialTypedGroups) {\n // Ensure each group has the trailing slash\n const groupsAsType = groups.split(',').map((group) => `'/(${group})'`);\n // `partialRoutes` allow you to skip a group\n if (partialTypedGroups) {\n groupsAsType.push(\"''\");\n }\n // Combine together into a union\n return `\\${${groupsAsType.join(' | ')}}`;\n } else {\n return match;\n }\n });\n\n const typeWithoutGroups = contextKey.replaceAll(GROUP, '');\n\n if (typeWithGroups === typeWithoutGroups) {\n return `\\`${typeWithGroups}\\``;\n } else {\n return `\\`${typeWithGroups}\\` | \\`${typeWithoutGroups}\\``;\n }\n}\n"]}
@@ -1,5 +1,10 @@
1
1
  import { RequireContextPonyFill } from '../testing-library/require-context-ponyfill';
2
2
  export type { RequireContextPonyFill } from '../testing-library/require-context-ponyfill';
3
+ /**
4
+ * This file is imported via `@expo/cli`. While users should be using the same SDK version of `expo-router` as `@expo/cli`,
5
+ * this export allows us to ensure that the version of the `expo-router` package is compatible with the version of `@expo/cli`.
6
+ */
7
+ export declare const version = 52;
3
8
  /**
4
9
  * Generate a Metro watch handler that regenerates the typed routes declaration file
5
10
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/typed-routes/index.ts"],"names":[],"mappings":"AAMA,OAAuB,EACrB,sBAAsB,EACvB,MAAM,6CAA6C,CAAC;AAIrD,YAAY,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AAE1F;;GAEG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,MAAM,EACjB,EAAE,GAAgB,EAAE,YAAqC,EAAE;;;CAAK;cAID,MAAM;UAAQ,MAAM;oBAkCpF;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,sBAAsB,0BAWlC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/typed-routes/index.ts"],"names":[],"mappings":"AAMA,OAAuB,EACrB,sBAAsB,EACvB,MAAM,6CAA6C,CAAC;AAIrD,YAAY,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AAE1F;;;GAGG;AACH,eAAO,MAAM,OAAO,KAAK,CAAC;AAE1B;;GAEG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,MAAM,EACjB,EAAE,GAAgB,EAAE,YAAqC,EAAE;;;CAAK;cAID,MAAM;UAAQ,MAAM;oBAkCpF;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,sBAAsB,0BAelC,CAAC"}