@superrouteca/slocker-react 0.0.0-stage → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,40 @@
1
+ # 0.2.0
2
+
3
+ ## SDK
4
+
5
+ ### Customer side (new)
6
+ - **Smart lockers for customer apps**: the locker operations an app makes for a service provider's customers come to sLocker: parcels waiting in lockers and their pickup codes, opening the door to collect, handing a pickup over to someone else and taking it back; locker locations, their indoor guides and the customer's preferred locker; locker storage rentals (claiming, keeping, the return time, sending on, pickup sites, resending the code); and the locker shop (catalogue, orders, opening the door, refund requests, access codes).
7
+ - **Same names as in sApp**: the 29 locker methods sApp 0.2.1 had keep exactly their names and arguments, so moving from sApp is a change of package, not of call.
8
+ - **Locker resale**: list the resale terms and the person's deals, create a deal, release or revoke the buyer's code, abort, cancel or report a deal.
9
+ - **Standalone or beside sApp**: create a customer client with the app code, the service provider's client code, the app key and a token store, or pass an sApp client the app already has to share one sign-in. Sign-in, token refresh, idempotency keys, retries and errors are sApp's own.
10
+ - **Every language**: JavaScript and TypeScript, Dart, Swift, Kotlin, Java, C#, Python, PHP and Go.
11
+
12
+ ### Carrier side
13
+ - **Unchanged**: the carrier and partner locker delivery API, its packages and their calls stay exactly as in 0.1.1 and do not depend on sApp.
14
+
15
+ ## UI kits
16
+
17
+ ### Flutter, web, React, React Native, SwiftUI, Jetpack Compose, WPF and WinForms (new)
18
+ - **Pickup list**: the person's parcels in lockers with their pickup codes, remaining parcels and expiry, and opening the door after confirming.
19
+ - **Locker map**: lockers near the person with distance, status and free compartments, search and filters for pickup, returns and free space, and the same lockers on the app's own sMap map, fitted to them; tapping a locker or its point selects it.
20
+ - **Themed by sApp**: the components use the sApp UI kit's branding, strings in 14 languages and sign-in handling, as they did in sApp.
21
+
22
+ # 0.1.1
23
+
24
+ ## Licence
25
+
26
+ ### Every package
27
+ - **Superroute SDK License**: from this version on the packages are licensed under the Superroute SDK License — see `LICENSE` and [open.superroute.ca/developer/license](https://open.superroute.ca/developer/license). Versions published before keep the licence they were published with.
28
+
29
+ # 0.1.0
30
+
31
+ ## SDK
32
+
33
+ ### Every language
34
+ - **The partner locker delivery API in nine languages**: Python, PHP, Java, Go, C# and JavaScript / TypeScript on the server; Kotlin (Android), Swift (iOS and macOS) and Dart (Flutter) in apps. Every operation of the API has its own method: delivery tasks, remote door opening and confirmation, reassigning, cancelling and correcting a placement, opening for pickup, scopes and locations, usage reports, carrier pre-advice and carrier packages, and the mock cabinet.
35
+ - **Sign-in**: sign in with the API account, refresh, rotate with a grace period, or sign out; the provider to act for is set once or per call.
36
+ - **Errors as the server names them**: every failure carries the HTTP status and the server's stable code (`LOCKER_DELIVERY_IN_USE`, `IDEMPOTENCY_CONFLICT`, …), its message, field errors and the wait the server asked for.
37
+ - **Safe retries**: only repeatable calls are retried — reads, deletes and creates that carry an idempotency key — after a timeout, a lost connection, 408, 425, 429 or 5xx, waiting as long as the server asks. Opening doors, confirming and every other change are never repeated by the SDK.
38
+ - **Idempotency**: creating a delivery task and pre-advising packages always send an idempotency key, the caller's or one made for the call and kept across its retries.
39
+ - **Webhook verification**: `partner_locker.*` and `carrier_package.distribution.*` webhooks are checked against the raw body, the content digest, the signature and the timestamp, with several secrets accepted during a key rotation, and with Standard Webhooks and CloudEvents bodies understood; sandbox events are told apart. Test requests can be signed the same way.
40
+ - **One set of test cases** run by every language: requests, answers, retries, sign-in and webhook vectors.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ Superroute SDK License
2
+
3
+ Copyright (c) 2026 Superroute Inc. All rights reserved, except as granted below.
4
+
5
+ 1. Permission is granted, free of charge, to any person obtaining a copy of this software and its documentation
6
+ (the "Software") to install, use, copy and distribute the Software, including as part of their own products and
7
+ services, to connect to Superroute services, on any other platform, and in their own commercial projects.
8
+
9
+ 2. The Software may not be sold on its own, whether alone or as the main part of a product whose value lies in the
10
+ Software rather than in the product built with it.
11
+
12
+ 3. The copyright notices, this license and the attribution of the Software to Superroute may not be removed or
13
+ changed, and must be kept in every copy or substantial portion of the Software that is distributed.
14
+
15
+ 4. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
16
+ THE WARRANTIES OF MERCHANTABILITY, 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 LIABILITY, WHETHER IN AN ACTION OF
18
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19
+ IN THE SOFTWARE.
20
+
21
+ 5. Use of Superroute services through the Software is governed by the terms of those services.
package/README.md CHANGED
@@ -1,3 +1,523 @@
1
- # Temporary Holding Version
1
+ <picture>
2
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Goodneo-Solutions/slocker-releases/main/assets/slocker-logo-dark.svg">
3
+ <img src="https://raw.githubusercontent.com/Goodneo-Solutions/slocker-releases/main/assets/slocker-logo.svg" alt="sLocker" height="56">
4
+ </picture>
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # sLocker
7
+
8
+ Deliver to Superroute smart lockers. sLocker is the SDK for carriers and delivery partners that put parcels into
9
+ Superroute smart lockers: create a delivery task, open the doors remotely for the driver, confirm the deposit, follow
10
+ the pickup, and receive and verify the webhooks — with a mock cabinet to rehearse all of it. For apps made for a
11
+ service provider's customers, its [customer side](#customer-side) brings the parcels waiting in lockers, locker
12
+ locations, locker storage, the locker shop and locker resale, with a pickup list and a locker map for every UI kit.
13
+ Superroute SDK License — see [LICENSE](LICENSE) and [open.superroute.ca/developer/license](https://open.superroute.ca/developer/license).
14
+
15
+ | Package | Platform | Install |
16
+ |---|---|---|
17
+ | `superroute-slocker` (PyPI) | Python 3.9+ | `pip install superroute-slocker` |
18
+ | `superroute/slocker` (Packagist) | PHP 8.1+ | `composer require superroute/slocker` |
19
+ | `ca.superroute:slocker` (Maven) | Java 11+ and Android | see [Java and Kotlin](#java-and-kotlin) |
20
+ | `ca.superroute:slocker-android` (Maven) | Kotlin coroutines and OkHttp, for Android | see [Java and Kotlin](#java-and-kotlin) |
21
+ | `github.com/Goodneo-Solutions/slocker-releases/go` | Go 1.21+ | `go get github.com/Goodneo-Solutions/slocker-releases/go` |
22
+ | `Superroute.SLocker` (NuGet) | .NET 8 | `dotnet add package Superroute.SLocker` |
23
+ | `@superrouteca/slocker` (npm) | Node 20+, browsers, Deno, Bun; TypeScript types | `npm install @superrouteca/slocker` |
24
+ | `SLocker` (Swift package) | iOS 15+, macOS 12+ | `https://github.com/Goodneo-Solutions/slocker-releases` |
25
+ | `slocker` (pub.dev) | Dart 3.5+ and Flutter | `dart pub add slocker` |
26
+
27
+ The customer side (built on [sApp](https://open.superroute.ca/developer/sapp), from sApp 0.2.2):
28
+
29
+ | Package | Platform | Install |
30
+ |---|---|---|
31
+ | `@superrouteca/slocker-customer` (npm) | JavaScript and TypeScript: web, Node 20+, React Native | `npm install @superrouteca/slocker-customer` |
32
+ | `@superrouteca/slocker-ui` (npm) | Web UI kit: `sr-pickup-list`, `sr-locker-map` | `npm install @superrouteca/slocker-ui` |
33
+ | `@superrouteca/slocker-react` / `@superrouteca/slocker-react-native` (npm) | React and React Native UI kits | `npm install @superrouteca/slocker-react` |
34
+ | `slocker_customer` / `slocker_ui` (pub.dev) | Dart; Flutter UI kit | `dart pub add slocker_customer`, `flutter pub add slocker_ui` |
35
+ | `SLockerCustomer` / `SLockerUI` (Swift package) | iOS 15+, macOS 12+; SwiftUI kit | `https://github.com/Goodneo-Solutions/slocker-customer-releases` |
36
+ | `ca.superroute:slocker-customer-kotlin` / `slocker-ui-android` (Maven) | Kotlin on the JVM and Android; Jetpack Compose kit | see [Java and Kotlin](#java-and-kotlin) |
37
+ | `ca.superroute:slocker-customer` (Maven) | Java 17+ | see [Java and Kotlin](#java-and-kotlin) |
38
+ | `Superroute.SLocker.Customer` / `.UI` / `.Wpf` / `.WinForms` (NuGet) | .NET 8; WPF and WinForms kits | `dotnet add package Superroute.SLocker.Customer` |
39
+ | `superroute-slocker[customer]` (PyPI) | Python 3.9+, `import slocker.customer` | `pip install "superroute-slocker[customer]"` |
40
+ | `superroute/slocker` with `superroute/sapp` (Packagist) | PHP 8.1+, `Superroute\SLocker\Customer` | `composer require superroute/slocker superroute/sapp` |
41
+ | `github.com/Goodneo-Solutions/slocker-releases/go/customer` | Go 1.21+ | `go get github.com/Goodneo-Solutions/slocker-releases/go/customer` |
42
+
43
+ Every package of a release carries the same version and covers the same operations. The carrier packages do not
44
+ depend on sApp; only the customer side does.
45
+
46
+ ## What it covers
47
+
48
+ The partner locker delivery API of Superroute (`/api/v1/third-party-delivery/…`), 40 operations, each a method:
49
+
50
+ - **Delivery tasks** — create (idempotent), list, read, cancel, rotate a code.
51
+ - **At the cabinet** — open the doors remotely with the delivery code, confirm (all or a partial delivery), abort,
52
+ reassign a package to another compartment, cancel the placement, reopen within the 60-second correction window,
53
+ open for pickup.
54
+ - **Scopes and locations** — the grants and sub-scopes, create / update / disable a sub-scope, the locations of a
55
+ scope, the locations near an address or a point.
56
+ - **Usage** — summary, daily, by location.
57
+ - **Carriers** — the carrier profile, intake locations and receiving warehouses, pre-advising packages into a
58
+ warehouse, the carrier's packages, cancelling, rerouting, and resetting a pickup code.
59
+ - **Mock cabinet** — create, list and delete mock lockers, force doors open or closed, take a cabinet offline, change
60
+ its features and compartment sizes, seed parcels, clear them, or declare them taken.
61
+
62
+ The operations are generated from Superroute's published OpenAPI document (`specs/partner-locker-api.json`). The same
63
+ operations exist in Superroute's GraphQL API (`specs/partner-locker-graphql.json` lists them); sLocker calls REST.
64
+
65
+ ## Signing in and choosing the provider
66
+
67
+ The API takes the bearer token of a Superroute API account (`POST /api/v1/user/login`; a token lasts a week). Pass a
68
+ token you already have, or sign in with the client, which keeps the token for the following calls:
69
+
70
+ ```js
71
+ import { SLockerClient } from '@superrouteca/slocker';
72
+
73
+ const sl = new SLockerClient({ providerId: 4611 }); // baseUrl defaults to https://api.superroute.ca
74
+ await sl.login({ email: 'api-partner@example.com', password: process.env.SR_PASSWORD });
75
+ // later: await sl.refreshToken(); await sl.rotateToken({ gracePeriodMinutes: 60 }); await sl.logout();
76
+ ```
77
+
78
+ `providerId` is your third-party delivery provider (sent as `X-Third-Party-Provider-Id`). It may be left out when the
79
+ account acts for exactly one provider; any call can name another one (`providerId` in its parameters).
80
+
81
+ ## A delivery, end to end
82
+
83
+ 1. **Create the task** with the order's own idempotency key. The answer carries `delivery_no`, the driver's
84
+ `access_code` and the recipient's `pickup_code`. A repeat with the same key and the same content answers the
85
+ original task (`replayed: true`); the same key with different content is `409 IDEMPOTENCY_CONFLICT`.
86
+ 2. **At the cabinet**, the driver types the code on the screen — or your app opens the doors remotely with
87
+ `openPartnerLockerDelivery`, which answers a `claim_token` and the compartments that opened.
88
+ 3. **Confirm** with the claim token (`confirm_all`, or `accept_partial` when some packages did not fit). For a remote
89
+ open the cabinet settles the deposit by itself once every opened door reports closed; an explicit confirm afterwards
90
+ answers the same result.
91
+ 4. **Webhooks** tell you the rest: `partner_locker.delivery.doors_opened`, `.delivered` (with the pickup code and the
92
+ compartments), `partner_locker.pickup.completed`, `.failed`, `.expired`, `.cancelled`, `.correction_reopened`.
93
+
94
+ ```js
95
+ const created = await sl.api.createPartnerLockerDelivery({
96
+ idempotencyKey: 'FOOD-20260714-1001-v1', // your own, stable for this order
97
+ body: {
98
+ external_order_id: 'FOOD-20260714-1001',
99
+ platform_scope_group_id: 12,
100
+ recipient: { phone: '+14165550123' },
101
+ package_count: 2,
102
+ },
103
+ });
104
+ const { delivery_no, access_code } = created.data;
105
+
106
+ const opened = await sl.api.openPartnerLockerDelivery({ body: { location_id: 101, access_code } });
107
+ const { claim_token, attempt } = opened.data;
108
+ if (attempt.can_confirm) {
109
+ await sl.api.confirmPartnerLockerDelivery({ body: { claim_token, decision: 'confirm_all' } });
110
+ }
111
+ const task = await sl.api.partnerLockerDelivery({ deliveryNo: delivery_no });
112
+ ```
113
+
114
+ The same in Python:
115
+
116
+ ```python
117
+ from slocker import SLockerClient, SLockerError
118
+
119
+ sl = SLockerClient(provider_id=4611)
120
+ sl.login('api-partner@example.com', password)
121
+ created = sl.create_partner_locker_delivery(
122
+ idempotency_key='FOOD-20260714-1001-v1',
123
+ body={'external_order_id': 'FOOD-20260714-1001', 'platform_scope_group_id': 12,
124
+ 'recipient': {'phone': '+14165550123'}, 'package_count': 2})
125
+ try:
126
+ opened = sl.open_partner_locker_delivery(body={'location_id': 101, 'access_code': created['data']['access_code']})
127
+ sl.confirm_partner_locker_delivery(body={'claim_token': opened['data']['claim_token'], 'decision': 'confirm_all'})
128
+ except SLockerError as e:
129
+ if e.code == 'LOCKER_DELIVERY_IN_USE':
130
+ ... # another attempt is in progress: wait, or use its claim token
131
+ raise
132
+ ```
133
+
134
+ ## The sandbox: a mock cabinet
135
+
136
+ A mock cabinet runs the same pipeline as a real one without hardware; a task created with `mock: true` only uses mock
137
+ cabinets, and its webhooks carry `livemode: false`, an `event_id` starting `PLE-MOCK-` and the header `X-Webhook-Test:
138
+ 1` (sent to your sandbox URL when one is set). Up to 5 mock cabinets per provider, 1–60 compartments each.
139
+
140
+ ```python
141
+ locker = sl.create_partner_locker_mock_locker(body={'location_id': 101, 'name': 'Dev cabinet', 'compartments': 8})
142
+ device_id = locker['data']['locker']['device_id']
143
+
144
+ task = sl.create_partner_locker_delivery(idempotency_key='TEST-1', body={
145
+ 'external_order_id': 'TEST-1', 'platform_scope_group_id': 12, 'recipient': {'email': 'qa@example.com'}, 'mock': True})
146
+ opened = sl.open_partner_locker_delivery(body={'location_id': 101, 'access_code': task['data']['access_code']})
147
+ sl.confirm_partner_locker_delivery(body={'claim_token': opened['data']['claim_token'], 'decision': 'confirm_all'})
148
+ # → webhook partner_locker.delivery.delivered, livemode false
149
+
150
+ sl.mark_partner_locker_mock_parcels_taken(device_id, body={'compartments': [1]})
151
+ # → webhook partner_locker.pickup.completed (a full pickup settlement)
152
+
153
+ sl.clear_partner_locker_mock_parcels(device_id) # empties the cabinet without a pickup settlement
154
+ sl.set_partner_locker_mock_door(device_id, body={'compartment': 2, 'action': 'open'}) # a door left open
155
+ sl.set_partner_locker_mock_compartments(device_id, body={'compartments': [1, 2], 'grid_length_cm': 20,
156
+ 'grid_width_cm': 20, 'grid_height_cm': 20, 'weight_limit_kg': 5}) # rehearse "does not fit"
157
+ sl.delete_partner_locker_mock_locker(device_id)
158
+ ```
159
+
160
+ Use the location list in the same mode as the task (`mock: true` on `partnerLockerScopeLocations` /
161
+ `partnerLockerNearbyLocations`): a live location for a mock task answers `409 LOCKER_NO_CABINET_FOR_MODE`.
162
+
163
+ ## Webhooks
164
+
165
+ Verify every webhook against the **raw body** exactly as received, before parsing it. sLocker checks the timestamp
166
+ (±5 minutes by default), the `X-Webhook-Content-Digest` and the `X-Webhook-Signature`
167
+ (`v1=` base64 HMAC-SHA256 of `{timestamp}\n{X-Webhook-Delivery-Id}\n{body}` with your endpoint's signing secret), and
168
+ answers the event. During a key rotation the previous secret stays valid for 24 hours: pass both. An endpoint switched
169
+ to Standard Webhooks (`webhook-id` / `webhook-timestamp` / `webhook-signature`) or to CloudEvents structured bodies is
170
+ verified too. The same verification covers the carrier channel's `carrier_package.distribution.*` events.
171
+
172
+ Deduplicate on `eventId` (stable across retries; `deliveryId` changes on every attempt), answer 2xx within 10 seconds,
173
+ and keep sandbox events (`event.test`) apart from production.
174
+
175
+ ```js
176
+ import { verifyWebhook, WebhookVerificationError } from '@superrouteca/slocker';
177
+
178
+ app.post('/webhooks/slocker', express.raw({ type: '*/*' }), async (req, res) => {
179
+ try {
180
+ const event = await verifyWebhook(req.body, req.headers, [process.env.SLOCKER_SECRET, process.env.SLOCKER_OLD_SECRET]);
181
+ if (!event.test) await queue.add(event.eventId, event);
182
+ res.sendStatus(204);
183
+ } catch (e) {
184
+ if (e instanceof WebhookVerificationError) return res.status(400).send(e.reason);
185
+ throw e;
186
+ }
187
+ });
188
+ ```
189
+
190
+ | Language | Verify | Sign a test request |
191
+ |---|---|---|
192
+ | Python | `slocker.verify(body, headers, secrets)` | `slocker.sign(secret, body)` |
193
+ | PHP | `Webhooks::verify(file_get_contents('php://input'), getallheaders(), $secrets)` | `Webhooks::sign($secret, $body)` |
194
+ | Java | `Webhooks.verify(body, headers, secrets)` | `Webhooks.sign(...)` |
195
+ | Go | `slocker.Verify(body, slocker.HeaderMap(r.Header), secrets, nil)` | `slocker.Sign(secret, body, slocker.SignOptions{})` |
196
+ | C# | `Webhooks.Verify(body, headers, secrets)` | `Webhooks.Sign(secret, body)` |
197
+ | JavaScript | `await verifyWebhook(body, headers, secrets)` | `await signWebhook(secret, body)` |
198
+ | Swift | `try Webhooks.verify(body:headers:secrets:)` | `Webhooks.sign(secret:body:)` |
199
+ | Dart | `verifyWebhook(bodyBytes, headers, secrets)` | `signWebhook(secret, bodyBytes)` |
200
+
201
+ A refused webhook raises an error whose reason is one of `MISSING_HEADER`, `INVALID_TIMESTAMP`,
202
+ `TIMESTAMP_OUT_OF_TOLERANCE`, `DIGEST_MISMATCH`, `SIGNATURE_MISMATCH` or `INVALID_PAYLOAD`.
203
+
204
+ ## Errors and retries
205
+
206
+ Every failed call raises one error type with the HTTP `status`, the server's stable `code`, its `message`, the field
207
+ `errors` and `retryAfter` (seconds). Act on the status and the code, never on the message. Codes the SDK adds:
208
+ `UNAUTHENTICATED` (401 without a code: sign in again), `HTTP_<status>` (an answer without a code), `NETWORK_ERROR`
209
+ (no answer; status 0) and `INVALID_ARGUMENT` (a missing path parameter or an unknown operation; nothing was sent).
210
+
211
+ Only repeatable calls are retried: reads, deletes, and the two creates that carry an idempotency key
212
+ (`createPartnerLockerDelivery`, `submitCarrierPackages`). They are repeated after a timeout, a lost connection, 408,
213
+ 425, 429 or 5xx — at most `maxRetries` times (2 by default), waiting what `Retry-After` asks (at most 60 seconds) or
214
+ an exponential backoff with jitter. Opening doors, confirming, aborting, reassigning and every other change are never
215
+ repeated by the SDK: after a timeout, read the task (`partnerLockerDelivery`) before deciding.
216
+
217
+ When the SDK makes the idempotency key itself it is kept across its own retries only; give your own key (one per
218
+ order, unchanged on every retry of yours) so that a retry after a crash finds the original task.
219
+
220
+ ## Each language
221
+
222
+ ### Python
223
+
224
+ ```python
225
+ from slocker import SLockerClient
226
+ sl = SLockerClient(token, provider_id=4611) # sync; urllib from the standard library
227
+ sl.partner_locker_deliveries(status='delivered', per_page=50)
228
+ sl.call('partnerLockerDeliveries', {'status': 'delivered'}) # any operation by name
229
+ ```
230
+
231
+ ### PHP
232
+
233
+ ```php
234
+ use Superroute\SLocker\Client;
235
+ $sl = new Client($token, providerId: 4611); // curl
236
+ $sl->partnerLockerDeliveries(status: 'delivered', perPage: 50);
237
+ ```
238
+
239
+ ### Java and Kotlin
240
+
241
+ Add the Maven repository `https://goodneo-solutions.github.io/slocker-releases/maven`, then
242
+ `implementation("ca.superroute:slocker:0.2.0")` — or, in an Android app, `ca.superroute:slocker-android:0.2.0`.
243
+
244
+ ```java
245
+ Client sl = Client.builder().token(token).providerId(4611L).build(); // java.net.http, or HttpURLConnection on Android
246
+ Object page = sl.partnerLockerDeliveries(Params.create().put("status", "delivered").put("per_page", 50));
247
+ ```
248
+
249
+ ```kotlin
250
+ val sl = SLockerAsync(Client.builder().token(token).providerId(4611L).transport(OkHttpTransport()).build())
251
+ val page = sl.api.partnerLockerDeliveries(status = "delivered", perPage = 50) // suspend, on Dispatchers.IO
252
+ ```
253
+
254
+ Answers are plain JSON values (`Map`, `List`, `String`, `Long`, `Double`, `Boolean`, `null`).
255
+
256
+ ### Go
257
+
258
+ ```go
259
+ sl := slocker.New(slocker.Config{Token: token, ProviderID: 4611})
260
+ page, err := sl.PartnerLockerDeliveries(ctx, slocker.Params{"status": "delivered", "per_page": 50})
261
+ var e *slocker.Error
262
+ if errors.As(err, &e) && e.Code == "LOCKER_RATE_LIMITED" { /* … */ }
263
+ ```
264
+
265
+ ### C#
266
+
267
+ ```csharp
268
+ var sl = new SLockerClient(new SLockerOptions { Token = token, ProviderId = 4611 });
269
+ var page = await sl.PartnerLockerDeliveriesAsync(status: "delivered", perPage: 50);
270
+ ```
271
+
272
+ ### Swift
273
+
274
+ ```swift
275
+ let sl = SLockerClient(token: token, providerId: 4611)
276
+ let page = try await sl.partnerLockerDeliveries(status: "delivered", perPage: 50)
277
+ ```
278
+
279
+ ### Dart and Flutter
280
+
281
+ ```dart
282
+ final sl = SLockerClient(token: token, providerId: 4611);
283
+ final page = await sl.partnerLockerDeliveries(status: 'delivered', perPage: 50);
284
+ ```
285
+
286
+ Every client takes its own transport (for tests, proxies or an HTTP stack the app already has), a base URL (white-label
287
+ API hosts and test environments), the retry count and the wait function.
288
+
289
+ ## Customer side
290
+
291
+ Apps made for a service provider's customers — on the Open Platform's partner app surface
292
+ (`open.superroute.ca/app/v1`) — use the customer side: 38 operations, each a method.
293
+
294
+ - **Pickups** — the person's parcels in lockers with their pickup codes, opening the door to collect, handing a pickup
295
+ over to someone else and taking it back.
296
+ - **Locker locations** — lockers near the person, one location, its indoor guide and feedback on it, the person's
297
+ preferred locker.
298
+ - **Locker storage** — claiming a rental, keeping it, the return time, sending it on (onward quote, delivery,
299
+ shipment), pickup sites, resending the code.
300
+ - **Locker shop** — the catalogue of a location, items, orders, opening the door of an order, refund requests, access
301
+ codes.
302
+ - **Locker resale** — the terms, the person's deals, creating a deal, releasing or revoking the buyer's code, aborting,
303
+ cancelling or reporting a deal.
304
+
305
+ The customer side is built on the sApp core: sign-in, token refresh, the app key for calls before sign-in, idempotency
306
+ keys, retries, extra query and errors (`SuperrouteError` / `SuperrouteException`, a `result: false` answer included)
307
+ are sApp's own. What a caller may do is decided by the server.
308
+
309
+ ### Moving from sApp
310
+
311
+ From sApp 0.2.2 the smart-locker methods are in sLocker, under the same names and with the same arguments as in sApp
312
+ 0.2.1: `api.platformAppPickups()` on an sApp client becomes `api.platformAppPickups()` on an sLocker customer. The
313
+ pickup list and the locker map of the UI kits move the same way. A path belongs to sLocker when its first segment after
314
+ the client scope is `pickups`, `locker-locations`, `locker-storage`, `locker-shop` or `locker-resale`
315
+ (`tools/locker_paths.json`, the same list as sApp's). Store orders stay in sApp, their locker open and refund included.
316
+
317
+ | sApp 0.2.1 method | Request |
318
+ |---|---|
319
+ | `platformAppPickups`, `platformAppPickup` | `GET /app/v1/pickups`, `GET /app/v1/pickups/{deliveryId}` |
320
+ | `platformAppCollectPickup` | `POST /app/v1/pickups/{deliveryId}/collect` |
321
+ | `platformAppHandOverPickup`, `platformAppTakeBackPickup` | `POST /app/v1/pickups/{deliveryId}/handoff`, `…/handoff/revoke` |
322
+ | `platformAppLockerLocations`, `platformAppLockerLocation` | `GET /app/v1/locker-locations`, `…/{locationId}` |
323
+ | `platformAppLockerLocationGuide`, `platformAppLockerLocationGuideFeedback` | `GET …/{locationId}/guide`, `POST …/guide/feedback` |
324
+ | `platformAppUpdateLockerPreference` | `PUT /app/v1/locker-locations/{locationId}/preference` |
325
+ | `platformAppLockerShopCatalog` | `GET /app/v1/locker-locations/{locationId}/shop` |
326
+ | `platformAppLockerShopItems`, `platformAppLockerShopOrders`, `platformAppLockerShopOrder` | `GET /app/v1/locker-shop/items`, `…/orders`, `…/orders/{id}` |
327
+ | `platformAppLockerShopCreateOrder`, `platformAppLockerShopOpen`, `platformAppLockerShopRefundRequest` | `POST /app/v1/locker-shop/orders`, `…/{id}/open`, `…/{id}/refund-request` |
328
+ | `platformAppLockerShopIssueAccessCode` | `POST /app/v1/locker-shop/access-codes` |
329
+ | `platformAppLockerStorageRentals`, `platformAppLockerStorageRental` | `GET /app/v1/locker-storage/rentals`, `…/{id}` |
330
+ | `platformAppLockerStorageClaim` | `POST /app/v1/locker-storage/rentals/claim` |
331
+ | `platformAppLockerStorageKeep`, `…ReturnTime`, `…ResendCode`, `…OnwardQuote`, `…Delivery`, `…Shipment`, `…PickupSite`, `…PickupSiteCancel` | `POST /app/v1/locker-storage/rentals/{id}/keep`, `return-time`, `resend-code`, `onward-quote`, `delivery`, `shipment`, `pickup-site`, `pickup-site/cancel` |
332
+
333
+ New in sLocker: `lockerResaleTerms`, `lockerResaleDeals`, `lockerResaleDeal`, `createLockerResaleDeal`,
334
+ `releaseLockerResaleCode`, `revokeLockerResaleCode`, `abortLockerResaleDeal`, `cancelLockerResaleDeal`,
335
+ `reportLockerResaleDeal` (`/app/v1/locker-resale/…`).
336
+
337
+ ### sLocker on its own
338
+
339
+ Create a customer with your partner app's code, the service provider's client code, the app key and a token store;
340
+ sLocker makes the sApp connection inside:
341
+
342
+ ```js
343
+ import { SLocker } from '@superrouteca/slocker-customer';
344
+
345
+ const locker = SLocker.customer({
346
+ appCode: 'p_acme_parcels',
347
+ clientCode: 'k3m9q2', // the service provider's public client code
348
+ appKey: 'sp_appkey_…', // restricted key for calls before sign-in
349
+ tokenStore, // your secure storage: { get, set, clear }
350
+ locale: 'en',
351
+ });
352
+
353
+ await locker.auth.signInWithIdToken(googleIdToken); // sApp's sign-in
354
+ const pickups = await locker.api.platformAppPickups({ status: 'ready' });
355
+ await locker.api.platformAppCollectPickup({ deliveryId: 42, body: { user_confirmed: true } });
356
+ const deals = await locker.api.lockerResaleDeals({ open: true });
357
+ ```
358
+
359
+ | Language | sLocker on its own | Beside an sApp client |
360
+ |---|---|---|
361
+ | JavaScript | `SLocker.customer({ appCode, clientCode, appKey, tokenStore })` | `SLocker.customer({ sapp: sr })` |
362
+ | Dart | `SLocker.customer(appCode: …, clientCode: …, appKey: …, tokenStore: …)` | `SLocker.customerFor(sr)` |
363
+ | Swift | `SLocker.customer(appCode:clientCode:appKey:tokenStore:)` | `SLocker.customer(sapp: sr)` |
364
+ | Kotlin | `SLocker.customer(appCode = …, clientCode = …, appKey = …, tokenStore = …)` | `SLocker.customer(sapp = sr)` |
365
+ | Java | `SLocker.customer(appCode, clientCode, appKey, tokenStore)` or `SLocker.customer(PartnerClient.builder(…))` | `SLocker.customer(sr)` |
366
+ | C# | `SLocker.Customer("p_acme_parcels", clientCode: …, appKey: …, tokenStore: …)` | `SLocker.Customer(sr)` |
367
+ | Python | `customer('p_acme_parcels', client_code=…, app_key=…, token_store=…)` | `customer(sapp=sr)` |
368
+ | PHP | `SLocker::customer('p_acme_parcels', clientCode: …, appKey: …)` | `SLocker::customer(sapp: $sr)` |
369
+ | Go | `customer.New(customer.Options{AppCode: …, ClientCode: …, AppKey: …})` | `customer.Share(sr)` |
370
+
371
+ Each answers a customer (`SLockerCustomerClient` in Swift) with `api` (one method per operation; `API` in Go, `Api` in
372
+ C#), the sApp client underneath
373
+ (`sapp`; `SApp` in Go and C#) for sign-in and every other partner operation, and `callOperation` for an operation
374
+ described by hand.
375
+
376
+ ### Beside an sApp client
377
+
378
+ An app that already uses sApp passes its client, so both share one sign-in and one token store:
379
+
380
+ ```dart
381
+ import 'package:sapp/sapp.dart';
382
+ import 'package:slocker_customer/slocker_customer.dart';
383
+
384
+ final sr = PartnerClient(appCode: 'p_acme_parcels', clientCode: 'k3m9q2', appKey: 'sp_appkey_…', tokenStore: store);
385
+ final locker = SLocker.customerFor(sr);
386
+ final notifications = await sr.api.platformAppNotifications(); // sApp
387
+ final pickups = await locker.api.platformAppPickups(page: 1); // sLocker
388
+ ```
389
+
390
+ ```python
391
+ from sapp import PartnerClient
392
+ from slocker.customer import customer
393
+
394
+ sr = PartnerClient('p_acme_parcels', client_code='k3m9q2', app_key='sp_appkey_…')
395
+ locker = customer(sapp=sr)
396
+ locker.api.platform_app_pickups(status='ready')
397
+ ```
398
+
399
+ ```swift
400
+ // Package.swift: .package(url: "https://github.com/Goodneo-Solutions/slocker-customer-releases", from: "0.2.0")
401
+ // in the target: .product(name: "SLockerCustomer", package: "slocker-customer-releases"), and "SLockerUI" for the kit;
402
+ // sApp (sapp-releases) comes with it.
403
+ import SApp
404
+ import SLockerCustomer
405
+
406
+ let locker = SLocker.customer(sapp: sr)
407
+ let pickups = try await locker.api.platformAppPickups(status: "ready")
408
+ ```
409
+
410
+ ### UI kits: the pickup list and the locker map
411
+
412
+ The pickup list (parcels in lockers, their pickup codes, opening the door after confirming) and the locker map (lockers
413
+ near the person with distance, status and free compartments, search and filters, and the same lockers on the app's own
414
+ sMap map) behave exactly as they did in the sApp UI kits. They sit inside the sApp kit's scope or provider, take its
415
+ client, theme and strings in 14 languages, raise events and never navigate.
416
+
417
+ | Kit | Pickup list | Locker map |
418
+ |---|---|---|
419
+ | Flutter (`slocker_ui`) | `SrPickupList` | `SrLockerMap` with `SrSMapAdapter`, `SrMapAdapter`, `SrMapPoint` |
420
+ | Web (`@superrouteca/slocker-ui`) | `<sr-pickup-list>` (`SrPickupList`) | `<sr-locker-map>` (`SrLockerMap`, `smapAdapter`) |
421
+ | React / React Native | `PickupList` | `LockerMap` (`smapAdapter`) |
422
+ | SwiftUI (`SLockerUI`) | `PickupList` | `LockerMap` with `SRSMapAdapter`, `SRMapAdapter`, `SRMapPoint` |
423
+ | Jetpack Compose (`slocker-ui-android`) | `PickupList` | `LockerMap` with `SrSMapAdapter`, `SrMapAdapter`, `SrMapPoint` |
424
+ | WPF / WinForms (`Superroute.SLocker.Wpf` / `.WinForms`) | `PickupList` (`PickupListViewModel`) | `LockerMap` (`LockerMapViewModel`, `SMapAdapter`, `IMapAdapter`, `MapPoint`) |
425
+
426
+ ```dart
427
+ SuperrouteScope(
428
+ client: sr,
429
+ theme: ThemeTokens.fromBranding(branding),
430
+ onSignInRequired: () => router.go('/sign-in'),
431
+ child: SrPickupList(onShowCode: (qr) => showQr(qr)),
432
+ )
433
+ ```
434
+
435
+ ```html
436
+ <script type="module">
437
+ import { configure } from '@superrouteca/sapp-ui';
438
+ import '@superrouteca/slocker-ui';
439
+ configure({ client: sr, theme: themeFromBranding(branding), locale: 'en' });
440
+ </script>
441
+ <sr-pickup-list></sr-pickup-list>
442
+ <sr-locker-map></sr-locker-map>
443
+ ```
444
+
445
+ ## Development
446
+
447
+ ```
448
+ specs/ the partner locker slice of Superroute's REST and GraphQL documents, and operations.json
449
+ tools/sync_specs.py copies the slice from a Superroute checkout (and checks no route lacks its Swagger entry)
450
+ tools/generate.py writes every language's operation table and typed methods from the spec
451
+ tools/make_client_cases.py writes tests/cases/client.json: requests, answers, retries, sign-in
452
+ tools/make_webhook_vectors.py writes tests/cases/webhooks.json, signed exactly as Superroute signs
453
+ tests/cases/ the cases every language runs
454
+ ```
455
+
456
+ ```sh
457
+ python3 -I tools/sync_specs.py ../Superroute # then commit specs/ and the generated files
458
+ cd python && python3 -m unittest discover -s tests
459
+ cd js && npm test
460
+ cd php && php tests/run.php
461
+ cd go && go test ./...
462
+ cd java && ./gradlew :slocker:test :slocker-android:test
463
+ dotnet test dotnet/tests/Superroute.SLocker.Tests
464
+ cd swift && swift test
465
+ cd dart && dart pub get && dart test
466
+ ```
467
+
468
+ Never edit generated files (`generated/`, `Generated/`, `_operations.py`, `operations_gen.go`, `SLockerOperations.kt`):
469
+ change Superroute's spec, sync, and generate again.
470
+
471
+ The customer side has its own spec and generator, and is built against the published sApp packages (0.2.2); the
472
+ generator and the locker path check read the sApp source:
473
+
474
+ ```
475
+ specs/customer-api.json the smart-locker operations of the partner app surface
476
+ tools/locker_paths.json the one list of locker paths, the same file as sApp's (tools/check_locker_paths.py)
477
+ tools/customer_operations.json the 38 operations the customer side must have
478
+ tools/sync_customer_specs.py copies the locker operations from a Superroute checkout, then generates
479
+ tools/generate_customer.py writes LockerApi in every language with sApp's own generator
480
+ tools/fetch-sapp.sh, sapp-ref the sApp source at .sapp (git-ignored), at its release tag
481
+ ```
482
+
483
+ ```sh
484
+ SAPP_DIR=../sApp tools/fetch-sapp.sh # or tools/fetch-sapp.sh to clone it (needs read access)
485
+ python3 -I tools/sync_customer_specs.py ../Superroute
486
+ npm install && npm test # js-customer, web-ui, react, react-native
487
+ cd dart-customer && dart pub get && dart test
488
+ cd flutter-ui && flutter test # with a pubspec_overrides.yaml naming ../dart-customer
489
+ cd swift-customer && swift test
490
+ cd java-customer && ./gradlew test
491
+ cd kotlin-customer && ./gradlew :slocker-customer-kotlin:test :slocker-ui-android:testDebugUnitTest
492
+ dotnet test dotnet/tests/Superroute.SLocker.Customer.Tests && dotnet test dotnet/tests/Superroute.SLocker.UI.Tests
493
+ pip install superroute-sapp && python3 -m unittest discover -s python/tests
494
+ php php/tests/customer.php # the sApp PHP source at .sapp/php
495
+ (cd go/customer && go test ./...)
496
+ ```
497
+
498
+ In CI the customer workflows (`customer-*.yml`) use the published sApp packages. Only the internal profile and the
499
+ locker path check read the private sApp repository, with the secret `SAPP_DEPLOY_KEY` (a read-only deploy key of the
500
+ sApp repository), and are skipped without it.
501
+
502
+ ## Releases
503
+
504
+ sLocker started at 0.1.0; each release adds 0.0.1 to the last one, skipping every version that contains the digit 3
505
+ or 4 (0.1.0, 0.1.1, 0.1.2, 0.1.5, 0.1.6, …, 0.1.9, 0.2.0, …). Tagging a version (`0.1.1`, no `v`) runs
506
+ `.github/workflows/release.yml`, which tests every language and then publishes:
507
+
508
+ - npm (`@superrouteca/slocker`; the customer side's `@superrouteca/slocker-customer`, `slocker-ui`, `slocker-react` and
509
+ `slocker-react-native`), PyPI (`superroute-slocker`, the customer side as its extra `[customer]`), NuGet
510
+ (`Superroute.SLocker`; `Superroute.SLocker.Customer`, `.UI`, `.Wpf` and `.WinForms`) and pub.dev (`slocker`;
511
+ `slocker_customer` and `slocker_ui`) directly, by trusted publishing;
512
+ - to the public repository `Goodneo-Solutions/slocker-releases`: the Swift package (a prebuilt XCFramework attached to
513
+ that repository's GitHub Release of the version), the Maven repository (`maven/`, served by GitHub Pages) with
514
+ `ca.superroute:slocker` and `slocker-android` and the customer side's `slocker-customer`, `slocker-customer-kotlin`
515
+ and `slocker-ui-android`, and the Go modules (`go/`, tag `go/v<version>`; `go/customer`, tag
516
+ `go/customer/v<version>`);
517
+ - to the public repository `Goodneo-Solutions/slocker-customer-releases`: the customer side for iOS and macOS
518
+ (`SLockerCustomer` and `SLockerUI` as prebuilt XCFrameworks attached to that repository's GitHub Release of the
519
+ version, depending on `sapp-releases`), so the carrier Swift package in `slocker-releases` depends on nothing;
520
+ - to the public repository `Goodneo-Solutions/slocker-php`: the PHP package at its root, tag `v<version>`, which
521
+ Packagist reads.
522
+
523
+ This source repository stays private; the packages are public under the Superroute SDK License (see [LICENSE](LICENSE)).
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@superrouteca/slocker-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "sLocker for React: the pickup list and the locker map as React components over the sLocker web UI kit, with the client from sApp's SuperrouteProvider.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "author": "Goodneo Solutions",
7
+ "homepage": "https://open.superroute.ca/developer",
8
+ "keywords": ["superroute", "smart locker", "react", "ui"],
9
+ "type": "module",
10
+ "main": "./src/index.js",
11
+ "types": "./types/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./types/index.d.ts",
15
+ "default": "./src/index.js"
16
+ }
17
+ },
18
+ "files": ["src", "types", "README.md", "LICENSE", "CHANGELOG.md"],
19
+ "sideEffects": false,
20
+ "dependencies": {
21
+ "@superrouteca/slocker-ui": "0.2.0",
22
+ "@superrouteca/sapp": "0.2.2",
23
+ "@superrouteca/sapp-react": "0.2.2"
24
+ },
25
+ "peerDependencies": {
26
+ "react": ">=18"
27
+ },
28
+ "devDependencies": {
29
+ "react": "18.3.1",
30
+ "react-dom": "18.3.1",
31
+ "@types/react": "18.3.12",
32
+ "@types/react-dom": "18.3.1",
33
+ "jsdom": "25.0.1"
34
+ },
35
+ "scripts": {
36
+ "test": "node --test test/*.test.mjs"
37
+ }
38
+ }
package/src/index.js ADDED
@@ -0,0 +1,50 @@
1
+ // React components over the sLocker web UI kit: each renders its custom element, gives it the client (the prop, else
2
+ // the nearest sApp SuperrouteProvider's), the theme and the language, and turns its events into onX props — the same
3
+ // wrapper as sApp's React UI kit.
4
+ import { createElement, forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
5
+ import '@superrouteca/slocker-ui';
6
+ import { useOptionalSuperroute } from '@superrouteca/sapp-react';
7
+
8
+ export { configure, smapAdapter, lockerApiFor } from '@superrouteca/slocker-ui';
9
+
10
+ function wrap(tag, events, properties) {
11
+ const Component = forwardRef(function SLockerElement(props, ref) {
12
+ const element = useRef(null);
13
+ const fromContext = useOptionalSuperroute();
14
+ useImperativeHandle(ref, () => element.current);
15
+
16
+ // Properties, not attributes: functions and objects reach the element as they are.
17
+ useEffect(() => {
18
+ const el = element.current;
19
+ if (!el) return;
20
+ for (const name of ['theme', 'locale', ...properties]) {
21
+ if (props[name] !== undefined) el[name] = props[name];
22
+ }
23
+ const client = props.client ?? fromContext;
24
+ if (client && el.client !== client) el.client = client;
25
+ if (el.render) el.render();
26
+ });
27
+
28
+ useEffect(() => {
29
+ const el = element.current;
30
+ if (!el) return undefined;
31
+ const handlers = Object.entries(events).map(([prop, [name, pick]]) => {
32
+ const handler = (event) => props[prop]?.(pick(event.detail));
33
+ el.addEventListener(name, handler);
34
+ return [name, handler];
35
+ });
36
+
37
+ return () => handlers.forEach(([name, handler]) => el.removeEventListener(name, handler));
38
+ });
39
+
40
+ return createElement(tag, { ref: element, class: props.className, style: props.style });
41
+ });
42
+ Component.displayName = tag;
43
+
44
+ return Component;
45
+ }
46
+
47
+ const signInRequired = { onSignInRequired: ['sr-sign-in-required', () => undefined] };
48
+
49
+ export const PickupList = wrap('sr-pickup-list', { onShowCode: ['sr-show-code', (d) => d.value], ...signInRequired }, []);
50
+ export const LockerMap = wrap('sr-locker-map', { onSelect: ['sr-select', (d) => d.location], ...signInRequired }, ['latitude', 'longitude', 'map']);
@@ -0,0 +1,20 @@
1
+ import type { CSSProperties, ForwardRefExoticComponent, RefAttributes } from 'react';
2
+ import type { PartnerClient, ThemeTokens } from '@superrouteca/sapp';
3
+ import type { SrMapAdapter } from '@superrouteca/slocker-ui';
4
+
5
+ export { configure, smapAdapter, lockerApiFor } from '@superrouteca/slocker-ui';
6
+ export type { SrMapAdapter, SrMapPoint } from '@superrouteca/slocker-ui';
7
+
8
+ interface Common {
9
+ client?: PartnerClient;
10
+ theme?: ThemeTokens;
11
+ locale?: string;
12
+ className?: string;
13
+ style?: CSSProperties;
14
+ onSignInRequired?: () => void;
15
+ }
16
+
17
+ type Element<P> = ForwardRefExoticComponent<Common & P & RefAttributes<HTMLElement>>;
18
+
19
+ export declare const PickupList: Element<{ onShowCode?: (value: string) => void }>;
20
+ export declare const LockerMap: Element<{ latitude?: number; longitude?: number; map?: SrMapAdapter; onSelect?: (location: Record<string, any>) => void }>;