├── .nvmrc
├── .watchmanconfig
├── .github
├── ISSUE_TEMPLATE
│ ├── config.yml
│ ├── feature_request.yml
│ └── bug_report.yml
├── workflows
│ └── ci.yml
└── actions
│ └── setup
│ └── action.yml
├── .gitattributes
├── tsconfig.build.json
├── assets
└── places-search-demo.gif
├── babel.config.js
├── lefthook.yml
├── .editorconfig
├── .yarnrc.yml
├── src
├── index.ts
├── __tests__
│ └── index.test.tsx
├── services
│ └── googlePlacesApi.ts
└── GooglePlacesTextInput.tsx
├── tsconfig.json
├── LICENSE
├── eslint.config.mjs
├── .gitignore
├── example
├── places-details-proxy.js
└── App.js
├── docs
├── expo-web-details-proxy.md
└── styling-guide.md
├── package.json
├── CONTRIBUTING.md
├── CODE_OF_CONDUCT.md
├── README.md
└── .yarn
└── plugins
└── @yarnpkg
└── plugin-workspace-tools.cjs
/.nvmrc:
--------------------------------------------------------------------------------
1 | v20
2 |
--------------------------------------------------------------------------------
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig",
3 | "exclude": ["example", "lib"]
4 | }
5 |
--------------------------------------------------------------------------------
/assets/places-search-demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amitpdev/react-native-google-places-textinput/HEAD/assets/places-search-demo.gif
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | overrides: [
3 | {
4 | exclude: /\/node_modules\//,
5 | presets: ['module:react-native-builder-bob/babel-preset'],
6 | },
7 | {
8 | include: /\/node_modules\//,
9 | presets: ['module:@react-native/babel-preset'],
10 | },
11 | ],
12 | };
13 |
--------------------------------------------------------------------------------
/lefthook.yml:
--------------------------------------------------------------------------------
1 | pre-commit:
2 | parallel: true
3 | commands:
4 | lint:
5 | glob: "*.{js,ts,jsx,tsx}"
6 | run: npx eslint {staged_files}
7 | types:
8 | glob: "*.{js,ts, jsx, tsx}"
9 | run: npx tsc
10 | commit-msg:
11 | parallel: true
12 | commands:
13 | commitlint:
14 | run: npx commitlint --edit
15 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent
2 | # coding styles between different editors and IDEs
3 | # editorconfig.org
4 |
5 | root = true
6 |
7 | [*]
8 |
9 | indent_style = space
10 | indent_size = 2
11 |
12 | end_of_line = lf
13 | charset = utf-8
14 | trim_trailing_whitespace = true
15 | insert_final_newline = true
16 |
--------------------------------------------------------------------------------
/.yarnrc.yml:
--------------------------------------------------------------------------------
1 | nodeLinker: node-modules
2 | nmHoistingLimits: workspaces
3 |
4 | plugins:
5 | - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
6 | spec: "@yarnpkg/plugin-interactive-tools"
7 | - path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
8 | spec: "@yarnpkg/plugin-workspace-tools"
9 |
10 | yarnPath: .yarn/releases/yarn-3.6.1.cjs
11 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import GooglePlacesTextInput from './GooglePlacesTextInput';
2 |
3 | export default GooglePlacesTextInput;
4 |
5 | // Export types
6 | export type {
7 | Place,
8 | PlacePrediction,
9 | PlaceStructuredFormat,
10 | PlaceDetailsFields,
11 | GooglePlacesTextInputProps,
12 | GooglePlacesTextInputRef,
13 | GooglePlacesTextInputStyles,
14 | GooglePlacesAccessibilityLabels,
15 | SuggestionTextProps,
16 | } from './GooglePlacesTextInput';
17 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "rootDir": ".",
4 | "paths": {
5 | "react-native-google-places-textinput": ["./src/index"]
6 | },
7 | "allowUnreachableCode": false,
8 | "allowUnusedLabels": false,
9 | "esModuleInterop": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "jsx": "react-jsx",
12 | "lib": ["ESNext"],
13 | "module": "ESNext",
14 | "moduleResolution": "bundler",
15 | "noEmit": true,
16 | "noFallthroughCasesInSwitch": true,
17 | "noImplicitReturns": true,
18 | "noImplicitUseStrict": false,
19 | "noStrictGenericChecks": false,
20 | "noUncheckedIndexedAccess": true,
21 | "noUnusedLocals": true,
22 | "noUnusedParameters": true,
23 | "resolveJsonModule": true,
24 | "resolvePackageJsonImports": false,
25 | "skipLibCheck": true,
26 | "strict": true,
27 | "target": "ESNext",
28 | "verbatimModuleSyntax": true
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.yml:
--------------------------------------------------------------------------------
1 | name: 🚀 Feature request
2 | description: Suggest an idea or enhancement for this library.
3 | labels: [enhancement]
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: |
8 | # Feature request
9 |
10 | 👋 Hi!
11 |
12 | **Thank you for suggesting a new feature for this library.**
13 | - type: checkboxes
14 | attributes:
15 | label: Before submitting a feature request
16 | description: Please check these items before proceeding.
17 | options:
18 | - label: I have searched the existing issues to ensure this feature hasn't been requested already.
19 | required: true
20 | - label: I am using the latest version of the library.
21 | required: true
22 | - type: textarea
23 | id: description
24 | attributes:
25 | label: Feature description
26 | description: |
27 | Provide a clear and detailed description of the feature you're proposing.
28 | How would it benefit users of the library?
29 | validations:
30 | required: true
31 |
32 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | branches:
8 | - main
9 | merge_group:
10 | types:
11 | - checks_requested
12 |
13 | jobs:
14 | lint:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Checkout
18 | uses: actions/checkout@v4
19 |
20 | - name: Setup
21 | uses: ./.github/actions/setup
22 |
23 | - name: Lint files
24 | run: yarn lint
25 |
26 | - name: Typecheck files
27 | run: yarn typecheck
28 |
29 | test:
30 | runs-on: ubuntu-latest
31 | steps:
32 | - name: Checkout
33 | uses: actions/checkout@v4
34 |
35 | - name: Setup
36 | uses: ./.github/actions/setup
37 |
38 | - name: Run unit tests
39 | run: yarn test --maxWorkers=2 --coverage
40 |
41 | build-library:
42 | runs-on: ubuntu-latest
43 | steps:
44 | - name: Checkout
45 | uses: actions/checkout@v4
46 |
47 | - name: Setup
48 | uses: ./.github/actions/setup
49 |
50 | - name: Build package
51 | run: yarn prepare
52 |
53 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2025 Amit Palomo
4 | Permission is hereby granted, free of charge, to any person obtaining a copy
5 | of this software and associated documentation files (the "Software"), to deal
6 | in the Software without restriction, including without limitation the rights
7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the Software is
9 | furnished to do so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in all
12 | copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | SOFTWARE.
21 |
--------------------------------------------------------------------------------
/eslint.config.mjs:
--------------------------------------------------------------------------------
1 | import { fixupConfigRules } from '@eslint/compat';
2 | import { FlatCompat } from '@eslint/eslintrc';
3 | import js from '@eslint/js';
4 | import prettier from 'eslint-plugin-prettier';
5 | import { defineConfig } from 'eslint/config';
6 | import path from 'node:path';
7 | import { fileURLToPath } from 'node:url';
8 |
9 | const __filename = fileURLToPath(import.meta.url);
10 | const __dirname = path.dirname(__filename);
11 | const compat = new FlatCompat({
12 | baseDirectory: __dirname,
13 | recommendedConfig: js.configs.recommended,
14 | allConfig: js.configs.all,
15 | });
16 |
17 | export default defineConfig([
18 | {
19 | extends: fixupConfigRules(compat.extends('@react-native', 'prettier')),
20 | plugins: { prettier },
21 | rules: {
22 | 'react/react-in-jsx-scope': 'off',
23 | 'prettier/prettier': [
24 | 'error',
25 | {
26 | quoteProps: 'consistent',
27 | singleQuote: true,
28 | tabWidth: 2,
29 | trailingComma: 'es5',
30 | useTabs: false,
31 | },
32 | ],
33 | },
34 | },
35 | {
36 | ignores: [
37 | 'node_modules/',
38 | 'lib/'
39 | ],
40 | },
41 | ]);
42 |
--------------------------------------------------------------------------------
/.github/actions/setup/action.yml:
--------------------------------------------------------------------------------
1 | name: Setup
2 | description: Setup Node.js and install dependencies
3 |
4 | runs:
5 | using: composite
6 | steps:
7 | - name: Setup Node.js
8 | uses: actions/setup-node@v4
9 | with:
10 | node-version-file: .nvmrc
11 |
12 | - name: Restore dependencies
13 | id: yarn-cache
14 | uses: actions/cache/restore@v4
15 | with:
16 | path: |
17 | **/node_modules
18 | .yarn/install-state.gz
19 | key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}-${{ hashFiles('**/package.json', '!node_modules/**') }}
20 | restore-keys: |
21 | ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
22 | ${{ runner.os }}-yarn-
23 |
24 | - name: Install dependencies
25 | if: steps.yarn-cache.outputs.cache-hit != 'true'
26 | run: yarn install --immutable
27 | shell: bash
28 |
29 | - name: Cache dependencies
30 | if: steps.yarn-cache.outputs.cache-hit != 'true'
31 | uses: actions/cache/save@v4
32 | with:
33 | path: |
34 | **/node_modules
35 | .yarn/install-state.gz
36 | key: ${{ steps.yarn-cache.outputs.cache-primary-key }}
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # Xcode
13 | #
14 | build/
15 | *.pbxuser
16 | !default.pbxuser
17 | *.mode1v3
18 | !default.mode1v3
19 | *.mode2v3
20 | !default.mode2v3
21 | *.perspectivev3
22 | !default.perspectivev3
23 | xcuserdata
24 | *.xccheckout
25 | *.moved-aside
26 | DerivedData
27 | *.hmap
28 | *.ipa
29 | *.xcuserstate
30 | project.xcworkspace
31 | **/.xcode.env.local
32 |
33 | # Android/IJ
34 | #
35 | .classpath
36 | .cxx
37 | .gradle
38 | .idea
39 | .project
40 | .settings
41 | local.properties
42 | android.iml
43 |
44 | # Cocoapods
45 | #
46 | example/ios/Pods
47 |
48 | # Ruby
49 | example/vendor/
50 |
51 | # node.js
52 | #
53 | node_modules/
54 | npm-debug.log
55 | yarn-debug.log
56 | yarn-error.log
57 |
58 | # BUCK
59 | buck-out/
60 | \.buckd/
61 | android/app/libs
62 | android/keystores/debug.keystore
63 |
64 | # Yarn
65 | .yarn/*
66 | !.yarn/patches
67 | !.yarn/plugins
68 | !.yarn/releases
69 | !.yarn/sdks
70 | !.yarn/versions
71 |
72 | # Expo
73 | .expo/
74 |
75 | # Turborepo
76 | .turbo/
77 |
78 | # generated by bob
79 | lib/
80 |
81 | # React Native Codegen
82 | ios/generated
83 | android/generated
84 |
85 | # React Native Nitro Modules
86 | nitrogen/
87 |
88 | # Test coverage
89 | coverage/
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.yml:
--------------------------------------------------------------------------------
1 | name: Bug report
2 | description: Report a reproducible bug or regression in this library.
3 | labels: [bug]
4 | body:
5 | - type: checkboxes
6 | attributes:
7 | label: Before submitting
8 | options:
9 | - label: I tested using the latest version
10 | required: true
11 | - label: I checked for duplicate issues
12 | required: true
13 | - label: I have enabled `enableDebug={true}` prop and included console logs below
14 | required: false
15 |
16 | - type: dropdown
17 | id: platform
18 | attributes:
19 | label: Platform
20 | multiple: true
21 | options:
22 | - iOS
23 | - Android
24 | - Web (Expo)
25 | - Web (RN Web)
26 | validations:
27 | required: true
28 |
29 | - type: textarea
30 | id: versions
31 | attributes:
32 | label: Versions
33 | description: |
34 | Run: `npm ls react-native react react-native-google-places-textinput` and paste the result here
35 | validations:
36 | required: true
37 |
38 | - type: textarea
39 | id: summary
40 | attributes:
41 | label: Bug summary
42 | description: |
43 | Provide a clear and concise description of what the bug is.
44 | If needed, you can also provide other samples: error messages / stack traces, screenshots, gifs, etc.
45 | validations:
46 | required: true
47 |
48 | - type: textarea
49 | id: debug-logs
50 | attributes:
51 | label: Debug logs (with enableDebug={true})
52 | description: Console logs starting with `[GooglePlacesTextInput:...]`
53 | render: text
54 |
55 |
--------------------------------------------------------------------------------
/example/places-details-proxy.js:
--------------------------------------------------------------------------------
1 | // Example of a minimal Express proxy for Google Places Details API (v1) with CORS support
2 |
3 | const express = require('express');
4 | const axios = require('axios');
5 | const app = express();
6 |
7 | // CORS middleware for all routes and preflight
8 | app.use((req, res, next) => {
9 | res.header('Access-Control-Allow-Origin', '*');
10 | res.header('Access-Control-Allow-Methods', 'GET,OPTIONS');
11 | res.header(
12 | 'Access-Control-Allow-Headers',
13 | 'Content-Type,X-Goog-Api-Key,X-Goog-SessionToken,X-Goog-FieldMask'
14 | );
15 | if (req.method === 'OPTIONS') {
16 | return res.sendStatus(200);
17 | }
18 | next();
19 | });
20 |
21 | app.get('/places-details/:placeId', async (req, res) => {
22 | const { placeId } = req.params;
23 | const { languageCode } = req.query;
24 |
25 | // Forward required headers
26 | const headers = {};
27 | if (req.header('X-Goog-Api-Key'))
28 | headers['X-Goog-Api-Key'] = req.header('X-Goog-Api-Key');
29 | if (req.header('X-Goog-SessionToken'))
30 | headers['X-Goog-SessionToken'] = req.header('X-Goog-SessionToken');
31 | if (req.header('X-Goog-FieldMask'))
32 | headers['X-Goog-FieldMask'] = req.header('X-Goog-FieldMask');
33 |
34 | let url = `https://places.googleapis.com/v1/places/${placeId}`;
35 | if (languageCode) {
36 | url += `?languageCode=${encodeURIComponent(languageCode)}`;
37 | }
38 |
39 | try {
40 | const response = await axios.get(url, { headers });
41 | res.json(response.data);
42 | } catch (e) {
43 | res.status(500).json({ error: e.message });
44 | }
45 | });
46 |
47 | const PORT = process.env.PORT || 3001;
48 | app.listen(PORT, () => {
49 | console.log(
50 | `Places Details proxy running on http://localhost:${PORT}/places-details/:placeId`
51 | );
52 | });
53 |
--------------------------------------------------------------------------------
/docs/expo-web-details-proxy.md:
--------------------------------------------------------------------------------
1 | # Using Place Details with Expo Web
2 |
3 | ## The CORS Issue with Google Places Details API
4 |
5 | When using the Google Places Details API in a web browser (including Expo Web), you'll encounter Cross-Origin Resource Sharing (CORS) restrictions. Google's Places API doesn't include the necessary CORS headers to allow direct browser requests, which results in errors like:
6 |
7 | ```
8 | Access to fetch at 'https://places.googleapis.com/v1/places/...' has been blocked by CORS policy:
9 | No 'Access-Control-Allow-Origin' header is present on the requested resource.
10 | ```
11 |
12 | ## Solution: Use a Proxy Server
13 |
14 | To work around this limitation, you need to set up a proxy server that:
15 |
16 | 1. Receives requests from your Expo Web application
17 | 2. Forwards them to the Google Places Details API
18 | 3. Returns the response back to your application
19 |
20 | The proxy server adds the necessary CORS headers to make the browser happy.
21 |
22 | ## Setting Up the Proxy Server
23 |
24 | We've included an example proxy server in the repository. Here's how to set it up:
25 |
26 | ### 1. Install Dependencies
27 |
28 | Navigate to your project directory and install the required packages:
29 |
30 | ```bash
31 | npm install express axios
32 | # or
33 | yarn add express axios
34 | ```
35 |
36 | ### 2. Copy the Proxy Server Code
37 |
38 | Copy the example proxy server code from `example/places-details-proxy.js` to your project. You can place it in your project root or in a server directory.
39 |
40 | ### 3. Run the Proxy Server
41 |
42 | Start the proxy server:
43 |
44 | ```bash
45 | node places-details-proxy.js
46 | ```
47 |
48 | By default, the server will run at `http://localhost:3001`.
49 |
50 | ### 4. Configure Your React Native Component
51 |
52 | Update your GooglePlacesTextInput component to use the proxy:
53 |
54 | ```javascript
55 |
62 | ```
63 |
64 | ## Deploying to Production
65 |
66 | For production use:
67 |
68 | 1. Deploy the proxy server to a hosting service (like Heroku, Vercel, AWS, etc.)
69 | 2. Update your `detailsProxyUrl` to point to your deployed proxy
70 |
71 | ## Security Considerations
72 |
73 | When implementing this in production:
74 |
75 | 1. **Don't expose your Google API key**: Consider validating requests and using your API key on the server side only
76 | 2. **Limit access**: Restrict who can use your proxy with authentication or origin checking
77 | 3. **Monitor usage**: Keep track of API usage to avoid unexpected costs
78 |
79 | By following these steps, you can use Google Places Details API with Expo Web applications effectively.
80 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.tsx:
--------------------------------------------------------------------------------
1 | import { render } from '@testing-library/react-native';
2 | import GooglePlacesTextInput from '../GooglePlacesTextInput';
3 |
4 | // Mock the API functions
5 | jest.mock('../services/googlePlacesApi', () => ({
6 | fetchPlaceDetails: jest.fn(),
7 | fetchPredictions: jest.fn(),
8 | generateUUID: jest.fn(() => 'mock-uuid'),
9 | isRTLText: jest.fn(() => false),
10 | }));
11 |
12 | const defaultProps = {
13 | apiKey: 'test-api-key',
14 | onPlaceSelect: jest.fn(),
15 | };
16 |
17 | describe('GooglePlacesTextInput', () => {
18 | beforeEach(() => {
19 | jest.clearAllMocks();
20 | });
21 |
22 | it('should render without crashing', () => {
23 | const { toJSON } = render();
24 | expect(toJSON()).toBeTruthy();
25 | });
26 |
27 | describe('scroll control props', () => {
28 | it('should render with scrollEnabled=true by default', () => {
29 | const { toJSON } = render();
30 | expect(toJSON()).toBeTruthy();
31 | });
32 |
33 | it('should render with scrollEnabled=false', () => {
34 | const { toJSON } = render(
35 |
36 | );
37 | expect(toJSON()).toBeTruthy();
38 | });
39 |
40 | it('should render with nestedScrollEnabled=true by default', () => {
41 | const { toJSON } = render();
42 | expect(toJSON()).toBeTruthy();
43 | });
44 |
45 | it('should render with nestedScrollEnabled=false', () => {
46 | const { toJSON } = render(
47 |
48 | );
49 | expect(toJSON()).toBeTruthy();
50 | });
51 |
52 | it('should render with both scroll props disabled', () => {
53 | const { toJSON } = render(
54 |
59 | );
60 | expect(toJSON()).toBeTruthy();
61 | });
62 | });
63 |
64 | describe('prop validation', () => {
65 | it('should accept scrollEnabled as boolean', () => {
66 | // These should not throw TypeScript or runtime errors
67 | expect(() => {
68 | render(
69 |
70 | );
71 | }).not.toThrow();
72 |
73 | expect(() => {
74 | render(
75 |
76 | );
77 | }).not.toThrow();
78 | });
79 |
80 | it('should accept nestedScrollEnabled as boolean', () => {
81 | // These should not throw TypeScript or runtime errors
82 | expect(() => {
83 | render(
84 |
85 | );
86 | }).not.toThrow();
87 |
88 | expect(() => {
89 | render(
90 |
94 | );
95 | }).not.toThrow();
96 | });
97 |
98 | it('should accept both scroll control props together', () => {
99 | expect(() => {
100 | render(
101 |
106 | );
107 | }).not.toThrow();
108 | });
109 | });
110 | });
111 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-google-places-textinput",
3 | "version": "0.9.1",
4 | "description": "A customizable React Native TextInput component for Google Places Autocomplete using the Places API (New)",
5 | "main": "./lib/module/index.js",
6 | "types": "./lib/typescript/src/index.d.ts",
7 | "exports": {
8 | ".": {
9 | "source": "./src/index.tsx",
10 | "types": "./lib/typescript/src/index.d.ts",
11 | "default": "./lib/module/index.js"
12 | },
13 | "./package.json": "./package.json"
14 | },
15 | "files": [
16 | "src",
17 | "lib",
18 | "android",
19 | "ios",
20 | "cpp",
21 | "*.podspec",
22 | "react-native.config.js",
23 | "!ios/build",
24 | "!android/build",
25 | "!android/gradle",
26 | "!android/gradlew",
27 | "!android/gradlew.bat",
28 | "!android/local.properties",
29 | "!**/__tests__",
30 | "!**/__fixtures__",
31 | "!**/__mocks__",
32 | "!**/.*"
33 | ],
34 | "scripts": {
35 | "example": "yarn workspace react-native-google-places-textinput-example",
36 | "test": "jest",
37 | "typecheck": "tsc",
38 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
39 | "clean": "del-cli lib",
40 | "prepare": "bob build",
41 | "release": "release-it --only-version"
42 | },
43 | "keywords": [
44 | "address",
45 | "android",
46 | "autocomplete",
47 | "geolocation",
48 | "google-places",
49 | "ios",
50 | "places-autocomplete",
51 | "places",
52 | "react-native",
53 | "textinput",
54 | "expo"
55 | ],
56 | "repository": {
57 | "type": "git",
58 | "url": "git+https://github.com/amitpdev/react-native-google-places-textinput.git"
59 | },
60 | "author": "Amit Palomo (https://github.com/amitpdev)",
61 | "license": "MIT",
62 | "bugs": {
63 | "url": "https://github.com/amitpdev/react-native-google-places-textinput/issues"
64 | },
65 | "homepage": "https://github.com/amitpdev/react-native-google-places-textinput#readme",
66 | "publishConfig": {
67 | "registry": "https://registry.npmjs.org/"
68 | },
69 | "devDependencies": {
70 | "@commitlint/config-conventional": "^19.6.0",
71 | "@eslint/compat": "^1.2.7",
72 | "@eslint/eslintrc": "^3.3.0",
73 | "@eslint/js": "^9.22.0",
74 | "@evilmartians/lefthook": "^1.5.0",
75 | "@react-native/babel-preset": "0.78.2",
76 | "@react-native/eslint-config": "^0.78.0",
77 | "@release-it/conventional-changelog": "^9.0.2",
78 | "@testing-library/react-native": "^13.2.0",
79 | "@types/jest": "^29.5.5",
80 | "@types/react": "^19.0.12",
81 | "commitlint": "^19.6.1",
82 | "del-cli": "^5.1.0",
83 | "eslint": "^9.22.0",
84 | "eslint-config-prettier": "^10.1.1",
85 | "eslint-plugin-prettier": "^5.2.3",
86 | "jest": "^29.7.0",
87 | "prettier": "^3.0.3",
88 | "react": "19.0.0",
89 | "react-native": "0.79.3",
90 | "react-native-builder-bob": "^0.40.11",
91 | "react-test-renderer": "19.0.0",
92 | "release-it": "^17.10.0",
93 | "typescript": "^5.8.3"
94 | },
95 | "peerDependencies": {
96 | "react": "*",
97 | "react-native": "*"
98 | },
99 | "workspaces": [
100 | "example"
101 | ],
102 | "packageManager": "yarn@3.6.1",
103 | "jest": {
104 | "preset": "react-native",
105 | "modulePathIgnorePatterns": [
106 | "/example/node_modules",
107 | "/lib/"
108 | ]
109 | },
110 | "commitlint": {
111 | "extends": [
112 | "@commitlint/config-conventional"
113 | ]
114 | },
115 | "release-it": {
116 | "git": {
117 | "commitMessage": "chore: release ${version}",
118 | "tagName": "v${version}"
119 | },
120 | "npm": {
121 | "publish": true
122 | },
123 | "github": {
124 | "release": true
125 | },
126 | "plugins": {
127 | "@release-it/conventional-changelog": {
128 | "preset": {
129 | "name": "angular"
130 | }
131 | }
132 | }
133 | },
134 | "prettier": {
135 | "quoteProps": "consistent",
136 | "singleQuote": true,
137 | "tabWidth": 2,
138 | "trailingComma": "es5",
139 | "useTabs": false
140 | },
141 | "react-native-builder-bob": {
142 | "source": "src",
143 | "output": "lib",
144 | "targets": [
145 | [
146 | "module",
147 | {
148 | "esm": true
149 | }
150 | ],
151 | [
152 | "typescript",
153 | {
154 | "project": "tsconfig.build.json"
155 | }
156 | ]
157 | ]
158 | },
159 | "create-react-native-library": {
160 | "languages": "js",
161 | "type": "library",
162 | "version": "0.50.3"
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are always welcome, no matter how large or small!
4 |
5 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. Before contributing, please read the [code of conduct](./CODE_OF_CONDUCT.md).
6 |
7 | ## Development workflow
8 |
9 | This project is a monorepo managed using [Yarn workspaces](https://yarnpkg.com/features/workspaces). It contains the following packages:
10 |
11 | - The library package in the root directory.
12 | - An example app in the `example/` directory.
13 |
14 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
15 |
16 | ```sh
17 | yarn
18 | ```
19 |
20 | > Since the project relies on Yarn workspaces, you cannot use [`npm`](https://github.com/npm/cli) for development.
21 |
22 | The [example app](/example/) demonstrates usage of the library. You need to run it to test any changes you make.
23 |
24 | It is configured to use the local version of the library, so any changes you make to the library's source code will be reflected in the example app. Changes to the library's JavaScript code will be reflected in the example app without a rebuild, but native code changes will require a rebuild of the example app.
25 |
26 | You can use various commands from the root directory to work with the project.
27 |
28 | To start the packager:
29 |
30 | ```sh
31 | yarn example start
32 | ```
33 |
34 | To run the example app on Android:
35 |
36 | ```sh
37 | yarn example android
38 | ```
39 |
40 | To run the example app on iOS:
41 |
42 | ```sh
43 | yarn example ios
44 | ```
45 |
46 | To run the example app on Web:
47 |
48 | ```sh
49 | yarn example web
50 | ```
51 |
52 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
53 |
54 | ```sh
55 | yarn typecheck
56 | yarn lint
57 | ```
58 |
59 | To fix formatting errors, run the following:
60 |
61 | ```sh
62 | yarn lint --fix
63 | ```
64 |
65 | Remember to add tests for your change if possible. Run the unit tests by:
66 |
67 | ```sh
68 | yarn test
69 | ```
70 |
71 | ### Commit message convention
72 |
73 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
74 |
75 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
76 | - `feat`: new features, e.g. add new method to the module.
77 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
78 | - `docs`: changes into documentation, e.g. add usage example for the module..
79 | - `test`: adding or updating tests, e.g. add integration tests using detox.
80 | - `chore`: tooling changes, e.g. change CI config.
81 |
82 | Our pre-commit hooks verify that your commit message matches this format when committing.
83 |
84 | ### Linting and tests
85 |
86 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
87 |
88 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
89 |
90 | Our pre-commit hooks verify that the linter and tests pass when committing.
91 |
92 | ### Publishing to npm
93 |
94 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
95 |
96 | To publish new versions, run the following:
97 |
98 | ```sh
99 | yarn release
100 | ```
101 |
102 | ### Scripts
103 |
104 | The `package.json` file contains various scripts for common tasks:
105 |
106 | - `yarn`: setup project by installing dependencies.
107 | - `yarn typecheck`: type-check files with TypeScript.
108 | - `yarn lint`: lint files with ESLint.
109 | - `yarn test`: run unit tests with Jest.
110 | - `yarn example start`: start the Metro server for the example app.
111 | - `yarn example android`: run the example app on Android.
112 | - `yarn example ios`: run the example app on iOS.
113 |
114 | ### Sending a pull request
115 |
116 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
117 |
118 | When you're sending a pull request:
119 |
120 | - Prefer small pull requests focused on one change.
121 | - Verify that linters and tests are passing.
122 | - Review the documentation to make sure it looks good.
123 | - Follow the pull request template when opening a pull request.
124 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
125 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 | # Contributor Covenant Code of Conduct
3 |
4 | ## Our Pledge
5 |
6 | We as members, contributors, and leaders pledge to make participation in our
7 | community a harassment-free experience for everyone, regardless of age, body
8 | size, visible or invisible disability, ethnicity, sex characteristics, gender
9 | identity and expression, level of experience, education, socio-economic status,
10 | nationality, personal appearance, race, caste, color, religion, or sexual
11 | identity and orientation.
12 |
13 | We pledge to act and interact in ways that contribute to an open, welcoming,
14 | diverse, inclusive, and healthy community.
15 |
16 | ## Our Standards
17 |
18 | Examples of behavior that contributes to a positive environment for our
19 | community include:
20 |
21 | * Demonstrating empathy and kindness toward other people
22 | * Being respectful of differing opinions, viewpoints, and experiences
23 | * Giving and gracefully accepting constructive feedback
24 | * Accepting responsibility and apologizing to those affected by our mistakes,
25 | and learning from the experience
26 | * Focusing on what is best not just for us as individuals, but for the overall
27 | community
28 |
29 | Examples of unacceptable behavior include:
30 |
31 | * The use of sexualized language or imagery, and sexual attention or advances of
32 | any kind
33 | * Trolling, insulting or derogatory comments, and personal or political attacks
34 | * Public or private harassment
35 | * Publishing others' private information, such as a physical or email address,
36 | without their explicit permission
37 | * Other conduct which could reasonably be considered inappropriate in a
38 | professional setting
39 |
40 | ## Enforcement Responsibilities
41 |
42 | Community leaders are responsible for clarifying and enforcing our standards of
43 | acceptable behavior and will take appropriate and fair corrective action in
44 | response to any behavior that they deem inappropriate, threatening, offensive,
45 | or harmful.
46 |
47 | Community leaders have the right and responsibility to remove, edit, or reject
48 | comments, commits, code, wiki edits, issues, and other contributions that are
49 | not aligned to this Code of Conduct, and will communicate reasons for moderation
50 | decisions when appropriate.
51 |
52 | ## Scope
53 |
54 | This Code of Conduct applies within all community spaces, and also applies when
55 | an individual is officially representing the community in public spaces.
56 | Examples of representing our community include using an official e-mail address,
57 | posting via an official social media account, or acting as an appointed
58 | representative at an online or offline event.
59 |
60 | ## Enforcement
61 |
62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
63 | reported to the community leaders responsible for enforcement at
64 | [INSERT CONTACT METHOD].
65 | All complaints will be reviewed and investigated promptly and fairly.
66 |
67 | All community leaders are obligated to respect the privacy and security of the
68 | reporter of any incident.
69 |
70 | ## Enforcement Guidelines
71 |
72 | Community leaders will follow these Community Impact Guidelines in determining
73 | the consequences for any action they deem in violation of this Code of Conduct:
74 |
75 | ### 1. Correction
76 |
77 | **Community Impact**: Use of inappropriate language or other behavior deemed
78 | unprofessional or unwelcome in the community.
79 |
80 | **Consequence**: A private, written warning from community leaders, providing
81 | clarity around the nature of the violation and an explanation of why the
82 | behavior was inappropriate. A public apology may be requested.
83 |
84 | ### 2. Warning
85 |
86 | **Community Impact**: A violation through a single incident or series of
87 | actions.
88 |
89 | **Consequence**: A warning with consequences for continued behavior. No
90 | interaction with the people involved, including unsolicited interaction with
91 | those enforcing the Code of Conduct, for a specified period of time. This
92 | includes avoiding interactions in community spaces as well as external channels
93 | like social media. Violating these terms may lead to a temporary or permanent
94 | ban.
95 |
96 | ### 3. Temporary Ban
97 |
98 | **Community Impact**: A serious violation of community standards, including
99 | sustained inappropriate behavior.
100 |
101 | **Consequence**: A temporary ban from any sort of interaction or public
102 | communication with the community for a specified period of time. No public or
103 | private interaction with the people involved, including unsolicited interaction
104 | with those enforcing the Code of Conduct, is allowed during this period.
105 | Violating these terms may lead to a permanent ban.
106 |
107 | ### 4. Permanent Ban
108 |
109 | **Community Impact**: Demonstrating a pattern of violation of community
110 | standards, including sustained inappropriate behavior, harassment of an
111 | individual, or aggression toward or disparagement of classes of individuals.
112 |
113 | **Consequence**: A permanent ban from any sort of public interaction within the
114 | community.
115 |
116 | ## Attribution
117 |
118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119 | version 2.1, available at
120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121 |
122 | Community Impact Guidelines were inspired by
123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124 |
125 | For answers to common questions about this code of conduct, see the FAQ at
126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127 | [https://www.contributor-covenant.org/translations][translations].
128 |
129 | [homepage]: https://www.contributor-covenant.org
130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131 | [Mozilla CoC]: https://github.com/mozilla/diversity
132 | [FAQ]: https://www.contributor-covenant.org/faq
133 | [translations]: https://www.contributor-covenant.org/translations
134 |
--------------------------------------------------------------------------------
/src/services/googlePlacesApi.ts:
--------------------------------------------------------------------------------
1 | const DEFAULT_GOOGLE_API_URL =
2 | 'https://places.googleapis.com/v1/places:autocomplete';
3 | const DEFAULT_PLACE_DETAILS_URL = 'https://places.googleapis.com/v1/places/';
4 |
5 | interface FetchPredictionsParams {
6 | text: string;
7 | apiKey?: string;
8 | proxyUrl?: string;
9 | proxyHeaders?: Record | null;
10 | sessionToken?: string | null;
11 | languageCode?: string;
12 | includedRegionCodes?: string[];
13 | locationBias?: Record;
14 | locationRestriction?: Record;
15 | types?: string[];
16 | biasPrefixText?: (text: string) => string;
17 | }
18 |
19 | interface FetchPlaceDetailsParams {
20 | placeId: string;
21 | apiKey?: string;
22 | detailsProxyUrl?: string | null;
23 | detailsProxyHeaders?: Record | null;
24 | sessionToken?: string | null;
25 | languageCode?: string;
26 | detailsFields?: string[];
27 | }
28 |
29 | interface PredictionResult {
30 | error: Error | null;
31 | predictions: any[];
32 | }
33 |
34 | interface PlaceDetailsResult {
35 | error: Error | null;
36 | details: any;
37 | }
38 |
39 | /**
40 | * Fetches place predictions from Google Places API
41 | */
42 | export const fetchPredictions = async ({
43 | text,
44 | apiKey,
45 | proxyUrl,
46 | proxyHeaders,
47 | sessionToken,
48 | languageCode,
49 | includedRegionCodes,
50 | locationBias,
51 | locationRestriction,
52 | types = [],
53 | biasPrefixText,
54 | }: FetchPredictionsParams): Promise => {
55 | if (!text) {
56 | return { error: null, predictions: [] };
57 | }
58 |
59 | const processedText = biasPrefixText ? biasPrefixText(text) : text;
60 |
61 | try {
62 | const API_URL = proxyUrl || DEFAULT_GOOGLE_API_URL;
63 | const headers: Record = {
64 | 'Content-Type': 'application/json',
65 | };
66 |
67 | if (proxyUrl && proxyHeaders) {
68 | Object.entries(proxyHeaders).forEach(([key, value]) => {
69 | headers[key] = value;
70 | });
71 | }
72 |
73 | if (apiKey) {
74 | headers['X-Goog-Api-Key'] = apiKey;
75 | }
76 |
77 | const body = {
78 | input: processedText,
79 | languageCode,
80 | ...(sessionToken && { sessionToken }),
81 | ...(includedRegionCodes &&
82 | includedRegionCodes.length > 0 && { includedRegionCodes }),
83 | ...(locationBias && { locationBias }),
84 | ...(locationRestriction && { locationRestriction }),
85 | ...(types.length > 0 && { includedPrimaryTypes: types }),
86 | };
87 |
88 | const response = await fetch(API_URL, {
89 | method: 'POST',
90 | headers,
91 | body: JSON.stringify(body),
92 | });
93 |
94 | const data = await response.json();
95 |
96 | if (data.error) {
97 | throw new Error(data.error.message || 'Error fetching predictions');
98 | }
99 |
100 | return { error: null, predictions: data.suggestions || [] };
101 | } catch (error) {
102 | console.error('Error fetching predictions:', error);
103 | return { error: error as Error, predictions: [] };
104 | }
105 | };
106 |
107 | /**
108 | * Fetches place details from Google Places API
109 | */
110 | export const fetchPlaceDetails = async ({
111 | placeId,
112 | apiKey,
113 | detailsProxyUrl,
114 | detailsProxyHeaders,
115 | sessionToken,
116 | languageCode,
117 | detailsFields = [],
118 | }: FetchPlaceDetailsParams): Promise => {
119 | if (!placeId) {
120 | return { error: null, details: null };
121 | }
122 |
123 | try {
124 | const API_URL = detailsProxyUrl
125 | ? `${detailsProxyUrl}/${placeId}`
126 | : `${DEFAULT_PLACE_DETAILS_URL}${placeId}`;
127 |
128 | const headers: Record = {
129 | 'Content-Type': 'application/json',
130 | };
131 |
132 | if (detailsProxyUrl && detailsProxyHeaders) {
133 | Object.entries(detailsProxyHeaders).forEach(([key, value]) => {
134 | headers[key] = value;
135 | });
136 | }
137 |
138 | if (apiKey) {
139 | headers['X-Goog-Api-Key'] = apiKey;
140 | }
141 |
142 | // Add the required field mask header
143 | const fieldsToRequest =
144 | detailsFields.length > 0
145 | ? detailsFields
146 | : ['displayName', 'formattedAddress', 'location', 'id'];
147 |
148 | headers['X-Goog-FieldMask'] = fieldsToRequest.join(',');
149 |
150 | // For the Places API v1, the session token is sent as a header
151 | if (sessionToken) {
152 | headers['X-Goog-SessionToken'] = sessionToken;
153 | }
154 |
155 | // Build query parameters - only include language
156 | const params = new URLSearchParams();
157 | if (languageCode) {
158 | params.append('languageCode', languageCode);
159 | }
160 |
161 | // Append query parameters if needed
162 | const url = `${API_URL}${params.toString() ? '?' + params.toString() : ''}`;
163 |
164 | const response = await fetch(url, {
165 | method: 'GET',
166 | headers,
167 | });
168 |
169 | const data = await response.json();
170 |
171 | if (data.error) {
172 | throw new Error(data.error.message || 'Error fetching place details');
173 | }
174 |
175 | return { error: null, details: data };
176 | } catch (error) {
177 | console.error('Error fetching place details:', error);
178 | return { error: error as Error, details: null };
179 | }
180 | };
181 |
182 | /**
183 | * Helper function to generate UUID v4
184 | */
185 | export const generateUUID = (): string => {
186 | return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
187 | /* eslint-disable no-bitwise */
188 | const r = (Math.random() * 16) | 0;
189 | const v = c === 'x' ? r : (r & 0x3) | 0x8;
190 | /* eslint-enable no-bitwise */
191 | return v.toString(16);
192 | });
193 | };
194 |
195 | /**
196 | * RTL detection logic
197 | */
198 | export const isRTLText = (text: string): boolean => {
199 | if (!text) return false;
200 | const rtlRegex =
201 | /[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\u0870-\u089F\uFB50-\uFDFF\uFE70-\uFEFF]/;
202 | return rtlRegex.test(text);
203 | };
204 |
--------------------------------------------------------------------------------
/example/App.js:
--------------------------------------------------------------------------------
1 | import { SafeAreaView, StyleSheet, View, Text, ScrollView } from 'react-native';
2 | import GooglePlacesTextInput from 'react-native-google-places-textinput';
3 |
4 | const App = () => {
5 | const handleBasicPlaceSelect = (place, token) => {
6 | console.log('Basic example selected place:', place);
7 | console.log('Session token generated for this session:', token);
8 | };
9 |
10 | const handleStyledPlaceSelect = (place) => {
11 | console.log('Styled example selected place:', place);
12 | };
13 |
14 | // Custom styles example
15 | const customStyles = {
16 | container: {
17 | width: '100%',
18 | paddingHorizontal: 16,
19 | },
20 | input: {
21 | height: 50,
22 | borderWidth: 1.5,
23 | borderColor: '#E0E0E0',
24 | borderRadius: 12,
25 | paddingHorizontal: 16,
26 | fontSize: 16,
27 | backgroundColor: '#F8F8F8',
28 | },
29 | suggestionsContainer: {
30 | backgroundColor: '#FFFFFF',
31 | borderRadius: 12,
32 | maxHeight: 300,
33 | marginTop: 8,
34 | elevation: 3,
35 | shadowColor: '#000',
36 | shadowOffset: { width: 0, height: 2 },
37 | shadowOpacity: 0.1,
38 | shadowRadius: 8,
39 | },
40 | suggestionItem: {
41 | paddingVertical: 10,
42 | paddingHorizontal: 16,
43 | borderBottomWidth: 1,
44 | borderBottomColor: '#F0F0F0',
45 | },
46 | suggestionText: {
47 | main: {
48 | fontSize: 16,
49 | color: '#333333',
50 | fontWeight: '500',
51 | },
52 | secondary: {
53 | fontSize: 14,
54 | color: '#666666',
55 | marginTop: 4,
56 | },
57 | },
58 | loadingIndicator: {
59 | color: '#666666',
60 | },
61 | placeholder: {
62 | color: '#999999',
63 | },
64 | };
65 |
66 | return (
67 |
68 | {/* Basic usage example with minimal configuration */}
69 |
70 | Basic Example
71 |
78 |
79 |
80 | {/* Example showing custom styling and filtered place types */}
81 |
82 | Styled Example
83 |
93 |
94 |
95 | {/* Example demonstrating how to fetch detailed place information */}
96 |
97 | Place Details Example
98 | {
102 | console.log('Place with details:', place);
103 | if (place?.details) {
104 | console.log(
105 | 'Address components:',
106 | place.details.addressComponents
107 | );
108 | console.log('Formatted address:', place.details.formattedAddress);
109 | console.log('Location:', place.details.location);
110 | console.log('Has photos:', place.details.photos?.length > 0);
111 | }
112 | }}
113 | onError={(error) => console.error('Places API error:', error)}
114 | fetchDetails={true}
115 | detailsFields={[
116 | 'addressComponents',
117 | 'formattedAddress',
118 | 'location',
119 | 'viewport',
120 | 'photos',
121 | 'types',
122 | ]}
123 | style={{
124 | container: {
125 | width: '100%',
126 | paddingHorizontal: 16,
127 | },
128 | input: {
129 | height: 50,
130 | borderWidth: 1.5,
131 | borderColor: '#7986CB',
132 | borderRadius: 12,
133 | paddingHorizontal: 16,
134 | fontSize: 16,
135 | backgroundColor: '#F5F7FF',
136 | },
137 | suggestionsContainer: {
138 | borderRadius: 12,
139 | maxHeight: 300,
140 | },
141 | }}
142 | />
143 |
144 |
145 | {/* This example shows how to properly integrate GooglePlacesTextInput inside a vertical ScrollView */}
146 |
147 |
151 | Scroll Disabled Example
152 | {
156 | console.log('Scroll disabled example, selected:', place);
157 | }}
158 | scrollEnabled={false}
159 | nestedScrollEnabled={false}
160 | style={{
161 | container: {
162 | width: '100%',
163 | paddingHorizontal: 16,
164 | },
165 | }}
166 | />
167 |
168 |
169 |
170 | );
171 | };
172 |
173 | const styles = StyleSheet.create({
174 | container: {
175 | flex: 1,
176 | backgroundColor: '#fff',
177 | },
178 | section: {
179 | marginVertical: 16,
180 | },
181 | sectionTitle: {
182 | fontSize: 18,
183 | fontWeight: '600',
184 | marginBottom: 12,
185 | marginLeft: 16,
186 | color: '#333333',
187 | },
188 | });
189 |
190 | export default App;
191 |
--------------------------------------------------------------------------------
/docs/styling-guide.md:
--------------------------------------------------------------------------------
1 | # Styling Guide for GooglePlacesTextInput
2 |
3 | This guide explains how to customize the appearance of the GooglePlacesTextInput component to match your app's design.
4 |
5 | ## Styling Structure
6 |
7 | The component accepts a `style` prop with the following structure:
8 |
9 | ```typescript
10 | type Styles = {
11 | container?: ViewStyle;
12 | input?: TextStyle;
13 | suggestionsContainer?: ViewStyle;
14 | suggestionsList?: ViewStyle;
15 | suggestionItem?: ViewStyle;
16 | suggestionText?: {
17 | main?: TextStyle;
18 | secondary?: TextStyle;
19 | };
20 | loadingIndicator?: {
21 | color?: string;
22 | };
23 | placeholder?: {
24 | color?: string;
25 | };
26 | clearButtonText?: ViewStyle;
27 | }
28 | ```
29 |
30 | ## Component Layout Structure
31 |
32 | Understanding the component's structure helps with styling. Here's how the component is organized:
33 |
34 | ```javascript
35 |
36 |
37 |
38 |
39 | {clearElement || (
40 |
41 | ×
42 |
43 | )}
44 |
45 | (Loading indicator)
46 |
47 |
48 | (
51 |
52 |
53 | {mainText}
54 |
55 |
56 | {secondaryText}
57 |
58 |
59 | )}
60 | />
61 |
62 |
63 | ```
64 |
65 | ## Styling Examples
66 |
67 | ### Basic Input Styling
68 |
69 | ```javascript
70 | const styles = {
71 | container: {
72 | width: '100%',
73 | marginHorizontal: 16,
74 | },
75 | input: {
76 | height: 50,
77 | borderRadius: 8,
78 | borderWidth: 1,
79 | borderColor: '#CCCCCC',
80 | paddingHorizontal: 12,
81 | fontSize: 16,
82 | },
83 | placeholder: {
84 | color: '#888888',
85 | },
86 | clearButtonText: {
87 | color: '#FF0000', // Red X
88 | fontSize: 20,
89 | }
90 | };
91 | ```
92 |
93 | ### Material Design Style
94 |
95 | ```javascript
96 | const materialStyles = {
97 | container: {
98 | width: '100%',
99 | marginHorizontal: 16,
100 | },
101 | input: {
102 | height: 56,
103 | borderWidth: 0,
104 | borderRadius: 4,
105 | fontSize: 16,
106 | paddingHorizontal: 12,
107 | backgroundColor: '#F5F5F5',
108 | elevation: 2,
109 | shadowColor: '#000',
110 | shadowOffset: { width: 0, height: 1 },
111 | shadowOpacity: 0.2,
112 | shadowRadius: 1,
113 | },
114 | suggestionsContainer: {
115 | backgroundColor: '#FFFFFF',
116 | borderRadius: 4,
117 | marginTop: 4,
118 | elevation: 3,
119 | shadowColor: '#000',
120 | shadowOffset: { width: 0, height: 2 },
121 | shadowOpacity: 0.2,
122 | shadowRadius: 2,
123 | },
124 | suggestionItem: {
125 | paddingVertical: 12,
126 | paddingHorizontal: 16,
127 | },
128 | suggestionText: {
129 | main: {
130 | fontSize: 16,
131 | color: '#212121',
132 | },
133 | secondary: {
134 | fontSize: 14,
135 | color: '#757575',
136 | }
137 | },
138 | loadingIndicator: {
139 | color: '#6200EE',
140 | },
141 | placeholder: {
142 | color: '#9E9E9E',
143 | },
144 | clearButtonText: {
145 | color: '#FFFFFF',
146 | fontSize: 22,
147 | fontWeight: '400',
148 | }
149 | };
150 | ```
151 |
152 | ### iOS Style
153 |
154 | ```javascript
155 | const iosStyles = {
156 | container: {
157 | width: '100%',
158 | paddingHorizontal: 16,
159 | },
160 | input: {
161 | height: 44,
162 | borderRadius: 10,
163 | backgroundColor: '#E9E9EB',
164 | paddingHorizontal: 15,
165 | fontSize: 17,
166 | fontWeight: '400',
167 | },
168 | suggestionsContainer: {
169 | backgroundColor: '#FFFFFF',
170 | borderRadius: 10,
171 | marginTop: 8,
172 | shadowColor: '#000',
173 | shadowOffset: { width: 0, height: 2 },
174 | shadowOpacity: 0.1,
175 | shadowRadius: 8,
176 | },
177 | suggestionItem: {
178 | paddingVertical: 12,
179 | paddingHorizontal: 15,
180 | borderBottomWidth: 0.5,
181 | borderBottomColor: '#C8C7CC',
182 | },
183 | suggestionText: {
184 | main: {
185 | fontSize: 17,
186 | color: '#000000',
187 | fontWeight: '400',
188 | },
189 | secondary: {
190 | fontSize: 15,
191 | color: '#8E8E93',
192 | }
193 | },
194 | loadingIndicator: {
195 | color: '#007AFF',
196 | },
197 | placeholder: {
198 | color: '#8E8E93',
199 | },
200 | clearButtonText: {
201 | color: '#FFFFFF',
202 | fontSize: 22,
203 | fontWeight: '400',
204 | }
205 | };
206 | ```
207 |
208 | ## ✨ NEW: Custom Close Element
209 |
210 | You can now provide a custom close element instead of the default "×" text:
211 |
212 | ```javascript
213 | import { Ionicons } from '@expo/vector-icons';
214 |
215 |
219 | }
220 | // ...other props
221 | />
222 | ```
223 |
224 | ## ✨ NEW: Accessibility Labels
225 |
226 | The component now supports comprehensive accessibility customization:
227 |
228 | {% raw %}
229 | ```javascript
230 |
237 | `Select ${prediction.structuredFormat.mainText.text}, ${prediction.structuredFormat.secondaryText?.text || ''}`
238 | }}
239 | // ...other props
240 | />
241 | ```
242 | {% endraw %}
243 |
244 | ## Styling the Suggestions List
245 |
246 | The suggestions list is implemented as a FlatList with customizable height:
247 |
248 | ```javascript
249 | const styles = {
250 | suggestionsContainer: {
251 | maxHeight: 250, // Set the maximum height
252 | backgroundColor: '#FFFFFF',
253 | borderBottomLeftRadius: 8,
254 | borderBottomRightRadius: 8,
255 | borderWidth: 1,
256 | borderColor: '#EEEEEE',
257 | borderTopWidth: 0,
258 | },
259 | // Make individual items stand out with dividers
260 | suggestionItem: {
261 | paddingVertical: 12,
262 | paddingHorizontal: 16,
263 | borderBottomWidth: 1,
264 | borderBottomColor: '#F0F0F0',
265 | }
266 | };
267 | ```
268 |
269 | ## Loading Indicator and Clear Button
270 |
271 | You can customize the color of the loading indicator:
272 |
273 | ```javascript
274 | const styles = {
275 | loadingIndicator: {
276 | color: '#FF5722', // orange color
277 | }
278 | };
279 | ```
280 |
281 | The clear button is automatically styled based on platform (iOS or Android) but you can hide it with the `showClearButton` prop:
282 |
283 | ```javascript
284 |
289 | ```
290 |
291 | ## ✨ NEW: Programmatic Control
292 |
293 | The component now exposes a `blur()` method in addition to the existing `clear()` and `focus()` methods:
294 |
295 | ```javascript
296 | const inputRef = useRef();
297 |
298 | // Blur the input
299 | inputRef.current?.blur();
300 |
301 | // Clear the input
302 | inputRef.current?.clear();
303 |
304 | // Focus the input
305 | inputRef.current?.focus();
306 |
307 | // Get current session token
308 | const token = inputRef.current?.getSessionToken();
309 | ```
310 |
311 | ## RTL Support
312 |
313 | The component automatically handles RTL layouts based on the text direction. You can also force RTL with the `forceRTL` prop:
314 |
315 | ```javascript
316 |
321 | ```
322 |
323 | ## TextInput Props Support
324 |
325 | All standard React Native `TextInput` props are supported and can be passed directly to the component:
326 |
327 | ```javascript
328 |
341 | ```
342 |
343 | **Common TextInput props:**
344 | - `autoCapitalize` - Control auto-capitalization behavior
345 | - `autoCorrect` - Enable/disable auto-correction
346 | - `keyboardType` - Set keyboard type (default, email-address, numeric, phone-pad, etc.)
347 | - `returnKeyType` - Customize the return key (done, search, next, go, etc.)
348 | - `textContentType` - Optimize keyboard suggestions (iOS: location, streetAddressLine1, etc.)
349 | - `autoFocus` - Auto-focus the input on mount
350 | - `maxLength` - Limit input length
351 | - `editable` - Make the input read-only
352 | - `secureTextEntry`, `multiline`, `selectTextOnFocus`, and many more
353 |
354 | See the [React Native TextInput documentation](https://reactnative.dev/docs/textinput#props) for a complete list.
355 |
356 | ## Suggestion Text Display Control
357 |
358 | Control how suggestion text is displayed using the `suggestionTextProps` prop:
359 |
360 | ```typescript
361 | type SuggestionTextProps = {
362 | mainTextNumberOfLines?: number; // Max lines for place name
363 | secondaryTextNumberOfLines?: number; // Max lines for address
364 | ellipsizeMode?: 'head' | 'middle' | 'tail' | 'clip';
365 | }
366 | ```
367 |
368 | ### Example: Single-line suggestions
369 |
370 | ```javascript
371 |
380 | ```
381 |
382 | ### Example: Two-line place name, one-line address
383 |
384 | ```javascript
385 |
394 | ```
395 |
396 | ### Example: Middle ellipsis
397 |
398 | ```javascript
399 |
407 | ```
408 |
409 | **Use cases:**
410 | - Limit vertical space usage in compact UIs
411 | - Prevent long place names/addresses from wrapping
412 | - Create a cleaner, more uniform suggestion list
413 | - Control where the ellipsis appears
414 | - Or allow unlimited lines by omitting `numberOfLines`
415 |
416 | ## Combining with Other Style Systems
417 |
418 | If you're using a styling library like styled-components or Tailwind, you can still use this component by generating the style object:
419 |
420 | ```javascript
421 | // Example with StyleSheet.create
422 | import { StyleSheet } from 'react-native';
423 |
424 | const styles = StyleSheet.create({
425 | container: {
426 | width: '100%',
427 | },
428 | input: {
429 | height: 50,
430 | borderWidth: 1,
431 | },
432 | // ...other styles
433 | });
434 |
435 | // Pass the styles to the component
436 |
443 | ```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React Native Google Places Autocomplete TextInput
2 |
3 | A customizable React Native TextInput component for Google Places Autocomplete using the Places API (New)
4 |
5 | ## Features
6 |
7 | - Fully customizable UI
8 | - Debounced search
9 | - Clear button (x)
10 | - Loading indicator
11 | - Keyboard-aware
12 | - Custom place types filtering
13 | - RTL support
14 | - Multi-language support
15 | - Session token support for reduced billing costs
16 | - Extended place details fetching (Optional)
17 | - Compatible with both Expo and non-Expo projects
18 | - Works with Expo Web
19 | - Supports all TextInput props (autoCapitalize, keyboardType, etc.)
20 | - Control suggestion text display (lines, ellipsis)
21 |
22 | ## Preview
23 |
24 |
25 |
26 |  |
27 |
28 |
29 |
30 | ## Installation
31 |
32 | ```bash
33 | npm install react-native-google-places-textinput
34 | # or
35 | yarn add react-native-google-places-textinput
36 | ```
37 |
38 | > **Note:** This package is written in TypeScript and works seamlessly with both Expo and non-Expo React Native projects with no additional configuration required.
39 |
40 | ## Prerequisites
41 |
42 | 1. **Enable the Places API (New)** in your Google Cloud Project
43 | - This component specifically requires the new `Places API (New)`, not the legacy `Places API`
44 | - In the [Google Cloud Console](https://console.cloud.google.com/), go to `APIs & Services` > `Library` and search for "*Places API (New)*"
45 |
46 | 2. **Create an API key**
47 | - Go to "APIs & Services" > "Credentials" and create a new API key
48 | - Under "API restrictions", make sure "Places API (New)" is selected
49 |
50 | ## Usage
51 |
52 | ### Basic Example
53 | ```javascript
54 | import GooglePlacesTextInput from 'react-native-google-places-textinput';
55 |
56 | const YourComponent = () => {
57 | const handlePlaceSelect = (place) => {
58 | console.log('Selected place:', place);
59 | };
60 |
61 | return (
62 |
66 | );
67 | };
68 | ```
69 |
70 |
71 | Example with language and region codes filtering
72 |
73 | ```javascript
74 | const ConfiguredExample = () => {
75 | const handlePlaceSelect = (place) => {
76 | console.log('Selected place:', place);
77 | };
78 |
79 | return (
80 |
88 | );
89 | };
90 | ```
91 |
92 |
93 |
94 | Example with full styling
95 |
96 | ```javascript
97 | const StyledExample = () => {
98 | const handlePlaceSelect = (place) => {
99 | console.log('Selected place:', place);
100 | };
101 |
102 | const customStyles = {
103 | container: {
104 | width: '100%',
105 | marginHorizontal: 0,
106 | },
107 | input: {
108 | height: 45,
109 | borderColor: '#ccc',
110 | borderRadius: 8,
111 | },
112 | suggestionsContainer: {
113 | backgroundColor: '#ffffff',
114 | maxHeight: 250,
115 | },
116 | suggestionItem: {
117 | padding: 15,
118 | },
119 | suggestionText: {
120 | main: {
121 | fontSize: 16,
122 | color: '#333',
123 | },
124 | secondary: {
125 | fontSize: 14,
126 | color: '#666',
127 | }
128 | },
129 | loadingIndicator: {
130 | color: '#999',
131 | },
132 | placeholder: {
133 | color: '#999',
134 | }
135 | };
136 |
137 | return (
138 |
144 | );
145 | };
146 | ```
147 |
148 |
149 |
150 | Example with place details fetching
151 |
152 | ```javascript
153 | const PlaceDetailsExample = () => {
154 | const handlePlaceSelect = (place) => {
155 | console.log('Selected place:', place);
156 |
157 | // Access detailed place information
158 | if (place.details) {
159 | console.log(place.details);
160 | }
161 | };
162 |
163 | const handleError = (error) => {
164 | console.error('API error:', error);
165 | };
166 |
167 | return (
168 |
182 | );
183 | };
184 | ```
185 |
186 |
187 |
188 | Example embed in vertical ScrollView
189 |
190 | ```javascript
191 |
195 | Fill in your address
196 |
202 |
203 | ```
204 |
205 |
206 |
207 | Example with TextInput props and suggestion text control
208 |
209 | ```javascript
210 | const CustomizedExample = () => {
211 | const handlePlaceSelect = (place) => {
212 | console.log('Selected place:', place);
213 | };
214 |
215 | return (
216 |
232 | );
233 | };
234 | ```
235 |
236 |
237 | ## Props
238 |
239 | | Prop | Type | Required | Default | Description |
240 | |------|------|----------|---------|-------------|
241 | | **Basic Configuration** |
242 | | apiKey | string | Yes | - | Your Google Places API key |
243 | | value | string | No | - | Controlled input value |
244 | | placeHolderText | string | No | - | Placeholder text for the input |
245 | | onPlaceSelect | (place: Place, sessionToken?: string) => void | Yes | - | Callback when a place is selected |
246 | | onTextChange | (text: string) => void | No | - | Callback when input text changes |
247 | | onFocus | (event: NativeSyntheticEvent) => void | No | - | Callback when input is focused |
248 | | onBlur | (event: NativeSyntheticEvent) => void | No | - | Callback when input is blurred |
249 | | **Search Configuration** |
250 | | proxyUrl | string | No | - | Custom proxy URL for API requests (Required for Expo web) |
251 | | proxyHeaders | object | No | - | Headers to pass to the proxy (ex. { Authorization: 'Bearer AUTHTOKEN' } ) |
252 | | languageCode | string | No | - | Language code (e.g., 'en', 'fr') |
253 | | includedRegionCodes | string[] | No | - | Array of region codes to filter results |
254 | | locationBias | Record | No | - | Bias search results by location (circle or rectangle). [Details](#location-filtering) |
255 | | locationRestriction | Record | No | - | Restrict search results to location (circle or rectangle). [Details](#location-filtering) |
256 | | types | string[] | No | [] | Array of place types to filter |
257 | | biasPrefixText | (text: string) => string | No | - | Optional function to modify the input text before sending to the Places API |
258 | | minCharsToFetch | number | No | 1 | Minimum characters before triggering search |
259 | | debounceDelay | number | No | 200 | Delay in milliseconds before triggering search |
260 | | **Place Details Configuration** |
261 | | fetchDetails | boolean | No | false | Automatically fetch place details when a place is selected |
262 | | detailsProxyUrl | string | No | null | Custom proxy URL for place details requests (Required on Expo web)|
263 | | detailsProxyHeaders | object | No | - | Headers to pass to the place details proxy (ex. { Authorization: 'Bearer AUTHTOKEN' } ) |
264 | | detailsFields | string[] | No | ['displayName', 'formattedAddress', 'location', 'id'] | Array of fields to include in the place details response. see [Valid Fields](https://developers.google.com/maps/documentation/places/web-service/place-details#fieldmask) |
265 | | **UI Customization** |
266 | | showLoadingIndicator | boolean | No | true | Show loading spinner during API requests |
267 | | showClearButton | boolean | No | true | Show clear (×) button when input has text |
268 | | forceRTL | boolean | No | - | Force RTL layout (auto-detected if not provided) |
269 | | style | GooglePlacesTextInputStyles | No | {} | Custom styling object |
270 | | hideOnKeyboardDismiss | boolean | No | false | Hide suggestions when keyboard is dismissed |
271 | | scrollEnabled | boolean | No | true | Enable/disable scrolling in the suggestions list |
272 | | nestedScrollEnabled | boolean | No | true | Enable/disable nested scrolling for the suggestions list |
273 | | suggestionTextProps | SuggestionTextProps | No | {} | Control suggestion text display (lines, ellipsis). [Details](./docs/styling-guide.md#suggestion-text-display-control) |
274 | | accessibilityLabels | GooglePlacesAccessibilityLabels | No | {} | Custom accessibility labels |
275 | | **TextInput Props** |
276 | | ...restProps | TextInputProps | No | - | All TextInput props supported. [Details](./docs/styling-guide.md#textinput-props-support) |
277 | | **Error Handling & Debugging** |
278 | | onError | (error: any) => void | No | - | Callback when API errors occur |
279 | | enableDebug | boolean | No | false | Enable detailed console logging for troubleshooting |
280 |
281 | ## Location Filtering
282 |
283 | You can filter or bias search results based on geographic location using `locationBias` or `locationRestriction`.
284 |
285 | ### Location Bias (Soft Filter)
286 |
287 | **Biases** results towards a location but can still return results outside the area if they're highly relevant:
288 |
289 | ```javascript
290 |
303 | ```
304 |
305 | ### Location Restriction (Hard Filter)
306 |
307 | **Restricts** results to only those within the specified area:
308 |
309 | ```javascript
310 |
320 | ```
321 |
322 | **Supported shapes:**
323 | - **Circle**: Define center (lat/lng) and radius in meters
324 | - **Rectangle**: Define southwest and northeast corners (low/high)
325 |
326 | **Use cases:**
327 | - Show places near user's current GPS location
328 | - Limit results to delivery radius
329 | - Search within a specific neighborhood or city bounds
330 |
331 | For more details, see [Google Places API Location Biasing](https://developers.google.com/maps/documentation/places/web-service/autocomplete#location_biasing).
332 |
333 | ## Place Details Fetching
334 |
335 | You can automatically fetch detailed place information when a user selects a place suggestion by enabling the `fetchDetails` prop:
336 |
337 | ```javascript
338 | console.log(place.details)}
343 | />
344 | ```
345 |
346 | When `fetchDetails` is enabled:
347 | 1. The component fetches place details immediately when a user selects a place suggestion
348 | 2. The details are attached to the place object passed to your `onPlaceSelect` callback in the `details` property
349 | 3. Use the `detailsFields` prop to specify which fields to include in the response, reducing API costs
350 |
351 | For a complete list of available fields, see the [Place Details API documentation](https://developers.google.com/maps/documentation/places/web-service/place-details#fieldmask).
352 |
353 | ### Place Details on Expo Web
354 |
355 | **Important:** To use Google Places Details on Expo Web, you must provide a `detailsProxyUrl` prop that points to a CORS-enabled proxy for the Google Places Details API. This is required due to browser security restrictions.
356 |
357 | ```javascript
358 | console.log(place.details)}
363 | />
364 | ```
365 |
366 | Without a proxy, the component will still work on Expo Web for place search, but place details fetching will fail with CORS errors.
367 |
368 | For a complete guide on setting up a proxy server for Expo Web, see [Expo Web Details Proxy Guide](./docs/expo-web-details-proxy.md).
369 |
370 | ## Session Tokens and Billing
371 |
372 | This component automatically manages session tokens to optimize your Google Places API billing:
373 |
374 | - A session token is generated when the component mounts
375 | - The same token is automatically used for all autocomplete requests and place details requests
376 | - The component automatically resets tokens after place selection, input clearing, or calling `clear()`
377 |
378 | **Note:** This automatic session token management ensures Google treats your autocomplete and details requests as part of the same session, reducing your billing costs with no additional configuration needed.
379 |
380 | ## Methods
381 |
382 | The component exposes the following methods through refs:
383 |
384 | - `clear()`: Clears the input and suggestions
385 | - `focus()`: Focuses the input field
386 | - `getSessionToken()`: Returns the current session token
387 |
388 | ```javascript
389 | const inputRef = useRef(null);
390 |
391 | // Usage
392 | inputRef.current?.clear();
393 | inputRef.current?.focus();
394 | const token = inputRef.current?.getSessionToken();
395 | ```
396 |
397 | ## Styling
398 |
399 | The component accepts a `style` prop with the following structure:
400 |
401 | ```typescript
402 | type Styles = {
403 | container?: ViewStyle;
404 | input?: TextStyle;
405 | suggestionsContainer?: ViewStyle;
406 | suggestionItem?: ViewStyle;
407 | suggestionText?: {
408 | main?: TextStyle;
409 | secondary?: TextStyle;
410 | };
411 | loadingIndicator?: {
412 | color?: string;
413 | };
414 | placeholder?: {
415 | color?: string;
416 | };
417 | }
418 | ```
419 |
420 | For detailed styling examples, TextInput props usage, and suggestion text control, see our [Styling Guide](./docs/styling-guide.md).
421 |
422 | ## Contributing
423 |
424 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
425 |
426 | ## License
427 |
428 | MIT
429 |
430 | ---
431 |
432 | Available on Github:
433 | [https://github.com/amitpdev/react-native-google-places-textinput](https://github.com/amitpdev/react-native-google-places-textinput)
434 |
435 | Written by [Amit Palomo](https://github.com/amitpdev)
436 | See other projects I built on [my blog](https://amitpdev.github.io)
437 |
438 | Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
--------------------------------------------------------------------------------
/src/GooglePlacesTextInput.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | forwardRef,
3 | useEffect,
4 | useImperativeHandle,
5 | useRef,
6 | useState,
7 | } from 'react';
8 | import type { ReactNode } from 'react';
9 | import type {
10 | StyleProp,
11 | TextStyle,
12 | ViewStyle,
13 | TextInputProps,
14 | TextInputFocusEventData,
15 | NativeSyntheticEvent,
16 | } from 'react-native';
17 | import {
18 | ActivityIndicator,
19 | FlatList,
20 | I18nManager,
21 | Keyboard,
22 | Platform,
23 | StyleSheet,
24 | Text,
25 | TextInput,
26 | TouchableOpacity,
27 | View,
28 | } from 'react-native';
29 |
30 | // Import the API functions
31 | import {
32 | fetchPlaceDetails as fetchPlaceDetailsApi,
33 | fetchPredictions as fetchPredictionsApi,
34 | generateUUID,
35 | isRTLText,
36 | } from './services/googlePlacesApi';
37 |
38 | // Type definitions
39 | interface PlaceStructuredFormat {
40 | mainText: {
41 | text: string;
42 | };
43 | secondaryText?: {
44 | text: string;
45 | };
46 | }
47 |
48 | interface PlacePrediction {
49 | placeId: string;
50 | structuredFormat: PlaceStructuredFormat;
51 | types: string[];
52 | }
53 |
54 | interface PlaceDetailsFields {
55 | [key: string]: any;
56 | }
57 |
58 | interface Place {
59 | placeId: string;
60 | structuredFormat: PlaceStructuredFormat;
61 | types: string[];
62 | details?: PlaceDetailsFields; // ✅ Optional details when fetchDetails is true
63 | }
64 |
65 | interface GooglePlacesTextInputStyles {
66 | container?: StyleProp;
67 | input?: StyleProp;
68 | suggestionsContainer?: StyleProp;
69 | suggestionsList?: StyleProp;
70 | suggestionItem?: StyleProp;
71 | suggestionText?: {
72 | main?: StyleProp;
73 | secondary?: StyleProp;
74 | };
75 | loadingIndicator?: {
76 | color?: string;
77 | };
78 | placeholder?: {
79 | color?: string;
80 | };
81 | clearButtonText?: StyleProp;
82 | }
83 |
84 | interface GooglePlacesAccessibilityLabels {
85 | input?: string;
86 | clearButton?: string;
87 | loadingIndicator?: string;
88 | /**
89 | * A function that receives a place prediction and returns a descriptive string
90 | * for the suggestion item.
91 | * @example (prediction) => `Select ${prediction.structuredFormat.mainText.text}, ${prediction.structuredFormat.secondaryText?.text}`
92 | */
93 | suggestionItem?: (prediction: PlacePrediction) => string;
94 | }
95 |
96 | interface SuggestionTextProps {
97 | /**
98 | * Maximum number of lines for the main text (place name)
99 | * @default undefined (no limit)
100 | */
101 | mainTextNumberOfLines?: number;
102 | /**
103 | * Maximum number of lines for the secondary text (address)
104 | * @default undefined (no limit)
105 | */
106 | secondaryTextNumberOfLines?: number;
107 | /**
108 | * Determines how text is truncated when it exceeds the number of lines
109 | * @default 'tail'
110 | */
111 | ellipsizeMode?: 'head' | 'middle' | 'tail' | 'clip';
112 | }
113 |
114 | interface GooglePlacesTextInputProps
115 | extends Omit<
116 | TextInputProps,
117 | | 'value'
118 | | 'onChangeText'
119 | | 'ref'
120 | | 'style'
121 | | 'placeholder'
122 | | 'placeholderTextColor'
123 | > {
124 | apiKey: string;
125 | value?: string;
126 | placeHolderText?: string;
127 | proxyUrl?: string;
128 | proxyHeaders?: Record;
129 | languageCode?: string;
130 | includedRegionCodes?: string[];
131 | locationBias?: Record;
132 | locationRestriction?: Record;
133 | types?: string[];
134 | biasPrefixText?: (text: string) => string;
135 | minCharsToFetch?: number;
136 | onPlaceSelect: (place: Place, sessionToken?: string | null) => void;
137 | onTextChange?: (text: string) => void;
138 | debounceDelay?: number;
139 | showLoadingIndicator?: boolean;
140 | showClearButton?: boolean;
141 | forceRTL?: boolean;
142 | style?: GooglePlacesTextInputStyles;
143 | clearElement?: ReactNode;
144 | hideOnKeyboardDismiss?: boolean;
145 | scrollEnabled?: boolean;
146 | nestedScrollEnabled?: boolean;
147 | fetchDetails?: boolean;
148 | detailsProxyUrl?: string | null;
149 | detailsProxyHeaders?: Record;
150 | detailsFields?: string[];
151 | onError?: (error: any) => void;
152 | enableDebug?: boolean;
153 | accessibilityLabels?: GooglePlacesAccessibilityLabels;
154 | suggestionTextProps?: SuggestionTextProps;
155 | }
156 |
157 | interface GooglePlacesTextInputRef {
158 | clear: () => void;
159 | blur: () => void;
160 | focus: () => void;
161 | getSessionToken: () => string | null;
162 | }
163 |
164 | interface PredictionItem {
165 | placePrediction: PlacePrediction;
166 | }
167 |
168 | const GooglePlacesTextInput = forwardRef<
169 | GooglePlacesTextInputRef,
170 | GooglePlacesTextInputProps
171 | >(
172 | (
173 | {
174 | apiKey,
175 | value,
176 | placeHolderText,
177 | proxyUrl,
178 | proxyHeaders = null,
179 | languageCode,
180 | includedRegionCodes,
181 | locationBias,
182 | locationRestriction,
183 | types = [],
184 | biasPrefixText,
185 | minCharsToFetch = 1,
186 | onPlaceSelect,
187 | onTextChange,
188 | debounceDelay = 200,
189 | showLoadingIndicator = true,
190 | showClearButton = true,
191 | forceRTL = undefined,
192 | style = {},
193 | clearElement,
194 | hideOnKeyboardDismiss = false,
195 | scrollEnabled = true,
196 | nestedScrollEnabled = true,
197 | fetchDetails = false,
198 | detailsProxyUrl = null,
199 | detailsProxyHeaders = null,
200 | detailsFields = [],
201 | onError,
202 | enableDebug = false,
203 | onFocus,
204 | onBlur,
205 | accessibilityLabels = {},
206 | suggestionTextProps = {},
207 | ...restTextInputProps
208 | },
209 | ref
210 | ) => {
211 | const [predictions, setPredictions] = useState([]);
212 | const [loading, setLoading] = useState(false);
213 | const [inputText, setInputText] = useState(value || '');
214 | const [showSuggestions, setShowSuggestions] = useState(false);
215 | const [sessionToken, setSessionToken] = useState(null);
216 | const [detailsLoading, setDetailsLoading] = useState(false);
217 | const debounceTimeout = useRef | null>(null);
218 | const inputRef = useRef(null);
219 | const suggestionPressing = useRef(false);
220 | const skipNextFocusFetch = useRef(false);
221 |
222 | const generateSessionToken = (): string => {
223 | return generateUUID();
224 | };
225 |
226 | // Initialize session token on mount
227 | useEffect(() => {
228 | setSessionToken(generateSessionToken());
229 |
230 | return () => {
231 | if (debounceTimeout.current) {
232 | clearTimeout(debounceTimeout.current);
233 | }
234 | };
235 | }, []);
236 |
237 | useEffect(() => {
238 | setInputText(value ?? '');
239 | }, [value]);
240 |
241 | // Add keyboard listener
242 | useEffect(() => {
243 | if (hideOnKeyboardDismiss) {
244 | const keyboardDidHideSubscription = Keyboard.addListener(
245 | 'keyboardDidHide',
246 | () => setShowSuggestions(false)
247 | );
248 |
249 | return () => {
250 | keyboardDidHideSubscription.remove();
251 | };
252 | }
253 | return () => {};
254 | }, [hideOnKeyboardDismiss]);
255 |
256 | // Expose methods to parent through ref
257 | useImperativeHandle(ref, () => ({
258 | clear: () => {
259 | if (debounceTimeout.current) {
260 | clearTimeout(debounceTimeout.current);
261 | }
262 | skipNextFocusFetch.current = true;
263 | setInputText('');
264 | setPredictions([]);
265 | setShowSuggestions(false);
266 | setSessionToken(generateSessionToken());
267 | },
268 | blur: () => {
269 | inputRef.current?.blur();
270 | },
271 | focus: () => {
272 | inputRef.current?.focus();
273 | },
274 | getSessionToken: () => sessionToken,
275 | }));
276 |
277 | // RTL detection logic
278 | const isRTL =
279 | forceRTL !== undefined ? forceRTL : isRTLText(placeHolderText ?? '');
280 |
281 | // Add missing CORS warning effect
282 | useEffect(() => {
283 | if (Platform.OS === 'web' && fetchDetails && !detailsProxyUrl) {
284 | console.warn(
285 | 'Google Places Details API does not support CORS. ' +
286 | 'To fetch place details on web, provide a detailsProxyUrl prop that points to a CORS-enabled proxy.'
287 | );
288 | }
289 | }, [fetchDetails, detailsProxyUrl]);
290 |
291 | // Debug logger utility
292 | const debugLog = (category: string, message: string, data?: any) => {
293 | if (enableDebug) {
294 | const timestamp = new Date().toISOString();
295 | console.log(
296 | `[GooglePlacesTextInput:${category}] ${timestamp} - ${message}`
297 | );
298 | if (data) {
299 | console.log(`[GooglePlacesTextInput:${category}] Data:`, data);
300 | }
301 | }
302 | };
303 |
304 | const fetchPredictions = async (text: string): Promise => {
305 | debugLog('PREDICTIONS', `Starting fetch for text: "${text}"`);
306 | debugLog('PREDICTIONS', 'Request params', {
307 | text,
308 | apiKey: apiKey ? '[PROVIDED]' : '[MISSING]', // ✅ Security fix
309 | proxyUrl,
310 | proxyHeaders,
311 | sessionToken,
312 | languageCode,
313 | includedRegionCodes,
314 | locationBias,
315 | locationRestriction,
316 | types,
317 | minCharsToFetch,
318 | });
319 |
320 | if (!text || text.length < minCharsToFetch) {
321 | debugLog(
322 | 'PREDICTIONS',
323 | `Text too short (${text.length} < ${minCharsToFetch})`
324 | );
325 | setPredictions([]);
326 | return;
327 | }
328 |
329 | setLoading(true);
330 |
331 | const { error, predictions: fetchedPredictions } =
332 | await fetchPredictionsApi({
333 | text,
334 | apiKey,
335 | proxyUrl,
336 | proxyHeaders,
337 | sessionToken,
338 | languageCode,
339 | includedRegionCodes,
340 | locationBias,
341 | locationRestriction,
342 | types,
343 | biasPrefixText,
344 | });
345 |
346 | if (error) {
347 | debugLog('PREDICTIONS', 'API Error occurred', {
348 | errorType: error.constructor.name,
349 | errorMessage: error.message,
350 | errorStack: error.stack,
351 | });
352 | onError?.(error);
353 | setPredictions([]);
354 | } else {
355 | debugLog(
356 | 'PREDICTIONS',
357 | `Success: ${fetchedPredictions.length} predictions received`
358 | );
359 | debugLog('PREDICTIONS', 'Predictions data', fetchedPredictions);
360 | setPredictions(fetchedPredictions);
361 | setShowSuggestions(fetchedPredictions.length > 0);
362 | }
363 |
364 | setLoading(false);
365 | };
366 |
367 | const fetchPlaceDetails = async (
368 | placeId: string
369 | ): Promise => {
370 | debugLog('DETAILS', `Starting details fetch for placeId: ${placeId}`);
371 | debugLog('DETAILS', 'Request params', {
372 | placeId,
373 | apiKey: apiKey ? '[PROVIDED]' : '[MISSING]', // ✅ Security fix
374 | detailsProxyUrl,
375 | detailsProxyHeaders,
376 | sessionToken,
377 | languageCode,
378 | detailsFields,
379 | fetchDetails,
380 | platform: Platform.OS,
381 | });
382 |
383 | if (!fetchDetails || !placeId) {
384 | debugLog('DETAILS', 'Skipping details fetch', {
385 | fetchDetails,
386 | placeId,
387 | });
388 | return null;
389 | }
390 |
391 | // Web CORS warning
392 | if (Platform.OS === 'web' && !detailsProxyUrl) {
393 | debugLog(
394 | 'DETAILS',
395 | 'WARNING: Web platform detected without detailsProxyUrl - CORS issues likely'
396 | );
397 | }
398 |
399 | setDetailsLoading(true);
400 |
401 | const { error, details } = await fetchPlaceDetailsApi({
402 | placeId,
403 | apiKey,
404 | detailsProxyUrl,
405 | detailsProxyHeaders,
406 | sessionToken,
407 | languageCode,
408 | detailsFields,
409 | });
410 |
411 | setDetailsLoading(false);
412 |
413 | if (error) {
414 | debugLog('DETAILS', 'API Error occurred', {
415 | errorType: error.constructor.name,
416 | errorMessage: error.message,
417 | errorStack: error.stack,
418 | });
419 | onError?.(error);
420 | return null;
421 | }
422 |
423 | debugLog('DETAILS', 'Success: Details received', details);
424 | return details;
425 | };
426 |
427 | const handleTextChange = (text: string): void => {
428 | setInputText(text);
429 | onTextChange?.(text);
430 |
431 | if (debounceTimeout.current) {
432 | clearTimeout(debounceTimeout.current);
433 | }
434 |
435 | debounceTimeout.current = setTimeout(() => {
436 | fetchPredictions(text);
437 | }, debounceDelay);
438 | };
439 |
440 | const handleSuggestionPress = async (
441 | suggestion: PredictionItem
442 | ): Promise => {
443 | const place = suggestion.placePrediction;
444 | debugLog(
445 | 'SELECTION',
446 | `User selected place: ${place.structuredFormat.mainText.text}`
447 | );
448 | debugLog('SELECTION', 'Selected place data', place);
449 |
450 | setInputText(place.structuredFormat.mainText.text);
451 | setShowSuggestions(false);
452 | Keyboard.dismiss();
453 |
454 | if (fetchDetails) {
455 | debugLog('SELECTION', 'Fetching place details...');
456 | setLoading(true);
457 | const details = await fetchPlaceDetails(place.placeId);
458 | const enrichedPlace: Place = details ? { ...place, details } : place;
459 |
460 | debugLog(
461 | 'SELECTION',
462 | 'Final place object being sent to onPlaceSelect',
463 | {
464 | hasDetails: !!details,
465 | placeKeys: Object.keys(enrichedPlace),
466 | detailsKeys: details ? Object.keys(details) : null,
467 | }
468 | );
469 |
470 | onPlaceSelect?.(enrichedPlace, sessionToken);
471 | setLoading(false);
472 | } else {
473 | debugLog(
474 | 'SELECTION',
475 | 'Sending place without details (fetchDetails=false)'
476 | );
477 | onPlaceSelect?.(place, sessionToken);
478 | }
479 | setSessionToken(generateSessionToken());
480 | };
481 |
482 | const handleFocus = (
483 | event: NativeSyntheticEvent
484 | ): void => {
485 | onFocus?.(event);
486 |
487 | if (skipNextFocusFetch.current) {
488 | skipNextFocusFetch.current = false;
489 | return;
490 | }
491 | if (inputText.length >= minCharsToFetch) {
492 | fetchPredictions(inputText);
493 | setShowSuggestions(true);
494 | }
495 | };
496 |
497 | const handleBlur = (
498 | event: NativeSyntheticEvent
499 | ): void => {
500 | onBlur?.(event);
501 |
502 | setTimeout(() => {
503 | if (suggestionPressing.current) {
504 | suggestionPressing.current = false;
505 | } else {
506 | setShowSuggestions(false);
507 | }
508 | }, 10);
509 | };
510 |
511 | const renderSuggestion = ({
512 | item,
513 | index,
514 | }: {
515 | item: PredictionItem;
516 | index: number;
517 | }) => {
518 | const { mainText, secondaryText } = item.placePrediction.structuredFormat;
519 |
520 | // Safely extract backgroundColor from style
521 | const suggestionsContainerStyle = StyleSheet.flatten(
522 | style.suggestionsContainer
523 | );
524 | const backgroundColor =
525 | suggestionsContainerStyle?.backgroundColor || '#efeff1';
526 |
527 | const defaultAccessibilityLabel = `${mainText.text}${
528 | secondaryText ? `, ${secondaryText.text}` : ''
529 | }`;
530 | const accessibilityLabel =
531 | accessibilityLabels.suggestionItem?.(item.placePrediction) ||
532 | defaultAccessibilityLabel;
533 |
534 | return (
535 | 0 ? styles.separatorLine : {},
541 | styles.suggestionItem,
542 | { backgroundColor },
543 | style.suggestionItem,
544 | ]}
545 | onPress={() => {
546 | suggestionPressing.current = false;
547 | handleSuggestionPress(item);
548 | }}
549 | // Fix for web: onBlur fires before onPress, hiding suggestions too early.
550 | {...(Platform.OS === 'web' &&
551 | ({
552 | onMouseDown: () => {
553 | suggestionPressing.current = true;
554 | },
555 | } as any))}
556 | >
557 |
566 | {mainText.text}
567 |
568 | {secondaryText && (
569 |
578 | {secondaryText.text}
579 |
580 | )}
581 |
582 | );
583 | };
584 |
585 | const getPadding = () => {
586 | const physicalRTL = I18nManager.isRTL;
587 | const clearButtonPadding = showClearButton ? 75 : 45;
588 | if (isRTL !== physicalRTL) {
589 | return {
590 | paddingStart: clearButtonPadding,
591 | paddingEnd: 15,
592 | };
593 | }
594 | return {
595 | paddingStart: 15,
596 | paddingEnd: clearButtonPadding,
597 | };
598 | };
599 |
600 | const getTextAlign = () => {
601 | const isDeviceRTL = I18nManager.isRTL;
602 | if (isDeviceRTL) {
603 | return { textAlign: isRTL ? 'left' : ('right' as 'left' | 'right') };
604 | } else {
605 | return { textAlign: isRTL ? 'right' : ('left' as 'left' | 'right') };
606 | }
607 | };
608 |
609 | const getIconPosition = (paddingValue: number) => {
610 | const physicalRTL = I18nManager.isRTL;
611 | if (isRTL !== physicalRTL) {
612 | return { start: paddingValue };
613 | }
614 | return { end: paddingValue };
615 | };
616 |
617 | // Debug initialization
618 | useEffect(() => {
619 | if (enableDebug) {
620 | debugLog('INIT', 'Component initialized with props', {
621 | apiKey: apiKey ? '[PROVIDED]' : '[MISSING]', // ✅ Security fix
622 | fetchDetails,
623 | detailsProxyUrl,
624 | detailsFields,
625 | platform: Platform.OS,
626 | minCharsToFetch,
627 | debounceDelay,
628 | });
629 | }
630 | // eslint-disable-next-line react-hooks/exhaustive-deps
631 | }, []);
632 |
633 | return (
634 |
635 |
636 |
650 |
651 | {/* Clear button - shown only if showClearButton is true */}
652 | {showClearButton && inputText !== '' && (
653 | {
656 | if (debounceTimeout.current) {
657 | clearTimeout(debounceTimeout.current);
658 | }
659 | skipNextFocusFetch.current = true;
660 | setInputText('');
661 | setPredictions([]);
662 | setShowSuggestions(false);
663 | onTextChange?.('');
664 | setSessionToken(generateSessionToken());
665 | inputRef.current?.focus();
666 | }}
667 | accessibilityRole="button"
668 | accessibilityLabel={
669 | accessibilityLabels.clearButton || 'Clear input text'
670 | }
671 | >
672 | {clearElement || (
673 |
674 |
685 | {'×'}
686 |
687 |
688 | )}
689 |
690 | )}
691 |
692 | {/* Loading indicator */}
693 | {(loading || detailsLoading) && showLoadingIndicator && (
694 |
703 | )}
704 |
705 |
706 | {/* Suggestions */}
707 | {showSuggestions && predictions.length > 0 && (
708 |
711 | item.placePrediction.placeId}
715 | keyboardShouldPersistTaps="always"
716 | scrollEnabled={scrollEnabled}
717 | nestedScrollEnabled={nestedScrollEnabled}
718 | bounces={false}
719 | style={style.suggestionsList}
720 | accessibilityRole="list"
721 | accessibilityLabel={`${predictions.length} place suggestion resuts`}
722 | />
723 |
724 | )}
725 |
726 | );
727 | }
728 | );
729 |
730 | const styles = StyleSheet.create({
731 | container: {},
732 | input: {
733 | flex: 1,
734 | borderRadius: 6,
735 | borderWidth: 1,
736 | paddingHorizontal: 10,
737 | backgroundColor: 'white',
738 | fontSize: 16,
739 | paddingVertical: 16,
740 | },
741 | suggestionsContainer: {
742 | backgroundColor: '#efeff1', // default background
743 | borderRadius: 6,
744 | marginTop: 3,
745 | overflow: 'hidden',
746 | maxHeight: 200,
747 | },
748 | suggestionItem: {
749 | padding: 10,
750 | },
751 | separatorLine: {
752 | borderTopWidth: StyleSheet.hairlineWidth,
753 | borderTopColor: '#c8c7cc',
754 | },
755 | mainText: {
756 | fontSize: 16,
757 | textAlign: 'left',
758 | color: '#000000',
759 | },
760 | secondaryText: {
761 | fontSize: 14,
762 | color: '#666',
763 | marginTop: 2,
764 | textAlign: 'left',
765 | },
766 | clearButton: {
767 | position: 'absolute',
768 | top: '50%',
769 | transform: [{ translateY: -13 }],
770 | padding: 0,
771 | },
772 | loadingIndicator: {
773 | position: 'absolute',
774 | top: '50%',
775 | transform: [{ translateY: -10 }],
776 | },
777 | clearTextWrapper: {
778 | backgroundColor: '#999',
779 | borderRadius: 12,
780 | width: 24,
781 | height: 24,
782 | alignItems: 'center',
783 | justifyContent: 'center',
784 | },
785 | //this is never going to be consistent between different phone fonts and sizes
786 | iOSclearText: {
787 | fontSize: 22,
788 | fontWeight: '400',
789 | color: 'white',
790 | lineHeight: 24,
791 | includeFontPadding: false,
792 | },
793 | androidClearText: {
794 | fontSize: 24,
795 | fontWeight: '400',
796 | color: 'white',
797 | lineHeight: 25.5,
798 | includeFontPadding: false,
799 | },
800 | });
801 |
802 | export type {
803 | GooglePlacesTextInputProps,
804 | GooglePlacesTextInputRef,
805 | GooglePlacesTextInputStyles,
806 | Place,
807 | PlaceDetailsFields,
808 | PlacePrediction,
809 | PlaceStructuredFormat,
810 | GooglePlacesAccessibilityLabels,
811 | SuggestionTextProps,
812 | };
813 |
814 | export default GooglePlacesTextInput;
815 |
--------------------------------------------------------------------------------
/.yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs:
--------------------------------------------------------------------------------
1 | /* eslint-disable */
2 | //prettier-ignore
3 | module.exports = {
4 | name: "@yarnpkg/plugin-workspace-tools",
5 | factory: function (require) {
6 | var plugin=(()=>{var yr=Object.create;var we=Object.defineProperty;var _r=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var br=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty;var W=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var q=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Cr=(e,r)=>{for(var t in r)we(e,t,{get:r[t],enumerable:!0})},Je=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Er(r))!xr.call(e,s)&&s!==t&&we(e,s,{get:()=>r[s],enumerable:!(n=_r(r,s))||n.enumerable});return e};var Be=(e,r,t)=>(t=e!=null?yr(br(e)):{},Je(r||!e||!e.__esModule?we(t,"default",{value:e,enumerable:!0}):t,e)),wr=e=>Je(we({},"__esModule",{value:!0}),e);var ve=q(ee=>{"use strict";ee.isInteger=e=>typeof e=="number"?Number.isInteger(e):typeof e=="string"&&e.trim()!==""?Number.isInteger(Number(e)):!1;ee.find=(e,r)=>e.nodes.find(t=>t.type===r);ee.exceedsLimit=(e,r,t=1,n)=>n===!1||!ee.isInteger(e)||!ee.isInteger(r)?!1:(Number(r)-Number(e))/Number(t)>=n;ee.escapeNode=(e,r=0,t)=>{let n=e.nodes[r];!n||(t&&n.type===t||n.type==="open"||n.type==="close")&&n.escaped!==!0&&(n.value="\\"+n.value,n.escaped=!0)};ee.encloseBrace=e=>e.type!=="brace"?!1:e.commas>>0+e.ranges>>0===0?(e.invalid=!0,!0):!1;ee.isInvalidBrace=e=>e.type!=="brace"?!1:e.invalid===!0||e.dollar?!0:e.commas>>0+e.ranges>>0===0||e.open!==!0||e.close!==!0?(e.invalid=!0,!0):!1;ee.isOpenOrClose=e=>e.type==="open"||e.type==="close"?!0:e.open===!0||e.close===!0;ee.reduce=e=>e.reduce((r,t)=>(t.type==="text"&&r.push(t.value),t.type==="range"&&(t.type="text"),r),[]);ee.flatten=(...e)=>{let r=[],t=n=>{for(let s=0;s{"use strict";var tt=ve();rt.exports=(e,r={})=>{let t=(n,s={})=>{let i=r.escapeInvalid&&tt.isInvalidBrace(s),a=n.invalid===!0&&r.escapeInvalid===!0,c="";if(n.value)return(i||a)&&tt.isOpenOrClose(n)?"\\"+n.value:n.value;if(n.value)return n.value;if(n.nodes)for(let p of n.nodes)c+=t(p);return c};return t(e)}});var st=q((Vn,nt)=>{"use strict";nt.exports=function(e){return typeof e=="number"?e-e===0:typeof e=="string"&&e.trim()!==""?Number.isFinite?Number.isFinite(+e):isFinite(+e):!1}});var ht=q((Jn,pt)=>{"use strict";var at=st(),le=(e,r,t)=>{if(at(e)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(r===void 0||e===r)return String(e);if(at(r)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let n={relaxZeros:!0,...t};typeof n.strictZeros=="boolean"&&(n.relaxZeros=n.strictZeros===!1);let s=String(n.relaxZeros),i=String(n.shorthand),a=String(n.capture),c=String(n.wrap),p=e+":"+r+"="+s+i+a+c;if(le.cache.hasOwnProperty(p))return le.cache[p].result;let m=Math.min(e,r),h=Math.max(e,r);if(Math.abs(m-h)===1){let y=e+"|"+r;return n.capture?`(${y})`:n.wrap===!1?y:`(?:${y})`}let R=ft(e)||ft(r),f={min:e,max:r,a:m,b:h},$=[],_=[];if(R&&(f.isPadded=R,f.maxLen=String(f.max).length),m<0){let y=h<0?Math.abs(h):1;_=it(y,Math.abs(m),f,n),m=f.a=0}return h>=0&&($=it(m,h,f,n)),f.negatives=_,f.positives=$,f.result=Sr(_,$,n),n.capture===!0?f.result=`(${f.result})`:n.wrap!==!1&&$.length+_.length>1&&(f.result=`(?:${f.result})`),le.cache[p]=f,f.result};function Sr(e,r,t){let n=Pe(e,r,"-",!1,t)||[],s=Pe(r,e,"",!1,t)||[],i=Pe(e,r,"-?",!0,t)||[];return n.concat(i).concat(s).join("|")}function vr(e,r){let t=1,n=1,s=ut(e,t),i=new Set([r]);for(;e<=s&&s<=r;)i.add(s),t+=1,s=ut(e,t);for(s=ct(r+1,n)-1;e1&&c.count.pop(),c.count.push(h.count[0]),c.string=c.pattern+lt(c.count),a=m+1;continue}t.isPadded&&(R=Lr(m,t,n)),h.string=R+h.pattern+lt(h.count),i.push(h),a=m+1,c=h}return i}function Pe(e,r,t,n,s){let i=[];for(let a of e){let{string:c}=a;!n&&!ot(r,"string",c)&&i.push(t+c),n&&ot(r,"string",c)&&i.push(t+c)}return i}function $r(e,r){let t=[];for(let n=0;nr?1:r>e?-1:0}function ot(e,r,t){return e.some(n=>n[r]===t)}function ut(e,r){return Number(String(e).slice(0,-r)+"9".repeat(r))}function ct(e,r){return e-e%Math.pow(10,r)}function lt(e){let[r=0,t=""]=e;return t||r>1?`{${r+(t?","+t:"")}}`:""}function kr(e,r,t){return`[${e}${r-e===1?"":"-"}${r}]`}function ft(e){return/^-?(0+)\d/.test(e)}function Lr(e,r,t){if(!r.isPadded)return e;let n=Math.abs(r.maxLen-String(e).length),s=t.relaxZeros!==!1;switch(n){case 0:return"";case 1:return s?"0?":"0";case 2:return s?"0{0,2}":"00";default:return s?`0{0,${n}}`:`0{${n}}`}}le.cache={};le.clearCache=()=>le.cache={};pt.exports=le});var Ue=q((es,Et)=>{"use strict";var Or=W("util"),At=ht(),dt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Nr=e=>r=>e===!0?Number(r):String(r),Me=e=>typeof e=="number"||typeof e=="string"&&e!=="",Ae=e=>Number.isInteger(+e),De=e=>{let r=`${e}`,t=-1;if(r[0]==="-"&&(r=r.slice(1)),r==="0")return!1;for(;r[++t]==="0";);return t>0},Ir=(e,r,t)=>typeof e=="string"||typeof r=="string"?!0:t.stringify===!0,Br=(e,r,t)=>{if(r>0){let n=e[0]==="-"?"-":"";n&&(e=e.slice(1)),e=n+e.padStart(n?r-1:r,"0")}return t===!1?String(e):e},gt=(e,r)=>{let t=e[0]==="-"?"-":"";for(t&&(e=e.slice(1),r--);e.length{e.negatives.sort((a,c)=>ac?1:0),e.positives.sort((a,c)=>ac?1:0);let t=r.capture?"":"?:",n="",s="",i;return e.positives.length&&(n=e.positives.join("|")),e.negatives.length&&(s=`-(${t}${e.negatives.join("|")})`),n&&s?i=`${n}|${s}`:i=n||s,r.wrap?`(${t}${i})`:i},mt=(e,r,t,n)=>{if(t)return At(e,r,{wrap:!1,...n});let s=String.fromCharCode(e);if(e===r)return s;let i=String.fromCharCode(r);return`[${s}-${i}]`},Rt=(e,r,t)=>{if(Array.isArray(e)){let n=t.wrap===!0,s=t.capture?"":"?:";return n?`(${s}${e.join("|")})`:e.join("|")}return At(e,r,t)},yt=(...e)=>new RangeError("Invalid range arguments: "+Or.inspect(...e)),_t=(e,r,t)=>{if(t.strictRanges===!0)throw yt([e,r]);return[]},Mr=(e,r)=>{if(r.strictRanges===!0)throw new TypeError(`Expected step "${e}" to be a number`);return[]},Dr=(e,r,t=1,n={})=>{let s=Number(e),i=Number(r);if(!Number.isInteger(s)||!Number.isInteger(i)){if(n.strictRanges===!0)throw yt([e,r]);return[]}s===0&&(s=0),i===0&&(i=0);let a=s>i,c=String(e),p=String(r),m=String(t);t=Math.max(Math.abs(t),1);let h=De(c)||De(p)||De(m),R=h?Math.max(c.length,p.length,m.length):0,f=h===!1&&Ir(e,r,n)===!1,$=n.transform||Nr(f);if(n.toRegex&&t===1)return mt(gt(e,R),gt(r,R),!0,n);let _={negatives:[],positives:[]},y=T=>_[T<0?"negatives":"positives"].push(Math.abs(T)),E=[],S=0;for(;a?s>=i:s<=i;)n.toRegex===!0&&t>1?y(s):E.push(Br($(s,S),R,f)),s=a?s-t:s+t,S++;return n.toRegex===!0?t>1?Pr(_,n):Rt(E,null,{wrap:!1,...n}):E},Ur=(e,r,t=1,n={})=>{if(!Ae(e)&&e.length>1||!Ae(r)&&r.length>1)return _t(e,r,n);let s=n.transform||(f=>String.fromCharCode(f)),i=`${e}`.charCodeAt(0),a=`${r}`.charCodeAt(0),c=i>a,p=Math.min(i,a),m=Math.max(i,a);if(n.toRegex&&t===1)return mt(p,m,!1,n);let h=[],R=0;for(;c?i>=a:i<=a;)h.push(s(i,R)),i=c?i-t:i+t,R++;return n.toRegex===!0?Rt(h,null,{wrap:!1,options:n}):h},$e=(e,r,t,n={})=>{if(r==null&&Me(e))return[e];if(!Me(e)||!Me(r))return _t(e,r,n);if(typeof t=="function")return $e(e,r,1,{transform:t});if(dt(t))return $e(e,r,0,t);let s={...n};return s.capture===!0&&(s.wrap=!0),t=t||s.step||1,Ae(t)?Ae(e)&&Ae(r)?Dr(e,r,t,s):Ur(e,r,Math.max(Math.abs(t),1),s):t!=null&&!dt(t)?Mr(t,s):$e(e,r,1,t)};Et.exports=$e});var Ct=q((ts,xt)=>{"use strict";var Gr=Ue(),bt=ve(),qr=(e,r={})=>{let t=(n,s={})=>{let i=bt.isInvalidBrace(s),a=n.invalid===!0&&r.escapeInvalid===!0,c=i===!0||a===!0,p=r.escapeInvalid===!0?"\\":"",m="";if(n.isOpen===!0||n.isClose===!0)return p+n.value;if(n.type==="open")return c?p+n.value:"(";if(n.type==="close")return c?p+n.value:")";if(n.type==="comma")return n.prev.type==="comma"?"":c?n.value:"|";if(n.value)return n.value;if(n.nodes&&n.ranges>0){let h=bt.reduce(n.nodes),R=Gr(...h,{...r,wrap:!1,toRegex:!0});if(R.length!==0)return h.length>1&&R.length>1?`(${R})`:R}if(n.nodes)for(let h of n.nodes)m+=t(h,n);return m};return t(e)};xt.exports=qr});var vt=q((rs,St)=>{"use strict";var Kr=Ue(),wt=He(),he=ve(),fe=(e="",r="",t=!1)=>{let n=[];if(e=[].concat(e),r=[].concat(r),!r.length)return e;if(!e.length)return t?he.flatten(r).map(s=>`{${s}}`):r;for(let s of e)if(Array.isArray(s))for(let i of s)n.push(fe(i,r,t));else for(let i of r)t===!0&&typeof i=="string"&&(i=`{${i}}`),n.push(Array.isArray(i)?fe(s,i,t):s+i);return he.flatten(n)},Wr=(e,r={})=>{let t=r.rangeLimit===void 0?1e3:r.rangeLimit,n=(s,i={})=>{s.queue=[];let a=i,c=i.queue;for(;a.type!=="brace"&&a.type!=="root"&&a.parent;)a=a.parent,c=a.queue;if(s.invalid||s.dollar){c.push(fe(c.pop(),wt(s,r)));return}if(s.type==="brace"&&s.invalid!==!0&&s.nodes.length===2){c.push(fe(c.pop(),["{}"]));return}if(s.nodes&&s.ranges>0){let R=he.reduce(s.nodes);if(he.exceedsLimit(...R,r.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let f=Kr(...R,r);f.length===0&&(f=wt(s,r)),c.push(fe(c.pop(),f)),s.nodes=[];return}let p=he.encloseBrace(s),m=s.queue,h=s;for(;h.type!=="brace"&&h.type!=="root"&&h.parent;)h=h.parent,m=h.queue;for(let R=0;R{"use strict";Ht.exports={MAX_LENGTH:1024*64,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
7 | `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var Nt=q((ss,Ot)=>{"use strict";var jr=He(),{MAX_LENGTH:Tt,CHAR_BACKSLASH:Ge,CHAR_BACKTICK:Fr,CHAR_COMMA:Qr,CHAR_DOT:Xr,CHAR_LEFT_PARENTHESES:Zr,CHAR_RIGHT_PARENTHESES:Yr,CHAR_LEFT_CURLY_BRACE:zr,CHAR_RIGHT_CURLY_BRACE:Vr,CHAR_LEFT_SQUARE_BRACKET:kt,CHAR_RIGHT_SQUARE_BRACKET:Lt,CHAR_DOUBLE_QUOTE:Jr,CHAR_SINGLE_QUOTE:en,CHAR_NO_BREAK_SPACE:tn,CHAR_ZERO_WIDTH_NOBREAK_SPACE:rn}=$t(),nn=(e,r={})=>{if(typeof e!="string")throw new TypeError("Expected a string");let t=r||{},n=typeof t.maxLength=="number"?Math.min(Tt,t.maxLength):Tt;if(e.length>n)throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${n})`);let s={type:"root",input:e,nodes:[]},i=[s],a=s,c=s,p=0,m=e.length,h=0,R=0,f,$={},_=()=>e[h++],y=E=>{if(E.type==="text"&&c.type==="dot"&&(c.type="text"),c&&c.type==="text"&&E.type==="text"){c.value+=E.value;return}return a.nodes.push(E),E.parent=a,E.prev=c,c=E,E};for(y({type:"bos"});h0){if(a.ranges>0){a.ranges=0;let E=a.nodes.shift();a.nodes=[E,{type:"text",value:jr(a)}]}y({type:"comma",value:f}),a.commas++;continue}if(f===Xr&&R>0&&a.commas===0){let E=a.nodes;if(R===0||E.length===0){y({type:"text",value:f});continue}if(c.type==="dot"){if(a.range=[],c.value+=f,c.type="range",a.nodes.length!==3&&a.nodes.length!==5){a.invalid=!0,a.ranges=0,c.type="text";continue}a.ranges++,a.args=[];continue}if(c.type==="range"){E.pop();let S=E[E.length-1];S.value+=c.value+f,c=S,a.ranges--;continue}y({type:"dot",value:f});continue}y({type:"text",value:f})}do if(a=i.pop(),a.type!=="root"){a.nodes.forEach(T=>{T.nodes||(T.type==="open"&&(T.isOpen=!0),T.type==="close"&&(T.isClose=!0),T.nodes||(T.type="text"),T.invalid=!0)});let E=i[i.length-1],S=E.nodes.indexOf(a);E.nodes.splice(S,1,...a.nodes)}while(i.length>0);return y({type:"eos"}),s};Ot.exports=nn});var Pt=q((as,Bt)=>{"use strict";var It=He(),sn=Ct(),an=vt(),on=Nt(),Z=(e,r={})=>{let t=[];if(Array.isArray(e))for(let n of e){let s=Z.create(n,r);Array.isArray(s)?t.push(...s):t.push(s)}else t=[].concat(Z.create(e,r));return r&&r.expand===!0&&r.nodupes===!0&&(t=[...new Set(t)]),t};Z.parse=(e,r={})=>on(e,r);Z.stringify=(e,r={})=>It(typeof e=="string"?Z.parse(e,r):e,r);Z.compile=(e,r={})=>(typeof e=="string"&&(e=Z.parse(e,r)),sn(e,r));Z.expand=(e,r={})=>{typeof e=="string"&&(e=Z.parse(e,r));let t=an(e,r);return r.noempty===!0&&(t=t.filter(Boolean)),r.nodupes===!0&&(t=[...new Set(t)]),t};Z.create=(e,r={})=>e===""||e.length<3?[e]:r.expand!==!0?Z.compile(e,r):Z.expand(e,r);Bt.exports=Z});var me=q((is,qt)=>{"use strict";var un=W("path"),se="\\\\/",Mt=`[^${se}]`,ie="\\.",cn="\\+",ln="\\?",Te="\\/",fn="(?=.)",Dt="[^/]",qe=`(?:${Te}|$)`,Ut=`(?:^|${Te})`,Ke=`${ie}{1,2}${qe}`,pn=`(?!${ie})`,hn=`(?!${Ut}${Ke})`,dn=`(?!${ie}{0,1}${qe})`,gn=`(?!${Ke})`,An=`[^.${Te}]`,mn=`${Dt}*?`,Gt={DOT_LITERAL:ie,PLUS_LITERAL:cn,QMARK_LITERAL:ln,SLASH_LITERAL:Te,ONE_CHAR:fn,QMARK:Dt,END_ANCHOR:qe,DOTS_SLASH:Ke,NO_DOT:pn,NO_DOTS:hn,NO_DOT_SLASH:dn,NO_DOTS_SLASH:gn,QMARK_NO_DOT:An,STAR:mn,START_ANCHOR:Ut},Rn={...Gt,SLASH_LITERAL:`[${se}]`,QMARK:Mt,STAR:`${Mt}*?`,DOTS_SLASH:`${ie}{1,2}(?:[${se}]|$)`,NO_DOT:`(?!${ie})`,NO_DOTS:`(?!(?:^|[${se}])${ie}{1,2}(?:[${se}]|$))`,NO_DOT_SLASH:`(?!${ie}{0,1}(?:[${se}]|$))`,NO_DOTS_SLASH:`(?!${ie}{1,2}(?:[${se}]|$))`,QMARK_NO_DOT:`[^.${se}]`,START_ANCHOR:`(?:^|[${se}])`,END_ANCHOR:`(?:[${se}]|$)`},yn={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};qt.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:yn,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:un.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===!0?Rn:Gt}}});var Re=q(Q=>{"use strict";var _n=W("path"),En=process.platform==="win32",{REGEX_BACKSLASH:bn,REGEX_REMOVE_BACKSLASH:xn,REGEX_SPECIAL_CHARS:Cn,REGEX_SPECIAL_CHARS_GLOBAL:wn}=me();Q.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Q.hasRegexChars=e=>Cn.test(e);Q.isRegexChar=e=>e.length===1&&Q.hasRegexChars(e);Q.escapeRegex=e=>e.replace(wn,"\\$1");Q.toPosixSlashes=e=>e.replace(bn,"/");Q.removeBackslashes=e=>e.replace(xn,r=>r==="\\"?"":r);Q.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".").map(Number);return e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10};Q.isWindows=e=>e&&typeof e.windows=="boolean"?e.windows:En===!0||_n.sep==="\\";Q.escapeLast=(e,r,t)=>{let n=e.lastIndexOf(r,t);return n===-1?e:e[n-1]==="\\"?Q.escapeLast(e,r,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Q.removePrefix=(e,r={})=>{let t=e;return t.startsWith("./")&&(t=t.slice(2),r.prefix="./"),t};Q.wrapOutput=(e,r={},t={})=>{let n=t.contains?"":"^",s=t.contains?"":"$",i=`${n}(?:${e})${s}`;return r.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var Yt=q((us,Zt)=>{"use strict";var Kt=Re(),{CHAR_ASTERISK:We,CHAR_AT:Sn,CHAR_BACKWARD_SLASH:ye,CHAR_COMMA:vn,CHAR_DOT:je,CHAR_EXCLAMATION_MARK:Fe,CHAR_FORWARD_SLASH:Xt,CHAR_LEFT_CURLY_BRACE:Qe,CHAR_LEFT_PARENTHESES:Xe,CHAR_LEFT_SQUARE_BRACKET:Hn,CHAR_PLUS:$n,CHAR_QUESTION_MARK:Wt,CHAR_RIGHT_CURLY_BRACE:Tn,CHAR_RIGHT_PARENTHESES:jt,CHAR_RIGHT_SQUARE_BRACKET:kn}=me(),Ft=e=>e===Xt||e===ye,Qt=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)},Ln=(e,r)=>{let t=r||{},n=e.length-1,s=t.parts===!0||t.scanToEnd===!0,i=[],a=[],c=[],p=e,m=-1,h=0,R=0,f=!1,$=!1,_=!1,y=!1,E=!1,S=!1,T=!1,L=!1,z=!1,I=!1,re=0,K,g,v={value:"",depth:0,isGlob:!1},k=()=>m>=n,l=()=>p.charCodeAt(m+1),H=()=>(K=g,p.charCodeAt(++m));for(;m0&&(B=p.slice(0,h),p=p.slice(h),R-=h),w&&_===!0&&R>0?(w=p.slice(0,R),o=p.slice(R)):_===!0?(w="",o=p):w=p,w&&w!==""&&w!=="/"&&w!==p&&Ft(w.charCodeAt(w.length-1))&&(w=w.slice(0,-1)),t.unescape===!0&&(o&&(o=Kt.removeBackslashes(o)),w&&T===!0&&(w=Kt.removeBackslashes(w)));let u={prefix:B,input:e,start:h,base:w,glob:o,isBrace:f,isBracket:$,isGlob:_,isExtglob:y,isGlobstar:E,negated:L,negatedExtglob:z};if(t.tokens===!0&&(u.maxDepth=0,Ft(g)||a.push(v),u.tokens=a),t.parts===!0||t.tokens===!0){let P;for(let b=0;b{"use strict";var ke=me(),Y=Re(),{MAX_LENGTH:Le,POSIX_REGEX_SOURCE:On,REGEX_NON_SPECIAL_CHARS:Nn,REGEX_SPECIAL_CHARS_BACKREF:In,REPLACEMENTS:zt}=ke,Bn=(e,r)=>{if(typeof r.expandRange=="function")return r.expandRange(...e,r);e.sort();let t=`[${e.join("-")}]`;try{new RegExp(t)}catch{return e.map(s=>Y.escapeRegex(s)).join("..")}return t},de=(e,r)=>`Missing ${e}: "${r}" - use "\\\\${r}" to match literal characters`,Vt=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=zt[e]||e;let t={...r},n=typeof t.maxLength=="number"?Math.min(Le,t.maxLength):Le,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:t.prepend||""},a=[i],c=t.capture?"":"?:",p=Y.isWindows(r),m=ke.globChars(p),h=ke.extglobChars(m),{DOT_LITERAL:R,PLUS_LITERAL:f,SLASH_LITERAL:$,ONE_CHAR:_,DOTS_SLASH:y,NO_DOT:E,NO_DOT_SLASH:S,NO_DOTS_SLASH:T,QMARK:L,QMARK_NO_DOT:z,STAR:I,START_ANCHOR:re}=m,K=A=>`(${c}(?:(?!${re}${A.dot?y:R}).)*?)`,g=t.dot?"":E,v=t.dot?L:z,k=t.bash===!0?K(t):I;t.capture&&(k=`(${k})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let l={input:e,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:a};e=Y.removePrefix(e,l),s=e.length;let H=[],w=[],B=[],o=i,u,P=()=>l.index===s-1,b=l.peek=(A=1)=>e[l.index+A],V=l.advance=()=>e[++l.index]||"",J=()=>e.slice(l.index+1),X=(A="",O=0)=>{l.consumed+=A,l.index+=O},Ee=A=>{l.output+=A.output!=null?A.output:A.value,X(A.value)},mr=()=>{let A=1;for(;b()==="!"&&(b(2)!=="("||b(3)==="?");)V(),l.start++,A++;return A%2===0?!1:(l.negated=!0,l.start++,!0)},be=A=>{l[A]++,B.push(A)},oe=A=>{l[A]--,B.pop()},C=A=>{if(o.type==="globstar"){let O=l.braces>0&&(A.type==="comma"||A.type==="brace"),d=A.extglob===!0||H.length&&(A.type==="pipe"||A.type==="paren");A.type!=="slash"&&A.type!=="paren"&&!O&&!d&&(l.output=l.output.slice(0,-o.output.length),o.type="star",o.value="*",o.output=k,l.output+=o.output)}if(H.length&&A.type!=="paren"&&(H[H.length-1].inner+=A.value),(A.value||A.output)&&Ee(A),o&&o.type==="text"&&A.type==="text"){o.value+=A.value,o.output=(o.output||"")+A.value;return}A.prev=o,a.push(A),o=A},xe=(A,O)=>{let d={...h[O],conditions:1,inner:""};d.prev=o,d.parens=l.parens,d.output=l.output;let x=(t.capture?"(":"")+d.open;be("parens"),C({type:A,value:O,output:l.output?"":_}),C({type:"paren",extglob:!0,value:V(),output:x}),H.push(d)},Rr=A=>{let O=A.close+(t.capture?")":""),d;if(A.type==="negate"){let x=k;A.inner&&A.inner.length>1&&A.inner.includes("/")&&(x=K(t)),(x!==k||P()||/^\)+$/.test(J()))&&(O=A.close=`)$))${x}`),A.inner.includes("*")&&(d=J())&&/^\.[^\\/.]+$/.test(d)&&(O=A.close=`)${d})${x})`),A.prev.type==="bos"&&(l.negatedExtglob=!0)}C({type:"paren",extglob:!0,value:u,output:O}),oe("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let A=!1,O=e.replace(In,(d,x,M,j,G,Ie)=>j==="\\"?(A=!0,d):j==="?"?x?x+j+(G?L.repeat(G.length):""):Ie===0?v+(G?L.repeat(G.length):""):L.repeat(M.length):j==="."?R.repeat(M.length):j==="*"?x?x+j+(G?k:""):k:x?d:`\\${d}`);return A===!0&&(t.unescape===!0?O=O.replace(/\\/g,""):O=O.replace(/\\+/g,d=>d.length%2===0?"\\\\":d?"\\":"")),O===e&&t.contains===!0?(l.output=e,l):(l.output=Y.wrapOutput(O,l,r),l)}for(;!P();){if(u=V(),u==="\0")continue;if(u==="\\"){let d=b();if(d==="/"&&t.bash!==!0||d==="."||d===";")continue;if(!d){u+="\\",C({type:"text",value:u});continue}let x=/^\\+/.exec(J()),M=0;if(x&&x[0].length>2&&(M=x[0].length,l.index+=M,M%2!==0&&(u+="\\")),t.unescape===!0?u=V():u+=V(),l.brackets===0){C({type:"text",value:u});continue}}if(l.brackets>0&&(u!=="]"||o.value==="["||o.value==="[^")){if(t.posix!==!1&&u===":"){let d=o.value.slice(1);if(d.includes("[")&&(o.posix=!0,d.includes(":"))){let x=o.value.lastIndexOf("["),M=o.value.slice(0,x),j=o.value.slice(x+2),G=On[j];if(G){o.value=M+G,l.backtrack=!0,V(),!i.output&&a.indexOf(o)===1&&(i.output=_);continue}}}(u==="["&&b()!==":"||u==="-"&&b()==="]")&&(u=`\\${u}`),u==="]"&&(o.value==="["||o.value==="[^")&&(u=`\\${u}`),t.posix===!0&&u==="!"&&o.value==="["&&(u="^"),o.value+=u,Ee({value:u});continue}if(l.quotes===1&&u!=='"'){u=Y.escapeRegex(u),o.value+=u,Ee({value:u});continue}if(u==='"'){l.quotes=l.quotes===1?0:1,t.keepQuotes===!0&&C({type:"text",value:u});continue}if(u==="("){be("parens"),C({type:"paren",value:u});continue}if(u===")"){if(l.parens===0&&t.strictBrackets===!0)throw new SyntaxError(de("opening","("));let d=H[H.length-1];if(d&&l.parens===d.parens+1){Rr(H.pop());continue}C({type:"paren",value:u,output:l.parens?")":"\\)"}),oe("parens");continue}if(u==="["){if(t.nobracket===!0||!J().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(de("closing","]"));u=`\\${u}`}else be("brackets");C({type:"bracket",value:u});continue}if(u==="]"){if(t.nobracket===!0||o&&o.type==="bracket"&&o.value.length===1){C({type:"text",value:u,output:`\\${u}`});continue}if(l.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(de("opening","["));C({type:"text",value:u,output:`\\${u}`});continue}oe("brackets");let d=o.value.slice(1);if(o.posix!==!0&&d[0]==="^"&&!d.includes("/")&&(u=`/${u}`),o.value+=u,Ee({value:u}),t.literalBrackets===!1||Y.hasRegexChars(d))continue;let x=Y.escapeRegex(o.value);if(l.output=l.output.slice(0,-o.value.length),t.literalBrackets===!0){l.output+=x,o.value=x;continue}o.value=`(${c}${x}|${o.value})`,l.output+=o.value;continue}if(u==="{"&&t.nobrace!==!0){be("braces");let d={type:"brace",value:u,output:"(",outputIndex:l.output.length,tokensIndex:l.tokens.length};w.push(d),C(d);continue}if(u==="}"){let d=w[w.length-1];if(t.nobrace===!0||!d){C({type:"text",value:u,output:u});continue}let x=")";if(d.dots===!0){let M=a.slice(),j=[];for(let G=M.length-1;G>=0&&(a.pop(),M[G].type!=="brace");G--)M[G].type!=="dots"&&j.unshift(M[G].value);x=Bn(j,t),l.backtrack=!0}if(d.comma!==!0&&d.dots!==!0){let M=l.output.slice(0,d.outputIndex),j=l.tokens.slice(d.tokensIndex);d.value=d.output="\\{",u=x="\\}",l.output=M;for(let G of j)l.output+=G.output||G.value}C({type:"brace",value:u,output:x}),oe("braces"),w.pop();continue}if(u==="|"){H.length>0&&H[H.length-1].conditions++,C({type:"text",value:u});continue}if(u===","){let d=u,x=w[w.length-1];x&&B[B.length-1]==="braces"&&(x.comma=!0,d="|"),C({type:"comma",value:u,output:d});continue}if(u==="/"){if(o.type==="dot"&&l.index===l.start+1){l.start=l.index+1,l.consumed="",l.output="",a.pop(),o=i;continue}C({type:"slash",value:u,output:$});continue}if(u==="."){if(l.braces>0&&o.type==="dot"){o.value==="."&&(o.output=R);let d=w[w.length-1];o.type="dots",o.output+=u,o.value+=u,d.dots=!0;continue}if(l.braces+l.parens===0&&o.type!=="bos"&&o.type!=="slash"){C({type:"text",value:u,output:R});continue}C({type:"dot",value:u,output:R});continue}if(u==="?"){if(!(o&&o.value==="(")&&t.noextglob!==!0&&b()==="("&&b(2)!=="?"){xe("qmark",u);continue}if(o&&o.type==="paren"){let x=b(),M=u;if(x==="<"&&!Y.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(o.value==="("&&!/[!=<:]/.test(x)||x==="<"&&!/<([!=]|\w+>)/.test(J()))&&(M=`\\${u}`),C({type:"text",value:u,output:M});continue}if(t.dot!==!0&&(o.type==="slash"||o.type==="bos")){C({type:"qmark",value:u,output:z});continue}C({type:"qmark",value:u,output:L});continue}if(u==="!"){if(t.noextglob!==!0&&b()==="("&&(b(2)!=="?"||!/[!=<:]/.test(b(3)))){xe("negate",u);continue}if(t.nonegate!==!0&&l.index===0){mr();continue}}if(u==="+"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){xe("plus",u);continue}if(o&&o.value==="("||t.regex===!1){C({type:"plus",value:u,output:f});continue}if(o&&(o.type==="bracket"||o.type==="paren"||o.type==="brace")||l.parens>0){C({type:"plus",value:u});continue}C({type:"plus",value:f});continue}if(u==="@"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){C({type:"at",extglob:!0,value:u,output:""});continue}C({type:"text",value:u});continue}if(u!=="*"){(u==="$"||u==="^")&&(u=`\\${u}`);let d=Nn.exec(J());d&&(u+=d[0],l.index+=d[0].length),C({type:"text",value:u});continue}if(o&&(o.type==="globstar"||o.star===!0)){o.type="star",o.star=!0,o.value+=u,o.output=k,l.backtrack=!0,l.globstar=!0,X(u);continue}let A=J();if(t.noextglob!==!0&&/^\([^?]/.test(A)){xe("star",u);continue}if(o.type==="star"){if(t.noglobstar===!0){X(u);continue}let d=o.prev,x=d.prev,M=d.type==="slash"||d.type==="bos",j=x&&(x.type==="star"||x.type==="globstar");if(t.bash===!0&&(!M||A[0]&&A[0]!=="/")){C({type:"star",value:u,output:""});continue}let G=l.braces>0&&(d.type==="comma"||d.type==="brace"),Ie=H.length&&(d.type==="pipe"||d.type==="paren");if(!M&&d.type!=="paren"&&!G&&!Ie){C({type:"star",value:u,output:""});continue}for(;A.slice(0,3)==="/**";){let Ce=e[l.index+4];if(Ce&&Ce!=="/")break;A=A.slice(3),X("/**",3)}if(d.type==="bos"&&P()){o.type="globstar",o.value+=u,o.output=K(t),l.output=o.output,l.globstar=!0,X(u);continue}if(d.type==="slash"&&d.prev.type!=="bos"&&!j&&P()){l.output=l.output.slice(0,-(d.output+o.output).length),d.output=`(?:${d.output}`,o.type="globstar",o.output=K(t)+(t.strictSlashes?")":"|$)"),o.value+=u,l.globstar=!0,l.output+=d.output+o.output,X(u);continue}if(d.type==="slash"&&d.prev.type!=="bos"&&A[0]==="/"){let Ce=A[1]!==void 0?"|$":"";l.output=l.output.slice(0,-(d.output+o.output).length),d.output=`(?:${d.output}`,o.type="globstar",o.output=`${K(t)}${$}|${$}${Ce})`,o.value+=u,l.output+=d.output+o.output,l.globstar=!0,X(u+V()),C({type:"slash",value:"/",output:""});continue}if(d.type==="bos"&&A[0]==="/"){o.type="globstar",o.value+=u,o.output=`(?:^|${$}|${K(t)}${$})`,l.output=o.output,l.globstar=!0,X(u+V()),C({type:"slash",value:"/",output:""});continue}l.output=l.output.slice(0,-o.output.length),o.type="globstar",o.output=K(t),o.value+=u,l.output+=o.output,l.globstar=!0,X(u);continue}let O={type:"star",value:u,output:k};if(t.bash===!0){O.output=".*?",(o.type==="bos"||o.type==="slash")&&(O.output=g+O.output),C(O);continue}if(o&&(o.type==="bracket"||o.type==="paren")&&t.regex===!0){O.output=u,C(O);continue}(l.index===l.start||o.type==="slash"||o.type==="dot")&&(o.type==="dot"?(l.output+=S,o.output+=S):t.dot===!0?(l.output+=T,o.output+=T):(l.output+=g,o.output+=g),b()!=="*"&&(l.output+=_,o.output+=_)),C(O)}for(;l.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing","]"));l.output=Y.escapeLast(l.output,"["),oe("brackets")}for(;l.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing",")"));l.output=Y.escapeLast(l.output,"("),oe("parens")}for(;l.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing","}"));l.output=Y.escapeLast(l.output,"{"),oe("braces")}if(t.strictSlashes!==!0&&(o.type==="star"||o.type==="bracket")&&C({type:"maybe_slash",value:"",output:`${$}?`}),l.backtrack===!0){l.output="";for(let A of l.tokens)l.output+=A.output!=null?A.output:A.value,A.suffix&&(l.output+=A.suffix)}return l};Vt.fastpaths=(e,r)=>{let t={...r},n=typeof t.maxLength=="number"?Math.min(Le,t.maxLength):Le,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=zt[e]||e;let i=Y.isWindows(r),{DOT_LITERAL:a,SLASH_LITERAL:c,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOTS:R,NO_DOTS_SLASH:f,STAR:$,START_ANCHOR:_}=ke.globChars(i),y=t.dot?R:h,E=t.dot?f:h,S=t.capture?"":"?:",T={negated:!1,prefix:""},L=t.bash===!0?".*?":$;t.capture&&(L=`(${L})`);let z=g=>g.noglobstar===!0?L:`(${S}(?:(?!${_}${g.dot?m:a}).)*?)`,I=g=>{switch(g){case"*":return`${y}${p}${L}`;case".*":return`${a}${p}${L}`;case"*.*":return`${y}${L}${a}${p}${L}`;case"*/*":return`${y}${L}${c}${p}${E}${L}`;case"**":return y+z(t);case"**/*":return`(?:${y}${z(t)}${c})?${E}${p}${L}`;case"**/*.*":return`(?:${y}${z(t)}${c})?${E}${L}${a}${p}${L}`;case"**/.*":return`(?:${y}${z(t)}${c})?${a}${p}${L}`;default:{let v=/^(.*?)\.(\w+)$/.exec(g);if(!v)return;let k=I(v[1]);return k?k+a+v[2]:void 0}}},re=Y.removePrefix(e,T),K=I(re);return K&&t.strictSlashes!==!0&&(K+=`${c}?`),K};Jt.exports=Vt});var rr=q((ls,tr)=>{"use strict";var Pn=W("path"),Mn=Yt(),Ze=er(),Ye=Re(),Dn=me(),Un=e=>e&&typeof e=="object"&&!Array.isArray(e),D=(e,r,t=!1)=>{if(Array.isArray(e)){let h=e.map(f=>D(f,r,t));return f=>{for(let $ of h){let _=$(f);if(_)return _}return!1}}let n=Un(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=r||{},i=Ye.isWindows(r),a=n?D.compileRe(e,r):D.makeRe(e,r,!1,!0),c=a.state;delete a.state;let p=()=>!1;if(s.ignore){let h={...r,ignore:null,onMatch:null,onResult:null};p=D(s.ignore,h,t)}let m=(h,R=!1)=>{let{isMatch:f,match:$,output:_}=D.test(h,a,r,{glob:e,posix:i}),y={glob:e,state:c,regex:a,posix:i,input:h,output:_,match:$,isMatch:f};return typeof s.onResult=="function"&&s.onResult(y),f===!1?(y.isMatch=!1,R?y:!1):p(h)?(typeof s.onIgnore=="function"&&s.onIgnore(y),y.isMatch=!1,R?y:!1):(typeof s.onMatch=="function"&&s.onMatch(y),R?y:!0)};return t&&(m.state=c),m};D.test=(e,r,t,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return{isMatch:!1,output:""};let i=t||{},a=i.format||(s?Ye.toPosixSlashes:null),c=e===n,p=c&&a?a(e):e;return c===!1&&(p=a?a(e):e,c=p===n),(c===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?c=D.matchBase(e,r,t,s):c=r.exec(p)),{isMatch:Boolean(c),match:c,output:p}};D.matchBase=(e,r,t,n=Ye.isWindows(t))=>(r instanceof RegExp?r:D.makeRe(r,t)).test(Pn.basename(e));D.isMatch=(e,r,t)=>D(r,t)(e);D.parse=(e,r)=>Array.isArray(e)?e.map(t=>D.parse(t,r)):Ze(e,{...r,fastpaths:!1});D.scan=(e,r)=>Mn(e,r);D.compileRe=(e,r,t=!1,n=!1)=>{if(t===!0)return e.output;let s=r||{},i=s.contains?"":"^",a=s.contains?"":"$",c=`${i}(?:${e.output})${a}`;e&&e.negated===!0&&(c=`^(?!${c}).*$`);let p=D.toRegex(c,r);return n===!0&&(p.state=e),p};D.makeRe=(e,r={},t=!1,n=!1)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return r.fastpaths!==!1&&(e[0]==="."||e[0]==="*")&&(s.output=Ze.fastpaths(e,r)),s.output||(s=Ze(e,r)),D.compileRe(s,r,t,n)};D.toRegex=(e,r)=>{try{let t=r||{};return new RegExp(e,t.flags||(t.nocase?"i":""))}catch(t){if(r&&r.debug===!0)throw t;return/$^/}};D.constants=Dn;tr.exports=D});var sr=q((fs,nr)=>{"use strict";nr.exports=rr()});var cr=q((ps,ur)=>{"use strict";var ir=W("util"),or=Pt(),ae=sr(),ze=Re(),ar=e=>e===""||e==="./",N=(e,r,t)=>{r=[].concat(r),e=[].concat(e);let n=new Set,s=new Set,i=new Set,a=0,c=h=>{i.add(h.output),t&&t.onResult&&t.onResult(h)};for(let h=0;h!n.has(h));if(t&&m.length===0){if(t.failglob===!0)throw new Error(`No matches found for "${r.join(", ")}"`);if(t.nonull===!0||t.nullglob===!0)return t.unescape?r.map(h=>h.replace(/\\/g,"")):r}return m};N.match=N;N.matcher=(e,r)=>ae(e,r);N.isMatch=(e,r,t)=>ae(r,t)(e);N.any=N.isMatch;N.not=(e,r,t={})=>{r=[].concat(r).map(String);let n=new Set,s=[],a=N(e,r,{...t,onResult:c=>{t.onResult&&t.onResult(c),s.push(c.output)}});for(let c of s)a.includes(c)||n.add(c);return[...n]};N.contains=(e,r,t)=>{if(typeof e!="string")throw new TypeError(`Expected a string: "${ir.inspect(e)}"`);if(Array.isArray(r))return r.some(n=>N.contains(e,n,t));if(typeof r=="string"){if(ar(e)||ar(r))return!1;if(e.includes(r)||e.startsWith("./")&&e.slice(2).includes(r))return!0}return N.isMatch(e,r,{...t,contains:!0})};N.matchKeys=(e,r,t)=>{if(!ze.isObject(e))throw new TypeError("Expected the first argument to be an object");let n=N(Object.keys(e),r,t),s={};for(let i of n)s[i]=e[i];return s};N.some=(e,r,t)=>{let n=[].concat(e);for(let s of[].concat(r)){let i=ae(String(s),t);if(n.some(a=>i(a)))return!0}return!1};N.every=(e,r,t)=>{let n=[].concat(e);for(let s of[].concat(r)){let i=ae(String(s),t);if(!n.every(a=>i(a)))return!1}return!0};N.all=(e,r,t)=>{if(typeof e!="string")throw new TypeError(`Expected a string: "${ir.inspect(e)}"`);return[].concat(r).every(n=>ae(n,t)(e))};N.capture=(e,r,t)=>{let n=ze.isWindows(t),i=ae.makeRe(String(e),{...t,capture:!0}).exec(n?ze.toPosixSlashes(r):r);if(i)return i.slice(1).map(a=>a===void 0?"":a)};N.makeRe=(...e)=>ae.makeRe(...e);N.scan=(...e)=>ae.scan(...e);N.parse=(e,r)=>{let t=[];for(let n of[].concat(e||[]))for(let s of or(String(n),r))t.push(ae.parse(s,r));return t};N.braces=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");return r&&r.nobrace===!0||!/\{.*\}/.test(e)?[e]:or(e,r)};N.braceExpand=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");return N.braces(e,{...r,expand:!0})};ur.exports=N});var fr=q((hs,lr)=>{"use strict";lr.exports=(e,...r)=>new Promise(t=>{t(e(...r))})});var hr=q((ds,Ve)=>{"use strict";var Gn=fr(),pr=e=>{if(e<1)throw new TypeError("Expected `concurrency` to be a number from 1 and up");let r=[],t=0,n=()=>{t--,r.length>0&&r.shift()()},s=(c,p,...m)=>{t++;let h=Gn(c,...m);p(h),h.then(n,n)},i=(c,p,...m)=>{tnew Promise(m=>i(c,m,...p));return Object.defineProperties(a,{activeCount:{get:()=>t},pendingCount:{get:()=>r.length}}),a};Ve.exports=pr;Ve.exports.default=pr});var jn={};Cr(jn,{default:()=>Wn});var Se=W("@yarnpkg/cli"),ne=W("@yarnpkg/core"),et=W("@yarnpkg/core"),ue=W("clipanion"),ce=class extends Se.BaseCommand{constructor(){super(...arguments);this.json=ue.Option.Boolean("--json",!1,{description:"Format the output as an NDJSON stream"});this.production=ue.Option.Boolean("--production",!1,{description:"Only install regular dependencies by omitting dev dependencies"});this.all=ue.Option.Boolean("-A,--all",!1,{description:"Install the entire project"});this.workspaces=ue.Option.Rest()}async execute(){let t=await ne.Configuration.find(this.context.cwd,this.context.plugins),{project:n,workspace:s}=await ne.Project.find(t,this.context.cwd),i=await ne.Cache.find(t);await n.restoreInstallState({restoreResolutions:!1});let a;if(this.all)a=new Set(n.workspaces);else if(this.workspaces.length===0){if(!s)throw new Se.WorkspaceRequiredError(n.cwd,this.context.cwd);a=new Set([s])}else a=new Set(this.workspaces.map(p=>n.getWorkspaceByIdent(et.structUtils.parseIdent(p))));for(let p of a)for(let m of this.production?["dependencies"]:ne.Manifest.hardDependencies)for(let h of p.manifest.getForScope(m).values()){let R=n.tryWorkspaceByDescriptor(h);R!==null&&a.add(R)}for(let p of n.workspaces)a.has(p)?this.production&&p.manifest.devDependencies.clear():(p.manifest.installConfig=p.manifest.installConfig||{},p.manifest.installConfig.selfReferences=!1,p.manifest.dependencies.clear(),p.manifest.devDependencies.clear(),p.manifest.peerDependencies.clear(),p.manifest.scripts.clear());return(await ne.StreamReport.start({configuration:t,json:this.json,stdout:this.context.stdout,includeLogs:!0},async p=>{await n.install({cache:i,report:p,persistProject:!1})})).exitCode()}};ce.paths=[["workspaces","focus"]],ce.usage=ue.Command.Usage({category:"Workspace-related commands",description:"install a single workspace and its dependencies",details:"\n This command will run an install as if the specified workspaces (and all other workspaces they depend on) were the only ones in the project. If no workspaces are explicitly listed, the active one will be assumed.\n\n Note that this command is only very moderately useful when using zero-installs, since the cache will contain all the packages anyway - meaning that the only difference between a full install and a focused install would just be a few extra lines in the `.pnp.cjs` file, at the cost of introducing an extra complexity.\n\n If the `-A,--all` flag is set, the entire project will be installed. Combine with `--production` to replicate the old `yarn install --production`.\n "});var Ne=W("@yarnpkg/cli"),ge=W("@yarnpkg/core"),_e=W("@yarnpkg/core"),F=W("@yarnpkg/core"),gr=W("@yarnpkg/plugin-git"),U=W("clipanion"),Oe=Be(cr()),Ar=Be(hr()),te=Be(W("typanion")),pe=class extends Ne.BaseCommand{constructor(){super(...arguments);this.recursive=U.Option.Boolean("-R,--recursive",!1,{description:"Find packages via dependencies/devDependencies instead of using the workspaces field"});this.from=U.Option.Array("--from",[],{description:"An array of glob pattern idents from which to base any recursion"});this.all=U.Option.Boolean("-A,--all",!1,{description:"Run the command on all workspaces of a project"});this.verbose=U.Option.Boolean("-v,--verbose",!1,{description:"Prefix each output line with the name of the originating workspace"});this.parallel=U.Option.Boolean("-p,--parallel",!1,{description:"Run the commands in parallel"});this.interlaced=U.Option.Boolean("-i,--interlaced",!1,{description:"Print the output of commands in real-time instead of buffering it"});this.jobs=U.Option.String("-j,--jobs",{description:"The maximum number of parallel tasks that the execution will be limited to; or `unlimited`",validator:te.isOneOf([te.isEnum(["unlimited"]),te.applyCascade(te.isNumber(),[te.isInteger(),te.isAtLeast(1)])])});this.topological=U.Option.Boolean("-t,--topological",!1,{description:"Run the command after all workspaces it depends on (regular) have finished"});this.topologicalDev=U.Option.Boolean("--topological-dev",!1,{description:"Run the command after all workspaces it depends on (regular + dev) have finished"});this.include=U.Option.Array("--include",[],{description:"An array of glob pattern idents; only matching workspaces will be traversed"});this.exclude=U.Option.Array("--exclude",[],{description:"An array of glob pattern idents; matching workspaces won't be traversed"});this.publicOnly=U.Option.Boolean("--no-private",{description:"Avoid running the command on private workspaces"});this.since=U.Option.String("--since",{description:"Only include workspaces that have been changed since the specified ref.",tolerateBoolean:!0});this.commandName=U.Option.String();this.args=U.Option.Proxy()}async execute(){let t=await ge.Configuration.find(this.context.cwd,this.context.plugins),{project:n,workspace:s}=await ge.Project.find(t,this.context.cwd);if(!this.all&&!s)throw new Ne.WorkspaceRequiredError(n.cwd,this.context.cwd);await n.restoreInstallState();let i=this.cli.process([this.commandName,...this.args]),a=i.path.length===1&&i.path[0]==="run"&&typeof i.scriptName<"u"?i.scriptName:null;if(i.path.length===0)throw new U.UsageError("Invalid subcommand name for iteration - use the 'run' keyword if you wish to execute a script");let c=this.all?n.topLevelWorkspace:s,p=this.since?Array.from(await gr.gitUtils.fetchChangedWorkspaces({ref:this.since,project:n})):[c,...this.from.length>0?c.getRecursiveWorkspaceChildren():[]],m=g=>Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.from),h=this.from.length>0?p.filter(m):p,R=new Set([...h,...h.map(g=>[...this.recursive?this.since?g.getRecursiveWorkspaceDependents():g.getRecursiveWorkspaceDependencies():g.getRecursiveWorkspaceChildren()]).flat()]),f=[],$=!1;if(a!=null&&a.includes(":")){for(let g of n.workspaces)if(g.manifest.scripts.has(a)&&($=!$,$===!1))break}for(let g of R)a&&!g.manifest.scripts.has(a)&&!$&&!(await ge.scriptUtils.getWorkspaceAccessibleBinaries(g)).has(a)||a===process.env.npm_lifecycle_event&&g.cwd===s.cwd||this.include.length>0&&!Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.include)||this.exclude.length>0&&Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.exclude)||this.publicOnly&&g.manifest.private===!0||f.push(g);let _=this.parallel?this.jobs==="unlimited"?1/0:Number(this.jobs)||Math.ceil(F.nodeUtils.availableParallelism()/2):1,y=_===1?!1:this.parallel,E=y?this.interlaced:!0,S=(0,Ar.default)(_),T=new Map,L=new Set,z=0,I=null,re=!1,K=await _e.StreamReport.start({configuration:t,stdout:this.context.stdout,includePrefix:!1},async g=>{let v=async(k,{commandIndex:l})=>{if(re)return-1;!y&&this.verbose&&l>1&&g.reportSeparator();let H=qn(k,{configuration:t,verbose:this.verbose,commandIndex:l}),[w,B]=dr(g,{prefix:H,interlaced:E}),[o,u]=dr(g,{prefix:H,interlaced:E});try{this.verbose&&g.reportInfo(null,`${H} Process started`);let P=Date.now(),b=await this.cli.run([this.commandName,...this.args],{cwd:k.cwd,stdout:w,stderr:o})||0;w.end(),o.end(),await B,await u;let V=Date.now();if(this.verbose){let J=t.get("enableTimers")?`, completed in ${F.formatUtils.pretty(t,V-P,F.formatUtils.Type.DURATION)}`:"";g.reportInfo(null,`${H} Process exited (exit code ${b})${J}`)}return b===130&&(re=!0,I=b),b}catch(P){throw w.end(),o.end(),await B,await u,P}};for(let k of f)T.set(k.anchoredLocator.locatorHash,k);for(;T.size>0&&!g.hasErrors();){let k=[];for(let[w,B]of T){if(L.has(B.anchoredDescriptor.descriptorHash))continue;let o=!0;if(this.topological||this.topologicalDev){let u=this.topologicalDev?new Map([...B.manifest.dependencies,...B.manifest.devDependencies]):B.manifest.dependencies;for(let P of u.values()){let b=n.tryWorkspaceByDescriptor(P);if(o=b===null||!T.has(b.anchoredLocator.locatorHash),!o)break}}if(!!o&&(L.add(B.anchoredDescriptor.descriptorHash),k.push(S(async()=>{let u=await v(B,{commandIndex:++z});return T.delete(w),L.delete(B.anchoredDescriptor.descriptorHash),u})),!y))break}if(k.length===0){let w=Array.from(T.values()).map(B=>F.structUtils.prettyLocator(t,B.anchoredLocator)).join(", ");g.reportError(_e.MessageName.CYCLIC_DEPENDENCIES,`Dependency cycle detected (${w})`);return}let H=(await Promise.all(k)).find(w=>w!==0);I===null&&(I=typeof H<"u"?1:I),(this.topological||this.topologicalDev)&&typeof H<"u"&&g.reportError(_e.MessageName.UNNAMED,"The command failed for workspaces that are depended upon by other workspaces; can't satisfy the dependency graph")}});return I!==null?I:K.exitCode()}};pe.paths=[["workspaces","foreach"]],pe.usage=U.Command.Usage({category:"Workspace-related commands",description:"run a command on all workspaces",details:"\n This command will run a given sub-command on current and all its descendant workspaces. Various flags can alter the exact behavior of the command:\n\n - If `-p,--parallel` is set, the commands will be ran in parallel; they'll by default be limited to a number of parallel tasks roughly equal to half your core number, but that can be overridden via `-j,--jobs`, or disabled by setting `-j unlimited`.\n\n - If `-p,--parallel` and `-i,--interlaced` are both set, Yarn will print the lines from the output as it receives them. If `-i,--interlaced` wasn't set, it would instead buffer the output from each process and print the resulting buffers only after their source processes have exited.\n\n - If `-t,--topological` is set, Yarn will only run the command after all workspaces that it depends on through the `dependencies` field have successfully finished executing. If `--topological-dev` is set, both the `dependencies` and `devDependencies` fields will be considered when figuring out the wait points.\n\n - If `-A,--all` is set, Yarn will run the command on all the workspaces of a project. By default yarn runs the command only on current and all its descendant workspaces.\n\n - If `-R,--recursive` is set, Yarn will find workspaces to run the command on by recursively evaluating `dependencies` and `devDependencies` fields, instead of looking at the `workspaces` fields.\n\n - If `--from` is set, Yarn will use the packages matching the 'from' glob as the starting point for any recursive search.\n\n - If `--since` is set, Yarn will only run the command on workspaces that have been modified since the specified ref. By default Yarn will use the refs specified by the `changesetBaseRefs` configuration option.\n\n - The command may apply to only some workspaces through the use of `--include` which acts as a whitelist. The `--exclude` flag will do the opposite and will be a list of packages that mustn't execute the script. Both flags accept glob patterns (if valid Idents and supported by [micromatch](https://github.com/micromatch/micromatch)). Make sure to escape the patterns, to prevent your own shell from trying to expand them.\n\n Adding the `-v,--verbose` flag will cause Yarn to print more information; in particular the name of the workspace that generated the output will be printed at the front of each line.\n\n If the command is `run` and the script being run does not exist the child workspace will be skipped without error.\n ",examples:[["Publish current and all descendant packages","yarn workspaces foreach npm publish --tolerate-republish"],["Run build script on current and all descendant packages","yarn workspaces foreach run build"],["Run build script on current and all descendant packages in parallel, building package dependencies first","yarn workspaces foreach -pt run build"],["Run build script on several packages and all their dependencies, building dependencies first","yarn workspaces foreach -ptR --from '{workspace-a,workspace-b}' run build"]]});function dr(e,{prefix:r,interlaced:t}){let n=e.createStreamReporter(r),s=new F.miscUtils.DefaultStream;s.pipe(n,{end:!1}),s.on("finish",()=>{n.end()});let i=new Promise(c=>{n.on("finish",()=>{c(s.active)})});if(t)return[s,i];let a=new F.miscUtils.BufferStream;return a.pipe(s,{end:!1}),a.on("finish",()=>{s.end()}),[a,i]}function qn(e,{configuration:r,commandIndex:t,verbose:n}){if(!n)return null;let i=`[${F.structUtils.stringifyIdent(e.locator)}]:`,a=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],c=a[t%a.length];return F.formatUtils.pretty(r,i,c)}var Kn={commands:[ce,pe]},Wn=Kn;return wr(jn);})();
8 | /*!
9 | * fill-range
10 | *
11 | * Copyright (c) 2014-present, Jon Schlinkert.
12 | * Licensed under the MIT License.
13 | */
14 | /*!
15 | * is-number
16 | *
17 | * Copyright (c) 2014-present, Jon Schlinkert.
18 | * Released under the MIT License.
19 | */
20 | /*!
21 | * to-regex-range
22 | *
23 | * Copyright (c) 2015-present, Jon Schlinkert.
24 | * Released under the MIT License.
25 | */
26 | return plugin;
27 | }
28 | };
29 |
--------------------------------------------------------------------------------