@wix/himalaya-cli 0.1768.0 → 0.1770.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/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-config.d.ts +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-module.d.ts +7 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +1 -0
- package/dist/cli.mjs +311 -56
- package/guides/himi-json-output.md +3 -3
- package/guides/qa-builds.md +73 -84
- package/package.json +2 -2
- package/templates/beauty-salon/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/beauty-salon/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/beauty-salon-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/branded-lite/config.ts +2 -1
- package/templates/branded-lite/dev/index.ts +2 -1
- package/templates/branded-lite/l10n/ar.json +120 -0
- package/templates/branded-lite/l10n/cs.json +120 -0
- package/templates/branded-lite/l10n/da.json +120 -0
- package/templates/branded-lite/l10n/de.json +120 -0
- package/templates/branded-lite/l10n/el.json +120 -0
- package/templates/branded-lite/l10n/es.json +120 -0
- package/templates/branded-lite/l10n/fi.json +120 -0
- package/templates/branded-lite/l10n/fr.json +120 -0
- package/templates/branded-lite/l10n/he.json +96 -0
- package/templates/branded-lite/l10n/hu.json +120 -0
- package/templates/branded-lite/l10n/id.json +120 -0
- package/templates/branded-lite/l10n/it.json +120 -0
- package/templates/branded-lite/l10n/ja.json +120 -0
- package/templates/branded-lite/l10n/ko.json +120 -0
- package/templates/branded-lite/l10n/lt.json +120 -0
- package/templates/branded-lite/l10n/nl.json +120 -0
- package/templates/branded-lite/l10n/no.json +120 -0
- package/templates/branded-lite/l10n/pl.json +120 -0
- package/templates/branded-lite/l10n/pt.json +120 -0
- package/templates/branded-lite/l10n/ru.json +120 -0
- package/templates/branded-lite/l10n/sv.json +120 -0
- package/templates/branded-lite/l10n/th.json +120 -0
- package/templates/branded-lite/l10n/tr.json +120 -0
- package/templates/branded-lite/l10n/uk.json +120 -0
- package/templates/branded-lite/l10n/vi.json +120 -0
- package/templates/branded-lite/l10n/zh.json +120 -0
- package/templates/branded-lite/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/branded-lite/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/branded-lite/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/branded-lite/tier5-src/_shared/inbox-search.ts +119 -0
- package/templates/branded-lite/tier5-src/_shared/member-inbox-transport.ts +64 -0
- package/templates/branded-lite/tier5-src/_shared/member-thread-rows.ts +233 -0
- package/templates/branded-lite/tier5-src/business-chat/index.ts +73 -22
- package/templates/branded-lite/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
- package/templates/branded-lite/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
- package/templates/branded-lite/tier5-src/wix-spaces-new-message/index.ts +4 -2
- package/templates/brandy/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/brandy/tier5-src/_shared/business-chat-transport.ts +164 -0
- package/templates/brandy/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/brandy/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/brandy/tier5-src/_shared/inbox-search.ts +119 -0
- package/templates/brandy/tier5-src/_shared/member-inbox-transport.ts +64 -0
- package/templates/brandy/tier5-src/_shared/member-thread-rows.ts +233 -0
- package/templates/brandy/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
- package/templates/brandy/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
- package/templates/community-club/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/community-club-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/conference/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/conference/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/conference/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/conference/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/conference/tier5-src/business-chat/index.ts +73 -22
- package/templates/events-meetups/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/events-meetups-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/fitness-gym/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/fitness-gym/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/fitness-gym/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/fitness-gym/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/fitness-gym/tier5-src/business-chat/index.ts +73 -22
- package/templates/gym-fitness/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/gym-fitness/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/gym-fitness-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/medical-services/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/medical-services/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/medical-services/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/medical-services/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/medical-services/tier5-src/business-chat/index.ts +73 -22
- package/templates/nonprofit-cause/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/nonprofit-cause-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/owner-lite/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/personal-fitness-trainer/dev/index.ts +2 -1
- package/templates/personal-fitness-trainer/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/personal-fitness-trainer/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/personal-fitness-trainer/tier5-src/business-chat/index.ts +73 -22
- package/templates/podcast-creator/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/podcast-creator-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/portfolio-creative/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/portfolio-creative-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/restaurant/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/restaurant-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/retail-store/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/retail-store-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/salon-spa/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/salon-spa/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/salon-spa/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/salon-spa/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/salon-spa/tier5-src/business-chat/index.ts +73 -22
- package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/wholesale-store/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/wholesale-store/tier5-src/business-chat/index.ts +73 -22
- package/templates/yoga-studio/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/yoga-studio/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/yoga-studio-owner/tier5-src/_shared/engine-intl.ts +6 -0
|
@@ -119,6 +119,12 @@ export function formatMonthDayLong(date: Date, locale = appLocale(), timeZone?:
|
|
|
119
119
|
|
|
120
120
|
const WEEKDAYS_LONG = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] as const;
|
|
121
121
|
|
|
122
|
+
/** `{ weekday: "short" }` — "Mon". */
|
|
123
|
+
export function formatWeekdayShort(date: Date, locale = appLocale(), timeZone?: string): string {
|
|
124
|
+
if (hasIntl()) return dateFormat(locale, { weekday: "short" }, timeZone).format(date);
|
|
125
|
+
return WEEKDAYS_SHORT[date.getDay()]!;
|
|
126
|
+
}
|
|
127
|
+
|
|
122
128
|
/** `{ weekday: "short", month: "short", day: "numeric" }` — "Mon, Jan 5". */
|
|
123
129
|
export function formatWeekdayMonthDay(date: Date, locale = appLocale(), timeZone?: string): string {
|
|
124
130
|
if (hasIntl()) {
|
|
@@ -119,6 +119,12 @@ export function formatMonthDayLong(date: Date, locale = appLocale(), timeZone?:
|
|
|
119
119
|
|
|
120
120
|
const WEEKDAYS_LONG = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] as const;
|
|
121
121
|
|
|
122
|
+
/** `{ weekday: "short" }` — "Mon". */
|
|
123
|
+
export function formatWeekdayShort(date: Date, locale = appLocale(), timeZone?: string): string {
|
|
124
|
+
if (hasIntl()) return dateFormat(locale, { weekday: "short" }, timeZone).format(date);
|
|
125
|
+
return WEEKDAYS_SHORT[date.getDay()]!;
|
|
126
|
+
}
|
|
127
|
+
|
|
122
128
|
/** `{ weekday: "short", month: "short", day: "numeric" }` — "Mon, Jan 5". */
|
|
123
129
|
export function formatWeekdayMonthDay(date: Date, locale = appLocale(), timeZone?: string): string {
|
|
124
130
|
if (hasIntl()) {
|
|
@@ -29,6 +29,19 @@ async function fenced<T>(identity: ChatIdentity, run: () => Promise<T>): Promise
|
|
|
29
29
|
/** Any other member-scoped call (the AI chat's) goes through the same fence. */
|
|
30
30
|
export const fence = fenced;
|
|
31
31
|
|
|
32
|
+
/** A signed-out visitor's Smart Chat calls are fenced the other way: still signed out before the request goes
|
|
33
|
+
* out and again before its response is used, so signing in mid-request never mixes the visitor's chat into
|
|
34
|
+
* the member's. Fails as `MemberAccessChanged`, like the member fence, so callers handle both alike. */
|
|
35
|
+
async function assertStillVisitor(): Promise<void> {
|
|
36
|
+
if ((await memberAccess()).email) throw Object.assign(new Error("visitor_signed_in"), { name: "MemberAccessChanged" });
|
|
37
|
+
}
|
|
38
|
+
export async function visitorFence<T>(run: () => Promise<T>): Promise<T> {
|
|
39
|
+
await assertStillVisitor();
|
|
40
|
+
const result = await run();
|
|
41
|
+
await assertStillVisitor();
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
|
|
32
45
|
// Minting a chat token is a network round trip, and every chat call used to mint its own. One token
|
|
33
46
|
// per member is reused until the member changes or a request using it is refused.
|
|
34
47
|
let cachedToken: { key: string; token: string } | null = null;
|
|
@@ -44,7 +57,7 @@ async function chatTokenFor(identity: ChatIdentity): Promise<string> {
|
|
|
44
57
|
return chatToken;
|
|
45
58
|
}
|
|
46
59
|
/** Runs `run` with the member's cached token; a refused request mints a fresh token and tries once more. */
|
|
47
|
-
async function withToken<T>(identity: ChatIdentity, run: (chatToken: string) => Promise<T>): Promise<T> {
|
|
60
|
+
export async function withToken<T>(identity: ChatIdentity, run: (chatToken: string) => Promise<T>): Promise<T> {
|
|
48
61
|
const reused = cachedToken?.key === tokenKey(identity);
|
|
49
62
|
try {
|
|
50
63
|
return await run(await chatTokenFor(identity));
|
|
@@ -80,7 +93,7 @@ export const unreadRoomCount = (identity: ChatIdentity): Promise<number> => fenc
|
|
|
80
93
|
export const messagesPage = (identity: ChatIdentity, roomId: string): Promise<Raw[]> => fenced(identity, async () =>
|
|
81
94
|
(await withToken(identity, (chatToken) => getMessagesPage(roomId, { ...MEMBER, chatToken, pageSize: 50, ordering: "Desc" }))).items as unknown as Raw[]);
|
|
82
95
|
|
|
83
|
-
function bridge(): Bridge {
|
|
96
|
+
export function bridge(): Bridge {
|
|
84
97
|
const api = (globalThis as unknown as { himalaya?: { wixApi?: Bridge } }).himalaya?.wixApi;
|
|
85
98
|
if (!api) throw new Error("wix_api_bridge_unavailable");
|
|
86
99
|
return api;
|
|
@@ -89,7 +102,10 @@ function bridge(): Bridge {
|
|
|
89
102
|
* Wix Smart Chat and the AI can answer it; a message posted straight into the room has no channel, so the AI never
|
|
90
103
|
* saw it and the owner's reply went out by email. Smart Chat chooses the conversation and stored message id.
|
|
91
104
|
* The bridge resolves once the AI has finished answering, not when the message is stored. */
|
|
92
|
-
export const sendMessage = (identity: ChatIdentity, text: string): Promise<string | undefined> => fenced(identity,
|
|
105
|
+
export const sendMessage = (identity: ChatIdentity, text: string): Promise<string | undefined> => fenced(identity, () => postQuestion(text));
|
|
106
|
+
/** The same Smart Chat send for a signed-out visitor: Smart Chat accepts the anonymous visitor token. */
|
|
107
|
+
export const sendVisitorMessage = (text: string): Promise<string | undefined> => visitorFence(() => postQuestion(text));
|
|
108
|
+
async function postQuestion(text: string): Promise<string | undefined> {
|
|
93
109
|
const response = await bridge().call("POST", "/wix-assistant-widget/v1/messages/stream", {
|
|
94
110
|
message: { sender: "SITE_VISITOR", messageType: "QUESTION", body: { mainText: text } },
|
|
95
111
|
});
|
|
@@ -123,7 +139,7 @@ export const sendMessage = (identity: ChatIdentity, text: string): Promise<strin
|
|
|
123
139
|
if (input?.sender === "SITE_VISITOR" && input.messageType === "QUESTION" && typeof input.id === "string" && input.id) return `smart-chat:${input.id}`;
|
|
124
140
|
}
|
|
125
141
|
return undefined;
|
|
126
|
-
}
|
|
142
|
+
}
|
|
127
143
|
/** A tapped button is a silent, ephemeral message carrying the button's chat action. */
|
|
128
144
|
export const sendButton = (identity: ChatIdentity, roomId: string, input: { id: string; text: string; appId: string; interactionId: string }): Promise<void> => fenced(identity, async () => {
|
|
129
145
|
await withToken(identity, (chatToken) => bridge().call("POST", `${MANAGE}/_api/chat-web/v2/chatrooms/${encodeURIComponent(roomId)}/messages`, {
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// How an open chat thread stays live — one helper for owner-lite's Inbox thread and
|
|
2
|
+
// branded-lite's member chat.
|
|
3
|
+
//
|
|
4
|
+
// Two paths, and the worker never has to choose between them by platform:
|
|
5
|
+
//
|
|
6
|
+
// 1. REALTIME. With a Wix Chat channel configured, `load` returns a `_stream` directive
|
|
7
|
+
// whose url is `wix-realtime://<appDefId>/<channel>?slug=<slug>&resourceId=<chatroom>`.
|
|
8
|
+
// The iOS and Android hosts open a Wix Duplexer channel for it and
|
|
9
|
+
// dispatch `onEvent` for each matching message.
|
|
10
|
+
// 2. FALLBACK. With no channel, or once the stream fails (`onError` — which is also what
|
|
11
|
+
// the web host answers, since it refuses `wix-realtime://`), a `_poll` directive asks
|
|
12
|
+
// the host to re-read the thread every 4 s.
|
|
13
|
+
//
|
|
14
|
+
// The fallback is a HOST timer, not a worker one: the worker sandbox has no
|
|
15
|
+
// `setInterval`. That is also what keeps it to the
|
|
16
|
+
// foreground — every host suspends a poll when the app is backgrounded or the screen is
|
|
17
|
+
// pooled off-view, and cancels it when the screen is torn down — so a hidden thread never
|
|
18
|
+
// polls. A poll has no stop verb; a thread that has its stream simply never asks for one.
|
|
19
|
+
//
|
|
20
|
+
// An event is only ever "the thread changed". Its payload is not read: its shape is
|
|
21
|
+
// unverified, and the host deliberately does not interpret it either. The worker re-reads
|
|
22
|
+
// the messages instead — one cheap call that cannot desync — and `createReloadGate`
|
|
23
|
+
// folds a burst of events into one read.
|
|
24
|
+
//
|
|
25
|
+
// This file is copied verbatim into every generated starter app, so it explains itself
|
|
26
|
+
// without pointing at anything only this repo has.
|
|
27
|
+
|
|
28
|
+
import type { PollDirective, StreamDirective } from "@himalaya/state";
|
|
29
|
+
|
|
30
|
+
/** A Wix Chat Duplexer channel: the `ns` (an app def id), the bare channel name, and the
|
|
31
|
+
* event slug a new message arrives under. */
|
|
32
|
+
export interface ChatRealtimeConfig {
|
|
33
|
+
appDefId: string;
|
|
34
|
+
channel: string;
|
|
35
|
+
slug: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The stream's id. One per screen: a new directive under the same id replaces the old
|
|
39
|
+
* channel instead of opening a second one. */
|
|
40
|
+
export const CHAT_LIVE_STREAM_ID = "chat-live";
|
|
41
|
+
/** The fallback poll's id. Re-arming it replaces the timer, never stacks a second one. */
|
|
42
|
+
export const CHAT_LIVE_POLL_ID = "chat-live-poll";
|
|
43
|
+
/** "A message from the other side appears within 5 s." */
|
|
44
|
+
export const CHAT_LIVE_POLL_MS = 4000;
|
|
45
|
+
|
|
46
|
+
/** Which path is keeping the thread live: `off` before a conversation is open, `stream`
|
|
47
|
+
* when a realtime channel was asked for, `poll` on the fallback. Diagnostic. */
|
|
48
|
+
export type ChatLiveMode = "off" | "stream" | "poll";
|
|
49
|
+
|
|
50
|
+
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
51
|
+
|
|
52
|
+
/** A complete, well-formed channel, or null. A half-filled one would subscribe to
|
|
53
|
+
* nothing and never fire, which looks exactly like a quiet conversation. */
|
|
54
|
+
export function chatRealtimeConfig(value: unknown): ChatRealtimeConfig | null {
|
|
55
|
+
let v = value;
|
|
56
|
+
if (typeof v === "string") {
|
|
57
|
+
if (!v.trim()) return null;
|
|
58
|
+
try { v = JSON.parse(v); } catch { return null; }
|
|
59
|
+
}
|
|
60
|
+
if (!v || typeof v !== "object") return null;
|
|
61
|
+
const { appDefId, channel, slug } = v as Record<string, unknown>;
|
|
62
|
+
if (typeof appDefId !== "string" || !GUID.test(appDefId)) return null;
|
|
63
|
+
if (typeof channel !== "string" || !channel.trim()) return null;
|
|
64
|
+
if (typeof slug !== "string" || !slug.trim()) return null;
|
|
65
|
+
return { appDefId, channel, slug };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The `wix-realtime://` url for one conversation. */
|
|
69
|
+
export function chatRealtimeUrl(cfg: ChatRealtimeConfig, chatroomId: string): string {
|
|
70
|
+
return `wix-realtime://${cfg.appDefId}/${encodeURIComponent(cfg.channel)}?slug=${encodeURIComponent(cfg.slug)}&resourceId=${encodeURIComponent(chatroomId)}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The stream directive that keeps `chatroomId` live, or null when there is no channel
|
|
74
|
+
* (or no conversation) to open. `onEvent` / `onError` are action names of the calling
|
|
75
|
+
* service. */
|
|
76
|
+
export function liveThreadDirective(
|
|
77
|
+
cfg: ChatRealtimeConfig | null,
|
|
78
|
+
chatroomId: string,
|
|
79
|
+
actions: { onEvent: string; onError: string },
|
|
80
|
+
): StreamDirective | null {
|
|
81
|
+
if (!cfg || !chatroomId) return null;
|
|
82
|
+
return {
|
|
83
|
+
id: CHAT_LIVE_STREAM_ID,
|
|
84
|
+
request: { method: "GET", url: chatRealtimeUrl(cfg, chatroomId) },
|
|
85
|
+
onEvent: actions.onEvent,
|
|
86
|
+
onError: actions.onError,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The 4 s foreground re-read. `action` is fully qualified (`"<service>.<action>"`). */
|
|
91
|
+
export function livePollDirective(action: string, intervalMs = CHAT_LIVE_POLL_MS): PollDirective {
|
|
92
|
+
return { id: CHAT_LIVE_POLL_ID, intervalMs, action, immediate: false };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** What `load` returns beside its state to keep the conversation live: the stream when a
|
|
96
|
+
* channel is configured, else the poll. Nothing when there is no conversation. The
|
|
97
|
+
* service's actions must be named `onStreamEvent`, `onStreamError` and `refresh`. */
|
|
98
|
+
export function liveDirectives(
|
|
99
|
+
cfg: ChatRealtimeConfig | null,
|
|
100
|
+
chatroomId: string,
|
|
101
|
+
service: string,
|
|
102
|
+
): { live: ChatLiveMode; _stream?: StreamDirective; _poll?: PollDirective } {
|
|
103
|
+
if (!chatroomId) return { live: "off" };
|
|
104
|
+
const stream = liveThreadDirective(cfg, chatroomId, { onEvent: "onStreamEvent", onError: "onStreamError" });
|
|
105
|
+
if (stream) return { live: "stream", _stream: stream };
|
|
106
|
+
return { live: "poll", _poll: livePollDirective(`${service}.refresh`) };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** What `onStreamError` returns beside its state: the stream is gone, so poll. */
|
|
110
|
+
export function liveFallback(service: string): { live: ChatLiveMode; _poll: PollDirective } {
|
|
111
|
+
return { live: "poll", _poll: livePollDirective(`${service}.refresh`) };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Fold re-read requests so a burst costs one read.
|
|
116
|
+
*
|
|
117
|
+
* Requests made in the same tick share one read. A request made while a read is in
|
|
118
|
+
* flight gets ONE trailing read after it — never more than one, however many arrive —
|
|
119
|
+
* because the in-flight read may have left the server before the change that prompted
|
|
120
|
+
* the request, and returning its answer would drop that message.
|
|
121
|
+
*/
|
|
122
|
+
export function createReloadGate<T>(read: () => Promise<T>): { request(): Promise<T> } {
|
|
123
|
+
let queued: Promise<T> | null = null;
|
|
124
|
+
let running: Promise<void> | null = null;
|
|
125
|
+
return {
|
|
126
|
+
request() {
|
|
127
|
+
if (queued) return queued;
|
|
128
|
+
const prior = running ?? Promise.resolve();
|
|
129
|
+
const next = prior.then(() => {
|
|
130
|
+
queued = null;
|
|
131
|
+
return read();
|
|
132
|
+
});
|
|
133
|
+
queued = next;
|
|
134
|
+
const settled = next.then(() => undefined, () => undefined);
|
|
135
|
+
running = settled;
|
|
136
|
+
void settled.then(() => {
|
|
137
|
+
if (running === settled) running = null;
|
|
138
|
+
});
|
|
139
|
+
return next;
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* One chat token per thread VISIT.
|
|
146
|
+
*
|
|
147
|
+
* Every chat-web call needs a token, and minting one is a request of its own — so a thread
|
|
148
|
+
* that re-reads every 4 s would otherwise mint every 4 s. `get()` mints on first use and
|
|
149
|
+
* shares that token with every read and send; `reset()` starts a new visit; `drop(p)`
|
|
150
|
+
* forgets a token after a call that used it failed (an expired token costs one failed call,
|
|
151
|
+
* and the next one mints again). `drop` only forgets THAT token: a late failure from an
|
|
152
|
+
* earlier visit must not throw away the token the current visit just minted.
|
|
153
|
+
*/
|
|
154
|
+
export function createVisitToken(mint: () => Promise<string>): {
|
|
155
|
+
get(): Promise<string>;
|
|
156
|
+
drop(token: Promise<string> | null): void;
|
|
157
|
+
reset(): void;
|
|
158
|
+
} {
|
|
159
|
+
let current: Promise<string> | null = null;
|
|
160
|
+
const drop = (token: Promise<string> | null): void => {
|
|
161
|
+
if (token && current === token) current = null;
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
get() {
|
|
165
|
+
if (!current) {
|
|
166
|
+
const minted = mint();
|
|
167
|
+
current = minted;
|
|
168
|
+
minted.catch(() => drop(minted));
|
|
169
|
+
}
|
|
170
|
+
return current;
|
|
171
|
+
},
|
|
172
|
+
drop,
|
|
173
|
+
reset() {
|
|
174
|
+
current = null;
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Did a chat-web call fail because its token was refused? The status chat-web uses for an
|
|
180
|
+
* expired chatToken is NOT verified against a live session: 401 and 403 are both treated as
|
|
181
|
+
* "refused", and either way a retry with the same message id is the same send intent, so a
|
|
182
|
+
* wrong guess costs one extra request, never a second message. Any other failure may have
|
|
183
|
+
* posted the message, so it is not retried. */
|
|
184
|
+
export function isTokenRejected(e: unknown): boolean {
|
|
185
|
+
return /HTTP 40[13]\b/.test(String((e as Error)?.message ?? e ?? ""));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** UUID v4 for a send's idempotency id (the worker realm has no crypto.randomUUID). */
|
|
189
|
+
export function uuidV4(): string {
|
|
190
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
191
|
+
const r = Math.floor(Math.random() * 16);
|
|
192
|
+
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Send ids that belong to the INTENT, not the tap.
|
|
198
|
+
*
|
|
199
|
+
* The same id on a retry is the same send to chat-web, so the server keeps one message. A
|
|
200
|
+
* send that failed ambiguously (a gateway timeout after the backend stored it) and is tapped
|
|
201
|
+
* again must reuse its id, or the business receives the message twice. An intent is the
|
|
202
|
+
* conversation plus the exact text; it is settled once the send succeeds, and any other text
|
|
203
|
+
* is a new intent.
|
|
204
|
+
*/
|
|
205
|
+
export function createSendIntents(): { idFor(chatroomId: string, text: string): string; settle(chatroomId: string, text: string): void } {
|
|
206
|
+
const ids = new Map<string, string>();
|
|
207
|
+
const keyOf = (chatroomId: string, text: string) => `${chatroomId}\u0000${text}`;
|
|
208
|
+
return {
|
|
209
|
+
idFor(chatroomId, text) {
|
|
210
|
+
const key = keyOf(chatroomId, text);
|
|
211
|
+
let id = ids.get(key);
|
|
212
|
+
if (!id) { id = uuidV4(); ids.set(key, id); }
|
|
213
|
+
return id;
|
|
214
|
+
},
|
|
215
|
+
settle(chatroomId, text) {
|
|
216
|
+
ids.delete(keyOf(chatroomId, text));
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Post with the visit's token, re-minting once if chat-web refused the token. Whichever
|
|
222
|
+
* token a failed attempt used is dropped, so a rejected token is never reused. */
|
|
223
|
+
export async function postWithVisitToken(
|
|
224
|
+
token: ReturnType<typeof createVisitToken>,
|
|
225
|
+
send: (chatToken: string) => Promise<void>,
|
|
226
|
+
): Promise<void> {
|
|
227
|
+
const first = token.get();
|
|
228
|
+
try {
|
|
229
|
+
await send(await first);
|
|
230
|
+
return;
|
|
231
|
+
} catch (e) {
|
|
232
|
+
token.drop(first);
|
|
233
|
+
if (!isTokenRejected(e)) throw e;
|
|
234
|
+
}
|
|
235
|
+
const retry = token.get();
|
|
236
|
+
try {
|
|
237
|
+
await send(await retry);
|
|
238
|
+
} catch (e) {
|
|
239
|
+
token.drop(retry);
|
|
240
|
+
throw e;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
@@ -119,6 +119,12 @@ export function formatMonthDayLong(date: Date, locale = appLocale(), timeZone?:
|
|
|
119
119
|
|
|
120
120
|
const WEEKDAYS_LONG = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] as const;
|
|
121
121
|
|
|
122
|
+
/** `{ weekday: "short" }` — "Mon". */
|
|
123
|
+
export function formatWeekdayShort(date: Date, locale = appLocale(), timeZone?: string): string {
|
|
124
|
+
if (hasIntl()) return dateFormat(locale, { weekday: "short" }, timeZone).format(date);
|
|
125
|
+
return WEEKDAYS_SHORT[date.getDay()]!;
|
|
126
|
+
}
|
|
127
|
+
|
|
122
128
|
/** `{ weekday: "short", month: "short", day: "numeric" }` — "Mon, Jan 5". */
|
|
123
129
|
export function formatWeekdayMonthDay(date: Date, locale = appLocale(), timeZone?: string): string {
|
|
124
130
|
if (hasIntl()) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The member's Inbox rows: every chatroom the member-role chat list returns, business and member alike.
|
|
2
2
|
// Pure, so the worker and its tests share one classification of what a room is.
|
|
3
|
+
import { calendarDay, formatClock, formatMonthDay, formatWeekdayShort } from "./engine-intl.js";
|
|
3
4
|
|
|
4
5
|
type RecordValue = Record<string, unknown>;
|
|
5
6
|
const object = (value: unknown): RecordValue =>
|
|
@@ -15,6 +16,8 @@ export function isBusinessRoom(value: unknown): boolean {
|
|
|
15
16
|
Object.keys(object(room.businessContext)).length > 0;
|
|
16
17
|
}
|
|
17
18
|
|
|
19
|
+
export const BUSINESS_SCREEN = "himi_business_chat";
|
|
20
|
+
|
|
18
21
|
export interface InboxRow {
|
|
19
22
|
id: string;
|
|
20
23
|
title: string;
|
|
@@ -24,14 +27,78 @@ export interface InboxRow {
|
|
|
24
27
|
/** `chatroom` makes the thread use `id` as the room instead of resolving it as a member id. */
|
|
25
28
|
kind: "chatroom" | "";
|
|
26
29
|
photo: string;
|
|
30
|
+
/** No photo: the screen draws the initial instead (`!photo`, kept with the photo by completeRow). */
|
|
31
|
+
noPhoto: boolean;
|
|
27
32
|
initial: string;
|
|
33
|
+
/** Has unread messages, or the member marked it unread. */
|
|
28
34
|
unread: boolean;
|
|
35
|
+
/** "●" when unread, else "". Kept for the screens that bind the glyph. */
|
|
29
36
|
unreadDot: string;
|
|
37
|
+
/** The server's unread count; 0 when none, or when the member marked a room unread (the count is then unknown). */
|
|
38
|
+
unreadCount: number;
|
|
39
|
+
/** The count as text: "" for 0 or unknown, "99+" above 99. */
|
|
40
|
+
unreadText: string;
|
|
41
|
+
/** hiddenWhen gates in both polarities: a count badge when the count is known, a plain dot when the room is
|
|
42
|
+
* unread but the count is not. */
|
|
43
|
+
showCount: boolean; hideCount: boolean; showDot: boolean; hideDot: boolean;
|
|
44
|
+
/** Last activity: the time today, "Yesterday", the weekday within the last six calendar days (as chat lists show it,
|
|
45
|
+
* not the calendar week), else the day. "" when unknown. */
|
|
46
|
+
dateLabel: string;
|
|
47
|
+
isArchived: boolean;
|
|
48
|
+
/** Only a private room can be deleted by a member (the Wix app's rule). */
|
|
49
|
+
isPrivate: boolean;
|
|
50
|
+
/** Swipe-action gates (hiddenWhen hides on TRUE). */
|
|
51
|
+
hideArchive: boolean; hideUnarchive: boolean; hideDelete: boolean; hideMarkRead: boolean; hideMarkUnread: boolean;
|
|
30
52
|
/** Sort key only; not bound to the screen. */
|
|
31
53
|
at: number;
|
|
32
54
|
}
|
|
33
55
|
|
|
34
56
|
const text = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
|
|
57
|
+
const MAX_COUNT = 99;
|
|
58
|
+
|
|
59
|
+
/** "" for 0 or an unknown count, "99+" above 99. */
|
|
60
|
+
export const unreadCountText = (count: number): string => (count > MAX_COUNT ? `${MAX_COUNT}+` : count > 0 ? String(count) : "");
|
|
61
|
+
|
|
62
|
+
/** Everything that follows from a row's base fields. The one place a flag is derived, so a row that changes
|
|
63
|
+
* (marked read, archived) can never carry a flag that disagrees with its base fields. */
|
|
64
|
+
export type RowBase = Pick<InboxRow, "id" | "title" | "subtitle" | "screenId" | "kind" | "photo" | "initial" | "unread" | "unreadCount" | "dateLabel" | "isArchived" | "isPrivate" | "at">;
|
|
65
|
+
export function completeRow(base: RowBase): InboxRow {
|
|
66
|
+
const unreadText = unreadCountText(base.unreadCount);
|
|
67
|
+
const showCount = base.unread && unreadText !== "";
|
|
68
|
+
const showDot = base.unread && !showCount;
|
|
69
|
+
return {
|
|
70
|
+
...base,
|
|
71
|
+
noPhoto: !base.photo,
|
|
72
|
+
unreadDot: base.unread ? "●" : "",
|
|
73
|
+
unreadText,
|
|
74
|
+
showCount, hideCount: !showCount, showDot, hideDot: !showDot,
|
|
75
|
+
hideArchive: base.isArchived, hideUnarchive: !base.isArchived,
|
|
76
|
+
hideDelete: !base.isPrivate,
|
|
77
|
+
hideMarkRead: !base.unread, hideMarkUnread: base.unread,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A row's read state changed: `count` is the server's count (0 = unknown or none). */
|
|
82
|
+
export function withUnread(row: InboxRow, unread: boolean, count: number): InboxRow {
|
|
83
|
+
const { id, title, subtitle, screenId, kind, photo, initial, dateLabel, isArchived, isPrivate, at } = row;
|
|
84
|
+
return completeRow({ id, title, subtitle, screenId, kind, photo, initial, dateLabel, isArchived, isPrivate, at, unread, unreadCount: unread ? count : 0 });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Last-activity label in the device's zone: today → the time, yesterday → [yesterday] (the caller passes the localised
|
|
88
|
+
* word), within the last six calendar days → the weekday, otherwise the day. "" for an unknown time. Days are calendar
|
|
89
|
+
* days (local midnight to midnight), never 24-hour spans, so one day never gets two label formats and DST cannot shift them. */
|
|
90
|
+
export function dateLabel(at: number, yesterday: string, now: number = Date.now()): string {
|
|
91
|
+
if (!Number.isFinite(at) || at <= 0) return "";
|
|
92
|
+
const date = new Date(at);
|
|
93
|
+
const day = calendarDay(date);
|
|
94
|
+
if (day === calendarDay(new Date(now))) return formatClock(date);
|
|
95
|
+
const today = new Date(now);
|
|
96
|
+
// Noon of the previous calendar day: a 23- or 25-hour day around DST cannot move it to another day.
|
|
97
|
+
if (day === calendarDay(new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1, 12))) return yesterday;
|
|
98
|
+
const sixDaysBack = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 6).getTime();
|
|
99
|
+
if (at >= sixDaysBack && at <= now) return formatWeekdayShort(date);
|
|
100
|
+
return formatMonthDay(date);
|
|
101
|
+
}
|
|
35
102
|
|
|
36
103
|
function titleOf(room: RecordValue, business: boolean): string {
|
|
37
104
|
const display = text(object(room.displayData).name);
|
|
@@ -39,30 +106,53 @@ function titleOf(room: RecordValue, business: boolean): string {
|
|
|
39
106
|
return display;
|
|
40
107
|
}
|
|
41
108
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
109
|
+
export interface InboxRowsOptions {
|
|
110
|
+
/** `inbox` (default): archived rooms are dropped. `archive`: the list is the archive, every room is kept and marked
|
|
111
|
+
* archived. `all`: search results, kept as they are. */
|
|
112
|
+
scope?: "inbox" | "archive" | "all";
|
|
113
|
+
/** The localised word for yesterday; "Yesterday" when absent. */
|
|
114
|
+
yesterday?: string;
|
|
115
|
+
now?: number;
|
|
116
|
+
/** Rooms the server lists as unread (`unreadChatroomIds`): a room the member marked unread has no count, only this. */
|
|
117
|
+
unreadIds?: ReadonlySet<string>;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Newest conversation first; rooms without an id are dropped, and so are archived rooms in the inbox. `fallbackTitle`
|
|
121
|
+
* names a room that carries no name (the caller passes the localised word, not a hard-coded English one). */
|
|
122
|
+
export function inboxRows(rooms: unknown[], fallbackTitle: string, options: InboxRowsOptions = {}): InboxRow[] {
|
|
123
|
+
const { scope = "inbox", yesterday = "Yesterday", now, unreadIds } = options;
|
|
45
124
|
const rows: InboxRow[] = [];
|
|
46
125
|
for (const value of rooms) {
|
|
47
126
|
const room = object(value);
|
|
48
127
|
const id = text(room.id);
|
|
49
|
-
if (!id
|
|
128
|
+
if (!id) continue;
|
|
129
|
+
if (scope === "inbox" && room.isArchived === true) continue;
|
|
50
130
|
const business = isBusinessRoom(room);
|
|
51
131
|
const title = titleOf(room, business) || fallbackTitle;
|
|
52
132
|
const last = object(room.lastMessage);
|
|
53
|
-
const
|
|
54
|
-
|
|
133
|
+
const count = typeof room.unreadCount === "number" && Number.isFinite(room.unreadCount) && room.unreadCount > 0 ? Math.floor(room.unreadCount) : 0;
|
|
134
|
+
const at = typeof last.createdAt === "number" ? last.createdAt : typeof room.createdAt === "number" ? room.createdAt : 0;
|
|
135
|
+
rows.push(completeRow({
|
|
55
136
|
id,
|
|
56
137
|
title,
|
|
57
138
|
subtitle: text(last.summary),
|
|
58
|
-
screenId: business ?
|
|
139
|
+
screenId: business ? BUSINESS_SCREEN : "himi_chat_thread",
|
|
59
140
|
kind: business ? "" : "chatroom",
|
|
60
141
|
photo: text(object(object(room.displayData).image).url),
|
|
61
142
|
initial: (title[0] ?? "#").toUpperCase(),
|
|
62
|
-
unread,
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
143
|
+
unread: count > 0 || unreadIds?.has(id) === true,
|
|
144
|
+
unreadCount: count,
|
|
145
|
+
dateLabel: dateLabel(at, yesterday, now),
|
|
146
|
+
isArchived: scope === "archive" || room.isArchived === true,
|
|
147
|
+
isPrivate: room.isPrivate === true,
|
|
148
|
+
at,
|
|
149
|
+
}));
|
|
66
150
|
}
|
|
67
151
|
return rows.sort((a, b) => b.at - a.at);
|
|
68
152
|
}
|
|
153
|
+
|
|
154
|
+
/** The newest message sequence a room's list entry carries, when it carries one (marking a room read needs it). */
|
|
155
|
+
export function lastSequenceOf(value: unknown): number | undefined {
|
|
156
|
+
const sequence = object(object(value).lastMessage).sequence;
|
|
157
|
+
return typeof sequence === "number" && Number.isSafeInteger(sequence) && sequence >= 0 ? sequence : undefined;
|
|
158
|
+
}
|