@opencloudcms/client 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +337 -2
- package/dist/cjs/actions/runner.js +434 -0
- package/dist/cjs/core/account.js +22 -0
- package/dist/cjs/core/actions.js +56 -0
- package/dist/cjs/core/auth.js +73 -0
- package/dist/cjs/core/client.js +160 -0
- package/dist/cjs/core/content.js +89 -0
- package/dist/cjs/core/default-client.js +27 -0
- package/dist/cjs/core/errors.js +53 -0
- package/dist/cjs/core/typed.js +22 -0
- package/dist/cjs/core/types.js +2 -0
- package/dist/cjs/core/utils.js +64 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/next/loopback.js +12 -0
- package/dist/cjs/next/server.js +99 -0
- package/dist/cjs/next/stubs.js +10 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/react/provider.js +162 -0
- package/dist/cjs/react/stubs.js +13 -0
- package/dist/cjs/server.js +38 -0
- package/dist/esm/actions/runner.d.ts +92 -0
- package/dist/esm/actions/runner.js +428 -0
- package/dist/esm/core/account.d.ts +20 -0
- package/dist/esm/core/account.js +19 -0
- package/dist/esm/core/actions.d.ts +81 -0
- package/dist/esm/core/actions.js +51 -0
- package/dist/esm/core/auth.d.ts +61 -0
- package/dist/esm/core/auth.js +69 -0
- package/dist/esm/core/client.d.ts +2 -0
- package/dist/esm/core/client.js +157 -0
- package/dist/esm/core/content.d.ts +5 -0
- package/dist/esm/core/content.js +85 -0
- package/dist/esm/core/default-client.d.ts +9 -0
- package/dist/esm/core/default-client.js +23 -0
- package/dist/esm/core/errors.d.ts +13 -0
- package/dist/esm/core/errors.js +47 -0
- package/dist/esm/core/typed.d.ts +31 -0
- package/dist/esm/core/typed.js +19 -0
- package/dist/esm/core/types.d.ts +90 -0
- package/dist/esm/core/types.js +1 -0
- package/dist/esm/core/utils.d.ts +27 -0
- package/dist/esm/core/utils.js +56 -0
- package/dist/esm/index.d.ts +20 -0
- package/dist/esm/index.js +12 -0
- package/dist/esm/next/loopback.d.ts +6 -0
- package/dist/esm/next/loopback.js +9 -0
- package/dist/esm/next/server.d.ts +19 -0
- package/dist/esm/next/server.js +60 -0
- package/dist/esm/next/stubs.d.ts +5 -0
- package/dist/esm/next/stubs.js +7 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/react/provider.d.ts +38 -0
- package/dist/esm/react/provider.js +153 -0
- package/dist/esm/react/stubs.d.ts +6 -0
- package/dist/esm/react/stubs.js +10 -0
- package/dist/esm/server.d.ts +21 -0
- package/dist/esm/server.js +13 -0
- package/package.json +61 -3
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { ApiError, isApiError } from './errors.js';
|
|
2
|
+
import { safeReturnTo } from './utils.js';
|
|
3
|
+
const enc = encodeURIComponent;
|
|
4
|
+
/** A same-site navigation target: a safe local path, or an absolute http(s) URL on this origin; else `/`. */
|
|
5
|
+
export function safeRedirectTarget(redirectTo) {
|
|
6
|
+
if (typeof redirectTo === 'string' && redirectTo.startsWith('/'))
|
|
7
|
+
return safeReturnTo(redirectTo);
|
|
8
|
+
const here = typeof location !== 'undefined' && location ? location : undefined;
|
|
9
|
+
if (!here || typeof redirectTo !== 'string')
|
|
10
|
+
return '/';
|
|
11
|
+
try {
|
|
12
|
+
const u = new URL(redirectTo);
|
|
13
|
+
if ((u.protocol === 'http:' || u.protocol === 'https:') && u.origin === here.origin)
|
|
14
|
+
return redirectTo;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
/* not absolute */
|
|
18
|
+
}
|
|
19
|
+
return '/';
|
|
20
|
+
}
|
|
21
|
+
function navigate(to) {
|
|
22
|
+
if (typeof location === 'undefined' || !location)
|
|
23
|
+
return;
|
|
24
|
+
location.assign(to);
|
|
25
|
+
}
|
|
26
|
+
export function createAuth(client) {
|
|
27
|
+
const post = (path, body) => client.request('POST', path, body === undefined ? {} : { body });
|
|
28
|
+
const auth = {
|
|
29
|
+
async me() {
|
|
30
|
+
try {
|
|
31
|
+
return await client.request('GET', '/api/customer/auth/me');
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
if (isApiError(e) && e.status === 401)
|
|
35
|
+
return null;
|
|
36
|
+
throw e;
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
methods: () => client.request('GET', '/api/customer/auth/methods'),
|
|
40
|
+
signIn(returnTo) {
|
|
41
|
+
if (client.options.auth === 'bearer') {
|
|
42
|
+
throw new ApiError(0, 'unsupported_in_bearer_mode', 'signIn() is not available in bearer mode; sign in with your own OAuth flow');
|
|
43
|
+
}
|
|
44
|
+
const current = typeof location !== 'undefined' && location ? `${location.pathname}${location.search ?? ''}` : '/';
|
|
45
|
+
navigate(`/api/customer/auth/login?returnTo=${enc(safeReturnTo(returnTo ?? current))}`);
|
|
46
|
+
},
|
|
47
|
+
async signOut(o) {
|
|
48
|
+
const out = await post('/api/customer/auth/logout');
|
|
49
|
+
if (o?.navigate !== false)
|
|
50
|
+
auth.followRedirect(out);
|
|
51
|
+
return out;
|
|
52
|
+
},
|
|
53
|
+
otp: {
|
|
54
|
+
request: (uid, identifier) => post(`/oauth2/interaction/${enc(uid)}/customer/otp`, { identifier }),
|
|
55
|
+
verify: (uid, identifier, code, name) => post(`/oauth2/interaction/${enc(uid)}/customer/otp/verify`, name === undefined ? { identifier, code } : { identifier, code, name }),
|
|
56
|
+
},
|
|
57
|
+
password: {
|
|
58
|
+
signIn: (uid, identifier, password) => post(`/oauth2/interaction/${enc(uid)}/customer/password`, { identifier, password }),
|
|
59
|
+
},
|
|
60
|
+
passwordReset: {
|
|
61
|
+
request: (identifier) => post('/api/customer/auth/password-reset', { identifier }),
|
|
62
|
+
async confirm(identifier, code, newPassword) {
|
|
63
|
+
await post('/api/customer/auth/password-reset/confirm', { identifier, code, newPassword });
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
followRedirect: (r) => navigate(safeRedirectTarget(r?.redirectTo)),
|
|
67
|
+
};
|
|
68
|
+
return auth;
|
|
69
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { ApiError } from './errors.js';
|
|
2
|
+
import { createAssets, createContent } from './content.js';
|
|
3
|
+
import { createAuth } from './auth.js';
|
|
4
|
+
import { createAccount } from './account.js';
|
|
5
|
+
import { createActions } from './actions.js';
|
|
6
|
+
/**
|
|
7
|
+
* Cookie mode: `same-origin` when `baseUrl` is the page origin (or empty). Another origin (or one that cannot be
|
|
8
|
+
* determined) gets `omit`: the SDK never sends cookies cross-origin; cross-origin storefronts use bearer mode.
|
|
9
|
+
*/
|
|
10
|
+
function credentialsFor(baseUrl) {
|
|
11
|
+
if (baseUrl === '')
|
|
12
|
+
return 'same-origin';
|
|
13
|
+
const here = typeof location !== 'undefined' && location ? location : undefined;
|
|
14
|
+
if (!here)
|
|
15
|
+
return 'omit';
|
|
16
|
+
try {
|
|
17
|
+
return new URL(baseUrl, here.href).origin === here.origin ? 'same-origin' : 'omit';
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return 'omit';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** `https://x`, `mailto:x` or `//host/x`: used as given, never prefixed with the base URL. */
|
|
24
|
+
const isAbsolute = (path) => /^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith('//');
|
|
25
|
+
function queryValue(key, v) {
|
|
26
|
+
if (v instanceof Date)
|
|
27
|
+
return v.toISOString();
|
|
28
|
+
if (typeof v === 'object' && v !== null)
|
|
29
|
+
throw new TypeError(`query value for ${key} must be a scalar or array`);
|
|
30
|
+
return String(v);
|
|
31
|
+
}
|
|
32
|
+
/** `path` (leading `/` ensured) with its own query merged with `query`; `locale` added on GET unless set (or `null`). */
|
|
33
|
+
function buildPath(path, query, locale) {
|
|
34
|
+
const p = isAbsolute(path) || path.startsWith('/') ? path : `/${path}`;
|
|
35
|
+
const at = p.indexOf('?');
|
|
36
|
+
const pathname = at < 0 ? p : p.slice(0, at);
|
|
37
|
+
const qs = new URLSearchParams(at < 0 ? '' : p.slice(at + 1));
|
|
38
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
39
|
+
if (v === undefined || v === null)
|
|
40
|
+
continue;
|
|
41
|
+
qs.append(k, Array.isArray(v) ? v.map((x) => queryValue(k, x)).join(',') : queryValue(k, v));
|
|
42
|
+
}
|
|
43
|
+
const suppressed = query !== undefined && Object.prototype.hasOwnProperty.call(query, 'locale') && query.locale === null;
|
|
44
|
+
if (locale && !suppressed && !qs.has('locale'))
|
|
45
|
+
qs.set('locale', locale);
|
|
46
|
+
// Keep `[ ] ,` readable (`filter[a][in]=x,y`); all are legal in a query string.
|
|
47
|
+
const s = qs.toString().replace(/%5B/gi, '[').replace(/%5D/gi, ']').replace(/%2C/gi, ',');
|
|
48
|
+
return s ? `${pathname}?${s}` : pathname;
|
|
49
|
+
}
|
|
50
|
+
async function readBody(res) {
|
|
51
|
+
if (res.status === 204)
|
|
52
|
+
return undefined;
|
|
53
|
+
const text = await res.text();
|
|
54
|
+
if (text === '')
|
|
55
|
+
return undefined;
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(text);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return text;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function toApiError(res, body) {
|
|
64
|
+
const error = typeof body === 'object' && body !== null ? body.error : undefined;
|
|
65
|
+
if (typeof error === 'object' && error !== null) {
|
|
66
|
+
const e = error;
|
|
67
|
+
const code = typeof e.code === 'string' && e.code ? e.code : `http_${res.status}`;
|
|
68
|
+
const message = typeof e.message === 'string' ? e.message : `${res.status} ${res.statusText}`.trim();
|
|
69
|
+
const issues = Array.isArray(e.issues) ? e.issues : undefined;
|
|
70
|
+
// A 401 from the actions endpoint carries the server's sign-in path next to `error`: expose it as `details.signIn`.
|
|
71
|
+
const signIn = body.signIn;
|
|
72
|
+
const details = typeof signIn === 'string' && !('signIn' in error) ? { ...error, signIn } : error;
|
|
73
|
+
return new ApiError(res.status, code, message, issues, details);
|
|
74
|
+
}
|
|
75
|
+
return new ApiError(res.status, `http_${res.status}`, `${res.status} ${res.statusText}`.trim());
|
|
76
|
+
}
|
|
77
|
+
export function createClient(o = {}) {
|
|
78
|
+
const options = Object.freeze({
|
|
79
|
+
...o,
|
|
80
|
+
baseUrl: (o.baseUrl ?? '').replace(/\/+$/, ''),
|
|
81
|
+
auth: o.auth ?? 'cookie',
|
|
82
|
+
});
|
|
83
|
+
const doFetch = o.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
84
|
+
const credentials = options.auth === 'cookie' ? credentialsFor(options.baseUrl) : undefined;
|
|
85
|
+
/**
|
|
86
|
+
* Credentials and bearer tokens go only to the client's own origin. The final URL is always resolved the way a
|
|
87
|
+
* browser would (so `/\\evil.com` or `/\t/evil.com` count as another host) and its origin compared; fails closed.
|
|
88
|
+
*/
|
|
89
|
+
function toBaseOrigin(url) {
|
|
90
|
+
try {
|
|
91
|
+
const here = typeof location !== 'undefined' && location ? location.href : 'http://invalid.invalid/';
|
|
92
|
+
const base = new URL(options.baseUrl || '/', here);
|
|
93
|
+
return new URL(url, base).origin === base.origin;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
async function request(method, path, r = {}) {
|
|
100
|
+
const abs = isAbsolute(path);
|
|
101
|
+
const url = `${abs ? '' : options.baseUrl}${buildPath(path, r.query, method === 'GET' && !abs ? options.locale : undefined)}`;
|
|
102
|
+
const headers = { accept: 'application/json' };
|
|
103
|
+
if (options.locale)
|
|
104
|
+
headers['accept-language'] = options.locale;
|
|
105
|
+
Object.assign(headers, lower(options.headers));
|
|
106
|
+
const own = toBaseOrigin(url);
|
|
107
|
+
if (own && options.auth === 'bearer' && options.getAccessToken) {
|
|
108
|
+
const token = await options.getAccessToken();
|
|
109
|
+
if (token)
|
|
110
|
+
headers.authorization = `Bearer ${token}`;
|
|
111
|
+
}
|
|
112
|
+
Object.assign(headers, lower(r.headers));
|
|
113
|
+
let body;
|
|
114
|
+
if (r.body !== undefined) {
|
|
115
|
+
body = JSON.stringify(r.body);
|
|
116
|
+
headers['content-type'] ??= 'application/json';
|
|
117
|
+
}
|
|
118
|
+
const init = { method, headers };
|
|
119
|
+
if (body !== undefined)
|
|
120
|
+
init.body = body;
|
|
121
|
+
if (credentials && own)
|
|
122
|
+
init.credentials = credentials;
|
|
123
|
+
if (r.signal)
|
|
124
|
+
init.signal = r.signal;
|
|
125
|
+
if (r.cache)
|
|
126
|
+
init.cache = r.cache;
|
|
127
|
+
if (r.next)
|
|
128
|
+
init.next = r.next;
|
|
129
|
+
let res;
|
|
130
|
+
let data;
|
|
131
|
+
try {
|
|
132
|
+
res = await doFetch(url, init);
|
|
133
|
+
data = await readBody(res);
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
if (r.signal?.aborted || e?.name === 'AbortError')
|
|
137
|
+
throw e;
|
|
138
|
+
throw new ApiError(0, 'network_error', e instanceof Error ? e.message : 'Network error');
|
|
139
|
+
}
|
|
140
|
+
if (!res.ok)
|
|
141
|
+
throw toApiError(res, data);
|
|
142
|
+
return data;
|
|
143
|
+
}
|
|
144
|
+
const client = { options, request };
|
|
145
|
+
client.content = createContent(client);
|
|
146
|
+
client.assets = createAssets(client);
|
|
147
|
+
client.auth = createAuth(client);
|
|
148
|
+
client.account = createAccount(client);
|
|
149
|
+
client.actions = createActions(client);
|
|
150
|
+
return client;
|
|
151
|
+
}
|
|
152
|
+
function lower(h) {
|
|
153
|
+
const out = {};
|
|
154
|
+
for (const [k, v] of Object.entries(h ?? {}))
|
|
155
|
+
out[k.toLowerCase()] = v;
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AssetsClient, Client, ContentClient, FilterValue } from './types.js';
|
|
2
|
+
export declare function createContent(client: Pick<Client, 'request'>): ContentClient;
|
|
3
|
+
/** Public delivery assets: `GET /api/content/assets?ids=a,b` in chunks of 100 (same parsing as core/blocks `fetchers.ts`). */
|
|
4
|
+
export declare function createAssets(client: Pick<Client, 'request'>): AssetsClient;
|
|
5
|
+
export type { FilterValue };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { isApiError } from './errors.js';
|
|
2
|
+
const MAX_IDS = 100;
|
|
3
|
+
function listQuery(o, extra = {}) {
|
|
4
|
+
const q = {};
|
|
5
|
+
for (const [k, v] of Object.entries(o?.filter ?? {})) {
|
|
6
|
+
if (v === undefined || v === null)
|
|
7
|
+
continue;
|
|
8
|
+
if (typeof v === 'object')
|
|
9
|
+
q[`filter[${k}][in]`] = v.in;
|
|
10
|
+
else
|
|
11
|
+
q[`filter[${k}]`] = v;
|
|
12
|
+
}
|
|
13
|
+
for (const [k, v] of Object.entries(extra))
|
|
14
|
+
q[k] = v;
|
|
15
|
+
if (o?.sort !== undefined)
|
|
16
|
+
q.sort = o.sort;
|
|
17
|
+
if (o?.limit !== undefined)
|
|
18
|
+
q.limit = o.limit;
|
|
19
|
+
if (o?.offset !== undefined)
|
|
20
|
+
q.offset = o.offset;
|
|
21
|
+
if (o?.locale !== undefined)
|
|
22
|
+
q.locale = o.locale;
|
|
23
|
+
if (o?.fallback !== undefined)
|
|
24
|
+
q.fallback = o.fallback;
|
|
25
|
+
return q;
|
|
26
|
+
}
|
|
27
|
+
const apiPath = (apiId) => `/api/content/${encodeURIComponent(apiId)}`;
|
|
28
|
+
export function createContent(client) {
|
|
29
|
+
async function list(apiId, o) {
|
|
30
|
+
const r = await client.request('GET', apiPath(apiId), { query: listQuery(o) });
|
|
31
|
+
return { data: r?.data ?? [], meta: r?.meta ?? {} };
|
|
32
|
+
}
|
|
33
|
+
async function get(apiId, documentId, o) {
|
|
34
|
+
try {
|
|
35
|
+
const r = await client.request('GET', `${apiPath(apiId)}/${encodeURIComponent(documentId)}`, {
|
|
36
|
+
query: { ...(o?.locale !== undefined ? { locale: o.locale } : {}), ...(o?.fallback !== undefined ? { fallback: o.fallback } : {}) },
|
|
37
|
+
});
|
|
38
|
+
return r?.data ?? null;
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
if (isApiError(e) && e.status === 404)
|
|
42
|
+
return null;
|
|
43
|
+
throw e;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function bySlug(apiId, slug, o) {
|
|
47
|
+
const r = await list(apiId, { ...o, filter: { slug }, limit: 1 });
|
|
48
|
+
return r.data[0] ?? null;
|
|
49
|
+
}
|
|
50
|
+
async function byIds(apiId, ids, o) {
|
|
51
|
+
const unique = [...new Set(ids)];
|
|
52
|
+
const found = new Map();
|
|
53
|
+
for (let i = 0; i < unique.length; i += MAX_IDS) {
|
|
54
|
+
const r = await list(apiId, { ...o, filter: { documentId: { in: unique.slice(i, i + MAX_IDS) } }, limit: MAX_IDS });
|
|
55
|
+
for (const e of r.data)
|
|
56
|
+
found.set(e.documentId, e);
|
|
57
|
+
}
|
|
58
|
+
return unique.flatMap((id) => (found.has(id) ? [found.get(id)] : []));
|
|
59
|
+
}
|
|
60
|
+
return { list, get, bySlug, byIds };
|
|
61
|
+
}
|
|
62
|
+
/** Public delivery assets: `GET /api/content/assets?ids=a,b` in chunks of 100 (same parsing as core/blocks `fetchers.ts`). */
|
|
63
|
+
export function createAssets(client) {
|
|
64
|
+
return {
|
|
65
|
+
async byIds(ids) {
|
|
66
|
+
const unique = [...new Set(ids)];
|
|
67
|
+
const out = [];
|
|
68
|
+
for (let i = 0; i < unique.length; i += MAX_IDS) {
|
|
69
|
+
const r = await client.request('GET', '/api/content/assets', { query: { ids: unique.slice(i, i + MAX_IDS) } });
|
|
70
|
+
for (const a of Array.isArray(r?.data) ? r.data : []) {
|
|
71
|
+
if (typeof a.id !== 'string' || typeof a.url !== 'string')
|
|
72
|
+
continue;
|
|
73
|
+
out.push({
|
|
74
|
+
id: a.id,
|
|
75
|
+
url: a.url,
|
|
76
|
+
...(typeof a.alt === 'string' ? { alt: a.alt } : {}),
|
|
77
|
+
...(typeof a.width === 'number' ? { width: a.width } : {}),
|
|
78
|
+
...(typeof a.height === 'number' ? { height: a.height } : {}),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Client } from './types.js';
|
|
2
|
+
/** Overrides the default content client (tests / apps). Pass `undefined` to go back to the environment rule. */
|
|
3
|
+
export declare function setDefaultClientFactory(fn: (() => Client) | undefined): void;
|
|
4
|
+
/**
|
|
5
|
+
* The client used by content entries without a bound client, chosen per call by environment (not by which entry
|
|
6
|
+
* loaded last): no `window` → the process-cached `publicClient()` (loopback, cacheable); otherwise a same-origin
|
|
7
|
+
* cookie client. No `next/*` is imported here; the server client is `publicClient()` minus the Next-only options.
|
|
8
|
+
*/
|
|
9
|
+
export declare function defaultClient(): Client;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createClient } from './client.js';
|
|
2
|
+
import { loopbackUrl } from '../next/loopback.js';
|
|
3
|
+
let override;
|
|
4
|
+
let overridden;
|
|
5
|
+
let server;
|
|
6
|
+
let browser;
|
|
7
|
+
/** Overrides the default content client (tests / apps). Pass `undefined` to go back to the environment rule. */
|
|
8
|
+
export function setDefaultClientFactory(fn) {
|
|
9
|
+
override = fn;
|
|
10
|
+
overridden = undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The client used by content entries without a bound client, chosen per call by environment (not by which entry
|
|
14
|
+
* loaded last): no `window` → the process-cached `publicClient()` (loopback, cacheable); otherwise a same-origin
|
|
15
|
+
* cookie client. No `next/*` is imported here; the server client is `publicClient()` minus the Next-only options.
|
|
16
|
+
*/
|
|
17
|
+
export function defaultClient() {
|
|
18
|
+
if (override)
|
|
19
|
+
return (overridden ??= override());
|
|
20
|
+
if (typeof window === 'undefined')
|
|
21
|
+
return (server ??= createClient({ baseUrl: loopbackUrl(), auth: 'cookie' }));
|
|
22
|
+
return (browser ??= createClient());
|
|
23
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ApiIssue, ErrorMessages } from './types.js';
|
|
2
|
+
/** A failed API call: `{ error: { code, message, issues? } }`, `http_<status>` for other bodies, `network_error` (status 0). */
|
|
3
|
+
export declare class ApiError extends Error {
|
|
4
|
+
readonly status: number;
|
|
5
|
+
readonly code: string;
|
|
6
|
+
readonly issues?: ApiIssue[];
|
|
7
|
+
/** The raw `error` object of the response body (extra fields such as `signIn`). */
|
|
8
|
+
readonly details?: Record<string, unknown>;
|
|
9
|
+
constructor(status: number, code: string, message?: string, issues?: ApiIssue[], details?: Record<string, unknown>);
|
|
10
|
+
}
|
|
11
|
+
export declare const isApiError: (e: unknown) => e is ApiError;
|
|
12
|
+
/** User-facing text for an error or error code (en-US / vi-VN), `extra` taking precedence over the built-ins. */
|
|
13
|
+
export declare function errorMessage(err: unknown, locale?: string, extra?: ErrorMessages): string;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** A failed API call: `{ error: { code, message, issues? } }`, `http_<status>` for other bodies, `network_error` (status 0). */
|
|
2
|
+
export class ApiError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
issues;
|
|
6
|
+
/** The raw `error` object of the response body (extra fields such as `signIn`). */
|
|
7
|
+
details;
|
|
8
|
+
constructor(status, code, message, issues, details) {
|
|
9
|
+
super(message || code);
|
|
10
|
+
this.name = 'ApiError';
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.code = code;
|
|
13
|
+
if (issues)
|
|
14
|
+
this.issues = issues;
|
|
15
|
+
if (details)
|
|
16
|
+
this.details = details;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export const isApiError = (e) => e instanceof ApiError || (typeof e === 'object' && e !== null && e.name === 'ApiError' && typeof e.code === 'string');
|
|
20
|
+
const GENERIC = '__generic';
|
|
21
|
+
const BUILT_IN = {
|
|
22
|
+
invalid_identifier: { 'en-US': 'Enter a valid email address or phone number.', 'vi-VN': 'Vui lòng nhập email hoặc số điện thoại hợp lệ.' },
|
|
23
|
+
identifier_kind_disabled: { 'en-US': 'This type of sign-in is not accepted.', 'vi-VN': 'Hình thức đăng nhập này không được hỗ trợ.' },
|
|
24
|
+
method_disabled: { 'en-US': 'This sign-in method is not available.', 'vi-VN': 'Phương thức đăng nhập này không khả dụng.' },
|
|
25
|
+
invalid_code: { 'en-US': 'The code is incorrect or has expired.', 'vi-VN': 'Mã không đúng hoặc đã hết hạn.' },
|
|
26
|
+
invalid_credentials: { 'en-US': 'Incorrect sign-in details.', 'vi-VN': 'Thông tin đăng nhập không đúng.' },
|
|
27
|
+
account_disabled: { 'en-US': 'This account has been disabled.', 'vi-VN': 'Tài khoản này đã bị vô hiệu hóa.' },
|
|
28
|
+
rate_limited: { 'en-US': 'Too many attempts. Please try again later.', 'vi-VN': 'Bạn đã thử quá nhiều lần. Vui lòng thử lại sau.' },
|
|
29
|
+
weak_password: { 'en-US': 'This password is too weak.', 'vi-VN': 'Mật khẩu quá yếu.' },
|
|
30
|
+
validation_failed: { 'en-US': 'Please check the information you entered.', 'vi-VN': 'Vui lòng kiểm tra lại thông tin đã nhập.' },
|
|
31
|
+
unauthenticated: { 'en-US': 'Please sign in to continue.', 'vi-VN': 'Vui lòng đăng nhập để tiếp tục.' },
|
|
32
|
+
login_expired: { 'en-US': 'Your sign-in has expired. Please start again.', 'vi-VN': 'Phiên đăng nhập đã hết hạn. Vui lòng thử lại.' },
|
|
33
|
+
invalid_state: { 'en-US': 'Sign-in could not be completed. Please start again.', 'vi-VN': 'Không thể hoàn tất đăng nhập. Vui lòng thử lại từ đầu.' },
|
|
34
|
+
unknown_action: { 'en-US': 'This action is not available.', 'vi-VN': 'Thao tác này không khả dụng.' },
|
|
35
|
+
action_failed: { 'en-US': 'The action could not be completed. Please try again.', 'vi-VN': 'Không thể thực hiện thao tác. Vui lòng thử lại.' },
|
|
36
|
+
network_error: { 'en-US': 'Cannot connect. Check your connection and try again.', 'vi-VN': 'Không thể kết nối. Vui lòng kiểm tra mạng và thử lại.' },
|
|
37
|
+
[GENERIC]: { 'en-US': 'Something went wrong. Please try again.', 'vi-VN': 'Đã xảy ra lỗi. Vui lòng thử lại.' },
|
|
38
|
+
};
|
|
39
|
+
const toMessageLocale = (locale) => (locale && /^vi(\b|[-_])/i.test(locale) ? 'vi-VN' : 'en-US');
|
|
40
|
+
/** User-facing text for an error or error code (en-US / vi-VN), `extra` taking precedence over the built-ins. */
|
|
41
|
+
export function errorMessage(err, locale, extra) {
|
|
42
|
+
const loc = toMessageLocale(locale);
|
|
43
|
+
const code = typeof err === 'string' ? err : isApiError(err) ? err.code : GENERIC;
|
|
44
|
+
const own = extra?.[code];
|
|
45
|
+
const builtIn = BUILT_IN[code];
|
|
46
|
+
return own?.[loc] ?? builtIn?.[loc] ?? own?.['en-US'] ?? BUILT_IN[GENERIC][loc];
|
|
47
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Client, FilterValue, ListResult, ReadOptions } from './types.js';
|
|
2
|
+
type Scalar = string | number | boolean;
|
|
3
|
+
type FilterFor<E> = {
|
|
4
|
+
[K in keyof E]?: Scalar | {
|
|
5
|
+
in: (string | number)[];
|
|
6
|
+
};
|
|
7
|
+
} & {
|
|
8
|
+
documentId?: FilterValue;
|
|
9
|
+
};
|
|
10
|
+
export interface TypedListOptions<E> {
|
|
11
|
+
filter?: FilterFor<E>;
|
|
12
|
+
sort?: string;
|
|
13
|
+
limit?: number;
|
|
14
|
+
offset?: number;
|
|
15
|
+
locale?: string;
|
|
16
|
+
fallback?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface TypedContent<E> {
|
|
19
|
+
list(o?: TypedListOptions<E>): Promise<ListResult<E>>;
|
|
20
|
+
get(documentId: string, o?: ReadOptions): Promise<E | null>;
|
|
21
|
+
bySlug(slug: string, o?: ReadOptions): Promise<E | null>;
|
|
22
|
+
byIds(ids: string[], o?: ReadOptions): Promise<E[]>;
|
|
23
|
+
}
|
|
24
|
+
export type ContentApi<M extends Record<string, unknown>> = {
|
|
25
|
+
[K in keyof M]: TypedContent<M[K]>;
|
|
26
|
+
} & {
|
|
27
|
+
with(client: Client): ContentApi<M>;
|
|
28
|
+
};
|
|
29
|
+
/** Typed access to content types: `createContentApi<{ product: Product }>().product.list({ filter: { slug: 'x' } })`. */
|
|
30
|
+
export declare function createContentApi<M extends Record<string, unknown>>(bound?: Client): ContentApi<M>;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { defaultClient } from './default-client.js';
|
|
2
|
+
/** Typed access to content types: `createContentApi<{ product: Product }>().product.list({ filter: { slug: 'x' } })`. */
|
|
3
|
+
export function createContentApi(bound) {
|
|
4
|
+
const clientOf = () => bound ?? defaultClient();
|
|
5
|
+
return new Proxy({}, {
|
|
6
|
+
get(_t, key) {
|
|
7
|
+
if (typeof key !== 'string' || key === 'then')
|
|
8
|
+
return undefined;
|
|
9
|
+
if (key === 'with')
|
|
10
|
+
return (c) => createContentApi(c);
|
|
11
|
+
return {
|
|
12
|
+
list: (o) => clientOf().content.list(key, o),
|
|
13
|
+
get: (id, o) => clientOf().content.get(key, id, o),
|
|
14
|
+
bySlug: (slug, o) => clientOf().content.bySlug(key, slug, o),
|
|
15
|
+
byIds: (ids, o) => clientOf().content.byIds(key, ids, o),
|
|
16
|
+
};
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { AccountClient } from './account.js';
|
|
2
|
+
import type { ActionsClient } from './actions.js';
|
|
3
|
+
import type { AuthClient } from './auth.js';
|
|
4
|
+
export type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
|
|
5
|
+
export type MessageLocale = 'en-US' | 'vi-VN';
|
|
6
|
+
/** Error texts by code, then by locale. Overrides and extends the built-in messages. */
|
|
7
|
+
export type ErrorMessages = Partial<Record<string, Partial<Record<MessageLocale, string>>>>;
|
|
8
|
+
export interface ClientOptions {
|
|
9
|
+
/** API origin (and optional path prefix). Default `''`: same origin as the page. */
|
|
10
|
+
baseUrl?: string;
|
|
11
|
+
/** `cookie` (default): the session cookie, tokens never exposed. `bearer`: `Authorization: Bearer <getAccessToken()>`. */
|
|
12
|
+
auth?: 'cookie' | 'bearer';
|
|
13
|
+
/** Bearer mode only. A `null` token sends no `Authorization` header. */
|
|
14
|
+
getAccessToken?: () => string | null | Promise<string | null>;
|
|
15
|
+
/** Sent as the `locale` query and `Accept-Language`. */
|
|
16
|
+
locale?: string;
|
|
17
|
+
/** Injectable fetch (tests, React Native). Default: the global `fetch`. */
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
/** Extra headers on every request (e.g. server-side cookie forwarding). */
|
|
20
|
+
headers?: Record<string, string>;
|
|
21
|
+
messages?: ErrorMessages;
|
|
22
|
+
}
|
|
23
|
+
export type ResolvedClientOptions = Readonly<Omit<ClientOptions, 'baseUrl' | 'auth'> & {
|
|
24
|
+
baseUrl: string;
|
|
25
|
+
auth: 'cookie' | 'bearer';
|
|
26
|
+
}>;
|
|
27
|
+
export interface RequestOptions {
|
|
28
|
+
body?: unknown;
|
|
29
|
+
query?: Record<string, unknown>;
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
cache?: RequestCache;
|
|
33
|
+
/** Next.js fetch cache options (ignored outside Next). */
|
|
34
|
+
next?: {
|
|
35
|
+
revalidate?: number | false;
|
|
36
|
+
tags?: string[];
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export interface Client {
|
|
40
|
+
readonly options: ResolvedClientOptions;
|
|
41
|
+
request<T = unknown>(method: HttpMethod, path: string, o?: RequestOptions): Promise<T>;
|
|
42
|
+
readonly content: ContentClient;
|
|
43
|
+
readonly assets: AssetsClient;
|
|
44
|
+
readonly auth: AuthClient;
|
|
45
|
+
readonly account: AccountClient;
|
|
46
|
+
readonly actions: ActionsClient;
|
|
47
|
+
}
|
|
48
|
+
export type FilterValue = string | number | boolean | {
|
|
49
|
+
in: (string | number)[];
|
|
50
|
+
};
|
|
51
|
+
export interface ListOptions<F = Record<string, FilterValue>> {
|
|
52
|
+
filter?: F;
|
|
53
|
+
sort?: string;
|
|
54
|
+
limit?: number;
|
|
55
|
+
offset?: number;
|
|
56
|
+
locale?: string;
|
|
57
|
+
fallback?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface ReadOptions {
|
|
60
|
+
locale?: string;
|
|
61
|
+
fallback?: string;
|
|
62
|
+
}
|
|
63
|
+
/** `meta` is returned by the API as is. */
|
|
64
|
+
export interface ListResult<T> {
|
|
65
|
+
data: T[];
|
|
66
|
+
meta: Record<string, unknown>;
|
|
67
|
+
}
|
|
68
|
+
export interface ContentClient {
|
|
69
|
+
list<T = Record<string, unknown>>(apiId: string, o?: ListOptions): Promise<ListResult<T>>;
|
|
70
|
+
/** `null` on 404. */
|
|
71
|
+
get<T = Record<string, unknown>>(apiId: string, documentId: string, o?: ReadOptions): Promise<T | null>;
|
|
72
|
+
bySlug<T = Record<string, unknown>>(apiId: string, slug: string, o?: ReadOptions): Promise<T | null>;
|
|
73
|
+
/** Chunks of 100; order of `ids` preserved, missing ids omitted. */
|
|
74
|
+
byIds<T = Record<string, unknown>>(apiId: string, ids: string[], o?: ReadOptions): Promise<T[]>;
|
|
75
|
+
}
|
|
76
|
+
export interface AssetRef {
|
|
77
|
+
id: string;
|
|
78
|
+
url: string;
|
|
79
|
+
alt?: string;
|
|
80
|
+
width?: number;
|
|
81
|
+
height?: number;
|
|
82
|
+
}
|
|
83
|
+
export interface AssetsClient {
|
|
84
|
+
/** Chunks of 100; unknown ids are omitted. */
|
|
85
|
+
byIds(ids: string[]): Promise<AssetRef[]>;
|
|
86
|
+
}
|
|
87
|
+
export interface ApiIssue {
|
|
88
|
+
path: (string | number)[];
|
|
89
|
+
message: string;
|
|
90
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface Money {
|
|
2
|
+
amount: number;
|
|
3
|
+
currency: string;
|
|
4
|
+
}
|
|
5
|
+
export type IdentifierKind = 'email' | 'phone';
|
|
6
|
+
export declare function formatMoney(m: Money, locale: string): string;
|
|
7
|
+
export declare function formatDate(v: string | Date, locale: string, style?: 'date' | 'datetime'): string;
|
|
8
|
+
/**
|
|
9
|
+
* Source of truth: packages/oauth2/src/customers/identifier.ts and its unit test (packages/oauth2/test/unit/identifier.test.ts);
|
|
10
|
+
* keep this copy in step with them.
|
|
11
|
+
* Same algorithm as the server's `normalizeIdentifier`: email trimmed + lower-cased; phone to E.164 (`region` for local numbers). */
|
|
12
|
+
export declare function normalizeIdentifier(raw: string, region: string): {
|
|
13
|
+
kind: IdentifierKind;
|
|
14
|
+
value: string;
|
|
15
|
+
} | null;
|
|
16
|
+
/** A local absolute path: starts with `/`, no `//`, no `\`, no control characters; anything else `/`. */
|
|
17
|
+
export declare function safeReturnTo(path?: string): string;
|
|
18
|
+
/** `a=1&b=x+y`; undefined / null skipped, arrays joined with `,`, dates as ISO strings. `[ ] ,` stay readable. */
|
|
19
|
+
export declare function buildQuery(params: Record<string, unknown>): string;
|
|
20
|
+
/** The public namespace: utilities are exported only through this object. */
|
|
21
|
+
export declare const utils: {
|
|
22
|
+
formatMoney: typeof formatMoney;
|
|
23
|
+
formatDate: typeof formatDate;
|
|
24
|
+
normalizeIdentifier: typeof normalizeIdentifier;
|
|
25
|
+
safeReturnTo: typeof safeReturnTo;
|
|
26
|
+
buildQuery: typeof buildQuery;
|
|
27
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { parsePhoneNumberFromString } from 'libphonenumber-js';
|
|
2
|
+
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
3
|
+
export function formatMoney(m, locale) {
|
|
4
|
+
return new Intl.NumberFormat(locale, { style: 'currency', currency: m.currency }).format(m.amount);
|
|
5
|
+
}
|
|
6
|
+
export function formatDate(v, locale, style = 'date') {
|
|
7
|
+
const d = v instanceof Date ? v : new Date(v);
|
|
8
|
+
return new Intl.DateTimeFormat(locale, style === 'datetime' ? { dateStyle: 'medium', timeStyle: 'short' } : { dateStyle: 'medium' }).format(d);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Source of truth: packages/oauth2/src/customers/identifier.ts and its unit test (packages/oauth2/test/unit/identifier.test.ts);
|
|
12
|
+
* keep this copy in step with them.
|
|
13
|
+
* Same algorithm as the server's `normalizeIdentifier`: email trimmed + lower-cased; phone to E.164 (`region` for local numbers). */
|
|
14
|
+
export function normalizeIdentifier(raw, region) {
|
|
15
|
+
const s = (raw ?? '').trim();
|
|
16
|
+
if (!s)
|
|
17
|
+
return null;
|
|
18
|
+
if (s.includes('@')) {
|
|
19
|
+
const value = s.toLowerCase();
|
|
20
|
+
return EMAIL_RE.test(value) ? { kind: 'email', value } : null;
|
|
21
|
+
}
|
|
22
|
+
const phone = parsePhoneNumberFromString(s, region);
|
|
23
|
+
if (phone?.isValid())
|
|
24
|
+
return { kind: 'phone', value: phone.number };
|
|
25
|
+
// Country code typed without '+' (e.g. 84912345678).
|
|
26
|
+
if (/^\d{8,15}$/.test(s)) {
|
|
27
|
+
const intl = parsePhoneNumberFromString(`+${s}`);
|
|
28
|
+
if (intl?.isValid())
|
|
29
|
+
return { kind: 'phone', value: intl.number };
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
/** A local absolute path: starts with `/`, no `//`, no `\`, no control characters; anything else `/`. */
|
|
34
|
+
export function safeReturnTo(path) {
|
|
35
|
+
if (typeof path !== 'string' || !path.startsWith('/'))
|
|
36
|
+
return '/';
|
|
37
|
+
if (path.includes('\\') || path.includes('//'))
|
|
38
|
+
return '/';
|
|
39
|
+
// eslint-disable-next-line no-control-regex
|
|
40
|
+
if (/[\u0000-\u001f\u007f]/.test(path))
|
|
41
|
+
return '/';
|
|
42
|
+
return path;
|
|
43
|
+
}
|
|
44
|
+
/** `a=1&b=x+y`; undefined / null skipped, arrays joined with `,`, dates as ISO strings. `[ ] ,` stay readable. */
|
|
45
|
+
export function buildQuery(params) {
|
|
46
|
+
const qs = new URLSearchParams();
|
|
47
|
+
for (const [k, v] of Object.entries(params)) {
|
|
48
|
+
if (v === undefined || v === null)
|
|
49
|
+
continue;
|
|
50
|
+
const one = (x) => (x instanceof Date ? x.toISOString() : String(x));
|
|
51
|
+
qs.append(k, Array.isArray(v) ? v.map(one).join(',') : one(v));
|
|
52
|
+
}
|
|
53
|
+
return qs.toString().replace(/%5B/gi, '[').replace(/%5D/gi, ']').replace(/%2C/gi, ',');
|
|
54
|
+
}
|
|
55
|
+
/** The public namespace: utilities are exported only through this object. */
|
|
56
|
+
export const utils = { formatMoney, formatDate, normalizeIdentifier, safeReturnTo, buildQuery };
|