@nuwah/vertical-sdk 0.0.0-stage → 0.2.0-rc.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.
Files changed (239) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +229 -2
  3. package/bin/nuwah-contract-check-rules.d.mts +41 -0
  4. package/bin/nuwah-contract-check-rules.mjs +333 -0
  5. package/bin/nuwah-contract-check.mjs +64 -0
  6. package/dist/accounting.d.ts +1417 -0
  7. package/dist/accounting.js +274 -0
  8. package/dist/active-org.d.ts +13 -0
  9. package/dist/active-org.js +59 -0
  10. package/dist/actors.d.ts +448 -0
  11. package/dist/actors.js +143 -0
  12. package/dist/ai.d.ts +359 -0
  13. package/dist/ai.js +229 -0
  14. package/dist/analytics.d.ts +37 -0
  15. package/dist/analytics.js +8 -0
  16. package/dist/atlas.d.ts +291 -0
  17. package/dist/atlas.js +78 -0
  18. package/dist/audit.d.ts +193 -0
  19. package/dist/audit.js +26 -0
  20. package/dist/authentication.d.ts +119 -0
  21. package/dist/authentication.js +83 -0
  22. package/dist/awards.d.ts +38 -0
  23. package/dist/awards.js +10 -0
  24. package/dist/blueprint/document.d.ts +178 -0
  25. package/dist/blueprint/document.js +17 -0
  26. package/dist/blueprint/index.d.ts +3 -0
  27. package/dist/blueprint/index.js +5 -0
  28. package/dist/blueprint/manifest.d.ts +105 -0
  29. package/dist/blueprint/manifest.js +11 -0
  30. package/dist/blueprint/validate.d.ts +14 -0
  31. package/dist/blueprint/validate.js +416 -0
  32. package/dist/bookings-directory.d.ts +118 -0
  33. package/dist/bookings-directory.js +289 -0
  34. package/dist/bookings-extra.d.ts +1448 -0
  35. package/dist/bookings-extra.js +582 -0
  36. package/dist/bookings.d.ts +1365 -0
  37. package/dist/bookings.js +305 -0
  38. package/dist/builder-code.d.ts +164 -0
  39. package/dist/builder-code.js +12 -0
  40. package/dist/builder-core-gaps.d.ts +83 -0
  41. package/dist/builder-core-gaps.js +8 -0
  42. package/dist/builder-repos.d.ts +73 -0
  43. package/dist/builder-repos.js +37 -0
  44. package/dist/builder.d.ts +730 -0
  45. package/dist/builder.js +105 -0
  46. package/dist/campaigns.d.ts +105 -0
  47. package/dist/campaigns.js +25 -0
  48. package/dist/catalogs.d.ts +188 -0
  49. package/dist/catalogs.js +36 -0
  50. package/dist/commerce-ai.d.ts +182 -0
  51. package/dist/commerce-ai.js +27 -0
  52. package/dist/connections.d.ts +278 -0
  53. package/dist/connections.js +96 -0
  54. package/dist/content-control.d.ts +121 -0
  55. package/dist/content-control.js +23 -0
  56. package/dist/contributions.d.ts +560 -0
  57. package/dist/contributions.js +140 -0
  58. package/dist/conversation-assist.d.ts +154 -0
  59. package/dist/conversation-assist.js +51 -0
  60. package/dist/conversation-info.d.ts +219 -0
  61. package/dist/conversation-info.js +43 -0
  62. package/dist/crm.d.ts +533 -0
  63. package/dist/crm.js +142 -0
  64. package/dist/dashboards.d.ts +119 -0
  65. package/dist/dashboards.js +22 -0
  66. package/dist/delegations.d.ts +161 -0
  67. package/dist/delegations.js +39 -0
  68. package/dist/docs.d.ts +289 -0
  69. package/dist/docs.js +49 -0
  70. package/dist/documents.d.ts +317 -0
  71. package/dist/documents.js +84 -0
  72. package/dist/drafts.d.ts +132 -0
  73. package/dist/drafts.js +56 -0
  74. package/dist/engagements.d.ts +133 -0
  75. package/dist/engagements.js +15 -0
  76. package/dist/event-stream.d.ts +54 -0
  77. package/dist/event-stream.js +228 -0
  78. package/dist/exchanges.d.ts +447 -0
  79. package/dist/exchanges.js +145 -0
  80. package/dist/exports.d.ts +113 -0
  81. package/dist/exports.js +81 -0
  82. package/dist/feeds.d.ts +228 -0
  83. package/dist/feeds.js +52 -0
  84. package/dist/files.d.ts +56 -0
  85. package/dist/files.js +55 -0
  86. package/dist/finance-insights.d.ts +41 -0
  87. package/dist/finance-insights.js +61 -0
  88. package/dist/fixed-assets.d.ts +155 -0
  89. package/dist/fixed-assets.js +28 -0
  90. package/dist/fulfilment-jobs.d.ts +405 -0
  91. package/dist/fulfilment-jobs.js +76 -0
  92. package/dist/fulfilment.d.ts +205 -0
  93. package/dist/fulfilment.js +39 -0
  94. package/dist/hr.d.ts +350 -0
  95. package/dist/hr.js +94 -0
  96. package/dist/http.d.ts +124 -0
  97. package/dist/http.js +392 -0
  98. package/dist/inbox.d.ts +206 -0
  99. package/dist/inbox.js +36 -0
  100. package/dist/index.d.ts +384 -0
  101. package/dist/index.js +294 -0
  102. package/dist/insights.d.ts +176 -0
  103. package/dist/insights.js +52 -0
  104. package/dist/inventory.d.ts +797 -0
  105. package/dist/inventory.js +120 -0
  106. package/dist/list-query.d.ts +211 -0
  107. package/dist/list-query.js +158 -0
  108. package/dist/listings.d.ts +381 -0
  109. package/dist/listings.js +173 -0
  110. package/dist/location-sharing.d.ts +83 -0
  111. package/dist/location-sharing.js +20 -0
  112. package/dist/marketplace.d.ts +268 -0
  113. package/dist/marketplace.js +59 -0
  114. package/dist/matching.d.ts +103 -0
  115. package/dist/matching.js +22 -0
  116. package/dist/media.d.ts +221 -0
  117. package/dist/media.js +239 -0
  118. package/dist/metrics.d.ts +125 -0
  119. package/dist/metrics.js +45 -0
  120. package/dist/moderation.d.ts +240 -0
  121. package/dist/moderation.js +40 -0
  122. package/dist/money.d.ts +41 -0
  123. package/dist/money.js +79 -0
  124. package/dist/my-data.d.ts +266 -0
  125. package/dist/my-data.js +32 -0
  126. package/dist/names.d.ts +14 -0
  127. package/dist/names.js +17 -0
  128. package/dist/occasions.d.ts +256 -0
  129. package/dist/occasions.js +40 -0
  130. package/dist/onboarding.d.ts +88 -0
  131. package/dist/onboarding.js +38 -0
  132. package/dist/pagination.d.ts +204 -0
  133. package/dist/pagination.js +141 -0
  134. package/dist/party-baseline-attributes.d.ts +245 -0
  135. package/dist/party-baseline-attributes.js +36 -0
  136. package/dist/party.d.ts +401 -0
  137. package/dist/party.js +56 -0
  138. package/dist/patient.d.ts +161 -0
  139. package/dist/patient.js +45 -0
  140. package/dist/payroll.d.ts +378 -0
  141. package/dist/payroll.js +60 -0
  142. package/dist/person-addresses.d.ts +88 -0
  143. package/dist/person-addresses.js +18 -0
  144. package/dist/person-cart.d.ts +250 -0
  145. package/dist/person-cart.js +63 -0
  146. package/dist/person-chat-assist.d.ts +47 -0
  147. package/dist/person-chat-assist.js +13 -0
  148. package/dist/person-data-webhooks.d.ts +72 -0
  149. package/dist/person-data-webhooks.js +86 -0
  150. package/dist/person-data.d.ts +212 -0
  151. package/dist/person-data.js +162 -0
  152. package/dist/person-locations.d.ts +54 -0
  153. package/dist/person-locations.js +6 -0
  154. package/dist/person-messaging.d.ts +405 -0
  155. package/dist/person-messaging.js +112 -0
  156. package/dist/person-notifications.d.ts +319 -0
  157. package/dist/person-notifications.js +164 -0
  158. package/dist/personalisation.d.ts +21 -0
  159. package/dist/personalisation.js +8 -0
  160. package/dist/platform.d.ts +63 -0
  161. package/dist/platform.js +45 -0
  162. package/dist/portfolio.d.ts +163 -0
  163. package/dist/portfolio.js +28 -0
  164. package/dist/pos.d.ts +743 -0
  165. package/dist/pos.js +129 -0
  166. package/dist/procurement.d.ts +664 -0
  167. package/dist/procurement.js +157 -0
  168. package/dist/promotions.d.ts +169 -0
  169. package/dist/promotions.js +39 -0
  170. package/dist/publications.d.ts +583 -0
  171. package/dist/publications.js +164 -0
  172. package/dist/ranking.d.ts +43 -0
  173. package/dist/ranking.js +34 -0
  174. package/dist/ratings.d.ts +293 -0
  175. package/dist/ratings.js +109 -0
  176. package/dist/reactions.d.ts +123 -0
  177. package/dist/reactions.js +41 -0
  178. package/dist/recipient-orders.d.ts +294 -0
  179. package/dist/recipient-orders.js +73 -0
  180. package/dist/relationships.d.ts +18 -0
  181. package/dist/relationships.js +8 -0
  182. package/dist/reporting.d.ts +107 -0
  183. package/dist/reporting.js +56 -0
  184. package/dist/sales.d.ts +270 -0
  185. package/dist/sales.js +66 -0
  186. package/dist/shares.d.ts +105 -0
  187. package/dist/shares.js +27 -0
  188. package/dist/shop.d.ts +993 -0
  189. package/dist/shop.js +215 -0
  190. package/dist/shopping-assistant.d.ts +65 -0
  191. package/dist/shopping-assistant.js +14 -0
  192. package/dist/spaces.d.ts +422 -0
  193. package/dist/spaces.js +118 -0
  194. package/dist/stored-value.d.ts +754 -0
  195. package/dist/stored-value.js +177 -0
  196. package/dist/types.d.ts +83 -0
  197. package/dist/types.js +2 -0
  198. package/dist/vault.d.ts +290 -0
  199. package/dist/vault.js +55 -0
  200. package/dist/vertical-runtime.d.ts +17 -0
  201. package/dist/vertical-runtime.js +8 -0
  202. package/dist/vite/build-manifest-plugin.d.ts +42 -0
  203. package/dist/vite/build-manifest-plugin.js +42 -0
  204. package/dist/vite/first-paint-plugin.d.ts +26 -0
  205. package/dist/vite/first-paint-plugin.js +57 -0
  206. package/dist/wishlists.d.ts +591 -0
  207. package/dist/wishlists.js +188 -0
  208. package/dist/workbench.d.ts +114 -0
  209. package/dist/workbench.js +22 -0
  210. package/dist/workspace.d.ts +190 -0
  211. package/dist/workspace.js +41 -0
  212. package/package.json +52 -4
  213. package/templates/extension-image.Dockerfile +38 -0
  214. package/templates/nuwah-vertical.yml +102 -0
  215. package/templates/vertical-app/.env.example +34 -0
  216. package/templates/vertical-app/README.md +108 -0
  217. package/templates/vertical-app/github/workflows/ci.yml +51 -0
  218. package/templates/vertical-app/gitignore +5 -0
  219. package/templates/vertical-app/index.html +12 -0
  220. package/templates/vertical-app/package.json +28 -0
  221. package/templates/vertical-app/src/App.tsx +64 -0
  222. package/templates/vertical-app/src/blueprint/blueprint.ts +45 -0
  223. package/templates/vertical-app/src/blueprint/screens.ts +15 -0
  224. package/templates/vertical-app/src/env.d.ts +18 -0
  225. package/templates/vertical-app/src/index.css +139 -0
  226. package/templates/vertical-app/src/lib/i18n.ts +5 -0
  227. package/templates/vertical-app/src/lib/iam.ts +19 -0
  228. package/templates/vertical-app/src/lib/operations.ts +93 -0
  229. package/templates/vertical-app/src/lib/router.ts +24 -0
  230. package/templates/vertical-app/src/lib/sdk.ts +21 -0
  231. package/templates/vertical-app/src/lib/theme.ts +18 -0
  232. package/templates/vertical-app/src/lib/words.ts +39 -0
  233. package/templates/vertical-app/src/main.tsx +25 -0
  234. package/templates/vertical-app/src/pages/AppScreens.tsx +71 -0
  235. package/templates/vertical-app/src/pages/AuthCallback.tsx +44 -0
  236. package/templates/vertical-app/src/pages/Home.tsx +36 -0
  237. package/templates/vertical-app/tsconfig.json +24 -0
  238. package/templates/vertical-app/vite.config.ts +23 -0
  239. package/templates/vertical-ci.yml +192 -0
package/dist/media.js ADDED
@@ -0,0 +1,239 @@
1
+ import { newIdempotencyKey, personDomainRequest, } from './actors.js';
2
+
3
+ export class MediaUploadError extends Error {
4
+ reason;
5
+ retryable;
6
+ assetId;
7
+ constructor(message, reason, retryable, assetId = null) {
8
+ super(message);
9
+ this.reason = reason;
10
+ this.retryable = retryable;
11
+ this.assetId = assetId;
12
+ this.name = 'MediaUploadError';
13
+ }
14
+ }
15
+ const BASE = '/api/person/media';
16
+ export function createMediaNamespace(http) {
17
+ const namespace = {
18
+ purposes: (options) => http.get(`${BASE}/purposes`, personDomainRequest(options)),
19
+ usage: (options) => http.get(`${BASE}/usage`, personDomainRequest(options)),
20
+ describe: (ids, options) => http.get(`${BASE}`, personDomainRequest(options, false, { ids })),
21
+ show: (assetId, options) => http.get(`${BASE}/${encodeURIComponent(assetId)}`, personDomainRequest(options)),
22
+ begin: (input, options) => http.post(`${BASE}/uploads`, input, personDomainRequest(options, true)),
23
+ presignParts: (assetId, partNumbers, options) => http.post(`${BASE}/uploads/${encodeURIComponent(assetId)}/parts`, { part_numbers: partNumbers }, personDomainRequest(options)),
24
+ finalise: (assetId, parts, options) => http.post(`${BASE}/uploads/${encodeURIComponent(assetId)}/finalise`, parts && parts.length > 0 ? { parts } : {}, personDomainRequest(options)),
25
+ abort: (assetId, options) => http.delete(`${BASE}/uploads/${encodeURIComponent(assetId)}`, personDomainRequest(options)),
26
+ describeAltText: (assetId, altText, options) => http.patch(`${BASE}/${encodeURIComponent(assetId)}`, { alt_text: altText }, personDomainRequest(options)),
27
+ upload: (file, options) => uploadMedia(namespace, file, options),
28
+ };
29
+ return namespace;
30
+ }
31
+
32
+ const SETTLED = ['ready', 'held', 'rejected', 'failed'];
33
+
34
+ export async function uploadMedia(media, file, options) {
35
+ const attempts = Math.max(1, options.attempts ?? 4);
36
+ const call = { actingAs: options.actingAs ?? null, ...(options.signal ? { signal: options.signal } : {}) };
37
+ const idempotencyKey = options.resume?.idempotencyKey ?? newIdempotencyKey();
38
+ const total = file.size;
39
+ let sent = 0;
40
+ const report = (phase) => {
41
+ options.onProgress?.({ phase, sentBytes: sent, totalBytes: total, fraction: total > 0 ? Math.min(1, sent / total) : 1 });
42
+ };
43
+ report('starting');
44
+ const ticket = (await withRetry(attempts, options.signal, () => media.begin({ purpose: options.purpose, mime_type: file.type || 'application/octet-stream', size_bytes: total, alt_text: options.altText ?? null, file_name: file.name ?? null }, { ...call, idempotencyKey }))).data;
45
+ const assetId = ticket.asset.id;
46
+ const onAbort = () => {
47
+ void media.abort(assetId, { actingAs: call.actingAs ?? null }).catch(() => undefined);
48
+ };
49
+ options.signal?.addEventListener('abort', onAbort, { once: true });
50
+ try {
51
+ let parts = [];
52
+ if (ticket.asset.status === 'awaiting_upload') {
53
+ report('sending');
54
+ if (ticket.mode === 'single') {
55
+ if (!ticket.upload_url)
56
+ throw new MediaUploadError('The server gave no upload URL.', null, true, assetId);
57
+ const uploadUrl = ticket.upload_url;
58
+ await withRetry(attempts, options.signal, () => putBytes(uploadUrl, file, ticket.upload_headers, options.signal, (loaded) => {
59
+ sent = loaded;
60
+ report('sending');
61
+ }));
62
+ sent = total;
63
+ }
64
+ else {
65
+ parts = await sendParts(media, file, ticket, idempotencyKey, call, options, attempts, (delta) => {
66
+ sent = Math.min(total, sent + delta);
67
+ report('sending');
68
+ });
69
+ }
70
+ }
71
+ report('finishing');
72
+ let asset = (await withRetry(attempts, options.signal, () => media.finalise(assetId, parts, call))).data;
73
+ if (options.waitUntilSettled) {
74
+ report('processing');
75
+ const interval = Math.max(250, options.pollIntervalMs ?? 1500);
76
+ while (!SETTLED.includes(asset.status)) {
77
+ await delay(interval, options.signal);
78
+ asset = (await media.show(assetId, call)).data;
79
+ }
80
+ if (asset.status === 'rejected' || asset.status === 'failed') {
81
+ throw new MediaUploadError(`The file was ${asset.status}.`, asset.rejection_reason, asset.status === 'failed', assetId);
82
+ }
83
+ }
84
+ report('done');
85
+ return asset;
86
+ }
87
+ finally {
88
+ options.signal?.removeEventListener('abort', onAbort);
89
+ }
90
+ }
91
+ async function sendParts(media, file, ticket, idempotencyKey, call, options, attempts, onSent) {
92
+ const assetId = ticket.asset.id;
93
+ const partSize = ticket.part_size_bytes ?? 0;
94
+ const partCount = ticket.part_count ?? 0;
95
+ if (partSize <= 0 || partCount <= 0)
96
+ throw new MediaUploadError('The server gave no part layout.', null, false, assetId);
97
+ const resumed = options.resume?.assetId === assetId ? options.resume.completedParts : [];
98
+ const done = new Map(resumed.map((part) => [part.part_number, part.etag]));
99
+ for (const number of done.keys())
100
+ onSent(Math.min(partSize, file.size - (number - 1) * partSize));
101
+ const pending = [];
102
+ for (let number = 1; number <= partCount; number++)
103
+ if (!done.has(number))
104
+ pending.push(number);
105
+ const remember = () => {
106
+ options.onResumeState?.({
107
+ assetId,
108
+ idempotencyKey,
109
+ partSizeBytes: partSize,
110
+ completedParts: [...done].map(([part_number, etag]) => ({ part_number, etag })),
111
+ });
112
+ };
113
+ remember();
114
+
115
+ const urls = new Map();
116
+ const urlFor = async (number, refresh) => {
117
+ if (!refresh && urls.has(number))
118
+ return urls.get(number);
119
+ const batch = pending.filter((candidate) => candidate >= number && !done.has(candidate)).slice(0, 20);
120
+ const answer = (await withRetry(attempts, options.signal, () => media.presignParts(assetId, batch.length > 0 ? batch : [number], call))).data;
121
+ for (const part of answer.parts)
122
+ urls.set(part.part_number, part.upload_url);
123
+ return urls.get(number);
124
+ };
125
+ let next = 0;
126
+ const worker = async () => {
127
+ while (next < pending.length) {
128
+ const number = pending[next++];
129
+ const start = (number - 1) * partSize;
130
+ const chunk = file.slice(start, Math.min(file.size, start + partSize));
131
+ let loadedHere = 0;
132
+ const etag = await withRetry(attempts, options.signal, async (attempt) => {
133
+ const url = await urlFor(number, attempt > 1);
134
+ onSent(-loadedHere);
135
+ loadedHere = 0;
136
+ return putBytes(url, chunk, {}, options.signal, (loaded) => {
137
+ onSent(loaded - loadedHere);
138
+ loadedHere = loaded;
139
+ });
140
+ });
141
+ onSent(chunk.size - loadedHere);
142
+ if (!etag)
143
+ throw new MediaUploadError('Storage exposed no ETag; the bucket CORS rule must expose it.', null, false, assetId);
144
+ done.set(number, etag);
145
+ remember();
146
+ }
147
+ };
148
+ const concurrency = Math.max(1, Math.min(options.concurrency ?? 3, pending.length || 1));
149
+ await Promise.all(Array.from({ length: concurrency }, () => worker()));
150
+ return [...done].map(([part_number, etag]) => ({ part_number, etag })).sort((left, right) => left.part_number - right.part_number);
151
+ }
152
+
153
+ export function putBytes(url, body, headers, signal, onProgress) {
154
+ if (signal?.aborted)
155
+ return Promise.reject(abortError());
156
+ const XhrConstructor = globalThis.XMLHttpRequest;
157
+ if (!XhrConstructor) {
158
+ return fetch(url, { method: 'PUT', body, headers, ...(signal ? { signal } : {}) }).then((response) => {
159
+ if (!response.ok)
160
+ throw new MediaUploadError(`Storage answered HTTP ${response.status}.`, null, response.status >= 500 || response.status === 429);
161
+ onProgress(body.size);
162
+ return response.headers.get('ETag');
163
+ });
164
+ }
165
+ return new Promise((resolve, reject) => {
166
+ const request = new XhrConstructor();
167
+ request.open('PUT', url);
168
+ for (const [name, value] of Object.entries(headers))
169
+ request.setRequestHeader(name, value);
170
+ request.upload.onprogress = (progress) => onProgress(progress.loaded);
171
+ request.onload = () => {
172
+ if (request.status >= 200 && request.status < 300) {
173
+ resolve(request.getResponseHeader('ETag'));
174
+ }
175
+ else {
176
+
177
+ reject(new MediaUploadError(`Storage answered HTTP ${request.status}.`, null, request.status >= 500 || request.status === 429 || request.status === 403));
178
+ }
179
+ };
180
+ request.onerror = () => reject(new MediaUploadError('The connection to storage dropped.', null, true));
181
+ request.ontimeout = () => reject(new MediaUploadError('Storage did not answer in time.', null, true));
182
+ const abort = () => request.abort();
183
+ request.onabort = () => reject(abortError());
184
+ signal?.addEventListener('abort', abort, { once: true });
185
+ request.onloadend = () => signal?.removeEventListener('abort', abort);
186
+ request.send(body);
187
+ });
188
+ }
189
+
190
+ async function withRetry(attempts, signal, step) {
191
+ let lastError;
192
+ for (let attempt = 1; attempt <= attempts; attempt++) {
193
+ try {
194
+ return await step(attempt);
195
+ }
196
+ catch (error) {
197
+ lastError = error;
198
+ if (signal?.aborted || !isRetryable(error) || attempt === attempts)
199
+ break;
200
+ await delay(Math.min(15_000, 500 * 2 ** (attempt - 1)) * (0.75 + Math.random() * 0.5), signal);
201
+ }
202
+ }
203
+ throw toUploadError(lastError);
204
+ }
205
+ function isRetryable(error) {
206
+ if (error instanceof MediaUploadError)
207
+ return error.retryable;
208
+ const status = error?.status;
209
+ if (typeof status === 'number')
210
+ return status >= 500 || status === 429 || status === 408;
211
+ return !(error instanceof DOMException && error.name === 'AbortError');
212
+ }
213
+ function toUploadError(error) {
214
+ if (error instanceof MediaUploadError || (error instanceof DOMException && error.name === 'AbortError'))
215
+ return error;
216
+ const body = error?.body;
217
+ const reason = typeof body?.reason === 'string' ? body.reason : null;
218
+ if (reason !== null)
219
+ return new MediaUploadError(typeof body?.message === 'string' ? body.message : reason, reason, false);
220
+ return error;
221
+ }
222
+ function delay(milliseconds, signal) {
223
+ return new Promise((resolve, reject) => {
224
+ if (signal?.aborted)
225
+ return reject(abortError());
226
+ const timer = setTimeout(() => {
227
+ signal?.removeEventListener('abort', onAbort);
228
+ resolve();
229
+ }, milliseconds);
230
+ const onAbort = () => {
231
+ clearTimeout(timer);
232
+ reject(abortError());
233
+ };
234
+ signal?.addEventListener('abort', onAbort, { once: true });
235
+ });
236
+ }
237
+ function abortError() {
238
+ return new DOMException('The upload was cancelled.', 'AbortError');
239
+ }
@@ -0,0 +1,125 @@
1
+ import type { Http, NuwahClientConfig } from './http.js';
2
+ export type MetricUnit = 'count' | 'money' | 'percentage' | 'hours' | 'tokens';
3
+ export type MetricAggregation = 'sum' | 'ratio' | 'latest' | 'distinct';
4
+ export type MetricGrain = 'day' | 'week' | 'month';
5
+ export type MetricScopeKind = 'organisation' | 'vertical' | 'platform';
6
+ export type MetricBilingualText = {
7
+ en: string;
8
+ ar: string;
9
+ };
10
+ /** One metric in the catalogue. */
11
+ export interface MetricDefinition {
12
+ /** Stable key, `<owner>.<thing>`, e.g. `shop.sales`. */
13
+ key: string;
14
+ /** The reader's words (neutral default renamed by vertical and organisation vocabulary). */
15
+ label: MetricBilingualText;
16
+ description: MetricBilingualText;
17
+ unit: MetricUnit;
18
+ /** `distinct` = distinct people per bucket; the period figure is the average per bucket. */
19
+ aggregation: MetricAggregation;
20
+ source: 'central' | 'tenant' | 'snapshot';
21
+ grains: MetricGrain[];
22
+ dimensions: Array<{
23
+ key: string;
24
+ label: MetricBilingualText;
25
+ values: Array<{
26
+ value: string;
27
+ label: MetricBilingualText;
28
+ }>;
29
+ }>;
30
+ scopes: MetricScopeKind[];
31
+ /** Card group: `sales`, `customers`, `money`, `people`, `ai`, `engagement`. */
32
+ group: string;
33
+ personal: boolean;
34
+ vocabulary_key: string;
35
+ }
36
+ /** A figure: a decimal string in the metric's unit, or null (suppressed or undefined). */
37
+ export interface MetricFigure {
38
+ value: string | null;
39
+ suppressed: boolean;
40
+ }
41
+ export interface MetricPoint extends MetricFigure {
42
+ /** The local date the bucket starts (`YYYY-MM-DD`; a week starts Monday). */
43
+ bucket: string;
44
+ }
45
+ /** One metric answered for a period. */
46
+ export interface MetricSeries {
47
+ metric: MetricDefinition;
48
+ label: MetricBilingualText;
49
+ scope: MetricScopeKind;
50
+ vertical_key: string | null;
51
+ period: {
52
+ from: string;
53
+ to: string;
54
+ };
55
+ previous_period: {
56
+ from: string;
57
+ to: string;
58
+ };
59
+ grain: MetricGrain;
60
+ /** ISO 4217 for a money metric (JOD has 3 decimals), else null. */
61
+ currency_code: string | null;
62
+ total: MetricFigure;
63
+ previous_total: MetricFigure;
64
+ /** Percentage change, two decimals (`"-12.50"`); null when unknown or the previous is zero. */
65
+ change: string | null;
66
+ points: MetricPoint[];
67
+ previous_points: MetricPoint[];
68
+ dimension: string | null;
69
+ /** Largest first, at most 20. */
70
+ breakdown: Array<{
71
+ value: string;
72
+ label: MetricBilingualText | null;
73
+ figure: MetricFigure;
74
+ }>;
75
+ /** The minimum group size in force (0 = none). */
76
+ minimum_group_size: number;
77
+ /** When the nightly rollup behind it was written, or null when read live. */
78
+ refreshed_at: string | null;
79
+ }
80
+ /** The question every read asks. All optional: default the last 30 days at the metric's first grain. */
81
+ export interface MetricReadParams {
82
+ /** First local day, `YYYY-MM-DD`. */
83
+ from?: string;
84
+ /** Last local day, `YYYY-MM-DD` (default today). At most 400 days. */
85
+ to?: string;
86
+ grain?: MetricGrain;
87
+ /** A declared dimension key to break down by. */
88
+ dimension?: string;
89
+ }
90
+ export interface MetricBoardParams extends Omit<MetricReadParams, 'dimension'> {
91
+ /** Up to 24 metric keys (default: every metric the caller may read). Unreadable keys are left out. */
92
+ metrics?: string[];
93
+ }
94
+ export interface MetricCsvDownload {
95
+ blob: Blob;
96
+ filename: string;
97
+ }
98
+ export declare function createMetricsNamespace(http: Http, config: NuwahClientConfig): {
99
+ /**
100
+ * GET /api/metrics — the metrics this business can see, labels in its own words.
101
+ *
102
+ * @example
103
+ * const metrics = await sdk.metrics.catalogue();
104
+ * const sales = metrics.filter((metric) => metric.group === 'sales');
105
+ */
106
+ catalogue: () => Promise<MetricDefinition[]>;
107
+ /**
108
+ * GET /api/metrics/board — several metrics for one period (a dashboard's tiles), batched
109
+ * per owning module on the server.
110
+ *
111
+ * @example
112
+ * const tiles = await sdk.metrics.board({ metrics: ['shop.sales', 'shop.orders'], grain: 'day' });
113
+ */
114
+ board: (params?: MetricBoardParams) => Promise<MetricSeries[]>;
115
+ read: (metricKey: string, params?: MetricReadParams) => Promise<MetricSeries>;
116
+ /**
117
+ * GET /api/metrics/{metric}/export — the same read as a CSV (headers follow the caller's
118
+ * language). Returns `{ blob, filename }` for the caller to save.
119
+ *
120
+ * @example
121
+ * const { blob, filename } = await sdk.metrics.exportCsv('shop.sales', { grain: 'month' });
122
+ */
123
+ exportCsv: (metricKey: string, params?: MetricReadParams) => Promise<MetricCsvDownload>;
124
+ };
125
+ export type MetricsNamespace = ReturnType<typeof createMetricsNamespace>;
@@ -0,0 +1,45 @@
1
+ function toQuery(params) {
2
+ const query = {};
3
+ if (!params)
4
+ return query;
5
+ for (const [key, value] of Object.entries(params)) {
6
+ if (value !== undefined && value !== null && value !== '')
7
+ query[key] = value;
8
+ }
9
+ return query;
10
+ }
11
+ export function createMetricsNamespace(http, config) {
12
+ const baseUrl = config.baseUrl.replace(/\/$/, '');
13
+ return {
14
+
15
+ catalogue: () => http.get('/api/metrics').then((response) => response.data),
16
+
17
+ board: (params) => http.get('/api/metrics/board', { params: toQuery(params) }).then((response) => response.data),
18
+
19
+ read: (metricKey, params) => http
20
+ .get(`/api/metrics/${encodeURIComponent(metricKey)}`, { params: toQuery(params) })
21
+ .then((response) => response.data),
22
+
23
+ exportCsv: async (metricKey, params) => {
24
+ const fetchImplementation = config.fetch ?? globalThis.fetch;
25
+ const token = await config.getToken();
26
+ const search = new URLSearchParams();
27
+ for (const [key, value] of Object.entries(toQuery(params)))
28
+ search.append(key, String(value));
29
+ const queryString = search.toString();
30
+ const response = await fetchImplementation(`${baseUrl}/api/metrics/${encodeURIComponent(metricKey)}/export${queryString ? `?${queryString}` : ''}`, {
31
+ method: 'GET',
32
+ headers: {
33
+ Accept: 'text/csv',
34
+ 'X-Requested-With': 'XMLHttpRequest',
35
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
36
+ },
37
+ });
38
+ if (!response.ok)
39
+ throw new Error(`Metric export failed with status ${response.status}`);
40
+ const disposition = response.headers.get('content-disposition') ?? '';
41
+ const match = disposition.match(/filename\*?=(?:UTF-8'')?"?([^;"]+)"?/i);
42
+ return { blob: await response.blob(), filename: match ? decodeURIComponent(match[1]) : `${metricKey}.csv` };
43
+ },
44
+ };
45
+ }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Moderation — the unified trust-and-safety seam: `/api/person/reports` and `/api/person/moderation/*`.
3
+ *
4
+ * Any person reports anything a module registered as moderatable (`reasons(subjectType)` lists the
5
+ * reasons that type accepts, in both languages). Reports become CASES that platform operators — or,
6
+ * where the vertical's policy allows, the moderators of the party HOSTING the content — decide.
7
+ * An author sees the decision against their content and may appeal it ONCE, inside the window the
8
+ * policy sets; a different operator reviews the appeal.
9
+ *
10
+ * What a client must never do:
11
+ * - tell a reporter anything about other reports: the receipt is only theirs (a repeat report
12
+ * answers 200 with the FIRST receipt and `duplicate: true` instead of 201);
13
+ * - show an author who reported them: no endpoint here can, and none should be built around it.
14
+ * A subject the reporter cannot see answers 422 `moderation_subject_unavailable` — missing, hidden
15
+ * and blocked alike. Another person's report, decision or appeal answers 404.
16
+ *
17
+ * The HOST queue (`queue`, `getCase`, `decide`, `escalate`) is for a person moderating for a host
18
+ * (`actor:<uuid>` with the `moderation.decide` capability, `space:<uuid>` as a space moderator):
19
+ * reporters appear as `reporter_1, reporter_2…`, legal cases never appear, appeals go to operators.
20
+ * Operators work in the Nuwah console, not through this SDK.
21
+ *
22
+ * Filing and appealing are rate limited per person (20 an hour, 100 a day) — on 429, back off.
23
+ */
24
+ import type { Http } from './http.js';
25
+ import { type BilingualText, type PersonDomainCallOptions, type PersonDomainCursorPage, type PersonDomainEnvelope } from './actors.js';
26
+ import { type ListPage, type ListQueryState } from './list-query.js';
27
+ /** The platform's report taxonomy; a type may accept a subset (see `reasons`). */
28
+ export type ModerationReasonKey = 'spam' | 'scam_or_fraud' | 'harassment' | 'hate' | 'violence_or_threat' | 'sexual_content' | 'child_safety' | 'self_harm' | 'misinformation' | 'intellectual_property' | 'impersonation' | 'illegal_goods_or_services' | 'privacy_violation' | 'other';
29
+ export type ModerationSeverity = 'low' | 'normal' | 'high' | 'critical';
30
+ export type ModerationReportStatus = 'open' | 'actioned' | 'dismissed';
31
+ export type ModerationCaseStatus = 'open' | 'assigned' | 'decided' | 'appealed' | 'closed';
32
+ export type ModerationAppealStatus = 'requested' | 'upheld' | 'overturned';
33
+ export type ModerationEnforcement = 'pending' | 'applied' | 'already_applied' | 'subject_gone' | 'deferred' | 'failed' | 'not_required';
34
+ /** Reasons that put a case on the legal path at once — say so in the report dialog. */
35
+ export declare const MODERATION_LEGAL_REASONS: readonly ModerationReasonKey[];
36
+ /** Free-text limits the server enforces. */
37
+ export declare const MODERATION_NOTES_MAXIMUM = 1000;
38
+ export declare const MODERATION_STATEMENT_MAXIMUM = 2000;
39
+ export interface ModerationReasonOption {
40
+ key: ModerationReasonKey;
41
+ label: BilingualText;
42
+ severity: ModerationSeverity;
43
+ }
44
+ /** What a type accepts — fetch once per subject type and cache. */
45
+ export interface ModerationReportableType {
46
+ subject_type: string;
47
+ label: BilingualText;
48
+ reasons: ModerationReasonOption[];
49
+ }
50
+ export interface ModerationReportInput {
51
+ subject_type: string;
52
+ subject_id: string;
53
+ reason_key: ModerationReasonKey;
54
+ /** At most {@link MODERATION_NOTES_MAXIMUM} characters; only operators read it. */
55
+ notes?: string | null;
56
+ }
57
+ export interface ModerationReportReceipt {
58
+ id: string;
59
+ reason_key: ModerationReasonKey;
60
+ status: ModerationReportStatus;
61
+ /** True when this person had already reported the subject; the receipt is the first one. */
62
+ duplicate: boolean;
63
+ received_at: string;
64
+ }
65
+ /** One of the person's own reports. */
66
+ export interface ModerationReport {
67
+ id: string;
68
+ subject_type: string;
69
+ subject_id: string;
70
+ reason_key: ModerationReasonKey;
71
+ status: ModerationReportStatus;
72
+ status_label: BilingualText;
73
+ created_at: string;
74
+ resolved_at: string | null;
75
+ }
76
+ export interface ModerationAppeal {
77
+ id: string;
78
+ decision_id: string;
79
+ status: ModerationAppealStatus;
80
+ status_label: BilingualText;
81
+ created_at: string;
82
+ decided_at: string | null;
83
+ }
84
+ /** A decision as its AUTHOR sees it — never who reported, never who decided. */
85
+ export interface ModerationAuthorDecision {
86
+ id: string;
87
+ subject_type: string;
88
+ subject_id: string;
89
+ subject_label: BilingualText | null;
90
+ action_key: string;
91
+ action_label: BilingualText | null;
92
+ reason_code: string;
93
+ reason_label: BilingualText | null;
94
+ adverse: boolean;
95
+ decided_at: string | null;
96
+ appealable: boolean;
97
+ appeal_closes_at: string | null;
98
+ appeal: (Omit<ModerationAppeal, 'decision_id'>) | null;
99
+ }
100
+ /** One case in a queue. */
101
+ export interface ModerationCaseSummary {
102
+ id: string;
103
+ subject_type: string;
104
+ subject_id: string;
105
+ status: ModerationCaseStatus;
106
+ status_label: BilingualText;
107
+ severity: ModerationSeverity;
108
+ severity_label: BilingualText;
109
+ escalation: 'none' | 'legal';
110
+ legal_hold: boolean;
111
+ priority_score: number;
112
+ report_count: number;
113
+ trusted_report_count: number;
114
+ coordinated_reporting_suspected: boolean;
115
+ automatically_hidden: boolean;
116
+ hosting_party: string | null;
117
+ assigned_to: string | null;
118
+ last_action_key: string | null;
119
+ /** Send back as `expected_version` when deciding. */
120
+ version: number;
121
+ due_at: string | null;
122
+ first_reported_at: string | null;
123
+ last_reported_at: string | null;
124
+ decided_at: string | null;
125
+ appeal_closes_at: string | null;
126
+ closed_at: string | null;
127
+ }
128
+ /** A redacted preview of the reported subject — never the record itself, never media URLs. */
129
+ export interface ModeratedSubjectPreview {
130
+ subject_type: string;
131
+ subject_id: string;
132
+ owner: string | null;
133
+ excerpt: string | null;
134
+ media_count: number;
135
+ state: string;
136
+ hosting_party: string | null;
137
+ kind_label: BilingualText | null;
138
+ deep_link_path: string | null;
139
+ created_at: string | null;
140
+ }
141
+ export interface ModerationActionOption {
142
+ key: string;
143
+ label: BilingualText;
144
+ adverse: boolean;
145
+ touches_subject: boolean;
146
+ strike_points: number;
147
+ reversed_by: string | null;
148
+ delegable: boolean;
149
+ automatic: boolean;
150
+ }
151
+ export interface ModerationCaseReport {
152
+ id: string;
153
+ /** `reporter_1…` for a host; a stable pseudonym for an operator. */
154
+ reporter: string;
155
+ reason_key: ModerationReasonKey;
156
+ /** Null for a host — free text is where a reporter names themselves. */
157
+ notes: string | null;
158
+ trust_weight: number | null;
159
+ status: ModerationReportStatus;
160
+ source: string;
161
+ created_at: string | null;
162
+ }
163
+ export interface ModerationCaseDecision {
164
+ id: string;
165
+ round: 'initial' | 'automatic' | 'appeal';
166
+ action_key: string;
167
+ reason_code: string;
168
+ adverse: boolean;
169
+ strike_points: number;
170
+ note: string | null;
171
+ decider_kind: 'operator' | 'delegate' | 'system';
172
+ decider_id: string | null;
173
+ host: string | null;
174
+ supersedes_decision_id: string | null;
175
+ enforcement: ModerationEnforcement;
176
+ enforcement_attempts: number;
177
+ enforcement_detail: string | null;
178
+ enforced_at: string | null;
179
+ created_at: string | null;
180
+ }
181
+ export interface ModerationCaseHistoryEntry {
182
+ id: string;
183
+ kind: string;
184
+ actor_kind: 'person' | 'operator' | 'delegate' | 'system';
185
+ actor_id: string | null;
186
+ detail: Record<string, unknown>;
187
+ occurred_at: string | null;
188
+ }
189
+ export interface ModerationCaseDetail extends ModerationCaseSummary {
190
+ owner: string | null;
191
+ vertical_key: string | null;
192
+ policies: Record<string, string>;
193
+ subject: ModeratedSubjectPreview | null;
194
+ type: {
195
+ subject_type: string;
196
+ label: BilingualText;
197
+ delegation: 'none' | 'hosting_party';
198
+ actions: ModerationActionOption[];
199
+ } | null;
200
+ reports: ModerationCaseReport[];
201
+ decisions: ModerationCaseDecision[];
202
+ /** Operators only; empty for a host. */
203
+ appeals: unknown[];
204
+ history: ModerationCaseHistoryEntry[];
205
+ }
206
+ /** Reason codes a decision may carry: a reason key, or `no_violation` (dismiss only). */
207
+ export type ModerationDecisionReasonCode = ModerationReasonKey | 'no_violation';
208
+ export interface ModerationDecisionInput {
209
+ action_key: string;
210
+ reason_code: ModerationDecisionReasonCode;
211
+ note?: string | null;
212
+ expected_version?: number;
213
+ }
214
+ export declare function createModerationNamespace(http: Http): {
215
+ /** GET /moderation/reasons — the reasons a subject type accepts, bilingual, with severity. */
216
+ reasons: (subjectType: string, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationReportableType>>;
217
+ /** POST /reports — always filed as the PERSON (never as a profile). 201 new, 200 repeat. */
218
+ report: (input: ModerationReportInput, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationReportReceipt>>;
219
+ /** GET /reports — the person's own reports, newest first. */
220
+ myReports: (cursor?: string | null, limit?: number, options?: PersonDomainCallOptions) => Promise<PersonDomainCursorPage<ModerationReport>>;
221
+ /** GET /reports/{report} */
222
+ getReport: (reportId: string, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationReport>>;
223
+ /** GET /moderation/decisions/{decision} — a decision against the person's (or their profile's) content. */
224
+ decision: (decisionId: string, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationAuthorDecision>>;
225
+ /** POST /moderation/decisions/{decision}/appeals — once per decision, inside the window. */
226
+ appeal: (decisionId: string, statement: string | null, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationAppeal>>;
227
+ /** GET /moderation/appeals/{appeal} */
228
+ getAppeal: (appealId: string, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationAppeal>>;
229
+ /** GET /moderation/queue?host= — a host's cases (ListQuery `moderation.cases`; `describe` once). */
230
+ queue: (host: string, query?: ListQueryState, options?: PersonDomainCallOptions) => Promise<ListPage<ModerationCaseSummary>>;
231
+ /** GET /moderation/cases/{case}?host= */
232
+ getCase: (host: string, caseId: string, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationCaseDetail>>;
233
+ /** POST /moderation/cases/{case}/decisions — only the actions the frozen policy lets a host take. */
234
+ decide: (host: string, caseId: string, input: ModerationDecisionInput, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationCaseDetail> & {
235
+ replayed: boolean;
236
+ }>;
237
+ /** POST /moderation/cases/{case}/escalations — hand to the platform's legal path; never undone. */
238
+ escalate: (host: string, caseId: string, reasonKey: ModerationReasonKey, options?: PersonDomainCallOptions) => Promise<PersonDomainEnvelope<ModerationCaseSummary>>;
239
+ };
240
+ export type ModerationNamespace = ReturnType<typeof createModerationNamespace>;