@geophrase/core 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,64 @@
1
1
  # @geophrase/core
2
2
 
3
- The core vanilla JavaScript library for Geophrase Connect. This package provides the foundational class and TypeScript definitions for integrating the Geophrase address selector to reduce Return to Origin (RTO) costs.
3
+ The core vanilla JavaScript library for Geophrase Connect. Drop the Geophrase address selector into any web checkout in minutes and capture perfectly structured Indian addresses and coordinates to eliminate Return to Origin (RTO) costs.
4
4
 
5
- 👉 **[Read the full documentation and integration guide here](https://business.geophrase.com/docs)**
5
+ 👉 **[Full documentation and integration guide](https://business.geophrase.com/docs)**
6
+
7
+ *Building a React or Next.js app? Use [`@geophrase/react`](https://www.npmjs.com/package/@geophrase/react) instead — it wraps this core library in native hooks.*
6
8
 
7
9
  ---
8
10
 
9
- *Note: If you are building a modern React or Next.js application, you should use the [`@geophrase/react`](https://www.npmjs.com/package/@geophrase/react) package instead, which wraps this core library in native hooks.*
11
+ ## Install
12
+
13
+ The fastest path is to include the hosted script directly — no build step, no bundler:
14
+
15
+ ```html
16
+ <script src="https://connect.geophrase.com/v1/geophrase.js"></script>
17
+ ```
18
+
19
+ Or install from npm:
20
+
21
+ ```bash
22
+ npm install @geophrase/core
23
+ ```
24
+
25
+ ```javascript
26
+ import Geophrase from '@geophrase/core';
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ```html
32
+ <button id="geophrase-btn">Select Delivery Address</button>
33
+
34
+ <script>
35
+ document.addEventListener('DOMContentLoaded', function () {
36
+ const geo = new Geophrase({
37
+ mode: 'client', // 'client' (default) or 'server'
38
+ key: 'YOUR_API_KEY', // required when mode is 'client'
39
+ theme: 'system', // 'light' | 'dark' | 'system'
40
+ orderId: 'ORD-98765', // your internal reference id
41
+ phone: '9999999999', // pre-fill the customer phone
42
+
43
+ onSuccess: (result) => console.log('Success:', result),
44
+ onError: (error) => console.error('Error:', error.message),
45
+ onClose: () => console.log('User dismissed the widget.')
46
+ });
47
+
48
+ document.getElementById('geophrase-btn').onclick = () => geo.open();
49
+ });
50
+ </script>
51
+ ```
52
+
53
+ In `client` mode, `onSuccess` receives the fully resolved `GeophraseAddress`. In `server` mode, it receives `{ token }` which you exchange on your backend using your API key. See the [full docs](https://business.geophrase.com/docs) for the complete configuration reference, security guidance, and response schemas.
54
+
55
+ ## API
56
+
57
+ | Method | Description |
58
+ | :--- | :--- |
59
+ | `new Geophrase(options)` | Create an instance. Pre-computes the widget URL; safe to construct at module scope. |
60
+ | `.open()` | Open the modal. Idempotent. |
61
+ | `.close()` | Close the modal without firing `onSuccess`. |
62
+ | `.destroy()` | Remove all DOM, listeners, and callbacks. Call this when your component unmounts. |
63
+
64
+ TypeScript definitions (`GeophraseOptions`, `GeophraseAddress`, `GeophraseToken`, `GeophraseError`) ship with the package.
package/index.d.ts CHANGED
@@ -3,6 +3,10 @@ export interface GeophraseAddress {
3
3
  [key: string]: any;
4
4
  }
5
5
 
6
+ export interface GeophraseToken {
7
+ token: string;
8
+ }
9
+
6
10
  export interface GeophraseError {
7
11
  type: 'API_ERROR' | 'NETWORK_ERROR';
8
12
  status?: number;
@@ -10,10 +14,12 @@ export interface GeophraseError {
10
14
  }
11
15
 
12
16
  export interface GeophraseOptions {
13
- key: string;
14
- order_id?: string;
17
+ mode?: 'client' | 'server';
18
+ theme?: 'light' | 'dark' | 'system';
19
+ key?: string;
20
+ orderId?: string;
15
21
  phone?: string;
16
- onSuccess: (address: GeophraseAddress) => void;
22
+ onSuccess: (result: GeophraseAddress | GeophraseToken) => void;
17
23
  onError?: (error: GeophraseError) => void;
18
24
  onClose?: () => void;
19
25
  }
package/package.json CHANGED
@@ -1,18 +1,28 @@
1
1
  {
2
2
  "name": "@geophrase/core",
3
- "version": "1.2.0",
4
- "description": "The core vanilla JavaScript library for Geophrase Connect.",
3
+ "version": "1.3.0",
4
+ "description": "Drop-in address picker widget for Indian e-commerce checkouts. Captures structured addresses with coordinates to reduce RTO.",
5
+ "license": "MIT",
6
+ "author": "Geophrase",
5
7
  "homepage": "https://business.geophrase.com/docs",
6
8
  "repository": {
7
9
  "type": "git",
8
- "url": "https://github.com/geophrase/geophrase-js.git"
10
+ "url": "git+https://github.com/geophrase/geophrase-js.git"
9
11
  },
10
12
  "bugs": {
11
13
  "url": "https://github.com/geophrase/geophrase-js/issues"
12
14
  },
13
15
  "keywords": [
14
16
  "javascript",
17
+ "vanilla-js",
18
+ "sdk",
19
+ "widget",
15
20
  "address",
21
+ "address-picker",
22
+ "address-autocomplete",
23
+ "address-verification",
24
+ "delivery-address",
25
+ "pincode",
16
26
  "india",
17
27
  "rto",
18
28
  "ecommerce",
@@ -23,10 +33,14 @@
23
33
  "type": "module",
24
34
  "main": "src/index.js",
25
35
  "types": "index.d.ts",
36
+ "sideEffects": false,
26
37
  "files": [
27
38
  "src",
28
39
  "index.d.ts",
29
40
  "package.json",
30
41
  "README.md"
31
- ]
32
- }
42
+ ],
43
+ "publishConfig": {
44
+ "access": "public"
45
+ }
46
+ }
package/src/index.js CHANGED
@@ -1,37 +1,92 @@
1
1
  class Geophrase {
2
+ static _instanceCounter = 0;
3
+
2
4
  constructor(options = {}) {
3
- // 1. Strict Constructor Validation
4
- if (!options.key) {
5
- throw new Error("Geophrase: 'key' is required.");
6
- }
7
5
  if (typeof document === 'undefined') {
8
- return; // SSR safe no-op
6
+ this._isSSR = true;
7
+ return;
8
+ }
9
+
10
+ // 1. Mode validation
11
+ this.mode = options.mode || 'client';
12
+ if (!['client', 'server'].includes(this.mode)) {
13
+ throw new Error(`Geophrase: Invalid mode '${this.mode}'. Expected 'client' or 'server'.`);
14
+ }
15
+
16
+ // 2. API key validation
17
+ if (this.mode === 'client' && !options.key) {
18
+ throw new Error("Geophrase Error: 'key' is required when mode is 'client'.");
9
19
  }
10
20
 
11
- this.apiKey = options.key;
12
- this.orderId = options.order_id;
21
+ if (this.mode === 'server' && options.key) {
22
+ console.warn("Geophrase Warning: 'key' is ignored when mode is 'server'. Ensure you are not exposing a Secret Key in your frontend.");
23
+ }
24
+
25
+ this.apiKey = this.mode === 'client' ? options.key : null;
26
+ this.orderId = options.orderId;
13
27
  this.phone = options.phone;
14
28
 
29
+ // 3. Theme validation
30
+ this.theme = options.theme;
31
+ if (this.theme && !['light', 'dark', 'system'].includes(this.theme)) {
32
+ console.warn(`Geophrase Warning: Invalid theme '${this.theme}'. Falling back to default.`);
33
+ this.theme = null;
34
+ }
35
+
15
36
  this.onSuccess = options.onSuccess;
16
37
  this.onError = options.onError;
17
38
  this.onClose = options.onClose;
18
39
 
19
- this.iframeId = 'geophrase-iframe-connect';
20
- this.overlayId = 'geophrase-overlay-container';
21
- this.styleId = 'geophrase-connect-styles';
22
- this.widgetOrigin = 'https://connect.geophrase.com';
23
- this.apiBase = 'https://api.geophrase.com';
40
+ // 4. Per-instance DOM IDs so multiple instances don't collide
41
+ const instanceId = ++Geophrase._instanceCounter;
42
+ this.iframeId = `geophrase-iframe-${instanceId}`;
43
+ this.overlayId = `geophrase-overlay-${instanceId}`;
44
+ this.styleId = `geophrase-styles-${instanceId}`;
45
+
46
+ // 5. Endpoints (undocumented override for staging/QA)
47
+ const endpoints = options._endpoints || {};
48
+ this.widgetOrigin = endpoints.widgetOrigin || 'https://connect.geophrase.com';
49
+ this.apiBase = endpoints.apiBase || 'https://api.geophrase.com';
24
50
 
25
51
  this._boundHandleMessage = this._handleMessage.bind(this);
52
+ this._prevBodyOverflow = null;
26
53
 
27
- // 2. Pre-compute the URL, but DO NOT inject or load it yet
54
+ // 6. Pre-compute the secure widget URL (API key purposefully excluded)
28
55
  const url = new URL(this.widgetOrigin);
29
- url.searchParams.append('api-key', this.apiKey);
30
56
  if (this.orderId) url.searchParams.append('order-id', this.orderId);
31
57
  if (this.phone) url.searchParams.append('phone', this.phone);
58
+ if (this.theme) url.searchParams.append('theme', this.theme);
32
59
  this.widgetUrl = url.toString();
33
60
  }
34
61
 
62
+ _getIframeBgCSS() {
63
+ const light = '#ffffff';
64
+ const dark = '#121212';
65
+
66
+ if (this.theme === 'light') {
67
+ return `#${this.iframeId} { background-color: ${light}; }`;
68
+ }
69
+ if (this.theme === 'dark') {
70
+ return `#${this.iframeId} { background-color: ${dark}; }`;
71
+ }
72
+ // 'system' or unspecified → follow OS preference, matching the widget
73
+ return `
74
+ #${this.iframeId} { background-color: ${light}; }
75
+ @media (prefers-color-scheme: dark) {
76
+ #${this.iframeId} { background-color: ${dark}; }
77
+ }
78
+ `;
79
+ }
80
+
81
+ _safeCall(fn, payload) {
82
+ if (typeof fn !== 'function') return;
83
+ try {
84
+ fn(payload);
85
+ } catch (err) {
86
+ console.error('Geophrase: merchant callback threw an error', err);
87
+ }
88
+ }
89
+
35
90
  _injectDOM() {
36
91
  if (document.getElementById(this.overlayId)) return;
37
92
 
@@ -46,7 +101,10 @@ class Geophrase {
46
101
  opacity: 0; visibility: hidden; transition: opacity 0.3s ease;
47
102
  }
48
103
  #${this.overlayId}.geophrase-active { opacity: 1; visibility: visible; }
49
- #${this.iframeId} { width: 100%; height: 100%; border: none; background-color: #fff; }
104
+
105
+ #${this.iframeId} { width: 100%; height: 100%; border: none; }
106
+ ${this._getIframeBgCSS()}
107
+
50
108
  @media (min-width: 768px) {
51
109
  #${this.iframeId} {
52
110
  width: 375px; height: 812px; max-height: 85vh;
@@ -62,41 +120,54 @@ class Geophrase {
62
120
 
63
121
  const iframe = document.createElement('iframe');
64
122
  iframe.id = this.iframeId;
65
- iframe.allow = "geolocation";
123
+ iframe.allow = 'geolocation';
66
124
 
67
125
  overlay.appendChild(iframe);
68
126
  document.body.appendChild(overlay);
69
127
 
70
- // Prevent duplicate listeners
71
128
  window.removeEventListener('message', this._boundHandleMessage);
72
129
  window.addEventListener('message', this._boundHandleMessage);
73
130
  }
74
131
 
75
132
  open() {
76
- // 3. Lazy-load the DOM and iframe src exactly when clicked
133
+ if (this._isSSR) return;
134
+
77
135
  this._injectDOM();
136
+
78
137
  const iframe = document.getElementById(this.iframeId);
79
138
  if (iframe && !iframe.hasAttribute('src')) {
80
139
  iframe.src = this.widgetUrl;
81
140
  }
82
141
 
142
+ // Preserve merchant's existing overflow; idempotent under repeated open()
143
+ if (this._prevBodyOverflow === null) {
144
+ this._prevBodyOverflow = document.body.style.overflow;
145
+ }
83
146
  document.body.style.overflow = 'hidden';
147
+
84
148
  document.getElementById(this.overlayId)?.classList.add('geophrase-active');
85
149
  }
86
150
 
87
151
  close() {
88
- document.body.style.overflow = '';
152
+ if (this._isSSR) return;
153
+
154
+ document.body.style.overflow = this._prevBodyOverflow ?? '';
155
+ this._prevBodyOverflow = null;
156
+
89
157
  document.getElementById(this.overlayId)?.classList.remove('geophrase-active');
90
158
 
91
159
  const iframe = document.getElementById(this.iframeId);
92
- if (iframe) iframe.removeAttribute('src'); // 4. Kill the background session safely
160
+ if (iframe) iframe.removeAttribute('src');
93
161
  }
94
162
 
95
163
  destroy() {
96
- const overlay = document.getElementById(this.overlayId);
97
- if (overlay) overlay.remove();
164
+ if (this._isSSR) return;
165
+
166
+ document.getElementById(this.overlayId)?.remove();
167
+ document.getElementById(this.styleId)?.remove();
98
168
 
99
- document.body.style.overflow = '';
169
+ document.body.style.overflow = this._prevBodyOverflow ?? '';
170
+ this._prevBodyOverflow = null;
100
171
 
101
172
  window.removeEventListener('message', this._boundHandleMessage);
102
173
 
@@ -108,58 +179,66 @@ class Geophrase {
108
179
  async _handleMessage(event) {
109
180
  if (event.origin !== this.widgetOrigin) return;
110
181
 
182
+ // Defense in depth: only accept messages from our own iframe
183
+ const iframe = document.getElementById(this.iframeId);
184
+ if (!iframe || event.source !== iframe.contentWindow) return;
185
+
111
186
  let data = event.data;
112
187
  if (typeof data === 'string') {
113
- try {
114
- data = JSON.parse(data);
115
- } catch (e) {
116
- return;
117
- }
188
+ try { data = JSON.parse(data); } catch (e) { return; }
118
189
  }
119
190
 
120
191
  if (data?.type === 'GEOPHRASE_CLOSE_WIDGET') {
121
192
  this.close();
122
- if (this.onClose) this.onClose();
193
+ this._safeCall(this.onClose);
194
+ return;
123
195
  }
124
196
 
125
197
  if (data?.type === 'GEOPHRASE_RESOLUTION_TOKEN') {
126
198
  this.close();
127
199
 
128
- // 5. Critical API Timeout protection
200
+ // Server mode: hand the raw token to the merchant for backend exchange
201
+ if (this.mode === 'server') {
202
+ this._safeCall(this.onSuccess, { token: data.token });
203
+ return;
204
+ }
205
+
206
+ // Client mode: resolve the token via the public API
129
207
  const controller = new AbortController();
130
208
  const timeoutId = setTimeout(() => controller.abort(), 15000);
131
209
 
132
210
  try {
133
211
  const response = await fetch(`${this.apiBase}/business/resolve/`, {
134
- method: "POST",
135
- headers: { "X-API-Key": this.apiKey, "Content-Type": "application/json" },
212
+ method: 'POST',
213
+ headers: {
214
+ 'X-API-Key': this.apiKey,
215
+ 'Content-Type': 'application/json'
216
+ },
136
217
  body: JSON.stringify({ token: data.token }),
137
218
  signal: controller.signal
138
219
  });
139
220
 
140
221
  if (!response.ok) {
141
222
  const errorData = await response.json().catch(() => ({}));
142
- if (this.onError) {
143
- this.onError({
144
- type: 'API_ERROR',
145
- status: response.status,
146
- message: errorData.message || 'Geophrase API resolution failed'
147
- });
148
- }
223
+ this._safeCall(this.onError, {
224
+ type: 'API_ERROR',
225
+ status: response.status,
226
+ message: errorData.message || 'Geophrase API resolution failed'
227
+ });
149
228
  return;
150
229
  }
151
230
 
152
231
  const responseData = await response.json();
153
- if (this.onSuccess) this.onSuccess(responseData);
232
+ this._safeCall(this.onSuccess, responseData);
154
233
 
155
234
  } catch (error) {
156
- console.error("Geophrase Resolution Error:", error);
157
- if (this.onError) {
158
- this.onError({
159
- type: 'NETWORK_ERROR',
160
- message: error.name === 'AbortError' ? 'Geophrase API request timed out' : error.message
161
- });
162
- }
235
+ console.error('Geophrase Resolution Error:', error);
236
+ this._safeCall(this.onError, {
237
+ type: 'NETWORK_ERROR',
238
+ message: error.name === 'AbortError'
239
+ ? 'Geophrase API request timed out'
240
+ : error.message
241
+ });
163
242
  } finally {
164
243
  clearTimeout(timeoutId);
165
244
  }