@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.
- package/LICENSE +17 -0
- package/README.md +229 -2
- package/bin/nuwah-contract-check-rules.d.mts +41 -0
- package/bin/nuwah-contract-check-rules.mjs +333 -0
- package/bin/nuwah-contract-check.mjs +64 -0
- package/dist/accounting.d.ts +1417 -0
- package/dist/accounting.js +274 -0
- package/dist/active-org.d.ts +13 -0
- package/dist/active-org.js +59 -0
- package/dist/actors.d.ts +448 -0
- package/dist/actors.js +143 -0
- package/dist/ai.d.ts +359 -0
- package/dist/ai.js +229 -0
- package/dist/analytics.d.ts +37 -0
- package/dist/analytics.js +8 -0
- package/dist/atlas.d.ts +291 -0
- package/dist/atlas.js +78 -0
- package/dist/audit.d.ts +193 -0
- package/dist/audit.js +26 -0
- package/dist/authentication.d.ts +119 -0
- package/dist/authentication.js +83 -0
- package/dist/awards.d.ts +38 -0
- package/dist/awards.js +10 -0
- package/dist/blueprint/document.d.ts +178 -0
- package/dist/blueprint/document.js +17 -0
- package/dist/blueprint/index.d.ts +3 -0
- package/dist/blueprint/index.js +5 -0
- package/dist/blueprint/manifest.d.ts +105 -0
- package/dist/blueprint/manifest.js +11 -0
- package/dist/blueprint/validate.d.ts +14 -0
- package/dist/blueprint/validate.js +416 -0
- package/dist/bookings-directory.d.ts +118 -0
- package/dist/bookings-directory.js +289 -0
- package/dist/bookings-extra.d.ts +1448 -0
- package/dist/bookings-extra.js +582 -0
- package/dist/bookings.d.ts +1365 -0
- package/dist/bookings.js +305 -0
- package/dist/builder-code.d.ts +164 -0
- package/dist/builder-code.js +12 -0
- package/dist/builder-core-gaps.d.ts +83 -0
- package/dist/builder-core-gaps.js +8 -0
- package/dist/builder-repos.d.ts +73 -0
- package/dist/builder-repos.js +37 -0
- package/dist/builder.d.ts +730 -0
- package/dist/builder.js +105 -0
- package/dist/campaigns.d.ts +105 -0
- package/dist/campaigns.js +25 -0
- package/dist/catalogs.d.ts +188 -0
- package/dist/catalogs.js +36 -0
- package/dist/commerce-ai.d.ts +182 -0
- package/dist/commerce-ai.js +27 -0
- package/dist/connections.d.ts +278 -0
- package/dist/connections.js +96 -0
- package/dist/content-control.d.ts +121 -0
- package/dist/content-control.js +23 -0
- package/dist/contributions.d.ts +560 -0
- package/dist/contributions.js +140 -0
- package/dist/conversation-assist.d.ts +154 -0
- package/dist/conversation-assist.js +51 -0
- package/dist/conversation-info.d.ts +219 -0
- package/dist/conversation-info.js +43 -0
- package/dist/crm.d.ts +533 -0
- package/dist/crm.js +142 -0
- package/dist/dashboards.d.ts +119 -0
- package/dist/dashboards.js +22 -0
- package/dist/delegations.d.ts +161 -0
- package/dist/delegations.js +39 -0
- package/dist/docs.d.ts +289 -0
- package/dist/docs.js +49 -0
- package/dist/documents.d.ts +317 -0
- package/dist/documents.js +84 -0
- package/dist/drafts.d.ts +132 -0
- package/dist/drafts.js +56 -0
- package/dist/engagements.d.ts +133 -0
- package/dist/engagements.js +15 -0
- package/dist/event-stream.d.ts +54 -0
- package/dist/event-stream.js +228 -0
- package/dist/exchanges.d.ts +447 -0
- package/dist/exchanges.js +145 -0
- package/dist/exports.d.ts +113 -0
- package/dist/exports.js +81 -0
- package/dist/feeds.d.ts +228 -0
- package/dist/feeds.js +52 -0
- package/dist/files.d.ts +56 -0
- package/dist/files.js +55 -0
- package/dist/finance-insights.d.ts +41 -0
- package/dist/finance-insights.js +61 -0
- package/dist/fixed-assets.d.ts +155 -0
- package/dist/fixed-assets.js +28 -0
- package/dist/fulfilment-jobs.d.ts +405 -0
- package/dist/fulfilment-jobs.js +76 -0
- package/dist/fulfilment.d.ts +205 -0
- package/dist/fulfilment.js +39 -0
- package/dist/hr.d.ts +350 -0
- package/dist/hr.js +94 -0
- package/dist/http.d.ts +124 -0
- package/dist/http.js +392 -0
- package/dist/inbox.d.ts +206 -0
- package/dist/inbox.js +36 -0
- package/dist/index.d.ts +384 -0
- package/dist/index.js +294 -0
- package/dist/insights.d.ts +176 -0
- package/dist/insights.js +52 -0
- package/dist/inventory.d.ts +797 -0
- package/dist/inventory.js +120 -0
- package/dist/list-query.d.ts +211 -0
- package/dist/list-query.js +158 -0
- package/dist/listings.d.ts +381 -0
- package/dist/listings.js +173 -0
- package/dist/location-sharing.d.ts +83 -0
- package/dist/location-sharing.js +20 -0
- package/dist/marketplace.d.ts +268 -0
- package/dist/marketplace.js +59 -0
- package/dist/matching.d.ts +103 -0
- package/dist/matching.js +22 -0
- package/dist/media.d.ts +221 -0
- package/dist/media.js +239 -0
- package/dist/metrics.d.ts +125 -0
- package/dist/metrics.js +45 -0
- package/dist/moderation.d.ts +240 -0
- package/dist/moderation.js +40 -0
- package/dist/money.d.ts +41 -0
- package/dist/money.js +79 -0
- package/dist/my-data.d.ts +266 -0
- package/dist/my-data.js +32 -0
- package/dist/names.d.ts +14 -0
- package/dist/names.js +17 -0
- package/dist/occasions.d.ts +256 -0
- package/dist/occasions.js +40 -0
- package/dist/onboarding.d.ts +88 -0
- package/dist/onboarding.js +38 -0
- package/dist/pagination.d.ts +204 -0
- package/dist/pagination.js +141 -0
- package/dist/party-baseline-attributes.d.ts +245 -0
- package/dist/party-baseline-attributes.js +36 -0
- package/dist/party.d.ts +401 -0
- package/dist/party.js +56 -0
- package/dist/patient.d.ts +161 -0
- package/dist/patient.js +45 -0
- package/dist/payroll.d.ts +378 -0
- package/dist/payroll.js +60 -0
- package/dist/person-addresses.d.ts +88 -0
- package/dist/person-addresses.js +18 -0
- package/dist/person-cart.d.ts +250 -0
- package/dist/person-cart.js +63 -0
- package/dist/person-chat-assist.d.ts +47 -0
- package/dist/person-chat-assist.js +13 -0
- package/dist/person-data-webhooks.d.ts +72 -0
- package/dist/person-data-webhooks.js +86 -0
- package/dist/person-data.d.ts +212 -0
- package/dist/person-data.js +162 -0
- package/dist/person-locations.d.ts +54 -0
- package/dist/person-locations.js +6 -0
- package/dist/person-messaging.d.ts +405 -0
- package/dist/person-messaging.js +112 -0
- package/dist/person-notifications.d.ts +319 -0
- package/dist/person-notifications.js +164 -0
- package/dist/personalisation.d.ts +21 -0
- package/dist/personalisation.js +8 -0
- package/dist/platform.d.ts +63 -0
- package/dist/platform.js +45 -0
- package/dist/portfolio.d.ts +163 -0
- package/dist/portfolio.js +28 -0
- package/dist/pos.d.ts +743 -0
- package/dist/pos.js +129 -0
- package/dist/procurement.d.ts +664 -0
- package/dist/procurement.js +157 -0
- package/dist/promotions.d.ts +169 -0
- package/dist/promotions.js +39 -0
- package/dist/publications.d.ts +583 -0
- package/dist/publications.js +164 -0
- package/dist/ranking.d.ts +43 -0
- package/dist/ranking.js +34 -0
- package/dist/ratings.d.ts +293 -0
- package/dist/ratings.js +109 -0
- package/dist/reactions.d.ts +123 -0
- package/dist/reactions.js +41 -0
- package/dist/recipient-orders.d.ts +294 -0
- package/dist/recipient-orders.js +73 -0
- package/dist/relationships.d.ts +18 -0
- package/dist/relationships.js +8 -0
- package/dist/reporting.d.ts +107 -0
- package/dist/reporting.js +56 -0
- package/dist/sales.d.ts +270 -0
- package/dist/sales.js +66 -0
- package/dist/shares.d.ts +105 -0
- package/dist/shares.js +27 -0
- package/dist/shop.d.ts +993 -0
- package/dist/shop.js +215 -0
- package/dist/shopping-assistant.d.ts +65 -0
- package/dist/shopping-assistant.js +14 -0
- package/dist/spaces.d.ts +422 -0
- package/dist/spaces.js +118 -0
- package/dist/stored-value.d.ts +754 -0
- package/dist/stored-value.js +177 -0
- package/dist/types.d.ts +83 -0
- package/dist/types.js +2 -0
- package/dist/vault.d.ts +290 -0
- package/dist/vault.js +55 -0
- package/dist/vertical-runtime.d.ts +17 -0
- package/dist/vertical-runtime.js +8 -0
- package/dist/vite/build-manifest-plugin.d.ts +42 -0
- package/dist/vite/build-manifest-plugin.js +42 -0
- package/dist/vite/first-paint-plugin.d.ts +26 -0
- package/dist/vite/first-paint-plugin.js +57 -0
- package/dist/wishlists.d.ts +591 -0
- package/dist/wishlists.js +188 -0
- package/dist/workbench.d.ts +114 -0
- package/dist/workbench.js +22 -0
- package/dist/workspace.d.ts +190 -0
- package/dist/workspace.js +41 -0
- package/package.json +52 -4
- package/templates/extension-image.Dockerfile +38 -0
- package/templates/nuwah-vertical.yml +102 -0
- package/templates/vertical-app/.env.example +34 -0
- package/templates/vertical-app/README.md +108 -0
- package/templates/vertical-app/github/workflows/ci.yml +51 -0
- package/templates/vertical-app/gitignore +5 -0
- package/templates/vertical-app/index.html +12 -0
- package/templates/vertical-app/package.json +28 -0
- package/templates/vertical-app/src/App.tsx +64 -0
- package/templates/vertical-app/src/blueprint/blueprint.ts +45 -0
- package/templates/vertical-app/src/blueprint/screens.ts +15 -0
- package/templates/vertical-app/src/env.d.ts +18 -0
- package/templates/vertical-app/src/index.css +139 -0
- package/templates/vertical-app/src/lib/i18n.ts +5 -0
- package/templates/vertical-app/src/lib/iam.ts +19 -0
- package/templates/vertical-app/src/lib/operations.ts +93 -0
- package/templates/vertical-app/src/lib/router.ts +24 -0
- package/templates/vertical-app/src/lib/sdk.ts +21 -0
- package/templates/vertical-app/src/lib/theme.ts +18 -0
- package/templates/vertical-app/src/lib/words.ts +39 -0
- package/templates/vertical-app/src/main.tsx +25 -0
- package/templates/vertical-app/src/pages/AppScreens.tsx +71 -0
- package/templates/vertical-app/src/pages/AuthCallback.tsx +44 -0
- package/templates/vertical-app/src/pages/Home.tsx +36 -0
- package/templates/vertical-app/tsconfig.json +24 -0
- package/templates/vertical-app/vite.config.ts +23 -0
- package/templates/vertical-ci.yml +192 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { Http } from './http.js';
|
|
2
|
+
import { type BilingualText, type PersonDomainCallOptions } from './actors.js';
|
|
3
|
+
import { type ListPage, type ListQueryState } from './list-query.js';
|
|
4
|
+
export type EngagementShape = 'ask' | 'signal' | 'act';
|
|
5
|
+
export interface EngagementAction {
|
|
6
|
+
key: string;
|
|
7
|
+
shape: EngagementShape;
|
|
8
|
+
weight_class: 'strong' | 'medium' | 'light';
|
|
9
|
+
label: BilingualText;
|
|
10
|
+
vocabulary_key: string;
|
|
11
|
+
enabled: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface EngagementSubject {
|
|
14
|
+
type: string;
|
|
15
|
+
id: string;
|
|
16
|
+
card: {
|
|
17
|
+
title: BilingualText;
|
|
18
|
+
summary: BilingualText | null;
|
|
19
|
+
image_url: string | null;
|
|
20
|
+
owner: string | null;
|
|
21
|
+
owner_display_name: string | null;
|
|
22
|
+
visibility: string;
|
|
23
|
+
deep_link: string;
|
|
24
|
+
};
|
|
25
|
+
state: 'available' | 'limited' | 'ended';
|
|
26
|
+
state_label: BilingualText | null;
|
|
27
|
+
viewer_manages: boolean;
|
|
28
|
+
actions: EngagementAction[];
|
|
29
|
+
signals: Record<string, {
|
|
30
|
+
active: boolean;
|
|
31
|
+
count: number | null;
|
|
32
|
+
}>;
|
|
33
|
+
}
|
|
34
|
+
export type EngagementHandoff = {
|
|
35
|
+
kind: 'actor_conversation';
|
|
36
|
+
actor_id: string;
|
|
37
|
+
share: {
|
|
38
|
+
subject_type: string;
|
|
39
|
+
subject_id: string;
|
|
40
|
+
};
|
|
41
|
+
question: BilingualText;
|
|
42
|
+
engagement_id: string;
|
|
43
|
+
facts_reply: BilingualText | null;
|
|
44
|
+
} | {
|
|
45
|
+
kind: 'person_conversation';
|
|
46
|
+
person_id: string;
|
|
47
|
+
share: {
|
|
48
|
+
subject_type: string;
|
|
49
|
+
subject_id: string;
|
|
50
|
+
};
|
|
51
|
+
question: BilingualText;
|
|
52
|
+
engagement_id: string;
|
|
53
|
+
facts_reply: BilingualText | null;
|
|
54
|
+
} | {
|
|
55
|
+
kind: 'signal';
|
|
56
|
+
action: string;
|
|
57
|
+
active: boolean;
|
|
58
|
+
count: number | null;
|
|
59
|
+
} | {
|
|
60
|
+
kind: 'navigate';
|
|
61
|
+
path: string;
|
|
62
|
+
} | {
|
|
63
|
+
kind: 'selection';
|
|
64
|
+
selection: unknown;
|
|
65
|
+
} | {
|
|
66
|
+
kind: 'none';
|
|
67
|
+
};
|
|
68
|
+
export interface EngagementOutcome {
|
|
69
|
+
engagement_id: string | null;
|
|
70
|
+
action: string;
|
|
71
|
+
shape: EngagementShape;
|
|
72
|
+
weight_class: string;
|
|
73
|
+
handoff: EngagementHandoff;
|
|
74
|
+
}
|
|
75
|
+
export interface EngageInput {
|
|
76
|
+
/** Required for `ask.custom` (at most 500 characters). */
|
|
77
|
+
question?: string;
|
|
78
|
+
/** Signals: the state wanted; omitted = toggle. */
|
|
79
|
+
active?: boolean;
|
|
80
|
+
quantity?: number;
|
|
81
|
+
}
|
|
82
|
+
export interface AttachableOffer {
|
|
83
|
+
suggestions: EngagementSubject[];
|
|
84
|
+
quick: Array<{
|
|
85
|
+
type: string;
|
|
86
|
+
label: BilingualText;
|
|
87
|
+
vocabulary_key: string;
|
|
88
|
+
}>;
|
|
89
|
+
}
|
|
90
|
+
export interface QuickSubjectInput {
|
|
91
|
+
type: string;
|
|
92
|
+
title: string;
|
|
93
|
+
description?: string | null;
|
|
94
|
+
/** A decimal string. */
|
|
95
|
+
price_amount: string;
|
|
96
|
+
currency_code: string;
|
|
97
|
+
media_asset_ids?: string[];
|
|
98
|
+
idempotency_key: string;
|
|
99
|
+
}
|
|
100
|
+
export interface EngagementRecord {
|
|
101
|
+
id: string;
|
|
102
|
+
subject_type: string;
|
|
103
|
+
subject_id: string;
|
|
104
|
+
action_key: string;
|
|
105
|
+
shape: EngagementShape;
|
|
106
|
+
created_at: string;
|
|
107
|
+
}
|
|
108
|
+
export interface EngagementsNamespace {
|
|
109
|
+
/** Subjects as you see them (≤100 per call); `missing` lists those you may not see. */
|
|
110
|
+
subjects(subjects: Array<{
|
|
111
|
+
type: string;
|
|
112
|
+
id: string;
|
|
113
|
+
}>, options?: PersonDomainCallOptions): Promise<{
|
|
114
|
+
data: EngagementSubject[];
|
|
115
|
+
missing: string[];
|
|
116
|
+
}>;
|
|
117
|
+
engage(subject: {
|
|
118
|
+
type: string;
|
|
119
|
+
id: string;
|
|
120
|
+
}, action: string, input?: EngageInput, options?: PersonDomainCallOptions): Promise<EngagementOutcome>;
|
|
121
|
+
/** Post an ask's structured question into the room you opened (once; 409 after). */
|
|
122
|
+
deliverQuestion(engagementId: string, conversationId: string, options?: PersonDomainCallOptions): Promise<unknown>;
|
|
123
|
+
attachable(options?: PersonDomainCallOptions): Promise<AttachableOffer>;
|
|
124
|
+
/** Answers the new subject's type and id, and its view when already readable. */
|
|
125
|
+
createQuickSubject(input: QuickSubjectInput, options?: PersonDomainCallOptions): Promise<{
|
|
126
|
+
type: string;
|
|
127
|
+
id: string;
|
|
128
|
+
subject: EngagementSubject | null;
|
|
129
|
+
}>;
|
|
130
|
+
/** Your own engagement history, newest first. */
|
|
131
|
+
mine(query?: ListQueryState, options?: PersonDomainCallOptions): Promise<ListPage<EngagementRecord>>;
|
|
132
|
+
}
|
|
133
|
+
export declare function createEngagementsNamespace(http: Http): EngagementsNamespace;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { personDomainRequest, } from './actors.js';
|
|
2
|
+
import { listQueryParams } from './list-query.js';
|
|
3
|
+
const BASE = '/api/person/engagements';
|
|
4
|
+
const segment = encodeURIComponent;
|
|
5
|
+
export function createEngagementsNamespace(http) {
|
|
6
|
+
const data = async (promise) => (await promise).data;
|
|
7
|
+
return {
|
|
8
|
+
subjects: (subjects, options) => http.get(`${BASE}/subjects`, personDomainRequest(options, false, { 'subjects[]': subjects.map((subject) => `${subject.type}:${subject.id}`) })),
|
|
9
|
+
engage: (subject, action, input = {}, options) => data(http.post(BASE, { subject_type: subject.type, subject_id: subject.id, action, ...input }, personDomainRequest(options, true))),
|
|
10
|
+
deliverQuestion: (engagementId, conversationId, options) => data(http.post(`${BASE}/${segment(engagementId)}/question-message`, { conversation_id: conversationId }, personDomainRequest(options, true))),
|
|
11
|
+
attachable: (options) => data(http.get(`${BASE}/attachable`, personDomainRequest(options))),
|
|
12
|
+
createQuickSubject: (input, options) => data(http.post(`${BASE}/quick-subjects`, input, personDomainRequest(options, true))),
|
|
13
|
+
mine: (query = {}, options) => http.get(`${BASE}/mine`, personDomainRequest(options, false, listQueryParams(query))),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type NuwahClientConfig } from './http.js';
|
|
2
|
+
/** One frame of a `text/event-stream` body. `event` defaults to `message`. */
|
|
3
|
+
export interface EventStreamFrame {
|
|
4
|
+
event: string;
|
|
5
|
+
data: string;
|
|
6
|
+
id: string | null;
|
|
7
|
+
}
|
|
8
|
+
export interface EventStreamRequest {
|
|
9
|
+
method?: 'GET' | 'POST';
|
|
10
|
+
/** JSON body for a POST. */
|
|
11
|
+
body?: unknown;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Parses a byte stream of `text/event-stream` into frames. Pure over an async iterable of chunks
|
|
17
|
+
* so it can be tested without a network. Handles `\r\n`, `\r` and `\n` line endings and frames
|
|
18
|
+
* split across chunks (including a multi-byte Arabic character split between two chunks: the
|
|
19
|
+
* decoder is streaming, so no replacement character appears mid-word).
|
|
20
|
+
*/
|
|
21
|
+
export declare function parseEventStream(chunks: AsyncIterable<Uint8Array | string>): AsyncGenerator<EventStreamFrame>;
|
|
22
|
+
/** True for the error `fetch` throws when its signal is aborted (DOMException or Node's AbortError). */
|
|
23
|
+
export declare function isAbortError(error: unknown): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Opens a stream and yields its frames. Throws `NuwahApiError` for a non-2xx answer (the JSON
|
|
26
|
+
* refusal core sends before a stream opens). Ends quietly when the signal aborts.
|
|
27
|
+
*/
|
|
28
|
+
export declare function openEventStream(config: NuwahClientConfig, path: string, request?: EventStreamRequest): AsyncGenerator<EventStreamFrame>;
|
|
29
|
+
export interface RetryOptions {
|
|
30
|
+
/** Total attempts including the first. Default 3. */
|
|
31
|
+
attempts?: number;
|
|
32
|
+
/** First wait in milliseconds; doubles each retry (with jitter). Default 500. */
|
|
33
|
+
baseDelayMilliseconds?: number;
|
|
34
|
+
/** Longest single wait. Default 8000. A server `retry_after_seconds` wins up to this. */
|
|
35
|
+
maximumDelayMilliseconds?: number;
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
/** Decides whether a failure is worth another attempt. Default: {@link isRetryable}. */
|
|
38
|
+
shouldRetry?: (error: unknown, attempt: number) => boolean;
|
|
39
|
+
/** Injectable sleep (tests). */
|
|
40
|
+
sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Worth retrying: a transport failure (no status), 429 and 502/503/504. Never a 4xx refusal, never
|
|
44
|
+
* an abort, and never a 503 that says the feature is OFF (`ai_disabled` is an answer, not an outage).
|
|
45
|
+
*/
|
|
46
|
+
export declare function isRetryable(error: unknown): boolean;
|
|
47
|
+
/** The server's own wait, in seconds, when the refusal named one (`retry_after_seconds` or `retry_after`). */
|
|
48
|
+
export declare function retryAfterSeconds(error: unknown): number | null;
|
|
49
|
+
/**
|
|
50
|
+
* Runs `operation` until it succeeds, the failure is not retryable, or the attempts run out.
|
|
51
|
+
* Only use it for reads and for writes carrying an idempotency key: a retried write without one
|
|
52
|
+
* may happen twice.
|
|
53
|
+
*/
|
|
54
|
+
export declare function withRetry<T>(operation: (attempt: number) => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
import { NuwahApiError, refusalReason } from './http.js';
|
|
4
|
+
|
|
5
|
+
export async function* parseEventStream(chunks) {
|
|
6
|
+
const decoder = new TextDecoder('utf-8');
|
|
7
|
+
let buffer = '';
|
|
8
|
+
let event = '';
|
|
9
|
+
let data = [];
|
|
10
|
+
let lastId = null;
|
|
11
|
+
const flush = () => {
|
|
12
|
+
if (data.length === 0 && event === '')
|
|
13
|
+
return null;
|
|
14
|
+
const frame = { event: event || 'message', data: data.join('\n'), id: lastId };
|
|
15
|
+
event = '';
|
|
16
|
+
data = [];
|
|
17
|
+
return frame;
|
|
18
|
+
};
|
|
19
|
+
const consumeLine = (line) => {
|
|
20
|
+
if (line === '')
|
|
21
|
+
return flush();
|
|
22
|
+
if (line.startsWith(':'))
|
|
23
|
+
return null;
|
|
24
|
+
const colon = line.indexOf(':');
|
|
25
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
26
|
+
let value = colon === -1 ? '' : line.slice(colon + 1);
|
|
27
|
+
if (value.startsWith(' '))
|
|
28
|
+
value = value.slice(1);
|
|
29
|
+
if (field === 'event')
|
|
30
|
+
event = value;
|
|
31
|
+
else if (field === 'data')
|
|
32
|
+
data.push(value);
|
|
33
|
+
else if (field === 'id')
|
|
34
|
+
lastId = value;
|
|
35
|
+
return null;
|
|
36
|
+
};
|
|
37
|
+
for await (const chunk of chunks) {
|
|
38
|
+
buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
39
|
+
let match;
|
|
40
|
+
const lineEnd = /\r\n|\r|\n/g;
|
|
41
|
+
let consumed = 0;
|
|
42
|
+
while ((match = lineEnd.exec(buffer)) !== null) {
|
|
43
|
+
|
|
44
|
+
if (match[0] === '\r' && match.index === buffer.length - 1)
|
|
45
|
+
break;
|
|
46
|
+
const frame = consumeLine(buffer.slice(consumed, match.index));
|
|
47
|
+
consumed = match.index + match[0].length;
|
|
48
|
+
if (frame)
|
|
49
|
+
yield frame;
|
|
50
|
+
}
|
|
51
|
+
buffer = buffer.slice(consumed);
|
|
52
|
+
}
|
|
53
|
+
buffer += decoder.decode();
|
|
54
|
+
if (buffer !== '') {
|
|
55
|
+
const frame = consumeLine(buffer);
|
|
56
|
+
if (frame)
|
|
57
|
+
yield frame;
|
|
58
|
+
}
|
|
59
|
+
const last = flush();
|
|
60
|
+
if (last)
|
|
61
|
+
yield last;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function* bodyChunks(body, signal) {
|
|
65
|
+
const reader = body.getReader();
|
|
66
|
+
const cancel = () => {
|
|
67
|
+
reader.cancel().catch(() => undefined);
|
|
68
|
+
};
|
|
69
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
70
|
+
try {
|
|
71
|
+
while (true) {
|
|
72
|
+
const { value, done } = await reader.read();
|
|
73
|
+
if (done)
|
|
74
|
+
return;
|
|
75
|
+
if (value)
|
|
76
|
+
yield value;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
signal?.removeEventListener('abort', cancel);
|
|
81
|
+
try {
|
|
82
|
+
reader.releaseLock();
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function isAbortError(error) {
|
|
91
|
+
return typeof error === 'object' && error !== null && error.name === 'AbortError';
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function* openEventStream(config, path, request = {}) {
|
|
95
|
+
const fetchImplementation = config.fetch ?? globalThis.fetch;
|
|
96
|
+
if (typeof fetchImplementation !== 'function') {
|
|
97
|
+
throw new Error('No fetch implementation available. Pass `fetch` in the client config on runtimes without a global fetch.');
|
|
98
|
+
}
|
|
99
|
+
const defaults = typeof config.defaultHeaders === 'function' ? config.defaultHeaders() : config.defaultHeaders;
|
|
100
|
+
const hasBody = request.body !== undefined && request.body !== null;
|
|
101
|
+
const send = (token) => fetchImplementation(`${config.baseUrl.replace(/\/$/, '')}${path}`, {
|
|
102
|
+
method: request.method ?? (hasBody ? 'POST' : 'GET'),
|
|
103
|
+
headers: {
|
|
104
|
+
Accept: 'text/event-stream, application/json',
|
|
105
|
+
'X-Requested-With': 'XMLHttpRequest',
|
|
106
|
+
...(hasBody ? { 'Content-Type': 'application/json' } : {}),
|
|
107
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
108
|
+
...defaults,
|
|
109
|
+
...request.headers,
|
|
110
|
+
},
|
|
111
|
+
body: hasBody ? JSON.stringify(request.body) : undefined,
|
|
112
|
+
signal: request.signal,
|
|
113
|
+
});
|
|
114
|
+
let response;
|
|
115
|
+
try {
|
|
116
|
+
const token = await config.getToken();
|
|
117
|
+
response = await send(token);
|
|
118
|
+
|
|
119
|
+
if (response.status === 401 && config.onUnauthorized && !request.signal?.aborted) {
|
|
120
|
+
const renewed = await config.onUnauthorized(token).catch(() => false);
|
|
121
|
+
if (renewed && !request.signal?.aborted)
|
|
122
|
+
response = await send(await config.getToken());
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (isAbortError(error) || request.signal?.aborted)
|
|
127
|
+
return;
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
const traceId = response.headers.get('x-trace-id');
|
|
131
|
+
if (response.status < 200 || response.status >= 300) {
|
|
132
|
+
const text = await response.text().catch(() => '');
|
|
133
|
+
let parsed = text;
|
|
134
|
+
try {
|
|
135
|
+
parsed = text ? JSON.parse(text) : null;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
|
|
139
|
+
}
|
|
140
|
+
throw new NuwahApiError(response.status, parsed, undefined, traceId);
|
|
141
|
+
}
|
|
142
|
+
const contentType = response.headers.get('content-type') ?? '';
|
|
143
|
+
if (!contentType.includes('text/event-stream') || response.body === null) {
|
|
144
|
+
|
|
145
|
+
const text = await response.text();
|
|
146
|
+
yield { event: 'message', data: text, id: null };
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
yield* parseEventStream(bodyChunks(response.body, request.signal));
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (isAbortError(error) || request.signal?.aborted)
|
|
154
|
+
return;
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function isRetryable(error) {
|
|
160
|
+
if (isAbortError(error))
|
|
161
|
+
return false;
|
|
162
|
+
if (error instanceof NuwahApiError) {
|
|
163
|
+
if (refusalReason(error) === 'ai_disabled')
|
|
164
|
+
return false;
|
|
165
|
+
return error.status === 429 || error.status === 502 || error.status === 503 || error.status === 504;
|
|
166
|
+
}
|
|
167
|
+
return error instanceof TypeError;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function retryAfterSeconds(error) {
|
|
171
|
+
const body = error?.body;
|
|
172
|
+
if (!body || typeof body !== 'object')
|
|
173
|
+
return null;
|
|
174
|
+
for (const key of ['retry_after_seconds', 'retry_after']) {
|
|
175
|
+
const value = body[key];
|
|
176
|
+
if (typeof value === 'number' && Number.isFinite(value) && value >= 0)
|
|
177
|
+
return value;
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
function defaultSleep(milliseconds, signal) {
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
if (signal?.aborted) {
|
|
184
|
+
reject(abortError());
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const timer = setTimeout(() => {
|
|
188
|
+
signal?.removeEventListener('abort', onAbort);
|
|
189
|
+
resolve();
|
|
190
|
+
}, milliseconds);
|
|
191
|
+
const onAbort = () => {
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
reject(abortError());
|
|
194
|
+
};
|
|
195
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
function abortError() {
|
|
199
|
+
const error = new Error('The operation was aborted.');
|
|
200
|
+
error.name = 'AbortError';
|
|
201
|
+
return error;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export async function withRetry(operation, options = {}) {
|
|
205
|
+
const attempts = Math.max(1, options.attempts ?? 3);
|
|
206
|
+
const base = options.baseDelayMilliseconds ?? 500;
|
|
207
|
+
const maximum = options.maximumDelayMilliseconds ?? 8000;
|
|
208
|
+
const shouldRetry = options.shouldRetry ?? isRetryable;
|
|
209
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
210
|
+
let lastError;
|
|
211
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
212
|
+
if (options.signal?.aborted)
|
|
213
|
+
throw abortError();
|
|
214
|
+
try {
|
|
215
|
+
return await operation(attempt);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
lastError = error;
|
|
219
|
+
if (attempt === attempts || !shouldRetry(error, attempt))
|
|
220
|
+
throw error;
|
|
221
|
+
const serverWait = retryAfterSeconds(error);
|
|
222
|
+
const backoff = base * 2 ** (attempt - 1) * (0.75 + Math.random() * 0.5);
|
|
223
|
+
const wait = Math.min(maximum, serverWait !== null ? serverWait * 1000 : backoff);
|
|
224
|
+
await sleep(wait, options.signal);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
throw lastError;
|
|
228
|
+
}
|