@framestudio/keel-sdk 0.0.0-stage → 0.1.1
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 +39 -0
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/client.js +207 -0
- package/normalize.js +188 -0
- package/package.json +49 -4
- package/react.js +63 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
- **The analytics re-export is named, not a wildcard.** `export *` published
|
|
6
|
+
`__reset`, `__state` and `__identity` — three functions `keel-analytics` annotates
|
|
7
|
+
"Not part of the public API. Used by the test suite." — plus `cleanPath`, an
|
|
8
|
+
internal privacy helper. They appeared in autocomplete and would have become part
|
|
9
|
+
of this package's contract, so removing them later would break a pinned site.
|
|
10
|
+
Re-exported now: `init`, `track`, `page`, `captureError`, `health`, `flush`,
|
|
11
|
+
`resetVisitor`, `EVENTS`. A test pins both directions.
|
|
12
|
+
|
|
13
|
+
No other changes: same API, same files, same dependency.
|
|
14
|
+
|
|
15
|
+
## 0.1.0
|
|
16
|
+
|
|
17
|
+
First release. Extracted from the hand-copied `keelClient.js` that every custom
|
|
18
|
+
site had grown separately — five copies, already drifted.
|
|
19
|
+
|
|
20
|
+
- `createClient({ token, apiBase? })` with products, catalogue, services,
|
|
21
|
+
settings, banners, page content and inquiries.
|
|
22
|
+
- Normalisers for every response, so a site renders the same shape whatever the
|
|
23
|
+
API sends: numbers coerced, `null` preserved as "not set", `stock: null` is
|
|
24
|
+
"not tracked" rather than "out of stock".
|
|
25
|
+
- `KeelError` with a `code` (`no_token`, `unauthorized`, `forbidden`,
|
|
26
|
+
`not_found`, `rate_limited`, `network`, `server`) so a site can tell "the API
|
|
27
|
+
is down" from "nothing matched".
|
|
28
|
+
- Retry budget of 4s × 2 with 500ms backoff; 4xx is not retried.
|
|
29
|
+
- `@framestudio/keel-analytics` re-exported, so a site installs one package.
|
|
30
|
+
- Optional React bindings at `@framestudio/keel-sdk/react`.
|
|
31
|
+
- Embed script for sites with no build step (`src/embed.js`, built to a single
|
|
32
|
+
IIFE and hosted by the dashboard).
|
|
33
|
+
|
|
34
|
+
### Deliberately not here
|
|
35
|
+
|
|
36
|
+
- No caching layer. A site's framework already has one, and a second cache is how
|
|
37
|
+
"I published it but my site is stale" happens.
|
|
38
|
+
- No server-side rendering helpers. Both live sites fetch on the client.
|
|
39
|
+
- No dependency on a specific UI stack.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 FrameStudio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,191 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @framestudio/keel-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Read a Keel shop's catalogue, services, settings and content from a custom
|
|
4
|
+
website — with one publishable key and no database credential in the browser.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install @framestudio/keel-sdk
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```js
|
|
11
|
+
import { createClient } from '@framestudio/keel-sdk'
|
|
12
|
+
|
|
13
|
+
const keel = createClient({ token: import.meta.env.VITE_KEEL_SITE_TOKEN })
|
|
14
|
+
|
|
15
|
+
const products = await keel.products()
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
That is the whole setup. The key comes from **Keel → Settings → Developer**;
|
|
19
|
+
copy the publishable one into the site's build (Vercel, Netlify, `.env`).
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## What the token is
|
|
24
|
+
|
|
25
|
+
A **publishable** credential. It ships in your site's JavaScript, so anyone can
|
|
26
|
+
read it — that is expected, and it is why the API decides what it may reach
|
|
27
|
+
rather than trusting the client. It identifies the shop and it is rate-limited.
|
|
28
|
+
|
|
29
|
+
Never treat it as a password, and never put it in a URL: query strings land in
|
|
30
|
+
access logs, browser history and `Referer` headers, where a credential outlives
|
|
31
|
+
the request that carried it. This package always sends it as a header.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Methods
|
|
36
|
+
|
|
37
|
+
| Call | Returns | Notes |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| `keel.products()` | `Product[]` | Inventory, with stock |
|
|
40
|
+
| `keel.catalogue()` | `CatalogueItem[]` | What the site shows — products **and** services |
|
|
41
|
+
| `keel.services()` | `Service[]` | Priced per job, with a unit |
|
|
42
|
+
| `keel.settings()` | `Settings` | Name, contact, hours, colours, feature switches |
|
|
43
|
+
| `keel.banners()` | `Banner[]` | Active ones, already ordered |
|
|
44
|
+
| `keel.pageContent({ page?, section? })` | `PageSection[]` | Copy blocks; `[]` if neither is given |
|
|
45
|
+
| `keel.inquire({ name, phone, message? })` | `{ ok: true }` | Needs the `inquiry` scope |
|
|
46
|
+
| `keel.request(path, opts)` | raw JSON | Escape hatch |
|
|
47
|
+
|
|
48
|
+
Every list is normalised: numbers coerced, `null` kept as "not set", and no
|
|
49
|
+
`cost_price` anywhere (a product never exposes what the shop paid).
|
|
50
|
+
|
|
51
|
+
### Shapes worth knowing
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
// CatalogueItem.type is the discriminator the whole page branches on
|
|
55
|
+
{ type: 'product' } // has specs, availability, stock via the linked product
|
|
56
|
+
{ type: 'service' } // priced per job, has includes, no stock
|
|
57
|
+
|
|
58
|
+
// Service.pricingMode — quote it, do not flatten it
|
|
59
|
+
'flat' | 'per_unit' | 'per_weight' | 'per_hour'
|
|
60
|
+
|
|
61
|
+
// Product.stock: null means "not tracked", which is NOT out of stock
|
|
62
|
+
{ stock: null, inStock: true }
|
|
63
|
+
{ stock: 0, inStock: false }
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Errors
|
|
69
|
+
|
|
70
|
+
Failures throw `KeelError` with a `code` you can branch on:
|
|
71
|
+
|
|
72
|
+
| `code` | Meaning | What to show |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| `no_token` | No key configured | "This site isn't connected yet" |
|
|
75
|
+
| `unauthorized` | Key rejected or revoked | Same — do not retry |
|
|
76
|
+
| `forbidden` | Key lacks the scope | A developer problem, not a visitor one |
|
|
77
|
+
| `not_found` | Wrong shop | Setup error |
|
|
78
|
+
| `rate_limited` | Too many requests | Try again shortly |
|
|
79
|
+
| `network` | Offline, DNS, timeout | **"Can't reach the shop right now"** |
|
|
80
|
+
| `server` | The API failed | Same as above |
|
|
81
|
+
|
|
82
|
+
**Keep `network`/`server` separate from an empty result.** "The API is down" and
|
|
83
|
+
"your filters matched nothing" are different screens; collapsing them into
|
|
84
|
+
"No products found" `<!-- -->` is the most common defect in these sites, and it
|
|
85
|
+
hides outages from the person who could fix them.
|
|
86
|
+
|
|
87
|
+
```js
|
|
88
|
+
try {
|
|
89
|
+
setProducts(await keel.products())
|
|
90
|
+
} catch (err) {
|
|
91
|
+
setError(err.code === 'network' || err.code === 'server' ? 'offline' : 'failed')
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Retries
|
|
96
|
+
|
|
97
|
+
`4s × 2` with a 500ms backoff. The API host sleeps when idle, so a cold start is
|
|
98
|
+
normal rather than exceptional — but a storefront that shows nothing for half a
|
|
99
|
+
minute reads as broken. 4xx responses are **not** retried: the same answer costs
|
|
100
|
+
another second of the visitor's time.
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## React
|
|
105
|
+
|
|
106
|
+
```jsx
|
|
107
|
+
import { KeelProvider, useProducts, useShopSettings } from '@framestudio/keel-sdk/react'
|
|
108
|
+
import { createClient } from '@framestudio/keel-sdk'
|
|
109
|
+
|
|
110
|
+
const client = createClient({ token })
|
|
111
|
+
|
|
112
|
+
export default function App() {
|
|
113
|
+
return (
|
|
114
|
+
<KeelProvider client={client}>
|
|
115
|
+
<Shop />
|
|
116
|
+
</KeelProvider>
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function Shop() {
|
|
121
|
+
const { data: products, error, loading } = useProducts()
|
|
122
|
+
if (loading) return <Skeleton />
|
|
123
|
+
if (error) return <Offline />
|
|
124
|
+
return products.map((p) => <Card key={p.id} product={p} />)
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`react` is an optional peer dependency; the core has none.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## Embed on a site with no build step
|
|
133
|
+
|
|
134
|
+
For a Wix page, a WordPress theme, or a single hand-written `index.html`:
|
|
135
|
+
|
|
136
|
+
```html
|
|
137
|
+
<div data-keel-catalogue data-keel-token="pk_site_…" data-keel-limit="12"></div>
|
|
138
|
+
<script src="https://keel.framestudio.co.ke/keel.js" defer></script>
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The token is the publishable key from **Keel → Settings → Developer**. Nothing else
|
|
142
|
+
to configure: the grid renders itself, and an "Ask on WhatsApp" button appears
|
|
143
|
+
when the shop has a WhatsApp number.
|
|
144
|
+
|
|
145
|
+
The script is built from this package (`npm run build:embed`) and copied to the
|
|
146
|
+
dashboard's `public/keel.js`, which Vercel serves. **Do not edit the built file** —
|
|
147
|
+
edit `src/embed.js` and rebuild. It is deliberately *not* served by `keel-api`,
|
|
148
|
+
which sleeps when idle and would be unavailable exactly when the embed is needed.
|
|
149
|
+
|
|
150
|
+
Deliberate limits: a read-only grid. No cart, no variants, no detail page. A site
|
|
151
|
+
that needs those is a bespoke build with this package installed, not a script tag.
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Analytics
|
|
156
|
+
|
|
157
|
+
The analytics SDK is re-exported, so one package covers both:
|
|
158
|
+
|
|
159
|
+
```js
|
|
160
|
+
import { createClient, init, track } from '@framestudio/keel-sdk'
|
|
161
|
+
|
|
162
|
+
createClient({ token })
|
|
163
|
+
init({ token }) // page views and errors report themselves
|
|
164
|
+
track('add_to_cart', { name: 'Kikoi', quantity: 1 })
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Re-exported: `init`, `track`, `page`, `captureError`, `health`, `flush`,
|
|
168
|
+
`resetVisitor`, `EVENTS`. Not re-exported: `keel-analytics`' test hooks
|
|
169
|
+
(`__reset`, `__state`, `__identity`) or its internal helpers — a wildcard would
|
|
170
|
+
have published those as part of this package's contract.
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
## Testing
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
npm test # node --test, no network
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
The client tests inject `fetch`, so they never touch a real shop.
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Publishing
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
npm publish --access public
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Sites pin a version deliberately: with several live storefronts, a release should
|
|
191
|
+
never reach them unannounced.
|
package/client.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import {
|
|
2
|
+
normalizeBanner,
|
|
3
|
+
normalizeCatalogueItem,
|
|
4
|
+
normalizePageContent,
|
|
5
|
+
normalizeProduct,
|
|
6
|
+
normalizeService,
|
|
7
|
+
normalizeSettings,
|
|
8
|
+
} from './normalize.js'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The client every custom site talks to Keel through.
|
|
12
|
+
*
|
|
13
|
+
* The token is a PUBLISHABLE credential: it ships in the site's own JavaScript,
|
|
14
|
+
* so its safety comes from what the API lets it reach, never from secrecy. It
|
|
15
|
+
* identifies the shop and it is rate-limited; it is not a password, and nothing
|
|
16
|
+
* here should be treated as if it were.
|
|
17
|
+
*
|
|
18
|
+
* The analytics SDK is re-exported so a site installs one package:
|
|
19
|
+
*
|
|
20
|
+
* import { createClient, init, track } from '@framestudio/keel-sdk'
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Analytics, re-exported so a site installs one package.
|
|
25
|
+
*
|
|
26
|
+
* ⚠️ NAMED, NOT `export *`. The analytics package deliberately exports three
|
|
27
|
+
* functions annotated "Not part of the public API. Used by the test suite."
|
|
28
|
+
* (`__reset`, `__state`, `__identity`), plus `cleanPath`, which is an internal
|
|
29
|
+
* privacy helper. A wildcard re-export published all four: they appeared in
|
|
30
|
+
* autocomplete and became part of THIS package's contract, so anyone using them
|
|
31
|
+
* would be coupled to internals neither package promised.
|
|
32
|
+
*
|
|
33
|
+
* `EVENTS` is included because it is the complete, closed vocabulary — a site
|
|
34
|
+
* author needs to know the valid names. `HEALTH_RESOURCES` is not, because the
|
|
35
|
+
* analytics README calls it "a starter set… not the catalogue".
|
|
36
|
+
*/
|
|
37
|
+
export {
|
|
38
|
+
init,
|
|
39
|
+
track,
|
|
40
|
+
page,
|
|
41
|
+
captureError,
|
|
42
|
+
health,
|
|
43
|
+
flush,
|
|
44
|
+
resetVisitor,
|
|
45
|
+
EVENTS,
|
|
46
|
+
} from '@framestudio/keel-analytics'
|
|
47
|
+
|
|
48
|
+
/** Matches the default in `@framestudio/keel-analytics`. */
|
|
49
|
+
export const API_BASE = 'https://keel-api-37rh.onrender.com'
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 4s × 2 with a 500ms backoff.
|
|
53
|
+
*
|
|
54
|
+
* Copied deliberately from the kikoi storefront, which measured the alternative:
|
|
55
|
+
* 10s × 3 with 1s/2s backoff meant a slow (not refused) API cost about 33 seconds
|
|
56
|
+
* of skeleton before a visitor saw anything. The API host sleeps when idle, so a
|
|
57
|
+
* cold start is the normal case rather than the exceptional one — and a storefront
|
|
58
|
+
* that shows nothing for half a minute reads as broken, not as slow.
|
|
59
|
+
*/
|
|
60
|
+
const TIMEOUT_MS = 4000
|
|
61
|
+
const ATTEMPTS = 2
|
|
62
|
+
const BACKOFF_MS = 500
|
|
63
|
+
|
|
64
|
+
export class KeelError extends Error {
|
|
65
|
+
constructor(message, { code = 'error', status = 0, cause } = {}) {
|
|
66
|
+
super(message)
|
|
67
|
+
this.name = 'KeelError'
|
|
68
|
+
this.code = code
|
|
69
|
+
this.status = status
|
|
70
|
+
this.cause = cause
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function codeForStatus(status) {
|
|
75
|
+
if (status === 401) return 'unauthorized'
|
|
76
|
+
if (status === 403) return 'forbidden'
|
|
77
|
+
if (status === 404) return 'not_found'
|
|
78
|
+
if (status === 429) return 'rate_limited'
|
|
79
|
+
if (status >= 500) return 'server'
|
|
80
|
+
return 'error'
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
84
|
+
|
|
85
|
+
export function createClient({
|
|
86
|
+
token,
|
|
87
|
+
apiBase = API_BASE,
|
|
88
|
+
fetch: fetchImpl,
|
|
89
|
+
timeoutMs = TIMEOUT_MS,
|
|
90
|
+
attempts = ATTEMPTS,
|
|
91
|
+
backoffMs = BACKOFF_MS,
|
|
92
|
+
} = {}) {
|
|
93
|
+
const doFetch = fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null)
|
|
94
|
+
const base = String(apiBase).replace(/\/+$/, '')
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* One authenticated call.
|
|
98
|
+
*
|
|
99
|
+
* The token goes in a header and never in the query string: query strings end
|
|
100
|
+
* up in access logs, browser history and Referer headers, where a credential
|
|
101
|
+
* outlives the request that carried it.
|
|
102
|
+
*/
|
|
103
|
+
async function request(path, { method = 'GET', body } = {}) {
|
|
104
|
+
if (!token) {
|
|
105
|
+
throw new KeelError('No site token configured. Pass `token` to createClient.', {
|
|
106
|
+
code: 'no_token',
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
if (!doFetch) {
|
|
110
|
+
throw new KeelError('No fetch available in this environment.', { code: 'no_fetch' })
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
let lastError = null
|
|
114
|
+
|
|
115
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
116
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null
|
|
117
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
|
|
118
|
+
|
|
119
|
+
let response = null
|
|
120
|
+
try {
|
|
121
|
+
response = await doFetch(`${base}${path}`, {
|
|
122
|
+
method,
|
|
123
|
+
headers: {
|
|
124
|
+
'x-keel-site-token': token,
|
|
125
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
126
|
+
},
|
|
127
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
128
|
+
signal: controller ? controller.signal : undefined,
|
|
129
|
+
})
|
|
130
|
+
} catch (cause) {
|
|
131
|
+
// Abort, DNS failure, offline — the visitor gets one more try, then an
|
|
132
|
+
// error they can be shown. Nothing here throws at the host app.
|
|
133
|
+
lastError = new KeelError('Could not reach the shop', { code: 'network', cause })
|
|
134
|
+
response = null
|
|
135
|
+
} finally {
|
|
136
|
+
if (timer) clearTimeout(timer)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (response) {
|
|
140
|
+
if (response.ok) return await response.json()
|
|
141
|
+
|
|
142
|
+
const error = new KeelError(`Request failed (${response.status})`, {
|
|
143
|
+
code: codeForStatus(response.status),
|
|
144
|
+
status: response.status,
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
// A 4xx is a fact about the request: retrying spends a second of the
|
|
148
|
+
// visitor's patience to be told the same thing. 429 and 5xx are weather.
|
|
149
|
+
const retryable = response.status >= 500 || response.status === 429
|
|
150
|
+
if (!retryable) throw error
|
|
151
|
+
|
|
152
|
+
lastError = error
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (attempt < attempts) await sleep(backoffMs * attempt)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
throw lastError || new KeelError('Request failed', { code: 'error' })
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
/** Whether a token was supplied. Never the token itself. */
|
|
163
|
+
configured: Boolean(token),
|
|
164
|
+
|
|
165
|
+
products: async () => (await request('/api/products')).map(normalizeProduct),
|
|
166
|
+
|
|
167
|
+
catalogue: async () => (await request('/api/catalogue')).map(normalizeCatalogueItem),
|
|
168
|
+
|
|
169
|
+
services: async () => (await request('/api/services')).map(normalizeService),
|
|
170
|
+
|
|
171
|
+
banners: async () => (await request('/api/banners')).map(normalizeBanner),
|
|
172
|
+
|
|
173
|
+
settings: async () => normalizeSettings(await request('/api/settings')),
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* `page` addresses the legacy model (page + section); `section` on its own
|
|
177
|
+
* addresses the newer one. The API returns an empty array when neither is
|
|
178
|
+
* given rather than dumping every row.
|
|
179
|
+
*/
|
|
180
|
+
pageContent: async ({ page, section } = {}) => {
|
|
181
|
+
const query = new URLSearchParams()
|
|
182
|
+
if (page) query.set('page', page)
|
|
183
|
+
if (section) query.set('section', section)
|
|
184
|
+
const suffix = query.toString() ? `?${query}` : ''
|
|
185
|
+
const rows = await request(`/api/page-content${suffix}`)
|
|
186
|
+
return Array.isArray(rows) ? rows.map(normalizePageContent) : []
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Send a customer message from a contact form.
|
|
191
|
+
*
|
|
192
|
+
* Requires the `inquiry` scope. The API takes the shop and the site from the
|
|
193
|
+
* token — passing either in the body is ignored, so a site cannot file a
|
|
194
|
+
* message against another shop.
|
|
195
|
+
*/
|
|
196
|
+
inquire: async ({ name, phone, email, message, productRef } = {}) => {
|
|
197
|
+
const payload = { name, phone }
|
|
198
|
+
if (email) payload.email = email
|
|
199
|
+
if (message) payload.message = message
|
|
200
|
+
if (productRef) payload.product_ref = productRef
|
|
201
|
+
return request('/api/inquiries', { method: 'POST', body: payload })
|
|
202
|
+
},
|
|
203
|
+
|
|
204
|
+
/** Escape hatch. Same credential, same retry budget, no normalising. */
|
|
205
|
+
request,
|
|
206
|
+
}
|
|
207
|
+
}
|
package/normalize.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the API returns, turned into what a site needs to render.
|
|
3
|
+
*
|
|
4
|
+
* Every field here exists on the endpoint named above the function. That is not
|
|
5
|
+
* a stylistic choice: a normaliser that reads `raw.costPrice` against a response
|
|
6
|
+
* that carries `cost_price` silently returns undefined, and the site renders a
|
|
7
|
+
* blank price with no error anywhere. So each function documents the columns it
|
|
8
|
+
* is allowed to see, and nothing is invented.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Postgres `numeric` arrives as a string; `Number('')` is 0, which is a lie. */
|
|
12
|
+
function toNumber(value) {
|
|
13
|
+
if (value === null || value === undefined || value === '') return null;
|
|
14
|
+
const n = Number(value);
|
|
15
|
+
return Number.isFinite(n) ? n : null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function toString(value, fallback = '') {
|
|
19
|
+
return typeof value === 'string' ? value : value === null || value === undefined ? fallback : String(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function toArray(value) {
|
|
23
|
+
return Array.isArray(value) ? value : [];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* GET /api/products
|
|
28
|
+
* columns: id, name, category, price, stock, barcode, image, created_at
|
|
29
|
+
*
|
|
30
|
+
* Note what is absent: the endpoint used to publish `cost_price`, so the shop's
|
|
31
|
+
* buying price and margin were readable from the storefront's own JavaScript.
|
|
32
|
+
* The normaliser never looks for it — a site prices from `price`.
|
|
33
|
+
*/
|
|
34
|
+
export function normalizeProduct(raw = {}) {
|
|
35
|
+
const stock = toNumber(raw.stock);
|
|
36
|
+
return {
|
|
37
|
+
id: raw.id ?? null,
|
|
38
|
+
name: toString(raw.name, 'Untitled'),
|
|
39
|
+
category: toString(raw.category),
|
|
40
|
+
price: toNumber(raw.price),
|
|
41
|
+
stock,
|
|
42
|
+
// A null stock means the shop does not track it; that is not "out of stock".
|
|
43
|
+
inStock: stock === null ? true : stock > 0,
|
|
44
|
+
barcode: raw.barcode || null,
|
|
45
|
+
image: raw.image || null,
|
|
46
|
+
createdAt: raw.created_at || null,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* GET /api/catalogue
|
|
52
|
+
* columns: id, name, type, category, price, price_label, description, image,
|
|
53
|
+
* available, featured, variants, specs, includes, new_arrival,
|
|
54
|
+
* sale_price, sale_ends_at, badge, badge_ends_at, product_id, created_at
|
|
55
|
+
*
|
|
56
|
+
* `type` is the discriminator the whole site branches on: a service is priced
|
|
57
|
+
* per job and has "what's included", a product has specs and stock.
|
|
58
|
+
*/
|
|
59
|
+
export function normalizeCatalogueItem(raw = {}) {
|
|
60
|
+
return {
|
|
61
|
+
id: raw.id ?? null,
|
|
62
|
+
name: toString(raw.name, 'Untitled'),
|
|
63
|
+
type: raw.type === 'service' ? 'service' : 'product',
|
|
64
|
+
category: toString(raw.category),
|
|
65
|
+
price: toNumber(raw.price),
|
|
66
|
+
salePrice: toNumber(raw.sale_price),
|
|
67
|
+
priceLabel: raw.price_label || null,
|
|
68
|
+
description: toString(raw.description),
|
|
69
|
+
image: raw.image || null,
|
|
70
|
+
available: raw.available !== false,
|
|
71
|
+
featured: raw.featured === true,
|
|
72
|
+
newArrival: raw.new_arrival === true,
|
|
73
|
+
badge: raw.badge || null,
|
|
74
|
+
variants: raw.variants ?? null,
|
|
75
|
+
specs: raw.specs ?? null,
|
|
76
|
+
includes: toArray(raw.includes),
|
|
77
|
+
// Set when the row is the published form of an inventory product: one button,
|
|
78
|
+
// one price, one stock rule.
|
|
79
|
+
productId: raw.product_id || null,
|
|
80
|
+
createdAt: raw.created_at || null,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const PRICING_MODES = ['flat', 'per_unit', 'per_weight', 'per_hour'];
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* GET /api/services
|
|
88
|
+
* columns: id, category, name, pricing_mode, price, unit_label, description,
|
|
89
|
+
* turnaround_hours, image
|
|
90
|
+
*
|
|
91
|
+
* `pricingMode` is not decoration. A laundry priced per kilo quoted as a flat
|
|
92
|
+
* "KSh 300" is a price the customer acts on and is wrong about.
|
|
93
|
+
*/
|
|
94
|
+
export function normalizeService(raw = {}) {
|
|
95
|
+
return {
|
|
96
|
+
id: raw.id ?? null,
|
|
97
|
+
name: toString(raw.name, 'Untitled'),
|
|
98
|
+
category: toString(raw.category),
|
|
99
|
+
price: toNumber(raw.price),
|
|
100
|
+
pricingMode: PRICING_MODES.includes(raw.pricing_mode) ? raw.pricing_mode : 'flat',
|
|
101
|
+
unitLabel: raw.unit_label || null,
|
|
102
|
+
description: toString(raw.description),
|
|
103
|
+
turnaroundHours: toNumber(raw.turnaround_hours),
|
|
104
|
+
image: raw.image || null,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* GET /api/settings
|
|
110
|
+
* columns: shop_id, store_name, description, about, tagline, store_phone,
|
|
111
|
+
* whatsapp, store_address, business_hours, currency_symbol, logo_url,
|
|
112
|
+
* instagram, facebook, tiktok, primary_color, secondary_color,
|
|
113
|
+
* accent_color, name_accent, featured_product_ids, website_url,
|
|
114
|
+
* feature_toggles
|
|
115
|
+
*
|
|
116
|
+
* `features` is the shop's own on/off switches, keyed the same way its manifest
|
|
117
|
+
* declares them. A site gating a component on a missing key reads undefined and
|
|
118
|
+
* the feature silently never renders, which is why it is always an object here.
|
|
119
|
+
*/
|
|
120
|
+
export function normalizeSettings(raw) {
|
|
121
|
+
const src = raw || {};
|
|
122
|
+
return {
|
|
123
|
+
shopId: src.shop_id ?? null,
|
|
124
|
+
name: toString(src.store_name, 'Our shop'),
|
|
125
|
+
description: toString(src.description),
|
|
126
|
+
about: toString(src.about),
|
|
127
|
+
tagline: toString(src.tagline),
|
|
128
|
+
phone: toString(src.store_phone),
|
|
129
|
+
whatsapp: toString(src.whatsapp),
|
|
130
|
+
address: toString(src.store_address),
|
|
131
|
+
hours: src.business_hours ?? null,
|
|
132
|
+
currency: toString(src.currency_symbol, 'KSh'),
|
|
133
|
+
logo: src.logo_url || null,
|
|
134
|
+
website: toString(src.website_url),
|
|
135
|
+
colours: {
|
|
136
|
+
primary: src.primary_color || null,
|
|
137
|
+
secondary: src.secondary_color || null,
|
|
138
|
+
accent: src.accent_color || null,
|
|
139
|
+
nameAccent: src.name_accent || null,
|
|
140
|
+
},
|
|
141
|
+
featuredProductIds: toArray(src.featured_product_ids),
|
|
142
|
+
features: src.feature_toggles && typeof src.feature_toggles === 'object' ? src.feature_toggles : {},
|
|
143
|
+
social: {
|
|
144
|
+
instagram: toString(src.instagram),
|
|
145
|
+
facebook: toString(src.facebook),
|
|
146
|
+
tiktok: toString(src.tiktok),
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* GET /api/banners
|
|
153
|
+
* columns: id, type, title, subtitle, message, image_url, link_url, active,
|
|
154
|
+
* sort_order
|
|
155
|
+
*
|
|
156
|
+
* The route already filters to active rows and orders them, so both are carried
|
|
157
|
+
* through unchanged rather than re-derived.
|
|
158
|
+
*/
|
|
159
|
+
export function normalizeBanner(raw = {}) {
|
|
160
|
+
return {
|
|
161
|
+
id: raw.id ?? null,
|
|
162
|
+
type: toString(raw.type, 'info'),
|
|
163
|
+
title: toString(raw.title),
|
|
164
|
+
subtitle: toString(raw.subtitle),
|
|
165
|
+
message: toString(raw.message),
|
|
166
|
+
image: raw.image_url || null,
|
|
167
|
+
link: raw.link_url || null,
|
|
168
|
+
active: raw.active !== false,
|
|
169
|
+
sortOrder: toNumber(raw.sort_order) ?? 0,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* GET /api/page-content
|
|
175
|
+
* columns: id, page_key, section_key, content, created_at, updated_at
|
|
176
|
+
*
|
|
177
|
+
* `content` is the jsonb block the site renders; it is passed through untouched
|
|
178
|
+
* because its shape belongs to the site's own design, not to this package.
|
|
179
|
+
*/
|
|
180
|
+
export function normalizePageContent(raw = {}) {
|
|
181
|
+
return {
|
|
182
|
+
id: raw.id ?? null,
|
|
183
|
+
pageKey: raw.page_key ?? null,
|
|
184
|
+
sectionKey: raw.section_key ?? null,
|
|
185
|
+
content: raw.content ?? null,
|
|
186
|
+
updatedAt: raw.updated_at || null,
|
|
187
|
+
};
|
|
188
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@framestudio/keel-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Read a Keel shop's catalogue, settings and content through a site token. One import, no database credential in the browser.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./client.js",
|
|
8
|
+
"module": "./client.js",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./client.js",
|
|
11
|
+
"./react": "./react.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"client.js",
|
|
15
|
+
"normalize.js",
|
|
16
|
+
"react.js",
|
|
17
|
+
"README.md",
|
|
18
|
+
"CHANGELOG.md"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"keywords": [
|
|
22
|
+
"keel",
|
|
23
|
+
"storefront",
|
|
24
|
+
"catalogue",
|
|
25
|
+
"minicatalogue",
|
|
26
|
+
"kenya"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "node --test test/",
|
|
30
|
+
"build:embed": "node scripts/build-embed.mjs"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@framestudio/keel-analytics": "^0.3.0"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"react": ">=18"
|
|
37
|
+
},
|
|
38
|
+
"peerDependenciesMeta": {
|
|
39
|
+
"react": {
|
|
40
|
+
"optional": true
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"esbuild": "^0.28.2",
|
|
45
|
+
"react": "^19.0.0",
|
|
46
|
+
"react-dom": "^19.0.0"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=18"
|
|
50
|
+
}
|
|
51
|
+
}
|
package/react.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createContext, createElement, useContext, useEffect, useState } from 'react'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* React bindings. Optional, and deliberately thin.
|
|
5
|
+
*
|
|
6
|
+
* The core is plain async so a site without React pays nothing for this file.
|
|
7
|
+
* What lives here is the two things that are easy to get wrong: reading the
|
|
8
|
+
* client out of context, and not setting state after a component unmounts.
|
|
9
|
+
*/
|
|
10
|
+
const KeelContext = createContext(null)
|
|
11
|
+
|
|
12
|
+
export function KeelProvider({ client, children }) {
|
|
13
|
+
return createElement(KeelContext.Provider, { value: client }, children)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function useKeel() {
|
|
17
|
+
const client = useContext(KeelContext)
|
|
18
|
+
if (!client) {
|
|
19
|
+
throw new Error('useKeel must be used inside <KeelProvider client={...}>')
|
|
20
|
+
}
|
|
21
|
+
return client
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Load one resource, with the three states a storefront actually renders:
|
|
26
|
+
* loading, data, and the error it must not swallow.
|
|
27
|
+
*
|
|
28
|
+
* `options` is compared by value (a serialised key), not by identity: a caller
|
|
29
|
+
* writing `usePageContent({ page: 'home' })` inline would otherwise create a new
|
|
30
|
+
* object every render and refetch forever.
|
|
31
|
+
*/
|
|
32
|
+
export function useKeelResource(method, options) {
|
|
33
|
+
const client = useKeel()
|
|
34
|
+
const [state, setState] = useState({ data: null, error: null, loading: true })
|
|
35
|
+
const key = options === undefined ? '' : JSON.stringify(options)
|
|
36
|
+
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
let cancelled = false
|
|
39
|
+
setState({ data: null, error: null, loading: true })
|
|
40
|
+
|
|
41
|
+
Promise.resolve()
|
|
42
|
+
.then(() => client[method](key ? JSON.parse(key) : undefined))
|
|
43
|
+
.then((data) => {
|
|
44
|
+
if (!cancelled) setState({ data, error: null, loading: false })
|
|
45
|
+
})
|
|
46
|
+
.catch((error) => {
|
|
47
|
+
if (!cancelled) setState({ data: null, error, loading: false })
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
return () => {
|
|
51
|
+
cancelled = true
|
|
52
|
+
}
|
|
53
|
+
}, [client, method, key])
|
|
54
|
+
|
|
55
|
+
return state
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const useProducts = () => useKeelResource('products')
|
|
59
|
+
export const useServices = () => useKeelResource('services')
|
|
60
|
+
export const useCatalogue = () => useKeelResource('catalogue')
|
|
61
|
+
export const useBanners = () => useKeelResource('banners')
|
|
62
|
+
export const useShopSettings = () => useKeelResource('settings')
|
|
63
|
+
export const usePageContent = (options) => useKeelResource('pageContent', options)
|