jp-postal-lookup 1.0.0 → 1.0.2
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 +134 -143
- package/dist/index.cjs +1 -0
- package/dist/index.js +1 -0
- package/package.json +32 -9
- package/src/index.cjs +0 -191
- package/src/index.js +0 -297
package/README.md
CHANGED
|
@@ -7,46 +7,60 @@
|
|
|
7
7
|
[](index.d.ts)
|
|
8
8
|
|
|
9
9
|
> **Zero-dependency** Japanese address and postal code lookup library powered by [HeartRails Geo API](https://geoapi.heartrails.com/).
|
|
10
|
-
>
|
|
10
|
+
> Lightweight, universal, and easy to use across **ESM**, **CommonJS**, **TypeScript**, **Node.js 18+**, and **Modern Browsers**.
|
|
11
|
+
> 日本の郵便番号・住所検索ライブラリ(ゼロ依存関係、ブラウザ・Node.js両対応)。
|
|
11
12
|
|
|
12
13
|
---
|
|
13
14
|
|
|
14
|
-
## 📑
|
|
15
|
+
## 📑 Table of Contents
|
|
15
16
|
|
|
16
|
-
1. [
|
|
17
|
-
2. [
|
|
18
|
-
3. [
|
|
19
|
-
4. [
|
|
17
|
+
1. [Key Features](#-key-features)
|
|
18
|
+
2. [Environment Requirements](#-environment-requirements)
|
|
19
|
+
3. [Installation](#-installation)
|
|
20
|
+
4. [Quick Start](#-quick-start)
|
|
21
|
+
5. [Framework Integration](#-framework-integration)
|
|
20
22
|
- [Vue 3 / Nuxt 3](#1-vue-3--nuxt-3)
|
|
21
23
|
- [React / Next.js](#2-react--nextjs)
|
|
22
24
|
- [Node.js (Express / Backend)](#3-nodejs-backend-express)
|
|
23
|
-
- [
|
|
24
|
-
|
|
25
|
+
- [Legacy Compatibility](#4-drop-in-replacement-for-legacy-getaddressjs)
|
|
26
|
+
6. [API Reference](#-api-reference)
|
|
25
27
|
- [Modern Promise API](#modern-promise-api)
|
|
26
28
|
- [Legacy Compatible API](#legacy-compatible-api)
|
|
27
|
-
- [
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
29
|
+
- [TypeScript Interfaces](#typescript-interfaces)
|
|
30
|
+
7. [Testing](#-testing)
|
|
31
|
+
8. [Error Handling & Gotchas](#-error-handling--gotchas)
|
|
32
|
+
9. [Publishing to npm](#-publishing-to-npm)
|
|
33
|
+
10. [License](#-license)
|
|
32
34
|
|
|
33
35
|
---
|
|
34
36
|
|
|
35
|
-
##
|
|
37
|
+
## ✨ Key Features
|
|
36
38
|
|
|
37
|
-
|
|
39
|
+
- 🚀 **Zero Dependencies**: Pure native JavaScript using built-in `fetch`. No external dependencies like `axios` or `lodash`.
|
|
40
|
+
- 🌐 **Universal Runtime**: Works seamlessly in modern browsers and Node.js 18+.
|
|
41
|
+
- 📦 **Dual Module Format**: Native ES Module (`import`) and CommonJS (`require`) support with comprehensive exports mapping.
|
|
42
|
+
- 🔷 **Full TypeScript Support**: Bundled type definitions (`index.d.ts`) with rich autocompletion and JSDoc documentation.
|
|
43
|
+
- 🧹 **Automatic Normalization**: Automatically handles full-width characters (`100ー0001`), hyphens (`-`, `ー`, `-`), and spaces.
|
|
44
|
+
- 🔄 **Two-Way Lookup**: Search address by postal code, or search postal code by address name.
|
|
45
|
+
- 🛡️ **Fail-Safe**: Gracefully handles network failures, malformed input, and non-existent codes without throwing uncaught exceptions.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 💻 Environment Requirements
|
|
50
|
+
|
|
51
|
+
| Environment | Supported Versions | Notes |
|
|
38
52
|
| :--- | :--- | :--- |
|
|
39
|
-
| **Node.js** | `>= 18.0.0` (
|
|
40
|
-
| **
|
|
41
|
-
| **TypeScript** | `>= 4.5.0` |
|
|
42
|
-
| **Package Managers** | npm 7+, yarn 1/3+, pnpm 7+, bun 1+ |
|
|
43
|
-
| **Dependencies** | **0 dependencies** |
|
|
53
|
+
| **Node.js** | `>= 18.0.0` (Recommended: 18.x, 20.x, 22.x LTS) | Utilizes native `globalThis.fetch` |
|
|
54
|
+
| **Browsers** | Chrome 66+, Firefox 57+, Safari 11.1+, Edge 79+ | Requires standard Fetch API & ES6 Modules |
|
|
55
|
+
| **TypeScript** | `>= 4.5.0` | Ships with complete `index.d.ts` definitions |
|
|
56
|
+
| **Package Managers** | npm 7+, yarn 1/3+, pnpm 7+, bun 1+ | Full `exports` map support |
|
|
57
|
+
| **Dependencies** | **0 dependencies** | Zero bloat, minimal bundle size |
|
|
44
58
|
|
|
45
59
|
---
|
|
46
60
|
|
|
47
|
-
## 📦
|
|
61
|
+
## 📦 Installation
|
|
48
62
|
|
|
49
|
-
###
|
|
63
|
+
### From npm registry:
|
|
50
64
|
|
|
51
65
|
```bash
|
|
52
66
|
# npm
|
|
@@ -62,21 +76,7 @@ pnpm add jp-postal-lookup
|
|
|
62
76
|
bun add jp-postal-lookup
|
|
63
77
|
```
|
|
64
78
|
|
|
65
|
-
###
|
|
66
|
-
|
|
67
|
-
```bash
|
|
68
|
-
# Cài đường dẫn trực tiếp từ thư mục
|
|
69
|
-
npm install /home/dungdao/projects/jp-postal-lookup
|
|
70
|
-
|
|
71
|
-
# Hoặc dùng npm link
|
|
72
|
-
cd /home/dungdao/projects/jp-postal-lookup
|
|
73
|
-
npm link
|
|
74
|
-
|
|
75
|
-
cd /path/to/your-project
|
|
76
|
-
npm link jp-postal-lookup
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
### 3. Sử dụng trực tiếp trên Browser (CDN):
|
|
79
|
+
### Direct Browser Usage (CDN):
|
|
80
80
|
|
|
81
81
|
```html
|
|
82
82
|
<script type="module">
|
|
@@ -89,19 +89,19 @@ npm link jp-postal-lookup
|
|
|
89
89
|
|
|
90
90
|
---
|
|
91
91
|
|
|
92
|
-
## ⚡
|
|
92
|
+
## ⚡ Quick Start
|
|
93
93
|
|
|
94
94
|
### ES Module (`import`)
|
|
95
95
|
|
|
96
96
|
```javascript
|
|
97
97
|
import { searchAddressByPostal, searchPostalByAddress } from 'jp-postal-lookup';
|
|
98
98
|
|
|
99
|
-
// 1.
|
|
99
|
+
// 1. Search address by postal code (auto-normalizes '100-0001', '100ー0001' -> '1000001')
|
|
100
100
|
const address = await searchAddressByPostal('100-0001');
|
|
101
101
|
console.log(address);
|
|
102
102
|
// Output: "東京都千代田区千代田"
|
|
103
103
|
|
|
104
|
-
// 2.
|
|
104
|
+
// 2. Search postal code by address keyword
|
|
105
105
|
const postal = await searchPostalByAddress('千代田区千代田');
|
|
106
106
|
console.log(postal);
|
|
107
107
|
// Output: "1000001"
|
|
@@ -121,7 +121,7 @@ run();
|
|
|
121
121
|
|
|
122
122
|
---
|
|
123
123
|
|
|
124
|
-
## 🧩
|
|
124
|
+
## 🧩 Framework Integration
|
|
125
125
|
|
|
126
126
|
### 1. Vue 3 / Nuxt 3
|
|
127
127
|
|
|
@@ -134,9 +134,9 @@ run();
|
|
|
134
134
|
@blur="handleLookup"
|
|
135
135
|
/>
|
|
136
136
|
<button :disabled="loading" @click="handleLookup">
|
|
137
|
-
{{ loading ? '
|
|
137
|
+
{{ loading ? 'Searching...' : 'Lookup Address' }}
|
|
138
138
|
</button>
|
|
139
|
-
<p v-if="address"
|
|
139
|
+
<p v-if="address">Address: {{ address }}</p>
|
|
140
140
|
<p v-if="error" class="error">{{ error }}</p>
|
|
141
141
|
</div>
|
|
142
142
|
</template>
|
|
@@ -159,10 +159,10 @@ const handleLookup = async () => {
|
|
|
159
159
|
if (result) {
|
|
160
160
|
address.value = result;
|
|
161
161
|
} else {
|
|
162
|
-
error.value = '
|
|
162
|
+
error.value = 'No address found for this postal code.';
|
|
163
163
|
}
|
|
164
164
|
} catch (err) {
|
|
165
|
-
error.value = '
|
|
165
|
+
error.value = 'Lookup failed: ' + err.message;
|
|
166
166
|
} finally {
|
|
167
167
|
loading.value = false;
|
|
168
168
|
}
|
|
@@ -181,7 +181,7 @@ export function AddressForm() {
|
|
|
181
181
|
const [location, setLocation] = useState<GeoLocation | null>(null);
|
|
182
182
|
|
|
183
183
|
const onSearch = async () => {
|
|
184
|
-
//
|
|
184
|
+
// Retrieve detailed object (prefecture, city, town, coordinates x/y)
|
|
185
185
|
const data = await searchAddressByPostal(postal, { raw: true });
|
|
186
186
|
setLocation(data);
|
|
187
187
|
};
|
|
@@ -193,12 +193,12 @@ export function AddressForm() {
|
|
|
193
193
|
onChange={(e) => setPostal(e.target.value)}
|
|
194
194
|
placeholder="100-0001"
|
|
195
195
|
/>
|
|
196
|
-
<button onClick={onSearch}>
|
|
196
|
+
<button onClick={onSearch}>Lookup</button>
|
|
197
197
|
{location && (
|
|
198
198
|
<div>
|
|
199
|
-
<p>
|
|
200
|
-
<p>
|
|
201
|
-
<p>
|
|
199
|
+
<p>Prefecture: {location.prefecture}</p>
|
|
200
|
+
<p>City: {location.city}</p>
|
|
201
|
+
<p>Town: {location.town}</p>
|
|
202
202
|
</div>
|
|
203
203
|
)}
|
|
204
204
|
</div>
|
|
@@ -217,7 +217,7 @@ const app = express();
|
|
|
217
217
|
app.get('/api/lookup-postal', async (req, res) => {
|
|
218
218
|
const { code } = req.query;
|
|
219
219
|
if (!code) {
|
|
220
|
-
return res.status(400).json({ error: 'Missing postal code' });
|
|
220
|
+
return res.status(400).json({ error: 'Missing postal code parameter' });
|
|
221
221
|
}
|
|
222
222
|
|
|
223
223
|
const address = await searchAddressByPostal(code, { raw: true });
|
|
@@ -228,43 +228,44 @@ app.get('/api/lookup-postal', async (req, res) => {
|
|
|
228
228
|
return res.json({ data: address });
|
|
229
229
|
});
|
|
230
230
|
|
|
231
|
-
app.listen(3000, () => console.log('Server running on
|
|
231
|
+
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
|
|
232
232
|
```
|
|
233
233
|
|
|
234
|
-
### 4.
|
|
234
|
+
### 4. Drop-in Replacement for Legacy `getAddress.js`
|
|
235
235
|
|
|
236
|
-
|
|
236
|
+
If your existing project has a legacy `getAddress.js` utility, simply update the import statement:
|
|
237
237
|
|
|
238
238
|
```diff
|
|
239
239
|
- import { onSearchAddressByPostcode, onSearchPostcodeByAddress } from '@/utilities/getAddress.js';
|
|
240
240
|
+ import { onSearchAddressByPostcode, onSearchPostcodeByAddress } from 'jp-postal-lookup';
|
|
241
241
|
```
|
|
242
|
-
|
|
242
|
+
|
|
243
|
+
All method names, parameters, callback signatures, and return formats remain 100% identical.
|
|
243
244
|
|
|
244
245
|
---
|
|
245
246
|
|
|
246
|
-
## 📖
|
|
247
|
+
## 📖 API Reference
|
|
247
248
|
|
|
248
249
|
### Modern Promise API
|
|
249
250
|
|
|
250
251
|
#### 1. `searchAddressByPostal(postal, options?)`
|
|
251
|
-
|
|
252
|
+
Searches address information by Japanese postal code.
|
|
252
253
|
|
|
253
|
-
- **
|
|
254
|
-
- `postal` (`string | number`):
|
|
255
|
-
- `options` (`object`,
|
|
256
|
-
- `raw` (`boolean`,
|
|
257
|
-
- `all` (`boolean`,
|
|
258
|
-
- `baseUrl` (`string`,
|
|
259
|
-
- **
|
|
254
|
+
- **Parameters**:
|
|
255
|
+
- `postal` (`string | number`): Japanese postal code (e.g. `'100-0001'`, `'1000001'`, `'100ー0001'`).
|
|
256
|
+
- `options` (`object`, optional):
|
|
257
|
+
- `raw` (`boolean`, default: `false`): When `true`, returns a `GeoLocation` object containing x, y coordinates and furigana.
|
|
258
|
+
- `all` (`boolean`, default: `false`): When `true`, returns an array `GeoLocation[]` of all matching locations.
|
|
259
|
+
- `baseUrl` (`string`, optional): Custom API endpoint (e.g., when routing through a reverse proxy).
|
|
260
|
+
- **Returns**: `Promise<string | GeoLocation | GeoLocation[] | null>`
|
|
260
261
|
|
|
261
262
|
```javascript
|
|
262
|
-
//
|
|
263
|
-
const
|
|
263
|
+
// Returns full address string
|
|
264
|
+
const address = await searchAddressByPostal('100-0001');
|
|
264
265
|
// "東京都千代田区千代田"
|
|
265
266
|
|
|
266
|
-
//
|
|
267
|
-
const
|
|
267
|
+
// Returns detailed GeoLocation object
|
|
268
|
+
const location = await searchAddressByPostal('100-0001', { raw: true });
|
|
268
269
|
// {
|
|
269
270
|
// postal: "1000001",
|
|
270
271
|
// prefecture: "東京都",
|
|
@@ -276,22 +277,22 @@ const obj = await searchAddressByPostal('100-0001', { raw: true });
|
|
|
276
277
|
// y: "35.6852"
|
|
277
278
|
// }
|
|
278
279
|
|
|
279
|
-
//
|
|
280
|
+
// Returns all matching locations
|
|
280
281
|
const list = await searchAddressByPostal('100-0001', { all: true });
|
|
281
282
|
```
|
|
282
283
|
|
|
283
284
|
---
|
|
284
285
|
|
|
285
286
|
#### 2. `searchPostalByAddress(address, options?)`
|
|
286
|
-
|
|
287
|
+
Searches postal codes by address name keyword.
|
|
287
288
|
|
|
288
|
-
- **
|
|
289
|
-
- `address` (`string`):
|
|
290
|
-
- `options` (`object`,
|
|
291
|
-
- `raw` (`boolean`,
|
|
292
|
-
- `all` (`boolean`,
|
|
293
|
-
- `matching` (`'prefix' | 'suffix' | 'like'`,
|
|
294
|
-
- **
|
|
289
|
+
- **Parameters**:
|
|
290
|
+
- `address` (`string`): Address keyword (e.g. `'千代田区千代田'`).
|
|
291
|
+
- `options` (`object`, optional):
|
|
292
|
+
- `raw` (`boolean`, default: `false`): Returns `GeoLocation` object.
|
|
293
|
+
- `all` (`boolean`, default: `false`): Returns array `GeoLocation[]`.
|
|
294
|
+
- `matching` (`'prefix' | 'suffix' | 'like'`, default: `'suffix'`).
|
|
295
|
+
- **Returns**: `Promise<string | GeoLocation | GeoLocation[] | null>`
|
|
295
296
|
|
|
296
297
|
```javascript
|
|
297
298
|
const postal = await searchPostalByAddress('千代田区千代田');
|
|
@@ -301,63 +302,65 @@ const postal = await searchPostalByAddress('千代田区千代田');
|
|
|
301
302
|
---
|
|
302
303
|
|
|
303
304
|
#### 3. `getAreas()`
|
|
304
|
-
|
|
305
|
-
- **
|
|
306
|
-
- **
|
|
305
|
+
Retrieves list of major Japanese geographic regions.
|
|
306
|
+
- **Returns**: `Promise<string[]>`
|
|
307
|
+
- **Result**: `['北海道', '東北', '関東', '中部', '近畿', '中国', '四国', '九州']`
|
|
307
308
|
|
|
308
309
|
---
|
|
309
310
|
|
|
310
311
|
#### 4. `getPrefectures(area)`
|
|
311
|
-
|
|
312
|
-
- **
|
|
313
|
-
- **
|
|
314
|
-
- **
|
|
312
|
+
Retrieves prefectures belonging to a specific region.
|
|
313
|
+
- **Parameters**: `area` (`string`): e.g. `'関東'`.
|
|
314
|
+
- **Returns**: `Promise<string[]>`
|
|
315
|
+
- **Result**: `['茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県']`
|
|
315
316
|
|
|
316
317
|
---
|
|
317
318
|
|
|
318
319
|
#### 5. `getCities(prefecture, area?)`
|
|
319
|
-
|
|
320
|
-
- **
|
|
321
|
-
- `prefecture` (`string`):
|
|
322
|
-
- `area` (`string`,
|
|
323
|
-
- **
|
|
324
|
-
- **
|
|
320
|
+
Retrieves cities/districts belonging to a prefecture.
|
|
321
|
+
- **Parameters**:
|
|
322
|
+
- `prefecture` (`string`): e.g. `'東京都'`.
|
|
323
|
+
- `area` (`string`, optional).
|
|
324
|
+
- **Returns**: `Promise<string[]>`
|
|
325
|
+
- **Result**: `['千代田区', '中央区', '港区', '新宿区', ...]`
|
|
325
326
|
|
|
326
327
|
---
|
|
327
328
|
|
|
328
329
|
#### 6. `getTowns(city, prefecture?)`
|
|
329
|
-
|
|
330
|
-
- **
|
|
331
|
-
- `city` (`string`):
|
|
332
|
-
- `prefecture` (`string`,
|
|
333
|
-
- **
|
|
334
|
-
- **
|
|
330
|
+
Retrieves towns/wards belonging to a city.
|
|
331
|
+
- **Parameters**:
|
|
332
|
+
- `city` (`string`): e.g. `'千代田区'`.
|
|
333
|
+
- `prefecture` (`string`, optional): e.g. `'東京都'`.
|
|
334
|
+
- **Returns**: `Promise<string[]>`
|
|
335
|
+
- **Result**: `['丸の内', '大手町', '一ツ橋', ...]`
|
|
335
336
|
|
|
336
337
|
---
|
|
337
338
|
|
|
338
339
|
#### 7. `normalizePostal(postal)`
|
|
339
|
-
|
|
340
|
-
- **
|
|
341
|
-
- **
|
|
340
|
+
Utility function that sanitizes and formats postal code strings.
|
|
341
|
+
- **Parameters**: `postal` (`string | number`)
|
|
342
|
+
- **Behavior**:
|
|
342
343
|
- `normalizePostal('100-0001')` ➜ `'1000001'`
|
|
343
344
|
- `normalizePostal(' 100ー0001 ')` ➜ `'1000001'`
|
|
344
|
-
- `normalizePostal('
|
|
345
|
+
- `normalizePostal('100 0001')` ➜ `'1000001'`
|
|
345
346
|
|
|
346
347
|
---
|
|
347
348
|
|
|
348
|
-
### Legacy Compatible API
|
|
349
|
+
### Legacy Compatible API
|
|
349
350
|
|
|
350
|
-
|
|
351
|
+
For backwards compatibility with legacy codebase conventions:
|
|
352
|
+
|
|
353
|
+
| Function Name | Signature | Description |
|
|
351
354
|
| :--- | :--- | :--- |
|
|
352
|
-
| `onSearchAddressByPostcode(postcode, isResponse?)` | `(string\|number, boolean?) => Promise<string \| GeoLocation \| null>` | `isResponse=false`
|
|
353
|
-
| `onSearchPostcodeByAddress(address, isResponse?, matching?)` | `(string, boolean?, string?) => Promise<string \| GeoLocation \| null>` |
|
|
354
|
-
| `getPrefecturesByArea(area, callback?)` | `(string, (res) => void) => Promise<object>` |
|
|
355
|
-
| `onGetCitiesByPrefecture(area, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` |
|
|
356
|
-
| `onGetTownsByCity(city, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` |
|
|
355
|
+
| `onSearchAddressByPostcode(postcode, isResponse?)` | `(string\|number, boolean?) => Promise<string \| GeoLocation \| null>` | `isResponse=false` returns formatted address string; `isResponse=true` returns location object |
|
|
356
|
+
| `onSearchPostcodeByAddress(address, isResponse?, matching?)` | `(string, boolean?, string?) => Promise<string \| GeoLocation \| null>` | Searches postal code by address keyword |
|
|
357
|
+
| `getPrefecturesByArea(area, callback?)` | `(string, (res) => void) => Promise<object>` | Gets prefectures, supports callback |
|
|
358
|
+
| `onGetCitiesByPrefecture(area, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` | Gets cities, supports callback |
|
|
359
|
+
| `onGetTownsByCity(city, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` | Gets towns, supports callback |
|
|
357
360
|
|
|
358
361
|
---
|
|
359
362
|
|
|
360
|
-
###
|
|
363
|
+
### TypeScript Interfaces
|
|
361
364
|
|
|
362
365
|
```typescript
|
|
363
366
|
export interface GeoLocation {
|
|
@@ -365,8 +368,8 @@ export interface GeoLocation {
|
|
|
365
368
|
city_kana: string; // "ちよだく"
|
|
366
369
|
town: string; // "千代田"
|
|
367
370
|
town_kana: string; // "ちよだ"
|
|
368
|
-
x: string; // "139.7533" (
|
|
369
|
-
y: string; // "35.6852" (
|
|
371
|
+
x: string; // "139.7533" (Longitude)
|
|
372
|
+
y: string; // "35.6852" (Latitude)
|
|
370
373
|
prefecture: string; // "東京都"
|
|
371
374
|
postal: string; // "1000001"
|
|
372
375
|
}
|
|
@@ -384,64 +387,52 @@ export interface SuggestOptions extends SearchOptions {
|
|
|
384
387
|
|
|
385
388
|
---
|
|
386
389
|
|
|
387
|
-
## 🧪
|
|
390
|
+
## 🧪 Testing
|
|
388
391
|
|
|
389
|
-
|
|
392
|
+
The library uses the standard Node.js native test runner (`node:test` and `node:assert/strict`), requiring zero test framework overhead:
|
|
390
393
|
|
|
391
394
|
```bash
|
|
392
|
-
cd /home/dungdao/projects/jp-postal-lookup
|
|
393
|
-
|
|
394
|
-
# Chạy test suite
|
|
395
395
|
npm test
|
|
396
396
|
```
|
|
397
397
|
|
|
398
|
-
###
|
|
399
|
-
1. `normalizePostal`:
|
|
400
|
-
2. `onSearchAddressByPostcode`:
|
|
401
|
-
3.
|
|
402
|
-
4. `onSearchPostcodeByAddress`:
|
|
403
|
-
5. `getPrefecturesByArea`, `onGetCitiesByPrefecture`, `onGetTownsByCity
|
|
404
|
-
6. Modern
|
|
398
|
+
### Test Coverage Highlights:
|
|
399
|
+
1. `normalizePostal`: Handles half-width, full-width hyphens (`-`, `ー`, `-`), spaces, and nullish inputs.
|
|
400
|
+
2. `onSearchAddressByPostcode`: Exact postal code match in string and object formats.
|
|
401
|
+
3. Non-existent codes (`000-0000`) or invalid inputs: Safely returns empty strings or `null` without throwing errors.
|
|
402
|
+
4. `onSearchPostcodeByAddress`: Keyword address search and unmatched fallback.
|
|
403
|
+
5. Regional breakdown: `getPrefecturesByArea`, `onGetCitiesByPrefecture`, `onGetTownsByCity` with Promises and callbacks.
|
|
404
|
+
6. Modern API features: `{ raw: true }`, `{ all: true }`, and `{ matching: 'like' }` options.
|
|
405
405
|
|
|
406
406
|
---
|
|
407
407
|
|
|
408
|
-
## ⚠️
|
|
408
|
+
## ⚠️ Error Handling & Gotchas
|
|
409
409
|
|
|
410
|
-
1. **HeartRails Geo API**:
|
|
411
|
-
-
|
|
412
|
-
-
|
|
410
|
+
1. **HeartRails Geo API Endpoint**:
|
|
411
|
+
- Queries are resolved via the public [HeartRails Geo API](https://geoapi.heartrails.com/api/json).
|
|
412
|
+
- If your environment requires an internal reverse proxy or custom mock server, pass `baseUrl`:
|
|
413
413
|
```javascript
|
|
414
|
-
searchAddressByPostal('1000001', { baseUrl: '/api/
|
|
414
|
+
searchAddressByPostal('1000001', { baseUrl: 'https://my-internal-proxy.com/api/json' });
|
|
415
415
|
```
|
|
416
|
-
2. **Network Fail-
|
|
417
|
-
-
|
|
416
|
+
2. **Network Fail-Safe**:
|
|
417
|
+
- All network calls are protected with internal `try/catch` handlers. If an outage occurs or the API returns non-200 status codes, the functions return `''`, `null`, or `[]` depending on options, preventing uncaught promise rejections.
|
|
418
418
|
|
|
419
419
|
---
|
|
420
420
|
|
|
421
|
-
## 🚢
|
|
421
|
+
## 🚢 Publishing to npm
|
|
422
422
|
|
|
423
|
-
###
|
|
423
|
+
### Step 1: Login to npm
|
|
424
424
|
```bash
|
|
425
425
|
npm login
|
|
426
426
|
```
|
|
427
427
|
|
|
428
|
-
###
|
|
429
|
-
Trong `package.json`:
|
|
430
|
-
- Nếu publish public: `"name": "jp-postal-lookup"`
|
|
431
|
-
- Nếu publish scoped theo user/org: `"name": "@dungdao/jp-postal-lookup"`
|
|
432
|
-
|
|
433
|
-
### Bước 3: Chạy test & kiểm tra files
|
|
428
|
+
### Step 2: Run Tests and Validate Bundle
|
|
434
429
|
```bash
|
|
435
430
|
npm test
|
|
436
431
|
npm pack --dry-run
|
|
437
432
|
```
|
|
438
433
|
|
|
439
|
-
###
|
|
434
|
+
### Step 3: Publish to npm Registry
|
|
440
435
|
```bash
|
|
441
|
-
# Package thường:
|
|
442
|
-
npm publish
|
|
443
|
-
|
|
444
|
-
# Hoặc Scoped package public:
|
|
445
436
|
npm publish --access public
|
|
446
437
|
```
|
|
447
438
|
|
|
@@ -449,4 +440,4 @@ npm publish --access public
|
|
|
449
440
|
|
|
450
441
|
## 📄 License
|
|
451
442
|
|
|
452
|
-
|
|
443
|
+
Published under the [MIT License](LICENSE).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u="https://geoapi.heartrails.com/api/json";function f(n){return n==null?"":String(n).replace(/[ー--]/g,"").replace(/[\s\u3000]/g,"").trim()}async function a(n,t={}){let e=typeof globalThis.fetch=="function"?globalThis.fetch:null;if(!e)throw new Error("jp-postal-lookup: Fetch API is not available in this environment.");try{let r=await e(n,t);return r.ok?(await r.json())?.response??null:null}catch{return null}}async function p(n,t,e=u){let r=`${e}?method=getPrefectures&area=${encodeURIComponent(n||"")}`,s=await a(r);return typeof t=="function"&&t(s),s}async function y(n,t,e,r=u){let s=n?`&area=${encodeURIComponent(n)}`:"",o=`${r}?method=getCities${s}&prefecture=${encodeURIComponent(t||"")}`,i=await a(o);return typeof e=="function"&&e(i),i}async function d(n,t,e,r=u){let s=`${r}?method=getTowns&city=${encodeURIComponent(n||"")}&prefecture=${encodeURIComponent(t||"")}`,o=await a(s);return typeof e=="function"&&e(o),o}async function h(n,t=!1,e=u){let r=f(n);if(!r)return t?null:"";let s=`${e}?method=searchByPostal&postal=${encodeURIComponent(r)}`,o=await a(s);if(!o)return t?null:"";let i=o?.location;if(Array.isArray(i)&&i.length>0){let c=i[0];return t?c:`${c.prefecture||""}${c.city||""}${c.town||""}`}return t?null:""}async function g(n,t=!1,e="suffix",r=u){if(!n||typeof n!="string"||!n.trim())return t?null:"";let s=`${r}?method=suggest&matching=${encodeURIComponent(e)}&keyword=${encodeURIComponent(n.trim())}`,o=await a(s);if(!o)return t?null:"";let i=o?.location;if(Array.isArray(i)&&i.length>0){let c=i[0];return t?c:c?.postal||""}return t?null:""}async function m(n,{raw:t=!1,all:e=!1,baseUrl:r=u}={}){let s=f(n);if(!s)return e?[]:t?null:"";let o=`${r}?method=searchByPostal&postal=${encodeURIComponent(s)}`,c=(await a(o))?.location||[];if(!c.length)return e?[]:t?null:"";if(e)return c;let l=c[0];return t?l:`${l.prefecture||""}${l.city||""}${l.town||""}`}async function $(n,{raw:t=!1,all:e=!1,matching:r="suffix",baseUrl:s=u}={}){if(!n||typeof n!="string"||!n.trim())return e?[]:t?null:"";let o=`${s}?method=suggest&matching=${encodeURIComponent(r)}&keyword=${encodeURIComponent(n.trim())}`,c=(await a(o))?.location||[];if(!c.length)return e?[]:t?null:"";if(e)return c;let l=c[0];return t?l:l.postal||""}async function w(n=u){let t=`${n}?method=getAreas`;return(await a(t))?.area||[]}async function A(n,t=u){return(await p(n,null,t))?.prefecture||[]}async function C(n,t="",e=u){return((await y(t,n,null,e))?.location||[]).map(o=>typeof o=="string"?o:o.city).filter(Boolean)}async function I(n,t="",e=u){return((await d(n,t,null,e))?.location||[]).map(o=>typeof o=="string"?o:o.town).filter(Boolean)}module.exports={DEFAULT_API_BASE_URL:u,normalizePostal:f,getPrefecturesByArea:p,onGetCitiesByPrefecture:y,onGetTownsByCity:d,onSearchAddressByPostcode:h,onSearchPostcodeByAddress:g,searchAddressByPostal:m,searchPostalByAddress:$,getAreas:w,getPrefectures:A,getCities:C,getTowns:I};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u="https://geoapi.heartrails.com/api/json";function f(t){return t==null?"":String(t).replace(/[ー--]/g,"").replace(/[\s\u3000]/g,"").trim()}async function a(t,n={}){let e=typeof globalThis.fetch=="function"?globalThis.fetch:null;if(!e)throw new Error("jp-postal-lookup: Fetch API is not available in this environment.");try{let r=await e(t,n);return r.ok?(await r.json())?.response??null:null}catch{return null}}async function p(t,n,e=u){let r=`${e}?method=getPrefectures&area=${encodeURIComponent(t||"")}`,s=await a(r);return typeof n=="function"&&n(s),s}async function y(t,n,e,r=u){let s=t?`&area=${encodeURIComponent(t)}`:"",o=`${r}?method=getCities${s}&prefecture=${encodeURIComponent(n||"")}`,i=await a(o);return typeof e=="function"&&e(i),i}async function d(t,n,e,r=u){let s=`${r}?method=getTowns&city=${encodeURIComponent(t||"")}&prefecture=${encodeURIComponent(n||"")}`,o=await a(s);return typeof e=="function"&&e(o),o}async function h(t,n=!1,e=u){let r=f(t);if(!r)return n?null:"";let s=`${e}?method=searchByPostal&postal=${encodeURIComponent(r)}`,o=await a(s);if(!o)return n?null:"";let i=o?.location;if(Array.isArray(i)&&i.length>0){let c=i[0];return n?c:`${c.prefecture||""}${c.city||""}${c.town||""}`}return n?null:""}async function g(t,n=!1,e="suffix",r=u){if(!t||typeof t!="string"||!t.trim())return n?null:"";let s=`${r}?method=suggest&matching=${encodeURIComponent(e)}&keyword=${encodeURIComponent(t.trim())}`,o=await a(s);if(!o)return n?null:"";let i=o?.location;if(Array.isArray(i)&&i.length>0){let c=i[0];return n?c:c?.postal||""}return n?null:""}async function m(t,{raw:n=!1,all:e=!1,baseUrl:r=u}={}){let s=f(t);if(!s)return e?[]:n?null:"";let o=`${r}?method=searchByPostal&postal=${encodeURIComponent(s)}`,c=(await a(o))?.location||[];if(!c.length)return e?[]:n?null:"";if(e)return c;let l=c[0];return n?l:`${l.prefecture||""}${l.city||""}${l.town||""}`}async function $(t,{raw:n=!1,all:e=!1,matching:r="suffix",baseUrl:s=u}={}){if(!t||typeof t!="string"||!t.trim())return e?[]:n?null:"";let o=`${s}?method=suggest&matching=${encodeURIComponent(r)}&keyword=${encodeURIComponent(t.trim())}`,c=(await a(o))?.location||[];if(!c.length)return e?[]:n?null:"";if(e)return c;let l=c[0];return n?l:l.postal||""}async function w(t=u){let n=`${t}?method=getAreas`;return(await a(n))?.area||[]}async function A(t,n=u){return(await p(t,null,n))?.prefecture||[]}async function x(t,n="",e=u){return((await y(n,t,null,e))?.location||[]).map(o=>typeof o=="string"?o:o.city).filter(Boolean)}async function C(t,n="",e=u){return((await d(t,n,null,e))?.location||[]).map(o=>typeof o=="string"?o:o.town).filter(Boolean)}var I={DEFAULT_API_BASE_URL:u,normalizePostal:f,getPrefecturesByArea:p,onGetCitiesByPrefecture:y,onGetTownsByCity:d,onSearchAddressByPostcode:h,onSearchPostcodeByAddress:g,searchAddressByPostal:m,searchPostalByAddress:$,getAreas:w,getPrefectures:A,getCities:x,getTowns:C};export{u as DEFAULT_API_BASE_URL,I as default,w as getAreas,x as getCities,A as getPrefectures,p as getPrefecturesByArea,C as getTowns,f as normalizePostal,y as onGetCitiesByPrefecture,d as onGetTownsByCity,h as onSearchAddressByPostcode,g as onSearchPostcodeByAddress,m as searchAddressByPostal,$ as searchPostalByAddress};
|
package/package.json
CHANGED
|
@@ -1,42 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jp-postal-lookup",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "Zero-dependency Japanese address and postal code lookup library using HeartRails Geo API. Supports ESM, CommonJS, and TypeScript.",
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "Zero-dependency Japanese address and postal code lookup library using HeartRails Geo API. Supports ESM, CommonJS, and TypeScript. 日本の郵便番号・住所検索ライブラリ。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"japan",
|
|
7
|
+
"japanese",
|
|
7
8
|
"postal",
|
|
8
9
|
"postcode",
|
|
9
10
|
"zipcode",
|
|
11
|
+
"postal-code",
|
|
12
|
+
"postal-code-lookup",
|
|
13
|
+
"japan-postal-code",
|
|
14
|
+
"japanese-postal-code",
|
|
15
|
+
"japan-zipcode",
|
|
10
16
|
"address",
|
|
17
|
+
"japan-address",
|
|
18
|
+
"japanese-address",
|
|
19
|
+
"address-lookup",
|
|
20
|
+
"address-search",
|
|
11
21
|
"heartrails",
|
|
12
22
|
"geo",
|
|
23
|
+
"geoapi",
|
|
13
24
|
"prefecture",
|
|
14
25
|
"city",
|
|
15
|
-
"town"
|
|
26
|
+
"town",
|
|
27
|
+
"yubinbango",
|
|
28
|
+
"ken-all",
|
|
29
|
+
"郵便番号",
|
|
30
|
+
"住所検索",
|
|
31
|
+
"郵便番号検索",
|
|
32
|
+
"都道府県"
|
|
16
33
|
],
|
|
17
34
|
"author": "dungdao",
|
|
18
35
|
"license": "MIT",
|
|
19
36
|
"type": "module",
|
|
20
|
-
"main": "./
|
|
21
|
-
"module": "./
|
|
37
|
+
"main": "./dist/index.cjs",
|
|
38
|
+
"module": "./dist/index.js",
|
|
22
39
|
"types": "./index.d.ts",
|
|
23
40
|
"exports": {
|
|
24
41
|
".": {
|
|
25
42
|
"types": "./index.d.ts",
|
|
26
|
-
"import": "./
|
|
27
|
-
"require": "./
|
|
43
|
+
"import": "./dist/index.js",
|
|
44
|
+
"require": "./dist/index.cjs"
|
|
28
45
|
}
|
|
29
46
|
},
|
|
30
47
|
"files": [
|
|
31
|
-
"
|
|
48
|
+
"dist",
|
|
32
49
|
"index.d.ts",
|
|
33
50
|
"README.md",
|
|
34
51
|
"LICENSE"
|
|
35
52
|
],
|
|
36
53
|
"scripts": {
|
|
37
|
-
"
|
|
54
|
+
"build": "node scripts/build.mjs",
|
|
55
|
+
"test": "node --test tests/index.test.js",
|
|
56
|
+
"test:dist": "npm run build && node --test tests/dist.test.js",
|
|
57
|
+
"prepublishOnly": "npm test && npm run test:dist"
|
|
38
58
|
},
|
|
39
59
|
"engines": {
|
|
40
60
|
"node": ">=18.0.0"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"esbuild": "^0.28.2"
|
|
41
64
|
}
|
|
42
65
|
}
|
package/src/index.cjs
DELETED
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
const DEFAULT_API_BASE_URL = 'https://geoapi.heartrails.com/api/json';
|
|
2
|
-
|
|
3
|
-
function normalizePostal(postal) {
|
|
4
|
-
if (postal === null || postal === undefined) return '';
|
|
5
|
-
return String(postal)
|
|
6
|
-
.replace(/[ー--]/g, '')
|
|
7
|
-
.replace(/[\s\u3000]/g, '')
|
|
8
|
-
.trim();
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
async function fetchJson(url, options = {}) {
|
|
12
|
-
const fetchFn = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
|
|
13
|
-
if (!fetchFn) {
|
|
14
|
-
throw new Error('jp-postal-lookup: Fetch API is not available in this environment.');
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
try {
|
|
18
|
-
const response = await fetchFn(url, options);
|
|
19
|
-
if (!response.ok) {
|
|
20
|
-
return null;
|
|
21
|
-
}
|
|
22
|
-
const data = await response.json();
|
|
23
|
-
return data?.response ?? null;
|
|
24
|
-
} catch {
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
async function getPrefecturesByArea(area, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
30
|
-
const url = `${baseUrl}?method=getPrefectures&area=${encodeURIComponent(area || '')}`;
|
|
31
|
-
const result = await fetchJson(url);
|
|
32
|
-
if (typeof callback === 'function') {
|
|
33
|
-
callback(result);
|
|
34
|
-
}
|
|
35
|
-
return result;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async function onGetCitiesByPrefecture(area, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
39
|
-
const queryArea = area ? `&area=${encodeURIComponent(area)}` : '';
|
|
40
|
-
const url = `${baseUrl}?method=getCities${queryArea}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
41
|
-
const result = await fetchJson(url);
|
|
42
|
-
if (typeof callback === 'function') {
|
|
43
|
-
callback(result);
|
|
44
|
-
}
|
|
45
|
-
return result;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
async function onGetTownsByCity(city, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
49
|
-
const url = `${baseUrl}?method=getTowns&city=${encodeURIComponent(city || '')}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
50
|
-
const result = await fetchJson(url);
|
|
51
|
-
if (typeof callback === 'function') {
|
|
52
|
-
callback(result);
|
|
53
|
-
}
|
|
54
|
-
return result;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function onSearchAddressByPostcode(postcode, isResponse = false, baseUrl = DEFAULT_API_BASE_URL) {
|
|
58
|
-
const cleanCode = normalizePostal(postcode);
|
|
59
|
-
if (!cleanCode) return isResponse ? null : '';
|
|
60
|
-
|
|
61
|
-
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(cleanCode)}`;
|
|
62
|
-
const response = await fetchJson(url);
|
|
63
|
-
|
|
64
|
-
if (!response) {
|
|
65
|
-
return isResponse ? null : '';
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const dataAddress = response?.location;
|
|
69
|
-
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
70
|
-
const address = dataAddress[0];
|
|
71
|
-
if (isResponse) {
|
|
72
|
-
return address;
|
|
73
|
-
}
|
|
74
|
-
return `${address.prefecture || ''}${address.city || ''}${address.town || ''}`;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
return isResponse ? null : '';
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async function onSearchPostcodeByAddress(
|
|
81
|
-
address,
|
|
82
|
-
isResponse = false,
|
|
83
|
-
matching = 'suffix',
|
|
84
|
-
baseUrl = DEFAULT_API_BASE_URL
|
|
85
|
-
) {
|
|
86
|
-
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
87
|
-
return isResponse ? null : '';
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
91
|
-
const response = await fetchJson(url);
|
|
92
|
-
|
|
93
|
-
if (!response) {
|
|
94
|
-
return isResponse ? null : '';
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const dataAddress = response?.location;
|
|
98
|
-
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
99
|
-
const item = dataAddress[0];
|
|
100
|
-
return isResponse ? item : item?.postal || '';
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
return isResponse ? null : '';
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
async function searchAddressByPostal(postal, { raw = false, all = false, baseUrl = DEFAULT_API_BASE_URL } = {}) {
|
|
107
|
-
const clean = normalizePostal(postal);
|
|
108
|
-
if (!clean) return all ? [] : raw ? null : '';
|
|
109
|
-
|
|
110
|
-
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(clean)}`;
|
|
111
|
-
const response = await fetchJson(url);
|
|
112
|
-
const locations = response?.location || [];
|
|
113
|
-
|
|
114
|
-
if (!locations.length) {
|
|
115
|
-
return all ? [] : raw ? null : '';
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
if (all) {
|
|
119
|
-
return locations;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const first = locations[0];
|
|
123
|
-
if (raw) {
|
|
124
|
-
return first;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
return `${first.prefecture || ''}${first.city || ''}${first.town || ''}`;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
async function searchPostalByAddress(
|
|
131
|
-
address,
|
|
132
|
-
{ raw = false, all = false, matching = 'suffix', baseUrl = DEFAULT_API_BASE_URL } = {}
|
|
133
|
-
) {
|
|
134
|
-
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
135
|
-
return all ? [] : raw ? null : '';
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
139
|
-
const response = await fetchJson(url);
|
|
140
|
-
const locations = response?.location || [];
|
|
141
|
-
|
|
142
|
-
if (!locations.length) {
|
|
143
|
-
return all ? [] : raw ? null : '';
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
if (all) {
|
|
147
|
-
return locations;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
const first = locations[0];
|
|
151
|
-
return raw ? first : first.postal || '';
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
async function getAreas(baseUrl = DEFAULT_API_BASE_URL) {
|
|
155
|
-
const url = `${baseUrl}?method=getAreas`;
|
|
156
|
-
const response = await fetchJson(url);
|
|
157
|
-
return response?.area || [];
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
async function getPrefectures(area, baseUrl = DEFAULT_API_BASE_URL) {
|
|
161
|
-
const response = await getPrefecturesByArea(area, null, baseUrl);
|
|
162
|
-
return response?.prefecture || [];
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async function getCities(prefecture, area = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
166
|
-
const response = await onGetCitiesByPrefecture(area, prefecture, null, baseUrl);
|
|
167
|
-
const locations = response?.location || [];
|
|
168
|
-
return locations.map((item) => (typeof item === 'string' ? item : item.city)).filter(Boolean);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
async function getTowns(city, prefecture = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
172
|
-
const response = await onGetTownsByCity(city, prefecture, null, baseUrl);
|
|
173
|
-
const locations = response?.location || [];
|
|
174
|
-
return locations.map((item) => (typeof item === 'string' ? item : item.town)).filter(Boolean);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
module.exports = {
|
|
178
|
-
DEFAULT_API_BASE_URL,
|
|
179
|
-
normalizePostal,
|
|
180
|
-
getPrefecturesByArea,
|
|
181
|
-
onGetCitiesByPrefecture,
|
|
182
|
-
onGetTownsByCity,
|
|
183
|
-
onSearchAddressByPostcode,
|
|
184
|
-
onSearchPostcodeByAddress,
|
|
185
|
-
searchAddressByPostal,
|
|
186
|
-
searchPostalByAddress,
|
|
187
|
-
getAreas,
|
|
188
|
-
getPrefectures,
|
|
189
|
-
getCities,
|
|
190
|
-
getTowns
|
|
191
|
-
};
|
package/src/index.js
DELETED
|
@@ -1,297 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* jp-postal-lookup
|
|
3
|
-
* Lightweight library to search Japanese addresses, postal codes, prefectures, cities, and towns
|
|
4
|
-
* using HeartRails Geo API with zero runtime dependencies.
|
|
5
|
-
*
|
|
6
|
-
* Compatible with Node.js 18+ and modern browsers.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
export const DEFAULT_API_BASE_URL = 'https://geoapi.heartrails.com/api/json';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Format postal code by removing hyphens and full-width spaces.
|
|
13
|
-
* E.g., "100-0001" -> "1000001"
|
|
14
|
-
* @param {string|number} postal
|
|
15
|
-
* @returns {string}
|
|
16
|
-
*/
|
|
17
|
-
export function normalizePostal(postal) {
|
|
18
|
-
if (postal === null || postal === undefined) return '';
|
|
19
|
-
return String(postal)
|
|
20
|
-
.replace(/[ー--]/g, '')
|
|
21
|
-
.replace(/[\s\u3000]/g, '')
|
|
22
|
-
.trim();
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Internal fetch helper with JSON parsing and error handling.
|
|
27
|
-
* @param {string} url
|
|
28
|
-
* @param {RequestInit} [options]
|
|
29
|
-
* @returns {Promise<any>}
|
|
30
|
-
*/
|
|
31
|
-
async function fetchJson(url, options = {}) {
|
|
32
|
-
const fetchFn = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
|
|
33
|
-
if (!fetchFn) {
|
|
34
|
-
throw new Error('jp-postal-lookup: Fetch API is not available in this environment.');
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
try {
|
|
38
|
-
const response = await fetchFn(url, options);
|
|
39
|
-
if (!response.ok) {
|
|
40
|
-
return null;
|
|
41
|
-
}
|
|
42
|
-
const data = await response.json();
|
|
43
|
-
return data?.response ?? null;
|
|
44
|
-
} catch {
|
|
45
|
-
return null;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Get list of prefectures by area.
|
|
51
|
-
* @param {string} area - e.g., '関東', '近畿', '中部', etc.
|
|
52
|
-
* @param {Function} [callback] - Optional callback (response) => void
|
|
53
|
-
* @param {string} [baseUrl]
|
|
54
|
-
* @returns {Promise<any>}
|
|
55
|
-
*/
|
|
56
|
-
export async function getPrefecturesByArea(area, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
57
|
-
const url = `${baseUrl}?method=getPrefectures&area=${encodeURIComponent(area || '')}`;
|
|
58
|
-
const result = await fetchJson(url);
|
|
59
|
-
if (typeof callback === 'function') {
|
|
60
|
-
callback(result);
|
|
61
|
-
}
|
|
62
|
-
return result;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Get cities by area and prefecture.
|
|
67
|
-
* @param {string} area
|
|
68
|
-
* @param {string} prefecture - e.g., '東京都'
|
|
69
|
-
* @param {Function} [callback]
|
|
70
|
-
* @param {string} [baseUrl]
|
|
71
|
-
* @returns {Promise<any>}
|
|
72
|
-
*/
|
|
73
|
-
export async function onGetCitiesByPrefecture(area, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
74
|
-
const queryArea = area ? `&area=${encodeURIComponent(area)}` : '';
|
|
75
|
-
const url = `${baseUrl}?method=getCities${queryArea}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
76
|
-
const result = await fetchJson(url);
|
|
77
|
-
if (typeof callback === 'function') {
|
|
78
|
-
callback(result);
|
|
79
|
-
}
|
|
80
|
-
return result;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Get towns by city and prefecture.
|
|
85
|
-
* @param {string} city - e.g., '千代田区'
|
|
86
|
-
* @param {string} prefecture - e.g., '東京都'
|
|
87
|
-
* @param {Function} [callback]
|
|
88
|
-
* @param {string} [baseUrl]
|
|
89
|
-
* @returns {Promise<any>}
|
|
90
|
-
*/
|
|
91
|
-
export async function onGetTownsByCity(city, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
92
|
-
const url = `${baseUrl}?method=getTowns&city=${encodeURIComponent(city || '')}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
93
|
-
const result = await fetchJson(url);
|
|
94
|
-
if (typeof callback === 'function') {
|
|
95
|
-
callback(result);
|
|
96
|
-
}
|
|
97
|
-
return result;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Search address by postal code.
|
|
102
|
-
* @param {string|number} postcode - Japanese postal code (with or without hyphen)
|
|
103
|
-
* @param {boolean} [isResponse=false] - If true, returns the raw location object; otherwise returns formatted address string
|
|
104
|
-
* @param {string} [baseUrl]
|
|
105
|
-
* @returns {Promise<string|object|null>}
|
|
106
|
-
*/
|
|
107
|
-
export async function onSearchAddressByPostcode(postcode, isResponse = false, baseUrl = DEFAULT_API_BASE_URL) {
|
|
108
|
-
const cleanCode = normalizePostal(postcode);
|
|
109
|
-
if (!cleanCode) return isResponse ? null : '';
|
|
110
|
-
|
|
111
|
-
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(cleanCode)}`;
|
|
112
|
-
const response = await fetchJson(url);
|
|
113
|
-
|
|
114
|
-
if (!response) {
|
|
115
|
-
return isResponse ? null : '';
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const dataAddress = response?.location;
|
|
119
|
-
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
120
|
-
const address = dataAddress[0];
|
|
121
|
-
if (isResponse) {
|
|
122
|
-
return address;
|
|
123
|
-
}
|
|
124
|
-
return `${address.prefecture || ''}${address.city || ''}${address.town || ''}`;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
return isResponse ? null : '';
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Search postal code by address string.
|
|
132
|
-
* @param {string} address - Address keyword (e.g. '東京都千代田区')
|
|
133
|
-
* @param {boolean} [isResponse=false] - If true, returns the raw location object; otherwise returns postal string
|
|
134
|
-
* @param {string} [matching='suffix'] - 'prefix', 'suffix', or 'like'
|
|
135
|
-
* @param {string} [baseUrl]
|
|
136
|
-
* @returns {Promise<string|object|null>}
|
|
137
|
-
*/
|
|
138
|
-
export async function onSearchPostcodeByAddress(
|
|
139
|
-
address,
|
|
140
|
-
isResponse = false,
|
|
141
|
-
matching = 'suffix',
|
|
142
|
-
baseUrl = DEFAULT_API_BASE_URL
|
|
143
|
-
) {
|
|
144
|
-
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
145
|
-
return isResponse ? null : '';
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
149
|
-
const response = await fetchJson(url);
|
|
150
|
-
|
|
151
|
-
if (!response) {
|
|
152
|
-
return isResponse ? null : '';
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
const dataAddress = response?.location;
|
|
156
|
-
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
157
|
-
const item = dataAddress[0];
|
|
158
|
-
return isResponse ? item : item?.postal || '';
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
return isResponse ? null : '';
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// -------------------------------------------------------------
|
|
165
|
-
// Modern Idiomatic Aliases
|
|
166
|
-
// -------------------------------------------------------------
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Search full address by postal code.
|
|
170
|
-
* @param {string|number} postal
|
|
171
|
-
* @param {object} [options]
|
|
172
|
-
* @param {boolean} [options.raw=false]
|
|
173
|
-
* @param {boolean} [options.all=false] - Return array of all matched locations
|
|
174
|
-
* @param {string} [options.baseUrl]
|
|
175
|
-
* @returns {Promise<string|object|object[]|null>}
|
|
176
|
-
*/
|
|
177
|
-
export async function searchAddressByPostal(postal, { raw = false, all = false, baseUrl = DEFAULT_API_BASE_URL } = {}) {
|
|
178
|
-
const clean = normalizePostal(postal);
|
|
179
|
-
if (!clean) return all ? [] : raw ? null : '';
|
|
180
|
-
|
|
181
|
-
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(clean)}`;
|
|
182
|
-
const response = await fetchJson(url);
|
|
183
|
-
const locations = response?.location || [];
|
|
184
|
-
|
|
185
|
-
if (!locations.length) {
|
|
186
|
-
return all ? [] : raw ? null : '';
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
if (all) {
|
|
190
|
-
return locations;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
const first = locations[0];
|
|
194
|
-
if (raw) {
|
|
195
|
-
return first;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
return `${first.prefecture || ''}${first.city || ''}${first.town || ''}`;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* Search postal code by address keyword.
|
|
203
|
-
* @param {string} address
|
|
204
|
-
* @param {object} [options]
|
|
205
|
-
* @param {boolean} [options.raw=false]
|
|
206
|
-
* @param {boolean} [options.all=false]
|
|
207
|
-
* @param {'prefix'|'suffix'|'like'} [options.matching='suffix']
|
|
208
|
-
* @param {string} [options.baseUrl]
|
|
209
|
-
* @returns {Promise<string|object|object[]|null>}
|
|
210
|
-
*/
|
|
211
|
-
export async function searchPostalByAddress(
|
|
212
|
-
address,
|
|
213
|
-
{ raw = false, all = false, matching = 'suffix', baseUrl = DEFAULT_API_BASE_URL } = {}
|
|
214
|
-
) {
|
|
215
|
-
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
216
|
-
return all ? [] : raw ? null : '';
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
220
|
-
const response = await fetchJson(url);
|
|
221
|
-
const locations = response?.location || [];
|
|
222
|
-
|
|
223
|
-
if (!locations.length) {
|
|
224
|
-
return all ? [] : raw ? null : '';
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
if (all) {
|
|
228
|
-
return locations;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const first = locations[0];
|
|
232
|
-
return raw ? first : first.postal || '';
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/**
|
|
236
|
-
* Get areas in Japan (Hokkaido, Tohoku, Kanto, Chubu, Kinki, Chugoku, Shikoku, Kyushu).
|
|
237
|
-
* @param {string} [baseUrl]
|
|
238
|
-
* @returns {Promise<string[]>}
|
|
239
|
-
*/
|
|
240
|
-
export async function getAreas(baseUrl = DEFAULT_API_BASE_URL) {
|
|
241
|
-
const url = `${baseUrl}?method=getAreas`;
|
|
242
|
-
const response = await fetchJson(url);
|
|
243
|
-
return response?.area || [];
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
/**
|
|
247
|
-
* Get prefectures in an area.
|
|
248
|
-
* @param {string} area
|
|
249
|
-
* @param {string} [baseUrl]
|
|
250
|
-
* @returns {Promise<string[]>}
|
|
251
|
-
*/
|
|
252
|
-
export async function getPrefectures(area, baseUrl = DEFAULT_API_BASE_URL) {
|
|
253
|
-
const response = await getPrefecturesByArea(area, null, baseUrl);
|
|
254
|
-
return response?.prefecture || [];
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Get cities in a prefecture.
|
|
259
|
-
* @param {string} prefecture
|
|
260
|
-
* @param {string} [area]
|
|
261
|
-
* @param {string} [baseUrl]
|
|
262
|
-
* @returns {Promise<string[]>}
|
|
263
|
-
*/
|
|
264
|
-
export async function getCities(prefecture, area = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
265
|
-
const response = await onGetCitiesByPrefecture(area, prefecture, null, baseUrl);
|
|
266
|
-
const locations = response?.location || [];
|
|
267
|
-
return locations.map((item) => (typeof item === 'string' ? item : item.city)).filter(Boolean);
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* Get towns in a city.
|
|
272
|
-
* @param {string} city
|
|
273
|
-
* @param {string} [prefecture]
|
|
274
|
-
* @param {string} [baseUrl]
|
|
275
|
-
* @returns {Promise<string[]>}
|
|
276
|
-
*/
|
|
277
|
-
export async function getTowns(city, prefecture = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
278
|
-
const response = await onGetTownsByCity(city, prefecture, null, baseUrl);
|
|
279
|
-
const locations = response?.location || [];
|
|
280
|
-
return locations.map((item) => (typeof item === 'string' ? item : item.town)).filter(Boolean);
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
export default {
|
|
284
|
-
DEFAULT_API_BASE_URL,
|
|
285
|
-
normalizePostal,
|
|
286
|
-
getPrefecturesByArea,
|
|
287
|
-
onGetCitiesByPrefecture,
|
|
288
|
-
onGetTownsByCity,
|
|
289
|
-
onSearchAddressByPostcode,
|
|
290
|
-
onSearchPostcodeByAddress,
|
|
291
|
-
searchAddressByPostal,
|
|
292
|
-
searchPostalByAddress,
|
|
293
|
-
getAreas,
|
|
294
|
-
getPrefectures,
|
|
295
|
-
getCities,
|
|
296
|
-
getTowns
|
|
297
|
-
};
|