@expo/cli 0.10.7 → 0.10.8

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 (32) hide show
  1. package/build/bin/cli +2 -2
  2. package/build/src/start/server/metro/inspector-proxy/device.js +21 -2
  3. package/build/src/start/server/metro/inspector-proxy/device.js.map +1 -1
  4. package/build/src/start/server/metro/inspector-proxy/handlers/DebuggerScriptSource.js.map +1 -1
  5. package/build/src/start/server/metro/inspector-proxy/handlers/NetworkResponse.js.map +1 -1
  6. package/build/src/start/server/metro/inspector-proxy/handlers/PageReload.js.map +1 -1
  7. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js +22 -0
  8. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js.map +1 -0
  9. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerScriptParsed.js +55 -0
  10. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerScriptParsed.js.map +1 -0
  11. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerSetBreakpointByUrl.js +17 -0
  12. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerSetBreakpointByUrl.js.map +1 -0
  13. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.js +39 -0
  14. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.js.map +1 -0
  15. package/build/src/start/server/metro/inspector-proxy/handlers/types.js.map +1 -1
  16. package/build/src/start/server/metro/inspector-proxy/proxy.js +14 -6
  17. package/build/src/start/server/metro/inspector-proxy/proxy.js.map +1 -1
  18. package/build/src/start/server/metro/withMetroMultiPlatform.js +2 -1
  19. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  20. package/build/src/start/server/middleware/ClassicManifestMiddleware.js +1 -1
  21. package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js +38 -0
  22. package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -0
  23. package/build/src/start/server/type-generation/__typetests__/generateFixtures.js +38 -0
  24. package/build/src/start/server/type-generation/__typetests__/generateFixtures.js.map +1 -0
  25. package/build/src/start/server/type-generation/__typetests__/route.test.js +165 -0
  26. package/build/src/start/server/type-generation/__typetests__/route.test.js.map +1 -0
  27. package/build/src/start/server/type-generation/routes.js +175 -62
  28. package/build/src/start/server/type-generation/routes.js.map +1 -1
  29. package/build/src/utils/analytics/rudderstackClient.js +2 -2
  30. package/package.json +10 -8
  31. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeCompat.js +0 -63
  32. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeCompat.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\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 */\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { learnMore } from '../../../utils/link';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT, projectRoot: string): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, EXTERNAL_REQUIRE_NATIVE_POLYFILL];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n projectRoot,\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n }: {\n projectRoot: string;\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n }\n) {\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'react-native/Libraries/Image/AssetRegistry'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n\n const isWebEnabled = platforms.includes('web');\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n },\n };\n\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n if (isTsconfigPathsEnabled && !env.CI) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(projectRoot, ['./tsconfig.json', './jsconfig.json']);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n\n return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n let context = {\n ...immutableContext,\n } as Mutable<ResolutionContext> & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n const environment = context.customResolverOptions?.environment;\n const isNode = environment === 'node';\n\n // TODO: We need to prevent the require.context from including API routes as these use externals.\n // Should be fine after async routes lands.\n if (isNode) {\n const moduleId = isNodeExternal(moduleName);\n if (moduleId) {\n moduleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${moduleName}\"`);\n }\n }\n\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n moduleName = aliases[platform][moduleName];\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n context = {\n ...context,\n nodeModulesPaths: [\n ...immutableContext.nodeModulesPaths,\n // add last to ensure node modules are resolved first\n tsconfig.baseUrl,\n ],\n };\n }\n\n let mainFields: string[] = context.mainFields;\n\n if (isNode) {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n mainFields = ['main'];\n } else if (env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {\n mainFields = context.mainFields;\n } else if (platform && platform in preferredMainFields) {\n mainFields = preferredMainFields[platform];\n }\n function doResolve(moduleName: string): Resolution | null {\n return resolve(\n {\n ...context,\n preferNativePlatform: platform !== 'web',\n resolveRequest: undefined,\n\n mainFields,\n\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n // @ts-ignore\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n },\n moduleName,\n platform\n );\n }\n\n function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n }\n\n let result: Resolution | null = null;\n\n if (tsConfigResolve) {\n result = tsConfigResolve(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n optionalResolve\n );\n }\n\n result ??= doResolve(moduleName);\n\n if (result) {\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n }\n return result;\n },\n ]);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n routerDirectory,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static';\n routerDirectory: string;\n }\n) {\n // Auto pick app entry for router.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot, routerDirectory);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (webOutput === 'static') {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // Ensure the cache is invalidated if these values change.\n // @ts-expect-error\n config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // TODO: import mode\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n } else if (!isTsconfigPathsEnabled) {\n // Bail out early for performance enhancements if no special features are enabled.\n return config;\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n Log.warn(\n chalk.yellow`Experimental path aliases feature is enabled. ` +\n learnMore('https://docs.expo.dev/guides/typescript/#path-aliases')\n );\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupNodeExternals(projectRoot);\n\n return withMetroMultiPlatform(projectRoot, {\n config,\n platformBundlers,\n tsconfig,\n isTsconfigPathsEnabled,\n });\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n tsconfig,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n tsconfig: TsConfigPaths | null;\n }\n) {\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n if (expoConfigPlatforms.includes('web')) {\n config = withWebPolyfills(config, projectRoot);\n }\n\n return withExtendedResolver(config, {\n projectRoot,\n tsconfig,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n });\n}\n"],"names":["withExtendedResolver","shouldAliasAssetRegistryForWeb","withMetroMultiPlatformAsync","debug","require","withWebPolyfills","config","projectRoot","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","tsconfig","platforms","isTsconfigPathsEnabled","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","isWebEnabled","includes","importMetroResolverFromProject","extraNodeModules","aliases","web","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","env","CI","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","withMetroResolvers","immutableContext","moduleName","context","environment","customResolverOptions","isNode","moduleId","isNodeExternal","getNodeExternalModuleId","originModulePath","nodeModulesPaths","mainFields","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","doResolve","preferNativePlatform","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","result","filePath","type","endsWith","platformBundlers","webOutput","routerDirectory","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","transformer","_expoRouterRootDirectory","_expoRouterWebRendering","WebSupportProjectPrerequisite","assertAsync","Log","warn","chalk","yellow","learnMore","setupNodeExternals","withMetroMultiPlatform","expoConfigPlatforms","entries","filter","bundler","map","Array","isArray","resolver","Set","concat"],"mappings":"AAMA;;;;QAuEgBA,oBAAoB,GAApBA,oBAAoB;QAsNpBC,8BAA8B,GAA9BA,8BAA8B;QAexBC,2BAA2B,GAA3BA,2BAA2B;AA5S/B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGF,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAElB,IAAA,IAAc,WA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,CAACS,MAAM,CAAC9G,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,CAAC,CAAC;SAAC,CAAC;KAC3F;IAED,yCAAyC;IACzCjB,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,GAAGoF,mBAAmB,CAAC;IAEhD,IAAIA,mBAAmB,CAAC5E,QAAQ,CAAC,KAAK,CAAC,EAAE;QACvCzB,MAAM,GAAGD,gBAAgB,CAACC,MAAM,EAAEC,WAAW,CAAC,CAAC;KAChD;IAED,OAAOP,oBAAoB,CAACM,MAAM,EAAE;QAClCC,WAAW;QACXe,QAAQ;QACRE,sBAAsB;QACtBD,SAAS,EAAEoF,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\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 */\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { learnMore } from '../../../utils/link';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT, projectRoot: string): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, EXTERNAL_REQUIRE_NATIVE_POLYFILL];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n projectRoot,\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n }: {\n projectRoot: string;\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n }\n) {\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'react-native/Libraries/Image/AssetRegistry'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n\n const isWebEnabled = platforms.includes('web');\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n },\n };\n\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n if (isTsconfigPathsEnabled && isInteractive()) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(projectRoot, ['./tsconfig.json', './jsconfig.json']);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n\n return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n let context = {\n ...immutableContext,\n } as Mutable<ResolutionContext> & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n const environment = context.customResolverOptions?.environment;\n const isNode = environment === 'node';\n\n // TODO: We need to prevent the require.context from including API routes as these use externals.\n // Should be fine after async routes lands.\n if (isNode) {\n const moduleId = isNodeExternal(moduleName);\n if (moduleId) {\n moduleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${moduleName}\"`);\n }\n }\n\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n moduleName = aliases[platform][moduleName];\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n context = {\n ...context,\n nodeModulesPaths: [\n ...immutableContext.nodeModulesPaths,\n // add last to ensure node modules are resolved first\n tsconfig.baseUrl,\n ],\n };\n }\n\n let mainFields: string[] = context.mainFields;\n\n if (isNode) {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n mainFields = ['main'];\n } else if (env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {\n mainFields = context.mainFields;\n } else if (platform && platform in preferredMainFields) {\n mainFields = preferredMainFields[platform];\n }\n function doResolve(moduleName: string): Resolution | null {\n return resolve(\n {\n ...context,\n preferNativePlatform: platform !== 'web',\n resolveRequest: undefined,\n\n mainFields,\n\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n // @ts-ignore\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n },\n moduleName,\n platform\n );\n }\n\n function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n }\n\n let result: Resolution | null = null;\n\n if (tsConfigResolve) {\n result = tsConfigResolve(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n optionalResolve\n );\n }\n\n result ??= doResolve(moduleName);\n\n if (result) {\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n }\n return result;\n },\n ]);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n routerDirectory,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static';\n routerDirectory: string;\n }\n) {\n // Auto pick app entry for router.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot, routerDirectory);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (webOutput === 'static') {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // Ensure the cache is invalidated if these values change.\n // @ts-expect-error\n config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // TODO: import mode\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n } else if (!isTsconfigPathsEnabled) {\n // Bail out early for performance enhancements if no special features are enabled.\n return config;\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n Log.warn(\n chalk.yellow`Experimental path aliases feature is enabled. ` +\n learnMore('https://docs.expo.dev/guides/typescript/#path-aliases')\n );\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupNodeExternals(projectRoot);\n\n return withMetroMultiPlatform(projectRoot, {\n config,\n platformBundlers,\n tsconfig,\n isTsconfigPathsEnabled,\n });\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n tsconfig,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n tsconfig: TsConfigPaths | null;\n }\n) {\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n if (expoConfigPlatforms.includes('web')) {\n config = withWebPolyfills(config, projectRoot);\n }\n\n return withExtendedResolver(config, {\n projectRoot,\n tsconfig,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n });\n}\n"],"names":["withExtendedResolver","shouldAliasAssetRegistryForWeb","withMetroMultiPlatformAsync","debug","require","withWebPolyfills","config","projectRoot","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","tsconfig","platforms","isTsconfigPathsEnabled","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","isWebEnabled","includes","importMetroResolverFromProject","extraNodeModules","aliases","web","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","withMetroResolvers","immutableContext","moduleName","context","environment","customResolverOptions","isNode","moduleId","isNodeExternal","getNodeExternalModuleId","originModulePath","nodeModulesPaths","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","doResolve","preferNativePlatform","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","result","filePath","type","endsWith","platformBundlers","webOutput","routerDirectory","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","transformer","_expoRouterRootDirectory","_expoRouterWebRendering","WebSupportProjectPrerequisite","assertAsync","Log","warn","chalk","yellow","learnMore","setupNodeExternals","withMetroMultiPlatform","expoConfigPlatforms","entries","filter","bundler","map","Array","isArray","resolver","Set","concat"],"mappings":"AAMA;;;;QAwEgBA,oBAAoB,GAApBA,oBAAoB;QAsNpBC,8BAA8B,GAA9BA,8BAA8B;QAexBC,2BAA2B,GAA3BA,2BAA2B;AA7S/B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGF,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAElB,IAA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EAAE;QAC5CoF,mBAAmB,GAAG;eAAI,IAAIQ,GAAG,CAACR,mBAAmB,CAACS,MAAM,CAAC9G,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,CAAC,CAAC;SAAC,CAAC;KAC3F;IAED,yCAAyC;IACzCjB,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,GAAGoF,mBAAmB,CAAC;IAEhD,IAAIA,mBAAmB,CAAC5E,QAAQ,CAAC,KAAK,CAAC,EAAE;QACvCzB,MAAM,GAAGD,gBAAgB,CAACC,MAAM,EAAEC,WAAW,CAAC,CAAC;KAChD;IAED,OAAOP,oBAAoB,CAACM,MAAM,EAAE;QAClCC,WAAW;QACXe,QAAQ;QACRE,sBAAsB;QACtBD,SAAS,EAAEoF,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
@@ -138,7 +138,7 @@ async function createHostInfoAsync() {
138
138
  host: await _userSettings.default.getAnonymousIdentifierAsync(),
139
139
  server: "expo",
140
140
  // Defined in the build step
141
- serverVersion: "0.10.7",
141
+ serverVersion: "0.10.8",
142
142
  serverDriver: _manifestMiddleware.DEVELOPER_TOOL,
143
143
  serverOS: _os.default.platform(),
144
144
  serverOSVersion: _os.default.release()
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ var _build = _interopRequireWildcard(require("expo-router/build"));
6
+ Object.keys(_build).forEach(function(key) {
7
+ if (key === "default" || key === "__esModule") return;
8
+ if (key in exports && exports[key] === _build[key]) return;
9
+ Object.defineProperty(exports, key, {
10
+ enumerable: true,
11
+ get: function() {
12
+ return _build[key];
13
+ }
14
+ });
15
+ });
16
+ function _interopRequireWildcard(obj) {
17
+ if (obj && obj.__esModule) {
18
+ return obj;
19
+ } else {
20
+ var newObj = {};
21
+ if (obj != null) {
22
+ for(var key in obj){
23
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
24
+ var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
25
+ if (desc.get || desc.set) {
26
+ Object.defineProperty(newObj, key, desc);
27
+ } else {
28
+ newObj[key] = obj[key];
29
+ }
30
+ }
31
+ }
32
+ }
33
+ newObj.default = obj;
34
+ return newObj;
35
+ }
36
+ }
37
+
38
+ //# sourceMappingURL=basic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../src/start/server/type-generation/__typetests__/fixtures/basic.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\n\nimport type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\nexport * from 'expo-router/build';\n\n// prettier-ignore\ntype StaticRoutes = `/apple` | `/banana`;\n// prettier-ignore\ntype DynamicRoutes<T extends string> = `/colors/${SingleRoutePart<T>}` | `/animals/${CatchAllRoutePart<T>}` | `/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}`;\n// prettier-ignore\ntype DynamicRouteTemplate = `/colors/[color]` | `/animals/[...animal]` | `/mix/[fruit]/[color]/[...animals]`;\n\ntype RelativePathString = `./${string}` | `../${string}` | '..';\ntype AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\ntype ExternalPathString = `http${string}`;\ntype ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\ntype AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n/****************\n * Route Utils *\n ****************/\n\ntype SearchOrHash = `?${string}` | `#${string}`;\n\n/**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\ntype SingleRoutePart<S extends string> = S extends `${string}/${string}`\n ? never\n : S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S;\n\n/**\n * Return only the CatchAll router part. If the string has search parameters or a hash return never\n */\ntype CatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S;\n\n// type OptionalCatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}` ? never : S\n\n/**\n * Return the name of a route parameter\n * '[test]' -> 'test'\n * 'test' -> never\n * '[...test]' -> '...test'\n */\ntype IsParameter<Part> = Part extends `[${infer ParamName}]` ? ParamName : never;\n\n/**\n * Return a union of all parameter names. If there are no names return never\n *\n * /[test] -> 'test'\n * /[abc]/[...def] -> 'abc'|'...def'\n */\ntype ParameterNames<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? IsParameter<PartA> | ParameterNames<PartB>\n : IsParameter<Path>;\n\n/**\n * Returns all segements of a route.\n *\n * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]'\n */\ntype RouteSegments<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? PartA extends '' | '.'\n ? [...RouteSegments<PartB>]\n : [PartA, ...RouteSegments<PartB>]\n : Path extends ''\n ? []\n : [Path];\n\n/**\n * Returns a Record of the routes parameters as strings and CatchAll parameters as string[]\n *\n * /[id]/[...rest] -> { id: string, rest: string[] }\n * /no-params -> {}\n */\ntype RouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? string[] : string;\n};\n\n/**\n * Returns the search parameters for a route\n */\nexport type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate\n ? RouteParams<T>\n : T extends StaticRoutes\n ? never\n : Record<string, string>;\n\n/**\n * Route is mostly used as part of Href to ensure that a valid route is provided\n *\n * Given a dynamic route, this will return never. This is helpful for conditional logic\n *\n * /test -> /test, /test2, etc\n * /test/[abc] -> never\n * /test/resolve -> /test, /test2, etc\n *\n * Note that if we provide a value for [abc] then the route is allowed\n *\n * This is named Route to prevent confusion, as users they will often see it in tooltips\n */\nexport type Route<T> = T extends DynamicRouteTemplate\n ? never\n :\n | StaticRoutes\n | RelativePathString\n | ExternalPathString\n | (T extends DynamicRoutes<infer _> ? T : never);\n\n/*********\n * Href *\n *********/\n\nexport type Href<T extends string> = Route<T> | HrefObject<T>;\n\nexport type HrefObject<T = AllRoutes> = T extends DynamicRouteTemplate\n ? { pathname: T; params: RouteParams<T> }\n : T extends Route<T>\n ? { pathname: Route<T>; params?: never }\n : never;\n\n/***********************\n * Expo Router Exports *\n ***********************/\n\nexport type Router = {\n /** Navigate to the provided href. */\n push: <T extends string>(href: Href<T>) => void;\n /** Navigate to route without appending to the history. */\n replace: <T extends string>(href: Href<T>) => void;\n /** Go back in the history. */\n back: () => void;\n /** Update the current route query params. */\n setParams: <T extends string = ''>(\n params?: T extends '' ? Record<string, string> : RouteParams<T>\n ) => void;\n};\n\n/************\n * <Link /> *\n ************/\nexport interface LinkProps<T extends string> extends OriginalLinkProps {\n href: T extends DynamicRouteTemplate ? HrefObject<T> : Href<T>;\n}\n\nexport interface LinkComponent {\n <T extends string>(props: React.PropsWithChildren<LinkProps<T>>): JSX.Element;\n /** Helper method to resolve an Href object into a string. */\n resolveHref: <T extends string>(href: Href<T>) => string;\n}\n\nexport declare const Link: LinkComponent;\n\n/************\n * Hooks *\n ************/\nexport declare function useRouter(): Router;\nexport declare function useLocalSearchParams<\n T extends DynamicRouteTemplate | StaticRoutes | RelativePathString\n>(): SearchParams<T>;\nexport declare function useSearchParams<\n T extends AllRoutes | SearchParams<DynamicRouteTemplate>\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useGlobalSearchParams<\n T extends AllRoutes | SearchParams<DynamicRouteTemplate>\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useSegments<\n T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString\n>(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T;\n"],"names":[],"mappings":"AAIA;;;;6CACc,mBAAmB;AAAjC,YAAA,MAAkC;;2CAAlC,MAAkC;;;;mBAAlC,MAAkC;;;EAAA"}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports.default = _default;
6
+ var _promises = require("fs/promises");
7
+ var _path = require("path");
8
+ var _routes = require("../routes");
9
+ const fixtures = {
10
+ basic: {
11
+ staticRoutes: [
12
+ "/apple",
13
+ "/banana"
14
+ ],
15
+ dynamicRoutes: [
16
+ "/colors/${SingleRoutePart<T>}",
17
+ "/animals/${CatchAllRoutePart<T>}",
18
+ "/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}",
19
+ ],
20
+ dynamicRouteTemplates: [
21
+ "/colors/[color]",
22
+ "/animals/[...animal]",
23
+ "/mix/[fruit]/[color]/[...animals]",
24
+ ]
25
+ }
26
+ };
27
+ async function _default() {
28
+ await Promise.all(Object.entries(fixtures).map(async ([key, value])=>{
29
+ const template = (0, _routes).getTemplateString(new Set(value.staticRoutes), new Set(value.dynamicRoutes), new Set(value.dynamicRouteTemplates))// The Template produces a global module .d.ts declaration
30
+ // These replacements turn it into a local module
31
+ .replaceAll(/^ /gm, "").replace(/declare module "expo-router" {/, "").replaceAll(/export function/g, "export declare function").replaceAll(/export const/g, "export declare const")// Remove the last `}`
32
+ .slice(0, -2);
33
+ return (0, _promises).writeFile((0, _path).join(__dirname, "./fixtures/", key + ".ts"), template);
34
+ }));
35
+ console.log("done");
36
+ }
37
+
38
+ //# sourceMappingURL=generateFixtures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../src/start/server/type-generation/__typetests__/generateFixtures.ts"],"sourcesContent":["import { writeFile } from 'fs/promises';\nimport { join } from 'path';\n\nimport { getTemplateString } from '../routes';\n\ntype Fixture = {\n staticRoutes: string[];\n dynamicRoutes: string[];\n dynamicRouteTemplates: string[];\n};\n\nconst fixtures: Record<string, Fixture> = {\n basic: {\n staticRoutes: ['/apple', '/banana'],\n dynamicRoutes: [\n '/colors/${SingleRoutePart<T>}',\n '/animals/${CatchAllRoutePart<T>}',\n '/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}',\n ],\n dynamicRouteTemplates: [\n '/colors/[color]',\n '/animals/[...animal]',\n '/mix/[fruit]/[color]/[...animals]',\n ],\n },\n};\n\nexport default async function () {\n await Promise.all(\n Object.entries(fixtures).map(async ([key, value]) => {\n const template = getTemplateString(\n new Set(value.staticRoutes),\n new Set(value.dynamicRoutes),\n new Set(value.dynamicRouteTemplates)\n )\n // The Template produces a global module .d.ts declaration\n // These replacements turn it into a local module\n .replaceAll(/^ /gm, '')\n .replace(/declare module \"expo-router\" {/, '')\n .replaceAll(/export function/g, 'export declare function')\n .replaceAll(/export const/g, 'export declare const')\n // Remove the last `}`\n .slice(0, -2);\n\n return writeFile(join(__dirname, './fixtures/', key + '.ts'), template);\n })\n );\n\n console.log('done');\n}\n"],"names":["fixtures","basic","staticRoutes","dynamicRoutes","dynamicRouteTemplates","Promise","all","Object","entries","map","key","value","template","getTemplateString","Set","replaceAll","replace","slice","writeFile","join","__dirname","console","log"],"mappings":"AAAA;;;;;AAA0B,IAAA,SAAa,WAAb,aAAa,CAAA;AAClB,IAAA,KAAM,WAAN,MAAM,CAAA;AAEO,IAAA,OAAW,WAAX,WAAW,CAAA;AAQ7C,MAAMA,QAAQ,GAA4B;IACxCC,KAAK,EAAE;QACLC,YAAY,EAAE;YAAC,QAAQ;YAAE,SAAS;SAAC;QACnCC,aAAa,EAAE;YACb,+BAA+B;YAC/B,kCAAkC;YAClC,0EAA0E;SAC3E;QACDC,qBAAqB,EAAE;YACrB,iBAAiB;YACjB,sBAAsB;YACtB,mCAAmC;SACpC;KACF;CACF,AAAC;AAEa,0BAAkB;IAC/B,MAAMC,OAAO,CAACC,GAAG,CACfC,MAAM,CAACC,OAAO,CAACR,QAAQ,CAAC,CAACS,GAAG,CAAC,OAAO,CAACC,GAAG,EAAEC,KAAK,CAAC,GAAK;QACnD,MAAMC,QAAQ,GAAGC,CAAAA,GAAAA,OAAiB,AAIjC,CAAA,kBAJiC,CAChC,IAAIC,GAAG,CAACH,KAAK,CAACT,YAAY,CAAC,EAC3B,IAAIY,GAAG,CAACH,KAAK,CAACR,aAAa,CAAC,EAC5B,IAAIW,GAAG,CAACH,KAAK,CAACP,qBAAqB,CAAC,CACrC,AACC,0DAA0D;QAC1D,iDAAiD;SAChDW,UAAU,UAAU,EAAE,CAAC,CACvBC,OAAO,mCAAmC,EAAE,CAAC,CAC7CD,UAAU,qBAAqB,yBAAyB,CAAC,CACzDA,UAAU,kBAAkB,sBAAsB,CAAC,AACpD,sBAAsB;SACrBE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,AAAC;QAEhB,OAAOC,CAAAA,GAAAA,SAAS,AAAuD,CAAA,UAAvD,CAACC,CAAAA,GAAAA,KAAI,AAAuC,CAAA,KAAvC,CAACC,SAAS,EAAE,aAAa,EAAEV,GAAG,GAAG,KAAK,CAAC,EAAEE,QAAQ,CAAC,CAAC;KACzE,CAAC,CACH,CAAC;IAEFS,OAAO,CAACC,GAAG,CAAC,MAAM,CAAC,CAAC;CACrB"}
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var _tsdLite = require("tsd-lite");
3
+ var _basic = require("./fixtures/basic");
4
+ // eslint-disable-next-line react-hooks/rules-of-hooks
5
+ const router = (0, _basic).useRouter();
6
+ describe("router.push()", ()=>{
7
+ // router.push will return void when the type matches, otherwise it should error
8
+ describe("href", ()=>{
9
+ it("will error on non-urls", ()=>{
10
+ (0, _tsdLite).expectError(router.push("should-error"));
11
+ });
12
+ it("can accept an absolute url", ()=>{
13
+ (0, _tsdLite).expectType(router.push("/apple"));
14
+ (0, _tsdLite).expectType(router.push("/banana"));
15
+ });
16
+ it("can accept a ANY relative url", ()=>{
17
+ // We only type-check absolute urls
18
+ (0, _tsdLite).expectType(router.push("./this/work/but/is/not/valid"));
19
+ });
20
+ it("works for dynamic urls", ()=>{
21
+ (0, _tsdLite).expectType(router.push("/colors/blue"));
22
+ });
23
+ it("works for CatchAll routes", ()=>{
24
+ (0, _tsdLite).expectType(router.push("/animals/bear"));
25
+ (0, _tsdLite).expectType(router.push("/animals/bear/cat/dog"));
26
+ (0, _tsdLite).expectType(router.push("/mix/apple/blue/cat/dog"));
27
+ });
28
+ it.skip("works for optional CatchAll routes", ()=>{
29
+ // CatchAll routes are not currently optional
30
+ // expectType<void>(router.push('/animals/'));
31
+ });
32
+ it("will error when providing extra parameters", ()=>{
33
+ (0, _tsdLite).expectError(router.push("/colors/blue/test"));
34
+ });
35
+ it("will error when providing too few parameters", ()=>{
36
+ (0, _tsdLite).expectError(router.push("/mix/apple"));
37
+ (0, _tsdLite).expectError(router.push("/mix/apple/cat"));
38
+ });
39
+ it("can accept any external url", ()=>{
40
+ (0, _tsdLite).expectType(router.push("http://expo.dev"));
41
+ });
42
+ it("throws if using inline search params", ()=>{
43
+ // While this is allowed in Expo Router, the Typed Routes version throws as we cannot type it
44
+ (0, _tsdLite).expectError(router.push("/colors?color=blue"));
45
+ (0, _tsdLite).expectError(router.push("/animals/bear?color=blue"));
46
+ });
47
+ });
48
+ describe("HrefObject", ()=>{
49
+ it("will error on non-urls", ()=>{
50
+ (0, _tsdLite).expectError(router.push({
51
+ pathname: "should-error"
52
+ }));
53
+ });
54
+ it("can accept an absolute url", ()=>{
55
+ (0, _tsdLite).expectType(router.push({
56
+ pathname: "/apple"
57
+ }));
58
+ (0, _tsdLite).expectType(router.push({
59
+ pathname: "/banana"
60
+ }));
61
+ });
62
+ it("can accept a ANY relative url", ()=>{
63
+ // We only type-check absolute urls
64
+ (0, _tsdLite).expectType(router.push({
65
+ pathname: "./this/work/but/is/not/valid"
66
+ }));
67
+ });
68
+ it("works for dynamic urls", ()=>{
69
+ (0, _tsdLite).expectType(router.push({
70
+ pathname: "/colors/[color]",
71
+ params: {
72
+ color: "blue"
73
+ }
74
+ }));
75
+ });
76
+ it("requires a valid pathname", ()=>{
77
+ (0, _tsdLite).expectError(router.push({
78
+ pathname: "/colors/[invalid]",
79
+ params: {
80
+ color: "blue"
81
+ }
82
+ }));
83
+ });
84
+ it("requires a valid param", ()=>{
85
+ (0, _tsdLite).expectError(router.push({
86
+ pathname: "/colors/[color]",
87
+ params: {
88
+ invalid: "blue"
89
+ }
90
+ }));
91
+ });
92
+ it("works for catch all routes", ()=>{
93
+ (0, _tsdLite).expectType(router.push({
94
+ pathname: "/animals/[...animal]",
95
+ params: {
96
+ animal: [
97
+ "cat",
98
+ "dog"
99
+ ]
100
+ }
101
+ }));
102
+ });
103
+ it("requires an array for catch all routes", ()=>{
104
+ (0, _tsdLite).expectError(router.push({
105
+ pathname: "/animals/[...animal]",
106
+ params: {
107
+ animal: "cat"
108
+ }
109
+ }));
110
+ });
111
+ it("works for mixed routes", ()=>{
112
+ (0, _tsdLite).expectType(router.push({
113
+ pathname: "/mix/[fruit]/[color]/[...animals]",
114
+ params: {
115
+ color: "red",
116
+ fruit: "apple",
117
+ animals: [
118
+ "cat",
119
+ "dog"
120
+ ]
121
+ }
122
+ }));
123
+ });
124
+ it("requires all params in mixed routes", ()=>{
125
+ (0, _tsdLite).expectError(router.push({
126
+ pathname: "/mix/[fruit]/[color]/[...animals]",
127
+ params: {
128
+ color: "red",
129
+ animals: [
130
+ "cat",
131
+ "dog"
132
+ ]
133
+ }
134
+ }));
135
+ });
136
+ });
137
+ });
138
+ describe("useSearchParams", ()=>{
139
+ (0, _tsdLite).expectType((0, _basic).useSearchParams());
140
+ (0, _tsdLite).expectType((0, _basic).useSearchParams());
141
+ (0, _tsdLite).expectError((0, _basic).useSearchParams());
142
+ (0, _tsdLite).expectError((0, _basic).useSearchParams());
143
+ });
144
+ describe("useGlobalSearchParams", ()=>{
145
+ (0, _tsdLite).expectType((0, _basic).useGlobalSearchParams());
146
+ (0, _tsdLite).expectType((0, _basic).useGlobalSearchParams());
147
+ (0, _tsdLite).expectError((0, _basic).useGlobalSearchParams());
148
+ (0, _tsdLite).expectError((0, _basic).useGlobalSearchParams());
149
+ });
150
+ describe("useSegments", ()=>{
151
+ it("can accept an absolute url", ()=>{
152
+ (0, _tsdLite).expectType((0, _basic).useSegments());
153
+ });
154
+ it("only accepts valid possible urls", ()=>{
155
+ (0, _tsdLite).expectError((0, _basic).useSegments());
156
+ });
157
+ it("can accept an array of segments", ()=>{
158
+ (0, _tsdLite).expectType((0, _basic).useSegments());
159
+ });
160
+ it("only accepts valid possible segments", ()=>{
161
+ (0, _tsdLite).expectError((0, _basic).useSegments());
162
+ });
163
+ });
164
+
165
+ //# sourceMappingURL=route.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../src/start/server/type-generation/__typetests__/route.test.ts"],"sourcesContent":["import { expectType, expectError } from 'tsd-lite';\n\nimport { useGlobalSearchParams, useSegments, useRouter, useSearchParams } from './fixtures/basic';\n\n// eslint-disable-next-line react-hooks/rules-of-hooks\nconst router = useRouter();\n\ndescribe('router.push()', () => {\n // router.push will return void when the type matches, otherwise it should error\n\n describe('href', () => {\n it('will error on non-urls', () => {\n expectError(router.push('should-error'));\n });\n\n it('can accept an absolute url', () => {\n expectType<void>(router.push('/apple'));\n expectType<void>(router.push('/banana'));\n });\n\n it('can accept a ANY relative url', () => {\n // We only type-check absolute urls\n expectType<void>(router.push('./this/work/but/is/not/valid'));\n });\n\n it('works for dynamic urls', () => {\n expectType<void>(router.push('/colors/blue'));\n });\n\n it('works for CatchAll routes', () => {\n expectType<void>(router.push('/animals/bear'));\n expectType<void>(router.push('/animals/bear/cat/dog'));\n expectType<void>(router.push('/mix/apple/blue/cat/dog'));\n });\n\n it.skip('works for optional CatchAll routes', () => {\n // CatchAll routes are not currently optional\n // expectType<void>(router.push('/animals/'));\n });\n\n it('will error when providing extra parameters', () => {\n expectError(router.push('/colors/blue/test'));\n });\n\n it('will error when providing too few parameters', () => {\n expectError(router.push('/mix/apple'));\n expectError(router.push('/mix/apple/cat'));\n });\n\n it('can accept any external url', () => {\n expectType<void>(router.push('http://expo.dev'));\n });\n\n it('throws if using inline search params', () => {\n // While this is allowed in Expo Router, the Typed Routes version throws as we cannot type it\n expectError(router.push('/colors?color=blue'));\n expectError(router.push('/animals/bear?color=blue'));\n });\n });\n\n describe('HrefObject', () => {\n it('will error on non-urls', () => {\n expectError(router.push({ pathname: 'should-error' }));\n });\n\n it('can accept an absolute url', () => {\n expectType<void>(router.push({ pathname: '/apple' }));\n expectType<void>(router.push({ pathname: '/banana' }));\n });\n\n it('can accept a ANY relative url', () => {\n // We only type-check absolute urls\n expectType<void>(router.push({ pathname: './this/work/but/is/not/valid' }));\n });\n\n it('works for dynamic urls', () => {\n expectType<void>(\n router.push({\n pathname: '/colors/[color]',\n params: { color: 'blue' },\n })\n );\n });\n\n it('requires a valid pathname', () => {\n expectError(\n router.push({\n pathname: '/colors/[invalid]',\n params: { color: 'blue' },\n })\n );\n });\n\n it('requires a valid param', () => {\n expectError(\n router.push({\n pathname: '/colors/[color]',\n params: { invalid: 'blue' },\n })\n );\n });\n\n it('works for catch all routes', () => {\n expectType<void>(\n router.push({\n pathname: '/animals/[...animal]',\n params: { animal: ['cat', 'dog'] },\n })\n );\n });\n\n it('requires an array for catch all routes', () => {\n expectError(\n router.push({\n pathname: '/animals/[...animal]',\n params: { animal: 'cat' },\n })\n );\n });\n\n it('works for mixed routes', () => {\n expectType<void>(\n router.push({\n pathname: '/mix/[fruit]/[color]/[...animals]',\n params: { color: 'red', fruit: 'apple', animals: ['cat', 'dog'] },\n })\n );\n });\n\n it('requires all params in mixed routes', () => {\n expectError(\n router.push({\n pathname: '/mix/[fruit]/[color]/[...animals]',\n params: { color: 'red', animals: ['cat', 'dog'] },\n })\n );\n });\n });\n});\n\ndescribe('useSearchParams', () => {\n expectType<Record<'color', string>>(useSearchParams<'/colors/[color]'>());\n expectType<Record<'color', string>>(useSearchParams<Record<'color', string>>());\n expectError(useSearchParams<'/invalid'>());\n expectError(useSearchParams<Record<'custom', string>>());\n});\n\ndescribe('useGlobalSearchParams', () => {\n expectType<Record<'color', string>>(useGlobalSearchParams<'/colors/[color]'>());\n expectType<Record<'color', string>>(useGlobalSearchParams<Record<'color', string>>());\n expectError(useGlobalSearchParams<'/invalid'>());\n expectError(useGlobalSearchParams<Record<'custom', string>>());\n});\n\ndescribe('useSegments', () => {\n it('can accept an absolute url', () => {\n expectType<['apple']>(useSegments<'/apple'>());\n });\n\n it('only accepts valid possible urls', () => {\n expectError(useSegments<'/invalid'>());\n });\n\n it('can accept an array of segments', () => {\n expectType<['apple']>(useSegments<['apple']>());\n });\n\n it('only accepts valid possible segments', () => {\n expectError(useSegments<['invalid segment']>());\n });\n});\n"],"names":["router","useRouter","describe","it","expectError","push","expectType","skip","pathname","params","color","invalid","animal","fruit","animals","useSearchParams","useGlobalSearchParams","useSegments"],"mappings":"AAAA;AAAwC,IAAA,QAAU,WAAV,UAAU,CAAA;AAE6B,IAAA,MAAkB,WAAlB,kBAAkB,CAAA;AAEjG,sDAAsD;AACtD,MAAMA,MAAM,GAAGC,CAAAA,GAAAA,MAAS,AAAE,CAAA,UAAF,EAAE,AAAC;AAE3BC,QAAQ,CAAC,eAAe,EAAE,IAAM;IAC9B,gFAAgF;IAEhFA,QAAQ,CAAC,MAAM,EAAE,IAAM;QACrBC,EAAE,CAAC,wBAAwB,EAAE,IAAM;YACjCC,CAAAA,GAAAA,QAAW,AAA6B,CAAA,YAA7B,CAACJ,MAAM,CAACK,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC;SAC1C,CAAC,CAAC;QAEHF,EAAE,CAAC,4BAA4B,EAAE,IAAM;YACrCG,CAAAA,GAAAA,QAAU,AAA6B,CAAA,WAA7B,CAAON,MAAM,CAACK,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;YACxCC,CAAAA,GAAAA,QAAU,AAA8B,CAAA,WAA9B,CAAON,MAAM,CAACK,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;SAC1C,CAAC,CAAC;QAEHF,EAAE,CAAC,+BAA+B,EAAE,IAAM;YACxC,mCAAmC;YACnC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