@wix/himalaya-cli 0.1648.0 → 0.1650.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/sdk/ui/src/index.d.ts +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/ui.mjs +1 -0
- package/dist/browser-plane/assets.json +5 -5
- package/dist/browser-plane/preview-deferred/{4ef4d326496b4d7809746936207067b4c921f5db9878ecc7030aa3a9e4d2aaeb.bin → 6ba3f2eb2ac29f4f9eeebd1294a8003820cd260274c5400149d76833b3171555.bin} +1 -1
- package/dist/browser-plane/sw.js +5 -5
- package/dist/cli.mjs +45 -40
- package/dist/preview-assets.generated.bin +0 -0
- package/guides/sdk-reference.json +8 -1
- package/package.json +2 -2
- package/template-icons/wholesale-store.png +0 -0
- package/templates/beauty-salon/config.ts +16 -1
- package/templates/branded-lite/config.ts +16 -1
- package/templates/branded-lite/dev/index.ts +292 -305
- package/templates/branded-lite/l10n/en.json +3 -3
- package/templates/branded-lite/tier5-src/_shared/branded-form.ts +22 -4
- package/templates/branded-lite/tier5-src/himi-branded-lite-form/index.ts +250 -74
- package/templates/community-club/config.ts +16 -1
- package/templates/events-meetups/config.ts +16 -1
- package/templates/gym-fitness/config.ts +16 -1
- package/templates/nonprofit-cause/config.ts +16 -1
- package/templates/podcast-creator/config.ts +16 -1
- package/templates/portfolio-creative/config.ts +16 -1
- package/templates/restaurant/config.ts +16 -1
- package/templates/retail-store/config.ts +16 -1
- package/templates/wholesale-store/README.md +53 -0
- package/templates/wholesale-store/config.ts +247 -0
- package/templates/wholesale-store/dev/index.ts +12194 -0
- package/templates/wholesale-store/himalaya.content.json +43 -0
- package/templates/wholesale-store/himalaya.template.json +14 -0
- package/templates/wholesale-store/icon.png +0 -0
- package/templates/wholesale-store/platforms.json +1 -0
- package/templates/wholesale-store/tier5-src/_shared/app-locale.ts +61 -0
- package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +279 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-copy.ts +40 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-history.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-model.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-presenter.ts +576 -0
- package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +148 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-contract.ts +228 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +194 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +252 -0
- package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +423 -0
- package/templates/wholesale-store/tier5-src/_shared/detail-presence.ts +51 -0
- package/templates/wholesale-store/tier5-src/_shared/empty-flags.ts +33 -0
- package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +508 -0
- package/templates/wholesale-store/tier5-src/_shared/exclusive-writes.ts +66 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-account.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-copy.ts +89 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-categories.ts +108 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +22 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +57 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-store.ts +7 -0
- package/templates/wholesale-store/tier5-src/_shared/himi-text.ts +24 -0
- package/templates/wholesale-store/tier5-src/_shared/hosted-checkout.ts +70 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-presentation.ts +207 -0
- package/templates/wholesale-store/tier5-src/_shared/iap-worker.ts +125 -0
- package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +68 -0
- package/templates/wholesale-store/tier5-src/_shared/live-session.ts +172 -0
- package/templates/wholesale-store/tier5-src/_shared/local-preferences.ts +38 -0
- package/templates/wholesale-store/tier5-src/_shared/member-access.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-account-routes.ts +52 -0
- package/templates/wholesale-store/tier5-src/_shared/member-orders.ts +8 -0
- package/templates/wholesale-store/tier5-src/_shared/member-screen.ts +99 -0
- package/templates/wholesale-store/tier5-src/_shared/online-actions.ts +76 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-editor-value.ts +164 -0
- package/templates/wholesale-store/tier5-src/_shared/owner-load-error.ts +348 -0
- package/templates/wholesale-store/tier5-src/_shared/payment-setup.ts +6 -0
- package/templates/wholesale-store/tier5-src/_shared/read-service.ts +255 -0
- package/templates/wholesale-store/tier5-src/_shared/restaurant-ordering.ts +201 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-body.ts +78 -0
- package/templates/wholesale-store/tier5-src/_shared/rich-content-link.ts +34 -0
- package/templates/wholesale-store/tier5-src/_shared/sign-in-sheet.ts +18 -0
- package/templates/wholesale-store/tier5-src/_shared/store-order-presentation.ts +56 -0
- package/templates/wholesale-store/tier5-src/_shared/store-product-info.ts +50 -0
- package/templates/wholesale-store/tier5-src/business-chat/index.ts +724 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +602 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-order/index.ts +472 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-orders/index.ts +327 -0
- package/templates/wholesale-store/tier5-src/himi-store-account/index.ts +998 -0
- package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +889 -0
- package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +68 -0
- package/templates/wholesale-store/tier5-src/himi-store-shop/index.ts +150 -0
- package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +507 -0
- package/templates/wholesale-store/tier5-src/wix-spaces-collection-detail/index.ts +195 -0
- package/templates/wholesale-store/tokens.json +340 -0
- package/templates/yoga-studio/config.ts +16 -1
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { copyParam } from "./himi-copy.js";
|
|
2
|
+
|
|
3
|
+
/** Host-owned preview input. Absent on native and older hosts.
|
|
4
|
+
*
|
|
5
|
+
* `"sample"` — the built-in demo records; `"live"` — the viewer's own business over the
|
|
6
|
+
* owner rung; `"fixtures"` — a DEV web host over a sealed hermetic gateway, where
|
|
7
|
+
* the dev fixtures are the sample data. `"fixtures"` is neither live nor demo, so a
|
|
8
|
+
* worker READS through the bridge as it does on a device; it is still a preview host
|
|
9
|
+
* (`isOwnerPreviewHost`), so failure copy may name the web preview. */
|
|
10
|
+
function ownerPreviewMode(): unknown {
|
|
11
|
+
return (globalThis as unknown as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input?.__himiOwnerPreview;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function isOwnerPreviewLive(): boolean {
|
|
15
|
+
return ownerPreviewMode() === "live";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Whether we are in the web preview AT ALL — i.e. the host declared a mode.
|
|
20
|
+
*
|
|
21
|
+
* `isBridgeUnavailable` cannot answer this: it reads "not live" as "preview",
|
|
22
|
+
* and on NATIVE there is no input at all, so `undefined` satisfies it. That is
|
|
23
|
+
* left alone for the other apps that use it to pick a demo fallback or to queue
|
|
24
|
+
* a write. Owner-lite reads ask `ownerDemoFallback` instead. It is NOT
|
|
25
|
+
* harmless for choosing COPY: native workers format their failures the same way (`"HTTP \(code): \(body)"`, JSWorker.swift;
|
|
26
|
+
* `"HTTP ${e.code}: ..."`, WebViewJSWorker.kt), so a transient `HTTP 503` on a
|
|
27
|
+
* phone would otherwise be answered with "open this app on a device" — on the
|
|
28
|
+
* device. Callers that pick a SENTENCE ask this instead.
|
|
29
|
+
*/
|
|
30
|
+
export function isOwnerPreviewHost(): boolean {
|
|
31
|
+
return ownerPreviewMode() !== undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function isOwnerPreviewDemo(): boolean {
|
|
35
|
+
return ownerPreviewMode() === "sample";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Legacy hosts can still request the old demo fallback. An explicit live
|
|
39
|
+
* preview must never replace an authentication failure or outage with samples. */
|
|
40
|
+
export function isBridgeUnavailable(e: unknown): boolean {
|
|
41
|
+
if (ownerPreviewMode() === "live") return false;
|
|
42
|
+
return /HTTP (405|501|502|503)\b/.test(String((e as Error)?.message ?? e));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Whether a failed owner-lite READ may answer with the built-in demo records.
|
|
47
|
+
*
|
|
48
|
+
* Only where a demo was asked for: a web preview host that is not live. On a phone no
|
|
49
|
+
* mode is injected, so `isBridgeUnavailable` alone is `true` for a transient Wix
|
|
50
|
+
* `HTTP 503` — and the owner was shown sample appointments, orders and sites as if
|
|
51
|
+
* they were their business. Native falls through to the screen's error state.
|
|
52
|
+
* `isBridgeUnavailable` keeps its semantics: other apps' callers depend on it.
|
|
53
|
+
*/
|
|
54
|
+
export function ownerDemoFallback(e: unknown): boolean {
|
|
55
|
+
return isOwnerPreviewHost() && !isOwnerPreviewLive() && isBridgeUnavailable(e);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The sentence for an owner WRITE that failed because the device could not reach Wix at
|
|
60
|
+
* all (a transport failure). Nothing replays a queued write on any platform — every host's
|
|
61
|
+
* `drain` passes an empty closure — so the honest answer is that nothing was saved.
|
|
62
|
+
* Copy-as-configuration under `ownerCommon.`, which every owner screen forwards.
|
|
63
|
+
*/
|
|
64
|
+
export function ownerOfflineNotSaved(): string {
|
|
65
|
+
return copyParam(
|
|
66
|
+
"ownerCommon.offlineNotSaved",
|
|
67
|
+
"You’re offline — nothing was saved. Try again when you reconnect.",
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The sentence for an owner WRITE that Wix answered with an unavailable status: the
|
|
72
|
+
* device is online, so it is not "offline" — but nothing was saved all the same. */
|
|
73
|
+
/**
|
|
74
|
+
* Whether a failed WRITE may have landed on Wix anyway, so the user must not be told it
|
|
75
|
+
* was not saved: a transport failure mid-request (timeout, reset, fetch rejection), the web
|
|
76
|
+
* host's after-send envelope (`HTTP 502 {…"sent":true}`), the serve bridge's mid-request
|
|
77
|
+
* `webwix_bridge_upstream_failed`, or a gateway status (502/503/504) that can arrive after
|
|
78
|
+
* the backend already ran. Only connect-time failures (`isOfflineFailure`) and the designed
|
|
79
|
+
* 405/501 bridge refusals prove nothing happened.
|
|
80
|
+
*/
|
|
81
|
+
export function writeMayHaveLanded(e: unknown): boolean {
|
|
82
|
+
if (isOfflineFailure(e)) return false;
|
|
83
|
+
if (isTransportFailure(e)) return true;
|
|
84
|
+
const msg = String((e as Error)?.message ?? e ?? "");
|
|
85
|
+
if (/"sent"\s*:\s*true/.test(msg)) return true;
|
|
86
|
+
// The web host's own envelope WITHOUT `sent: true` failed before the request left it, and
|
|
87
|
+
// a disabled owner rung / bridge refuses by design without sending anything.
|
|
88
|
+
if (/\bwebwix_(?:direct_failed|owner_disabled|bridge_disabled)\b/.test(msg)) return false;
|
|
89
|
+
// `webwix_bridge_upstream_failed` stays ambiguous: the same code covers a lookup that failed
|
|
90
|
+
// before sending and a serve-bridge failure mid-request, and nothing in it says which.
|
|
91
|
+
return /\bwebwix_bridge_upstream_failed\b/.test(msg) || /HTTP (502|503|504)\b/.test(msg);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Wix answered that the record does not exist (`HTTP 404`). A detail must not fall back to
|
|
95
|
+
* its cached row then: that row is what a delete whose reply was lost leaves behind. */
|
|
96
|
+
export function isNotFound(e: unknown): boolean {
|
|
97
|
+
if (/HTTP 404\b/.test(String((e as Error)?.message ?? e ?? ""))) return true;
|
|
98
|
+
// An SDK that answers a 404 with its own "not found" error keeps the HTTP one as `cause`
|
|
99
|
+
// (the blog SDK's getPost, after its query fallback also finds nothing).
|
|
100
|
+
const cause = (e as { cause?: unknown } | null | undefined)?.cause;
|
|
101
|
+
return cause !== undefined && cause !== e && /HTTP 404\b/.test(String((cause as Error)?.message ?? cause));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function ownerUnavailableNotSaved(): string {
|
|
105
|
+
return copyParam(
|
|
106
|
+
"ownerCommon.unavailableNotSaved",
|
|
107
|
+
"Wix isn’t available right now — nothing was saved. Try again in a moment.",
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The sentence for an owner WRITE that may have landed (`writeMayHaveLanded`): it can't
|
|
112
|
+
* be called saved or not saved. */
|
|
113
|
+
export function ownerWriteUnconfirmed(): string {
|
|
114
|
+
return copyParam(
|
|
115
|
+
"ownerCommon.writeUnconfirmed",
|
|
116
|
+
"Wix didn’t confirm this, so it may or may not have been saved. Check before trying again.",
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Display copy for a failed owner write: `ownerOfflineNotSaved` when the request never
|
|
121
|
+
* left the device, `ownerWriteUnconfirmed` when it may have landed, `ownerUnavailableNotSaved`
|
|
122
|
+
* for the designed 405/501 bridge refusals outside a live preview, else `ownerLoadError`. */
|
|
123
|
+
export function ownerWriteError(e: unknown): string {
|
|
124
|
+
if (isOfflineFailure(e)) return ownerOfflineNotSaved();
|
|
125
|
+
if (writeMayHaveLanded(e)) return ownerWriteUnconfirmed();
|
|
126
|
+
if (!isOwnerPreviewLive() && /HTTP (405|501)\b/.test(String((e as Error)?.message ?? e))) return ownerUnavailableNotSaved();
|
|
127
|
+
return ownerLoadError(e);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `HTTP 403: …` → "403", when the message carries a status at all. */
|
|
131
|
+
const STATUS = /HTTP (\d{3})\b/;
|
|
132
|
+
/** A wire body that is an HTML DOCUMENT, not a message. */
|
|
133
|
+
const HTML_BODY = /<!DOCTYPE html|<html[\s>]|<head[\s>]/i;
|
|
134
|
+
/** A wire body that is a JSON ENVELOPE, not a message. The serve bridge answers
|
|
135
|
+
* its typed refusals this way — `HTTP 501: {"error":"webwix_owner_no_session",
|
|
136
|
+
* "app":"…"}` — and it is short enough to slip under MAX_RAW, so truncation
|
|
137
|
+
* never caught it and the owner read the machine's word for it. */
|
|
138
|
+
const JSON_BODY = /HTTP \d{3}:\s*[[{]/;
|
|
139
|
+
/** `HTTP <status> [SERVICE_CODE]: message` — the shape a Wix service uses when
|
|
140
|
+
* it refuses with a named reason. */
|
|
141
|
+
const CODED = /HTTP (\d{3}) \[([A-Z0-9_]+)\]/;
|
|
142
|
+
/**
|
|
143
|
+
* The codes that all mean one thing to an owner: the session cannot address this
|
|
144
|
+
* business. Found on a real session whose account did not own the business the app
|
|
145
|
+
* had persisted — Home rendered
|
|
146
|
+
* `HTTP 428 [MISSING_METASITE_ID]: Couldn't extract metasiteId from the request
|
|
147
|
+
* context` where "6 orders" belongs.
|
|
148
|
+
*/
|
|
149
|
+
const SITE_CONTEXT_CODES = ["MISSING_METASITE_ID", "MISSING_REQUEST_SITE_CONTEXT", "MISSING_SITE_CONTEXT"];
|
|
150
|
+
/** Longest raw upstream text worth showing. Beyond this it stops being a
|
|
151
|
+
* message and starts being a payload dump. */
|
|
152
|
+
const MAX_RAW = 200;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* A TRANSPORT failure: the request never got an HTTP answer at all.
|
|
156
|
+
*
|
|
157
|
+
* Each host describes one in its own platform's words, and every one of them is a
|
|
158
|
+
* diagnostic dump rather than a message. iOS's JSWorker hands a worker the Swift
|
|
159
|
+
* description of the `NSError` —
|
|
160
|
+
* `Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server."
|
|
161
|
+
* UserInfo={… NSErrorFailingURLStringKey=http://127.0.0.1:8178/__dev/wix/proxy, …}`
|
|
162
|
+
* — which Aria painted verbatim: the domain, the code, and the local server's
|
|
163
|
+
* own URL. Android's bridge carries the `java.net` exception text, and a browser's
|
|
164
|
+
* fetch rejects with "Failed to fetch" / "Load failed" / "NetworkError …".
|
|
165
|
+
*
|
|
166
|
+
* Only a message with NO HTTP status qualifies: a status means Wix answered, and
|
|
167
|
+
* that case keeps its own reductions below.
|
|
168
|
+
*/
|
|
169
|
+
const TRANSPORT = [
|
|
170
|
+
/\bError Domain=\w+/, // any Cocoa NSError description
|
|
171
|
+
/\bNSURLErrorDomain\b/,
|
|
172
|
+
/\bjava\.(?:net|io)\.\w+(?:Exception|Error)\b/,
|
|
173
|
+
/\b(?:UnknownHost|Connect|SocketTimeout|NoRouteToHost|SSLHandshake)Exception\b/,
|
|
174
|
+
// Android's WebViewJSWorker bridges `e.message ?: e.javaClass.simpleName`, so
|
|
175
|
+
// the class name is usually absent and only OkHttp's own message arrives.
|
|
176
|
+
/^Failed to connect to \S/,
|
|
177
|
+
/^Unable to resolve host\b/,
|
|
178
|
+
/\b(?:Connection refused|Network is unreachable|Software caused connection abort)\b/,
|
|
179
|
+
// OkHttp / HttpURLConnection messages a dropped connection produces mid-request, which
|
|
180
|
+
// Android's bridge forwards without the exception class.
|
|
181
|
+
/\b(?:Connection reset|ECONNRESET|ETIMEDOUT|EPIPE|Broken pipe|stream was reset)\b/,
|
|
182
|
+
/^unexpected end of stream\b/i,
|
|
183
|
+
/^(?:timeout|Read timed out|connect timed out)$/i,
|
|
184
|
+
/\bFailed to fetch\b/,
|
|
185
|
+
/\bNetworkError when attempting to fetch\b/,
|
|
186
|
+
/^(?:TypeError: )?Load failed$/,
|
|
187
|
+
/\bnet::ERR_[A-Z_]+/,
|
|
188
|
+
];
|
|
189
|
+
|
|
190
|
+
/** Did this failure happen below HTTP — no answer from Wix at all? */
|
|
191
|
+
export function isTransportFailure(e: unknown): boolean {
|
|
192
|
+
const msg = String((e as Error)?.message ?? e ?? "");
|
|
193
|
+
if (STATUS.test(msg)) return false;
|
|
194
|
+
return TRANSPORT.some((re) => re.test(msg));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** A failed READ says nothing about the record's existence when Wix is
|
|
198
|
+
* unreachable, overloaded or failing. Unlike the legacy bridge predicate this
|
|
199
|
+
* is independent of preview mode; a live preview's gateway failure is one too. */
|
|
200
|
+
export function readWasUnreachable(e: unknown): boolean {
|
|
201
|
+
const msg = String((e as Error)?.message ?? e ?? "");
|
|
202
|
+
return isTransportFailure(e) || /HTTP (?:408|429|5\d{2})\b/.test(msg);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Transport failures that happen while CONNECTING — no connection, no route, no such host,
|
|
206
|
+
* connection refused — so the request provably never left the device. Every other
|
|
207
|
+
* transport failure (a timeout, a reset, a bad or truncated response, a browser's fetch
|
|
208
|
+
* rejection, which says nothing about when it failed) may come after Wix took the write. */
|
|
209
|
+
const NEVER_SENT = [
|
|
210
|
+
/\bNSURLErrorDomain Code=-10(?:09|04|03|06|20|18)\b/, // not connected / cannot connect / no host / DNS / data not allowed / roaming off
|
|
211
|
+
/\b(?:UnknownHost|Connect|NoRouteToHost)Exception\b/,
|
|
212
|
+
/^Failed to connect to \S/,
|
|
213
|
+
/^Unable to resolve host\b/,
|
|
214
|
+
/\b(?:Connection refused|Network is unreachable)\b/,
|
|
215
|
+
/\bnet::ERR_(?:INTERNET_DISCONNECTED|NAME_NOT_RESOLVED|CONNECTION_REFUSED|ADDRESS_UNREACHABLE|NETWORK_ACCESS_DENIED)\b/,
|
|
216
|
+
];
|
|
217
|
+
|
|
218
|
+
/** No HTTP answer, and the request provably never left the device: the user is offline, and
|
|
219
|
+
* a write certainly did not happen. Anything else may have landed (see `NEVER_SENT`). */
|
|
220
|
+
export function isOfflineFailure(e: unknown): boolean {
|
|
221
|
+
if (!isTransportFailure(e)) return false;
|
|
222
|
+
const msg = String((e as Error)?.message ?? e ?? "");
|
|
223
|
+
return NEVER_SENT.some((re) => re.test(msg));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The one sentence for a transport failure. Copy-as-configuration: the key is
|
|
227
|
+
* under `ownerCommon.`, which every owner screen (Aria included) forwards. */
|
|
228
|
+
export function ownerTransportFailureText(): string {
|
|
229
|
+
return copyParam(
|
|
230
|
+
"ownerCommon.networkUnreachable",
|
|
231
|
+
"Couldn’t reach Wix. Check your connection and try again.",
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Reduce a wire failure to something a PERSON can read.
|
|
237
|
+
*
|
|
238
|
+
* Wix's edge answers some failures with a full HTML error page rather than JSON
|
|
239
|
+
* — a `403 Error: Forbidden | Wix.com` document. `ownerLoadError` used to return
|
|
240
|
+
* the raw body, so the Orders screen rendered an entire `<!DOCTYPE html>…<head>…`
|
|
241
|
+
* document as its error message (seen on iOS, and the same worker code runs on
|
|
242
|
+
* every surface). Keep the STATUS, which is the diagnosable part, and drop the
|
|
243
|
+
* markup; a long non-HTML body is truncated for the same reason.
|
|
244
|
+
*/
|
|
245
|
+
function humanWireError(msg: string): string {
|
|
246
|
+
if (isTransportFailure(msg)) return ownerTransportFailureText();
|
|
247
|
+
const status = STATUS.exec(msg)?.[1];
|
|
248
|
+
// A JSON ENVELOPE or a NAMED REASON CODE is the machine's word for it, and the
|
|
249
|
+
// owner gets neither. Both reductions used to live in `ownerDisplayError` only,
|
|
250
|
+
// on the belief that this function's output was parsed downstream — see the note
|
|
251
|
+
// on `ownerLoadError`, which records why that was wrong and how it was checked.
|
|
252
|
+
if (JSON_BODY.test(msg) && status) {
|
|
253
|
+
return copyParam(
|
|
254
|
+
"ownerCommon.upstreamStatus",
|
|
255
|
+
`Wix returned an error (HTTP ${status}). Try again in a moment.`,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const coded = CODED.exec(msg);
|
|
259
|
+
if (coded) {
|
|
260
|
+
if (SITE_CONTEXT_CODES.includes(coded[2])) {
|
|
261
|
+
return copyParam(
|
|
262
|
+
"ownerCommon.noSiteContext",
|
|
263
|
+
"This business isn’t available to your Wix account right now. Switch business, or sign in again as its owner.",
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
return copyParam(
|
|
267
|
+
"ownerCommon.upstreamStatus",
|
|
268
|
+
`Wix returned an error (HTTP ${coded[1]}). Try again in a moment.`,
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
if (HTML_BODY.test(msg)) {
|
|
272
|
+
if (status === "403") {
|
|
273
|
+
return copyParam(
|
|
274
|
+
"ownerCommon.forbidden",
|
|
275
|
+
"This account isn’t permitted to read that. Check the site’s permissions for your Wix user, then try again.",
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
return copyParam(
|
|
279
|
+
"ownerCommon.upstreamHtml",
|
|
280
|
+
status ? `Wix returned an error (HTTP ${status}). Try again in a moment.` : "Wix returned an unreadable error. Try again in a moment.",
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
return msg.length > MAX_RAW ? `${msg.slice(0, MAX_RAW).trimEnd()}…` : msg;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The one sentence every owner screen gives for the DESIGNED bridge boundary.
|
|
288
|
+
*
|
|
289
|
+
* Copy-as-configuration (himi-copy): the key lives under the `ownerCommon.`
|
|
290
|
+
* prefix the dev module forwards to all owner screens, so one pack retitles it
|
|
291
|
+
* everywhere. With no pack this returns the stock copy verbatim.
|
|
292
|
+
*/
|
|
293
|
+
export function ownerPreviewUnavailable(): string {
|
|
294
|
+
return copyParam(
|
|
295
|
+
"ownerCommon.bridgeUnavailable",
|
|
296
|
+
"Owner data isn’t available in the web preview — open this app on a device (▦ Open on phone) and sign in as the site owner.",
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* `ownerLoadError` for a screen that does nothing but RENDER the string.
|
|
302
|
+
*
|
|
303
|
+
* One difference left, and it is about WHERE the app is rather than what the
|
|
304
|
+
* error says: this names the web preview when there IS one. `isBridgeUnavailable`
|
|
305
|
+
* reads "not live" as "preview", and native injects no mode at all, so the
|
|
306
|
+
* default would answer a device-side `HTTP 503` with "open this app on a device"
|
|
307
|
+
* — on the device. That predicate is deliberately left alone: other apps'
|
|
308
|
+
* demo and write-queue decisions depend on exactly it.
|
|
309
|
+
*
|
|
310
|
+
* The reductions this used to add are now in `humanWireError`, so every owner
|
|
311
|
+
* screen gets them rather than the two that happened to call this.
|
|
312
|
+
*/
|
|
313
|
+
export function ownerDisplayError(e: unknown): string {
|
|
314
|
+
if (isOwnerPreviewHost() && isBridgeUnavailable(e)) return ownerPreviewUnavailable();
|
|
315
|
+
return humanWireError(String((e as Error)?.message ?? e));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The default. Reduces the same shapes as `ownerDisplayError`.
|
|
320
|
+
*
|
|
321
|
+
* It used to reduce LESS, on the stated grounds that its output is parsed
|
|
322
|
+
* downstream — "the products worker matches `CATALOG_V3_CALLING_CATALOG_V1_API`
|
|
323
|
+
* in it to choose its v1 fallback". **That was not true**, and it cost 17 owner
|
|
324
|
+
* screens their error copy: they printed `HTTP 428 [MISSING_METASITE_ID]: …`
|
|
325
|
+
* verbatim for a contract that does not exist.
|
|
326
|
+
*
|
|
327
|
+
* Checked before changing it, and worth recording so nobody restores the belief:
|
|
328
|
+
*
|
|
329
|
+
* • the catalog v1/v3 decision is made INSIDE the Wix stores SDK, on the RAW
|
|
330
|
+
* thrown error — its `catalogVersionFromMismatch` reads the error's own
|
|
331
|
+
* `message`, and only that module calls it. It never sees this function's
|
|
332
|
+
* output.
|
|
333
|
+
* • `CATALOG_V3_CALLING_CATALOG_V1_API` appears nowhere else in the codebase
|
|
334
|
+
* outside comments, tests and that one SDK module.
|
|
335
|
+
* • the collection framework's `clearOnError` is handed the RAW error
|
|
336
|
+
* (`error => /401|403|forbidden/i.test(String(error))`), separately from
|
|
337
|
+
* `errorMessage: ownerLoadError` — so the one place that does match on a
|
|
338
|
+
* failure is unaffected by what this returns.
|
|
339
|
+
*
|
|
340
|
+
* So: the raw error remains available to logic everywhere it was; this function's
|
|
341
|
+
* result is display copy, and now reads like it.
|
|
342
|
+
*/
|
|
343
|
+
export function ownerLoadError(e: unknown): string {
|
|
344
|
+
const msg = String((e as Error)?.message ?? e);
|
|
345
|
+
// Same host guard as `ownerDisplayError`: on a phone, "open this app on a device" is false.
|
|
346
|
+
if (isOwnerPreviewHost() && isBridgeUnavailable(e)) return ownerPreviewUnavailable();
|
|
347
|
+
return humanWireError(msg);
|
|
348
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { copyParam } from "./himi-copy.js";
|
|
2
|
+
|
|
3
|
+
/** No provider or country guess: Wix only established that online payment is unavailable. */
|
|
4
|
+
export function paymentSetupMessage(prefix: string): string {
|
|
5
|
+
return copyParam(`${prefix}.paymentSetupUnavailable`, "This site is not accepting online payments. Go back or contact the business for other payment options.");
|
|
6
|
+
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { stashCopy } from './himi-copy.js';
|
|
2
|
+
const offlineReadsEnabled = true;
|
|
3
|
+
import { isNotFound } from './owner-load-error.js';
|
|
4
|
+
import { defineService as register, createReadController, initialReadStatus, type ServiceDefinition, type ReadMetadata, type ReadStatus } from '@himalaya/state';
|
|
5
|
+
|
|
6
|
+
export interface ReadOptions {
|
|
7
|
+
cache: 'only-if-cached' | 'reload';
|
|
8
|
+
onCacheResult(metadata: ReadMetadata): void;
|
|
9
|
+
}
|
|
10
|
+
/** Passed explicitly down the loader's call graph; never a process-global cache mode. */
|
|
11
|
+
export function readOptions(arg: unknown): ReadOptions | undefined {
|
|
12
|
+
return (arg as { __himiRead?: ReadOptions } | undefined)?.__himiRead;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Explicit request context for loaders with their own presentation state (e.g. IAP). */
|
|
16
|
+
export async function policyRead<T>(cache: ReadOptions['cache'], load: (options: ReadOptions) => Promise<T>, localResult?: (data: T) => boolean) {
|
|
17
|
+
let metadata: ReadMetadata | undefined;
|
|
18
|
+
const data = await load({ cache, onCacheResult(value) {
|
|
19
|
+
metadata = metadata ? { ...value, source: metadata.source === 'cache' || value.source === 'cache' ? 'cache' : 'network',
|
|
20
|
+
cacheable: metadata.cacheable && value.cacheable,
|
|
21
|
+
fetchedAt: Math.min(metadata.fetchedAt, value.fetchedAt),
|
|
22
|
+
expiresAt: Math.min(metadata.expiresAt ?? 0, value.expiresAt ?? 0) } : value;
|
|
23
|
+
} });
|
|
24
|
+
if (!metadata && localResult?.(data)) metadata = { source: 'local', cacheable: false, fetchedAt: Date.now() };
|
|
25
|
+
if (!metadata) throw new Error('Read loader did not provide response provenance');
|
|
26
|
+
return { data, metadata };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type State = Record<string, unknown>;
|
|
30
|
+
type Action = (state: State, arg?: unknown) => State | undefined | Promise<State | undefined>;
|
|
31
|
+
type ReadFailure = Error & { userMessage?: string; signInRequired?: boolean };
|
|
32
|
+
// A record Wix answers 404 for is gone (a delete whose reply was lost): its retained snapshot must
|
|
33
|
+
// not outlive it. Unlike `denied`, it leaves drafts and local controls alone.
|
|
34
|
+
const gone = (error: unknown) => isNotFound(error);
|
|
35
|
+
const denied = (error: unknown) => /HTTP (401|403)\b|forbidden|principal.changed|identity.changed|member access changed/i.test(String(error));
|
|
36
|
+
|
|
37
|
+
/** Adapts a read-only load reducer. Callers forward readOptions(arg) to every
|
|
38
|
+
* primary SDK read and let errors reject. Other actions remain ordinary reducers.
|
|
39
|
+
* The retained snapshot is in memory; persistence belongs exclusively to the
|
|
40
|
+
* policy-controlled Wix cache, never to generic worker hydration or local-db rows.
|
|
41
|
+
*/
|
|
42
|
+
export function withReadLifecycle(registerService: typeof register = register, loadAction = 'load', options: {
|
|
43
|
+
errorMessage?(error: unknown): string;
|
|
44
|
+
/** Only an authored create form or guest shell; never a server-derived fallback. */
|
|
45
|
+
localResult?(state: State): boolean;
|
|
46
|
+
/** Additional host-owned scope when a read explicitly addresses another site. */
|
|
47
|
+
scopeKey?(): string;
|
|
48
|
+
/** Clear module-owned read sidecars on identity loss, access denial, or disposal. */
|
|
49
|
+
onInvalidate?(): void;
|
|
50
|
+
/** Editable fields survive recovery once loaded, and edits during an initial read. */
|
|
51
|
+
preserveFields?: readonly string[];
|
|
52
|
+
unavailable?(state: State, status: ReadStatus): State;
|
|
53
|
+
/** Authored source content only; never return a network mirror or demo fallback here. */
|
|
54
|
+
authoredFallback?(state: State, status: ReadStatus): State | undefined;
|
|
55
|
+
} = {}): typeof register {
|
|
56
|
+
if (!offlineReadsEnabled) return registerService;
|
|
57
|
+
return ((name: string, definition: ServiceDefinition<State>) => {
|
|
58
|
+
if ((globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input?.__himiOwnerPreview === 'sample') return registerService(name, definition);
|
|
59
|
+
const load = definition.actions?.[loadAction] as Action | undefined;
|
|
60
|
+
if (!load || definition.readLifecycle) return registerService(name, definition);
|
|
61
|
+
let args: Record<string, unknown> = {}, key = '', page: State | undefined, read = initialReadStatus();
|
|
62
|
+
let replacePage = false;
|
|
63
|
+
let activeLoad: { promise: Promise<void>; revision: number } | undefined;
|
|
64
|
+
let startedState: State | undefined;
|
|
65
|
+
let hadSnapshot = false, accessRevoked = false, accessNeedsSignIn = false;
|
|
66
|
+
const localResult = options.localResult ?? (value => value.notFound === true);
|
|
67
|
+
let projectedState: State | undefined;
|
|
68
|
+
const editedFields = new Set<string>();
|
|
69
|
+
let service: { getState(): State; readChanged(): Promise<unknown> };
|
|
70
|
+
const project = (state: State): State => {
|
|
71
|
+
for (const field of options.preserveFields ?? []) {
|
|
72
|
+
if (projectedState && JSON.stringify(state[field]) !== JSON.stringify(projectedState[field])) editedFields.add(field);
|
|
73
|
+
}
|
|
74
|
+
const value: State = { ...state, ...(replacePage && page ? page : !read.hasSnapshot ? definition.state : {}), readStatus: read };
|
|
75
|
+
replacePage = false;
|
|
76
|
+
if (accessRevoked) for (const field of options.preserveFields ?? []) {
|
|
77
|
+
if (Object.prototype.hasOwnProperty.call(definition.state, field)) value[field] = definition.state[field];
|
|
78
|
+
else delete value[field];
|
|
79
|
+
}
|
|
80
|
+
// Drafts and local controls survive both missing snapshots and pending reads.
|
|
81
|
+
for (const field of accessRevoked ? [] : Object.keys(state)) {
|
|
82
|
+
if (options.preserveFields?.includes(field) && (hadSnapshot || editedFields.has(field))) value[field] = state[field];
|
|
83
|
+
if (/Draft$|^draft$|^quantity$|^selection$|^selected|^expandedIds$|^searchQuery$|^query$|^filter$|^sort$/.test(field) &&
|
|
84
|
+
(!read.hasSnapshot || (startedState && JSON.stringify(state[field]) !== JSON.stringify(startedState[field])))) value[field] = state[field];
|
|
85
|
+
}
|
|
86
|
+
if (!read.hasSnapshot) {
|
|
87
|
+
const authored = options.authoredFallback?.(value, read);
|
|
88
|
+
if (authored) return projectedState = { ...authored, readStatus: { ...read, hasLocalContent: true } };
|
|
89
|
+
const message = read.offline ? 'This content isn’t available offline. Connect to load it.' : read.error;
|
|
90
|
+
const unavailable = { ...value, status: read.refreshing ? 'loading' : 'error', isLoading: read.refreshing,
|
|
91
|
+
notLoading: !read.refreshing, busy: !read.refreshing, hideContent: true, errored: !read.refreshing, isErrored: !read.refreshing,
|
|
92
|
+
notErrored: read.refreshing, found: false, noEntity: true, hideNotFound: true, hideLoading: !read.refreshing, hideLoadError: read.refreshing, error: message, errorText: message, emptyText: message, noEmpty: true };
|
|
93
|
+
if (accessRevoked) Object.assign(unavailable, { readDenied: true, signInRequired: accessNeedsSignIn, noSignIn: !accessNeedsSignIn });
|
|
94
|
+
return projectedState = options.unavailable?.(unavailable, read) ?? unavailable;
|
|
95
|
+
}
|
|
96
|
+
return projectedState = definition.readPresentation?.(value) ?? value;
|
|
97
|
+
};
|
|
98
|
+
const perform = async (cache: ReadOptions['cache'], requestKey: string) => {
|
|
99
|
+
const requestArgs = requestKey ? JSON.parse(requestKey) as Record<string, unknown> : {};
|
|
100
|
+
return policyRead(cache, async readContext => {
|
|
101
|
+
const input = { ...(service?.getState() ?? definition.state), __himiRead: readContext } as State;
|
|
102
|
+
// Unavailable-state flags added by this adapter are presentation, not a failed
|
|
103
|
+
// domain read. A reducer that spreads its input must not inherit those flags
|
|
104
|
+
// and have its successful cached/local result rejected as another failure.
|
|
105
|
+
for (const field of ['errored', 'isErrored']) {
|
|
106
|
+
if (!Object.prototype.hasOwnProperty.call(definition.state, field)) delete input[field];
|
|
107
|
+
}
|
|
108
|
+
// An unsaved create form is authored local content. Its no-op loader must
|
|
109
|
+
// receive its declared status, not the adapter's temporary unavailable state.
|
|
110
|
+
if (!read.hasSnapshot && options.localResult?.(input)) input.status = definition.state.status;
|
|
111
|
+
const data = await load(input, { ...requestArgs, __himiRead: readContext });
|
|
112
|
+
if (!data || data.status === 'error' || data.errored === true || data.isErrored === true) {
|
|
113
|
+
const unauthorized = data?.signInRequired === true || /HTTP 401|unauthori[sz]ed|sign[\s-]?in/i.test(String(data?.error || data?.errorText || ''));
|
|
114
|
+
const failure = new Error(unauthorized ? 'HTTP 401 unauthorized' : data?.readDenied ? 'HTTP 403 forbidden' : 'Read failed') as ReadFailure;
|
|
115
|
+
failure.signInRequired = data?.signInRequired === true;
|
|
116
|
+
const userMessage = data?.error || data?.errorText || data?.emptyText;
|
|
117
|
+
if (typeof userMessage === 'string' && userMessage.trim()) failure.userMessage = userMessage.trim();
|
|
118
|
+
throw failure;
|
|
119
|
+
}
|
|
120
|
+
delete data.__himiRead;
|
|
121
|
+
return data;
|
|
122
|
+
}, localResult);
|
|
123
|
+
};
|
|
124
|
+
const controller = createReadController<State>({
|
|
125
|
+
allowLocal: true, cached: key => perform('only-if-cached', key), fetch: key => perform('reload', key), clearOnError(error) {
|
|
126
|
+
accessRevoked = denied(error);
|
|
127
|
+
accessNeedsSignIn = (error as ReadFailure | null)?.signInRequired === true || /HTTP 401|unauthori[sz]ed|sign[\s-]?in/i.test(String(error));
|
|
128
|
+
const clear = accessRevoked || gone(error);
|
|
129
|
+
if (clear) options.onInvalidate?.();
|
|
130
|
+
return clear;
|
|
131
|
+
}, errorMessage(error) {
|
|
132
|
+
return (error as ReadFailure | null)?.userMessage || options.errorMessage?.(error) || (accessNeedsSignIn ? 'Sign in to view this content.' : '') || '';
|
|
133
|
+
},
|
|
134
|
+
publish(data, status) {
|
|
135
|
+
// A failed revalidation republishes the controller's retained snapshot. The worker
|
|
136
|
+
// state can contain newer local changes (for example, another fetched page or a
|
|
137
|
+
// selected row), so do not replace that state with the older controller page on a
|
|
138
|
+
// stale/error publication. A first cached paint and a successful refresh still
|
|
139
|
+
// replace the visible read data.
|
|
140
|
+
replacePage = status.hasSnapshot && data !== undefined
|
|
141
|
+
&& (!page || (!status.refreshing && !status.stale && !status.error));
|
|
142
|
+
page = data;
|
|
143
|
+
read = status;
|
|
144
|
+
void service?.readChanged();
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
const host = (globalThis as { himalaya?: { __subscribeReadLifecycle?(listener: (signal: string) => void): () => void } }).himalaya;
|
|
148
|
+
let unsubscribeAdapter: (() => void) | undefined;
|
|
149
|
+
unsubscribeAdapter = host?.__subscribeReadLifecycle?.(signal => {
|
|
150
|
+
if (signal === 'dispose') { options.onInvalidate?.(); unsubscribeAdapter?.(); return; }
|
|
151
|
+
if (signal !== 'invalidate') return;
|
|
152
|
+
options.onInvalidate?.();
|
|
153
|
+
// Identity invalidation clears the controller's private snapshot, so the
|
|
154
|
+
// adapter must also forget that its form fields came from a prior user.
|
|
155
|
+
// Otherwise project() can preserve those fields while the host clears the
|
|
156
|
+
// shared read state.
|
|
157
|
+
hadSnapshot = false;
|
|
158
|
+
accessRevoked = true;
|
|
159
|
+
accessNeedsSignIn = false;
|
|
160
|
+
editedFields.clear();
|
|
161
|
+
page = undefined;
|
|
162
|
+
read = initialReadStatus();
|
|
163
|
+
replacePage = true;
|
|
164
|
+
void service?.readChanged();
|
|
165
|
+
});
|
|
166
|
+
const refresh: Action = async (_state, arg) => {
|
|
167
|
+
stashCopy(arg);
|
|
168
|
+
if (arg && typeof arg === 'object') {
|
|
169
|
+
args = { ...arg as Record<string, unknown> };
|
|
170
|
+
// Localized copy is presentation, not a different backend query.
|
|
171
|
+
delete args.copy;
|
|
172
|
+
}
|
|
173
|
+
const next = JSON.stringify({ ...((globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input ?? {}), ...args, ...(options.scopeKey ? { __readScope: options.scopeKey() } : {}) });
|
|
174
|
+
// Coalesce through the final state projection, not only the controller's
|
|
175
|
+
// network task. A module-scope load() and the host's boot/onAppear load()
|
|
176
|
+
// commonly join the same request; returning when the fetch settles lets the
|
|
177
|
+
// host snapshot the worker before the first caller's readChanged() publishes.
|
|
178
|
+
if (key === next && activeLoad && activeLoad.revision === controller.getRevision()) {
|
|
179
|
+
await activeLoad.promise;
|
|
180
|
+
await service?.readChanged();
|
|
181
|
+
return service?.getState();
|
|
182
|
+
}
|
|
183
|
+
hadSnapshot = read.hasSnapshot && key === next;
|
|
184
|
+
key = next;
|
|
185
|
+
startedState = service?.getState() ?? definition.state;
|
|
186
|
+
projectedState = startedState; editedFields.clear(); accessRevoked = false; accessNeedsSignIn = false;
|
|
187
|
+
const load = controller.load(key);
|
|
188
|
+
const revision = controller.getRevision();
|
|
189
|
+
const task = (async () => {
|
|
190
|
+
await load;
|
|
191
|
+
// Controller publications project through this service action. Await its final
|
|
192
|
+
// projection before resolving load/retry so hosts that serialize worker actions
|
|
193
|
+
// cannot render the pre-read state after the request has completed.
|
|
194
|
+
await service?.readChanged();
|
|
195
|
+
})();
|
|
196
|
+
const active = { promise: task, revision };
|
|
197
|
+
activeLoad = active;
|
|
198
|
+
try {
|
|
199
|
+
await task;
|
|
200
|
+
} finally { if (activeLoad === active) activeLoad = undefined; }
|
|
201
|
+
return await service?.getState();
|
|
202
|
+
};
|
|
203
|
+
service = registerService(name, { ...definition, readLifecycle: { refreshAction: 'refreshRead', statusPath: 'readStatus' },
|
|
204
|
+
state: { ...definition.state, readStatus: read },
|
|
205
|
+
actions: { ...definition.actions, ...(loadAction !== "refresh" && definition.actions?.refresh ? { refresh: () => controller.refresh().then(() => undefined) } : {}), [loadAction]: refresh, retry: () => controller.refresh().then(() => undefined),
|
|
206
|
+
refreshRead: refresh, readChanged: project },
|
|
207
|
+
});
|
|
208
|
+
return service;
|
|
209
|
+
}) as typeof register;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Generic services keep their existing behavior. A `load` action is not proof
|
|
213
|
+
// that it is a safe, cache-eligible read: local device state and writes often use
|
|
214
|
+
// that name too. Shared read helpers and opted-in screens register through
|
|
215
|
+
// withReadLifecycle explicitly.
|
|
216
|
+
export const defineService: typeof register = register;
|
|
217
|
+
/** Safe opt-in for a service whose load action is a cache-eligible read. */
|
|
218
|
+
export const readService: typeof register = withReadLifecycle();
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
/** Raw read escape hatch for an endpoint without a generated SDK binding. */
|
|
222
|
+
export async function rawRead<T>(method: string, path: string, body?: unknown, options?: ReadOptions): Promise<T> {
|
|
223
|
+
const api = (globalThis as any).himalaya?.wixApi;
|
|
224
|
+
if (!api) throw new Error('Wix bridge unavailable');
|
|
225
|
+
if (!options) return api.call(method, path, body) as Promise<T>;
|
|
226
|
+
if (!api.read) throw new Error('READ_LIFECYCLE_UNSUPPORTED');
|
|
227
|
+
const result = await api.read(method, path, body, undefined, { cache: options.cache });
|
|
228
|
+
options.onCacheResult(result.cache);
|
|
229
|
+
return result.data as T;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Editor recovery refreshes its read eligibility without replacing an open draft
|
|
233
|
+
* or its concurrency revision. Field values remain owned by the form until the
|
|
234
|
+
* user explicitly submits or reopens it. Only a new, unsaved form is local data. */
|
|
235
|
+
export function withFormReadLifecycle(registerService: typeof register = register): typeof register {
|
|
236
|
+
if (!offlineReadsEnabled) return registerService;
|
|
237
|
+
return ((name: string, definition: ServiceDefinition<State>) => withReadLifecycle(registerService, 'load', {
|
|
238
|
+
preserveFields: ['title', 'name', 'price', 'sku', 'visible', 'revision', 'category',
|
|
239
|
+
'description', 'originalDescription', 'descriptionMode', 'descriptionJson', 'descriptionDirty', 'descriptionEdits',
|
|
240
|
+
'when', 'location', 'excerpt', 'body', 'richContent', 'bodyJson', 'bodyDirty', 'bodyEdits',
|
|
241
|
+
'detailsOpen', 'coverUrl', 'originalCoverUrl', 'coverPreview', 'isFeatured',
|
|
242
|
+
'question', 'answer', 'answerFormat', 'answerMode', 'answerJson', 'answerDirty', 'answerEdits', 'categoryId', 'statusValue'],
|
|
243
|
+
localResult: value => value.mode === 'create' && !value.id,
|
|
244
|
+
})(name, definition)) as typeof register;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Server-derived state is never a generic worker snapshot; explicit drafts may persist. */
|
|
248
|
+
export function withReadPersistence(registerService: typeof register, draftFields: readonly string[] = []): typeof register {
|
|
249
|
+
if (!offlineReadsEnabled) return registerService;
|
|
250
|
+
return ((name: string, definition: ServiceDefinition<State>) => registerService(name, {
|
|
251
|
+
...definition,
|
|
252
|
+
notPersisted: [...new Set([...(definition.notPersisted ?? []),
|
|
253
|
+
...Object.keys(definition.state).filter(key => !draftFields.includes(key))])],
|
|
254
|
+
})) as typeof register;
|
|
255
|
+
}
|