Coder Social home page Coder Social logo

charpeni / react-native-url-polyfill Goto Github PK

View Code? Open in Web Editor NEW
331.0 3.0 18.0 2.95 MB

๐Ÿ”—A lightweight and trustworthy URL polyfill for React Native.

License: MIT License

JavaScript 26.24% Java 36.86% Objective-C 8.17% Ruby 10.08% Starlark 1.25% Shell 0.06% Makefile 1.58% C++ 7.20% Objective-C++ 7.68% TypeScript 0.90%
react-native whatwg-url polyfill url urlsearchparams javascript

react-native-url-polyfill's People

Contributors

charpeni avatar dependabot-preview[bot] avatar dependabot[bot] avatar plbrault avatar raykle avatar staltz avatar thibmaek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-native-url-polyfill's Issues

Document minimum React Native version supported

Thanks for this! ๐Ÿ™‚ The list of bugs in React Native core's polyfill in the README is quite startling, and I've reproduced facebook/react-native#25717, so far.


A file in react-native-url-polyfill, which was added in 1.0.0, the initial release, depends on a file in React Native, which was added in v0.61.0.

On RN v0.59.10, which I'm using, I get this error from Metro:

error: bundling failed: Error: Unable to resolve module `react-native/Libraries/Blob/NativeBlobModule` from `/Users/chrisbobbe/dev/zulip-mobile/node_modules/react-native-url-polyfill/js/URL.js`: Module `react-native/Libraries/Blob/NativeBlobModule` does not exist in the Haste module map

There may be other factors preventing react-native-url-polyfill from working prior to RN v0.61.0, or indeed it might continue to not work until after that (maybe even v0.62?).

It would be nice to have a note, maybe in the install instructions in the README, on what the earliest supported React Native version is, for the latest release of react-native-url-polyfill, and perhaps mention in the notes for each release if that number changes.

Hopefully this data point will help with that. ๐Ÿ™‚

Security: Doesn't encode urls with punycode

Malicious actors could trick victims into click phishing links, because they look exactly like the valid original domain.
E.g. the original apple.com url could be converted using the cyrillic alphabet to ะฐั€ั€lะต.com which looks identical to the original url.
That's why the browser encodes urls with special characters using punycode to xn--l-7sbq6ba.com
You can check it, if you enter this in the browser console:

new URL("https://ะฐั€ั€lะต.com").href

this should result in

'https://xn--l-7sbq6ba.com/'

However this react-native-url-polyfill library doesn't encode urls using punycode which results in a huge security risk for the end user.

Why are new versions not published?

HI,
I've noticed there were a lot of fixes and updates but there was no new version published for quite some time.
Was the package renamed on npm? Or is there a reason it is not published?

Thank you

Support for React Native Web

Currently, this library isn't working well with react-native-web because we depend on polyfillGlobals from React Native:

import {polyfillGlobal} from 'react-native/Libraries/Utilities/PolyfillFunctions';

We could easily bypass this with a Platform.OS check and fallback on applying polyfills directly on globalThis for the web platform. But should we?

What should be the behavior when you use the auto-import or setupURLPolyfill with react-native-web?

  • No op
  • Fallback to globalThis instead of using polyfillGlobals

ES6 import statements breaks Jest with TS

Although ES6 imports work with React Native bundlers, Jest does not support it natively.

Recently I introduced this package to our library. It works perfectly in RN integration test but

  • it breaks our unit test using Jest and:
  • all the consumers that does NOT mock our library.
/home/runner/work/amplify-ui/amplify-ui/node_modules/react-native-url-polyfill/auto.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import {setupURLPolyfill} from './index';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

I have (aws-amplify/amplify-js#11411) to workaround it by vendoring a bundle that transpiles this package to CommonJS module.

According to the Node.js doc on the dual module packages, historically the main is entry point for the CommonJS module and module is the entrypoint for the ES6 modules.

I think this repo should use the CommonJS require, or at least change the main to point to a CommonJS module version of it.

I can contribute a PR if we agree this is the right direction.

URL should normalize host according to spec

The URL implementation used by this library doesn't appear to normalize URL hostnames in the same way as the implementations of Node 18 and WHATWG.

Here's a repro: https://replit.com/@estrattonbailey/URL-normalization

whatwg-url-without-unicode doesn't have Issues enabled or I would have filed there.

The spec says this:

Although host is case-insensitive, producers and normalizers should use lowercase for registered names and hexadecimal addresses for the sake of uniformity, while only using uppercase letters for percent-encodings.

Crash on react-native app using expo

After adding import 'react-native-url-polyfill/auto'; to an expo app, it no longer works on web (see screenshot for error)

Steps to reproduce:

  1. create app using npx create-expo-app@latest -e with-router
  2. Install react-native-url-polyfill/auto
  3. Add import 'react-native-url-polyfill/auto'; to the app
image

Test Suite breaking!

Using import {URL} from 'react-native-url-polyfill'; breaks Jest Test suite with the error TypeError: Cannot read properties of undefined (reading 'Version')

Stack Trace:
 at Object.<anonymous> (node_modules/react-native-url-polyfill/js/ios10Fix.js:2:54)
 at Object.<anonymous> (node_modules/react-native-url-polyfill/index.js:9:1)

Error in import package.json

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/react-native-url-polyfill/index.js b/node_modules/react-native-url-polyfill/index.js
index 675947e..e832063 100644
--- a/node_modules/react-native-url-polyfill/index.js
+++ b/node_modules/react-native-url-polyfill/index.js
@@ -2,13 +2,13 @@ import './js/ios10Fix';
 
 import {polyfillGlobal} from 'react-native/Libraries/Utilities/PolyfillFunctions';
 
-import {name, version} from './package.json';
+import packageJson from './package.json';
 
 export * from './js/URL';
 export * from './js/URLSearchParams';
 
 export function setupURLPolyfill() {
-  global.REACT_NATIVE_URL_POLYFILL = `${name}@${version}`;
+  global.REACT_NATIVE_URL_POLYFILL = `${packageJson.name}@${packageJson.version}`;
 
   polyfillGlobal('URL', () => require('./js/URL').URL);
   polyfillGlobal(

This issue body was partially generated by patch-package.

Incompatability with react-native-gesture-handler v2

Description

If you attempt to install this package in a project using react-native-gesture-handler@^2.0.0 it fails to work.

I created this issue based on my findings here: #369 (comment)

Steps to Reproduce

As I said in the comment above I've started getting this after upgrading a package. However, when I attempted to reproduce it in a brand new RN install, it started showing up once I added this line to my tsconfig.json:

{
  "compilerOptions": {
    ...
    "typeRoots": [ "./types", " ./node_modules/types"]
  },
  ...
}

Example Errors Message

error TS2554: Expected 0 arguments, but got 1.
       const url = new URL("https://github.com");
                                 ~~~
error TS2339: Property 'searchParams' does not exist on type 'URL'.
        url.searchParams.append('height', heightConstraint.toString());
                   ~~~~~~~~~~~~

etc.

Different behavior from browser URL

Hello Nicolas, I'm working with IPFS URLS and I noticed the properties are parsed differently than the URL implementation present on the browsers: https://snack.expo.dev/ar0b1IBPg

Is this a bug? I would like to rely on this library to separate the protocol from the rest of the URL in order to replace it with a gateway, what would you recommend to do?


Properties of ipfs://QmXnnyufdzAWL5CqZ2RnSNgPbvCc1ALT73s6epPrRnZ1Xy with URL and the polyfill

Screen Shot 2021-10-14 at 11 50 12

undefined is not an object

Receiving the following after installing using option 1 (index.js):

[TypeError: undefined is not an object (evaluating 'this.localStorage.getItem')]
 LOG  Error getting session from URL.

Do I have it in the wrong place?

Error: Cannot create URL for blob

Hi!
When I use URl.createObjectUrl at RN for web, raised title error.
Maybe this issue similer by #223.
Are anyone bumped this error?

I know that this library is not supported RN for web.
However, it would be wonderful if this problem could be solved with a little bit trick.

Error using Jest.

We are experiencing errors with polyfills using the Jest tool, is displayed the messages :

type error errorHandler , SyntaxError: Unexpected identifier

at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)
at Object.<anonymous> (node_modules/react-native/jest/setup.js:439:6) 

in the file error-guard.js

Not working on iPhone 5, iOS 10.3.4

Hello,
It took me a while to track down a bug, but it leads to your lib, as it's not working on iPhone 5/iOS 10.3.4

Here is the error output:
Capture dโ€™eฬcran 2020-06-12 aฬ€ 15 33 53

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

After implementing branch.io in my project I've installed this package input my project, to be able to gracefully handle deconstruction of the link. This works like a charm. Thanks

However when I run my tests i get a the following error

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at node_modules/react-native-url-polyfill/index.js:13:69
      at Object.getValue [as URL] (node_modules/react-native/Libraries/Utilities/defineLazyObjectProperty.js:43:16)
          at Array.forEach (<anonymous>)

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at node_modules/react-native-url-polyfill/index.js:16:23
      at Object.getValue [as URLSearchParams] (node_modules/react-native/Libraries/Utilities/defineLazyObjectProperty.js:43:16)
          at Array.forEach (<anonymous>)

In my code i import URL from this lib like this import { URL } from 'react-native-url-polyfill'

Should I write a mock for this? Does such a mock already exist?

A bit info about my system

npx envinfo --preset jest

  System:
    OS: macOS 11.2
    CPU: (8) x64 Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
  Binaries:
    Node: 12.13.0 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 6.12.0 - /usr/local/bin/npm
  npmPackages:
    jest: ^26.6.3 => 26.6.3 

npx react-native info

info Fetching system and libraries information...
System:
    OS: macOS 11.2
    CPU: (8) x64 Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
    Memory: 118.13 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 12.13.0 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 6.12.0 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.10.0 - /Users/______/.rvm/gems/ruby-2.7.2/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
    Android SDK:
      API Levels: 30
      Build Tools: 29.0.2, 30.0.3
      System Images: android-30 | Google APIs Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 4.1 AI-201.8743.12.41.7042882
    Xcode: 12.4/12D4e - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_282 - /usr/bin/javac
    Python: 2.7.16 - /usr/bin/python
  npmPackages:
    @react-native-community/cli: Not Found
    react: 16.13.1 => 16.13.1 
    react-native: 0.63.4 => 0.63.4 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found

Make react-native peerDependency optional

Is your feature request related to a problem? Please describe.

When a project depends on react-native-url-polyfill and uses npm v7, the react-native peerDependency is installed by default. This happens as npm v7 automatically installs peer dependencies.

The npm v7 was made generally available on February 2, 2021, and is shipped with latest versions of Node.js

This is a problem, as some packages which depend on react-native-url-polyfill may support all JavaScript platforms in a single package. Even if the consumers of those packages do not need support for react-native, the react-native dependency will be installed by default in npm v7.

An example is AWS SDK for JavaScript (v3) which supports Node.js, browser and react-native platforms in a single package.

Describe the solution you'd like

Use peerDependenciesMeta configuration to set react-native dependency as optional in package.json as follows:

{
  // ...
  "peerDependencies": {
    "react-native": "*"
  },
  "peerDependenciesMeta": {
    "react-native": {
      "optional": true
    }
  },
  // ...
}

The peerDependenciesMeta is supported in:

Describe alternatives you've considered

Setting react-native-url-polyfill as optional in projects which consume it.
Example in aws-sdk-js-v3 with another polyfill react-native-get-random-values aws/aws-sdk-js-v3#2108

Additional context

Attempted to import "punycode"

I'm running the expo-cli attached to an Android phone and am getting the following error after importing [email protected].

import "react-native-url-polyfill/auto";

The package at "node_modules/whatwg-url-without-unicode/lib/url-state-machine.js" attempted to import the Node standard library module "punycode". It failed because React Native does not include the Node standard library. Read more at https://docs.expo.io/versions/latest/introduction/faq/#can-i-use-nodejs-packages-with-expo
Failed building JavaScript bundle.

Is this a known issue, and what can I do about it?

Incompatible with HermesJS?

Hi! I am using react-native-url-polyfill (with RN 0.61.5). After enabling Hermes I get:

info Copying 81 asset files
info Done copying assets
/mnt/store/MyApp/android/app/build/generated/assets/react/release/index.android.bundle:889:533: error: ')' expected at end of function call

> Task :app:bundleReleaseJsAndAssets FAILED

FAILURE: Build failed with an exception.

* Where:
Script '/mnt/store/MyApp/node_modules/react-native/react.gradle' line: 151

* What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
> Process 'command '../../node_modules/hermes-engine/linux64-bin/hermes'' finished with non-zero exit value 2

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 2m 23s
139 actionable tasks: 139 executed

If I uninstall react-native-url-polyfill I can succesfully build with HermesJS enabled.

Thank you!

Parsing search params

Hi,
First, thanks for putting this out there.

That said, I've got an issue that I think must be me, because it's such an obvious one:

  const myURL = new URL('https://example.org/abc?foo=bar');
  console.log("Search", myURL.search);
  console.log("Params ", myURL.searchParams);

results in the following output:

Search ?foo=bar
Params  {}

Again - that's such an obvious miss, that it must be me, but I can't figure out why!

Doesn't work with Android App Bundle

I really appreciate your work. Today, I published my app as an .aab file to the Play Store. When testing it on real devices, this package caused the app to become stuck at a blank white view that covered the entire screen.

After I removed this package and resubmitted the .aab file, everything worked fine. I also noticed that this package works fine in the .apk file.

react-native version: 0.64.2
react-native-url-polyfill version: 2.0.0
Testing devices: Xiaomi Note 8 Pro, Pixel 5.

HTML entities

Hi!

I have this link as example, with &amp;:
const link = 'https://my.domain/pathname?action=theAction&amp;id=theId&amp;username=theUsername';

When I use const url = new URL(link);, I have the following:
const action = url.searchParams.get('action'); gives me theAction
const id = url.searchParams.get('id'); gives me null
const username = url.searchParams.get('username'); gives me null

If I debug url with console.log({ url }), I have the following:

url: URL
hash: (...)
host: (...)
hostname: (...)
href: (...)
origin: (...)
password: (...)
pathname: (...)
port: (...)
protocol: (...)
search: (...)
searchParams: (...)
username: (...)
Symbol(SameObject caches):
searchParams: URLSearchParams
Symbol(impl): URLSearchParamsImpl
Symbol(wrapper): URLSearchParams {Symbol(impl): URLSearchParamsImpl}
_list: Array(3)
0: (2) ["action", "delegation"]
1: (2) ["amp;id", "abc123"]
2: (2) ["amp;username", "qij2jg1lef5lgndnal9c"]
length: 3
__proto__: Array(0)

In here, the error is quite obvious.

The solution for me now will be to create a helper function which passes the link into decode() first:

import { decode } from 'html-entities';
import { URL } from 'react-native-url-polyfill';

export function parseURL(url: string): URL {
  return new URL(decode(url));
}

But, shouldn't this be done automatically?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.