@wix/himalaya-cli 0.1724.0 → 0.1726.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.
Files changed (69) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/iap/src/wix-payments-contract.d.ts +6 -4
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/location/src/index.d.ts +5 -3
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/on-device-ai/src/index.d.ts +19 -7
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/sdk-types/src/capabilities.generated.d.ts +1 -1
  5. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/checkout-source.d.ts +3 -0
  6. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-verticals/videos.d.ts +31 -1
  7. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/index.d.ts +1 -1
  8. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/audio-record.mjs +1 -1
  9. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/calendar.mjs +1 -1
  10. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/calls.mjs +1 -1
  11. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/contacts.mjs +1 -1
  12. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/iap-checkout.mjs +83 -9
  13. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/location.mjs +1 -1
  14. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/motion.mjs +1 -1
  15. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/on-device-ai.mjs +49 -3
  16. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/photos.mjs +1 -1
  17. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/screens.mjs +92 -2
  18. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdk-types.mjs +1 -1
  19. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/tasks.mjs +1 -1
  20. package/dist/browser-plane/assets.json +7 -7
  21. package/dist/browser-plane/preview-deferred/{a6e25c06d2a17ab2b5e34bf2b5965fa3ddd76ce3da32a036e546a60938130d7b.bin → 2df92277f550d6bf34ff43d15ae4a9082d012643a6bff39bd78724115505b716.bin} +1 -1
  22. package/dist/browser-plane/sw.js +8 -8
  23. package/dist/browser-plane/t5-frame.html +16 -0
  24. package/dist/browser-plane/t5-worker-frame.html +16 -0
  25. package/dist/cli.mjs +1830 -1480
  26. package/dist/preview-assets.generated.bin +0 -0
  27. package/fixtures/wix-canned.json +51 -0
  28. package/guides/capabilities.md +2 -2
  29. package/guides/headless-loop.md +2 -1
  30. package/guides/iap-products.md +2 -2
  31. package/guides/iap-screen-adoption.md +1 -1
  32. package/guides/one-app-section-mappings.md +2 -2
  33. package/guides/sdk-reference.json +36 -8
  34. package/guides/skill.md +1 -1
  35. package/guides/testing-himi-apps.md +4 -3
  36. package/guides/web-page-sdk-reference.md +1 -1
  37. package/package.json +2 -2
  38. package/templates/beauty-salon/l10n/en.json +2 -2
  39. package/templates/beauty-salon/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  40. package/templates/branded-lite/config.ts +14 -1
  41. package/templates/branded-lite/dev/index.ts +729 -2
  42. package/templates/branded-lite/himalaya.content.json +3 -0
  43. package/templates/branded-lite/l10n/en.json +93 -2
  44. package/templates/branded-lite/l10n/he.json +173 -0
  45. package/templates/branded-lite/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  46. package/templates/branded-lite/tier5-src/_shared/wix-file-share.ts +332 -0
  47. package/templates/branded-lite/tier5-src/himi-branded-lite-file-share/index.ts +635 -0
  48. package/templates/branded-lite/tier5-src/himi-branded-lite-video/index.ts +82 -12
  49. package/templates/community-club/l10n/en.json +2 -2
  50. package/templates/community-club/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  51. package/templates/conference/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  52. package/templates/events-meetups/l10n/en.json +2 -2
  53. package/templates/events-meetups/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  54. package/templates/gym-fitness/l10n/en.json +2 -2
  55. package/templates/gym-fitness/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  56. package/templates/nonprofit-cause/l10n/en.json +2 -2
  57. package/templates/nonprofit-cause/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  58. package/templates/podcast-creator/l10n/en.json +2 -2
  59. package/templates/podcast-creator/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  60. package/templates/portfolio-creative/l10n/en.json +2 -2
  61. package/templates/portfolio-creative/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  62. package/templates/restaurant/l10n/en.json +2 -2
  63. package/templates/restaurant/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  64. package/templates/retail-store/l10n/en.json +2 -2
  65. package/templates/retail-store/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  66. package/templates/salon-spa/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  67. package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +3 -2
  68. package/templates/yoga-studio/l10n/en.json +2 -2
  69. package/templates/yoga-studio/tier5-src/_shared/branded-lite-hosted.ts +3 -2
@@ -0,0 +1,635 @@
1
+ // himi-branded-lite-file-share — branded-lite "Documents" worker (Wix File Share).
2
+ //
3
+ // Reads the bound site's real File Share library through `_shared/wix-file-share.ts` with the
4
+ // visitor or member credential: folders and files, page by page, search, open, save, and upload
5
+ // where the library allows it. What a reader may see and do is decided by the File Share server
6
+ // on every call (folder permissions, member-only and paid-plan folders, who may download). The
7
+ // worker asks `authorize-actions` only to leave out a Save or Upload button the server would
8
+ // refuse; a hidden button is never the protection.
9
+ //
10
+ // IDENTITY. Every read captures who is signed in (`readAccess`) and drops its answer when the
11
+ // account changed while it was in flight, then reloads for the new account at the root. A
12
+ // reappearing screen keeps its folder only for the same reader. Download links are fetched at the
13
+ // moment of the tap.
14
+ //
15
+ // STATE. The runtime applies what an action RETURNS. So navigation, Open, Save and Upload return
16
+ // their in-progress state at once and finish in the background through `settleRead` / `settle`
17
+ // (the account-settings pattern); `load` (onAppear) awaits its read, because the host paints the
18
+ // state it returns. A newer read always wins: every answer carries its read's generation.
19
+ //
20
+ // NOT HERE, on purpose: creating, renaming, moving and deleting items, and folder permissions.
21
+ // The service has those calls, but they belong to the library's managers, and Wix's own member
22
+ // mobile section does not offer them either (wix-mobile-media-manager FileShare: list, search,
23
+ // download).
24
+ import { defineService } from "@himalaya/state";
25
+ import { download as downloadFile, export as exportFile, isFilesError, readBase64, remove as removeFile, type FileHandle } from "@himalaya/files";
26
+ import { pickDetailed } from "@himalaya/file-picker";
27
+ import { open as openUrl } from "@himalaya/open-url";
28
+ import { put as uploadPut } from "@himalaya/presigned-upload";
29
+ import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
30
+ import { assertReadAccess, readAccess, type ReadAccess } from "../_shared/member-read.js";
31
+ import {
32
+ UPLOAD_MAX_BYTES,
33
+ UPLOAD_RESPONSE_MAX,
34
+ appSettings,
35
+ authorize,
36
+ completeUpload,
37
+ downloadUrl,
38
+ formatSize,
39
+ httpStatus,
40
+ multipartBase64,
41
+ queryFolder,
42
+ searchLibrary,
43
+ sizeOf,
44
+ startUpload,
45
+ viewUrl,
46
+ type Authorization,
47
+ type UploadRefusal,
48
+ type WixLibraryItem,
49
+ } from "../_shared/wix-file-share.js";
50
+
51
+ /** `files.download`'s default cap. A larger file is offered to open in the browser instead. */
52
+ const SAVE_MAX_BYTES = 100 * 1024 * 1024;
53
+
54
+ interface Row {
55
+ id: string;
56
+ name: string;
57
+ isFolder: boolean;
58
+ subtitle: string;
59
+ icon: string;
60
+ sizeBytes: number;
61
+ /** hiddenWhen gate for the row's Save button: true for folders, and for files the server
62
+ * said this reader may not download. */
63
+ saveHidden: boolean;
64
+ }
65
+
66
+ interface Crumb { id: string; name: string }
67
+
68
+ type Status = "loading" | "ready" | "error" | "signIn" | "forbidden" | "notInstalled";
69
+
70
+ export interface FileShareState {
71
+ status: Status;
72
+ /** "" is the library root. */
73
+ folderId: string;
74
+ trail: Crumb[];
75
+ folderTitle: string;
76
+ query: string;
77
+ rows: Row[];
78
+ nextCursor: string;
79
+ canUpload: boolean;
80
+ /** An open, save or upload is running: their buttons are disabled. */
81
+ busy: boolean;
82
+ /** A "Show more" page is being read. */
83
+ moreBusy: boolean;
84
+ /** One line about the last open, save, upload or page read. */
85
+ message: string;
86
+ emptyText: string;
87
+ loadingHidden: boolean;
88
+ contentHidden: boolean;
89
+ emptyHidden: boolean;
90
+ errorHidden: boolean;
91
+ signInHidden: boolean;
92
+ forbiddenHidden: boolean;
93
+ notInstalledHidden: boolean;
94
+ moreHidden: boolean;
95
+ backHidden: boolean;
96
+ uploadHidden: boolean;
97
+ messageHidden: boolean;
98
+ }
99
+
100
+ export const INITIAL: FileShareState = {
101
+ status: "loading",
102
+ folderId: "",
103
+ trail: [],
104
+ folderTitle: "",
105
+ query: "",
106
+ rows: [],
107
+ nextCursor: "",
108
+ canUpload: false,
109
+ busy: false,
110
+ moreBusy: false,
111
+ message: "",
112
+ emptyText: "",
113
+ loadingHidden: false,
114
+ contentHidden: true,
115
+ emptyHidden: true,
116
+ errorHidden: true,
117
+ signInHidden: true,
118
+ forbiddenHidden: true,
119
+ notInstalledHidden: true,
120
+ moreHidden: true,
121
+ backHidden: true,
122
+ uploadHidden: true,
123
+ messageHidden: true,
124
+ };
125
+
126
+ /** The newest read; an answer from an older one is dropped. */
127
+ let generation = 0;
128
+ /** Who the screen was last read for (`readerKey`), so a reappearing screen keeps its folder only
129
+ * for the same reader. */
130
+ let reader = "";
131
+ /** The library root's id (app settings), for the same reader. */
132
+ let rootFolderId = "";
133
+ /** One open, save or upload at a time. A module flag, because the runtime state an action is
134
+ * given does not change until a running action returns. */
135
+ let actionInFlight = false;
136
+ /** Files by id from the rows on screen: the size and name an action needs without a read. */
137
+ let known = new Map<string, Row>();
138
+
139
+ function readerKey(access: ReadAccess): string {
140
+ return JSON.stringify([access.member.email, access.member.scope, access.tenant]);
141
+ }
142
+
143
+ function current(fallback: FileShareState): FileShareState {
144
+ return (svc?.getState?.() as FileShareState | undefined) ?? fallback;
145
+ }
146
+
147
+ function iconOf(item: WixLibraryItem): string {
148
+ if (item.folderFields || !item.fileFields) return "folder";
149
+ const category = item.fileFields.category ?? "";
150
+ if (category === "IMAGE") return "image";
151
+ if (category === "VIDEO") return "play";
152
+ if (category === "MUSIC") return "music";
153
+ return "doc";
154
+ }
155
+
156
+ function subtitleOf(item: WixLibraryItem, searching: boolean): string {
157
+ const parts: string[] = [];
158
+ if (item.fileFields) {
159
+ const ext = (item.fileFields.extension ?? "").trim().toUpperCase();
160
+ if (ext) parts.push(ext);
161
+ const size = sizeOf(item);
162
+ if (size >= 0) parts.push(formatSize(size));
163
+ } else {
164
+ const count = Number(item.folderFields?.childrenCount);
165
+ if (Number.isFinite(count) && count >= 0) {
166
+ parts.push(count === 1 ? copyParam("fileShare.itemCountOne", "1 item") : copyTemplate("fileShare.itemCount", "{count} items", { count }));
167
+ }
168
+ }
169
+ const availability = item.availability ?? item.folderFields?.availability;
170
+ if (availability === "MEMBER") parts.push(copyParam("fileShare.membersOnly", "Members only"));
171
+ if (availability === "PAID") parts.push(copyParam("fileShare.paidOnly", "Plan required"));
172
+ if (searching) {
173
+ const where = (item.path ?? []).map((p) => (p?.name ?? "").trim()).filter((name) => name && name !== "/");
174
+ if (where.length) parts.push(where.join(" / "));
175
+ }
176
+ return parts.join(" · ");
177
+ }
178
+
179
+ /** What `authorize-actions` said. `unknown`: it failed or was not asked; the server still decides. */
180
+ type Permissions = { known: true; auth: Authorization } | { known: false };
181
+
182
+ function rowsOf(items: WixLibraryItem[], access: Permissions, searching: boolean): Row[] {
183
+ return items.filter((item) => item.id && item.name).map((item) => {
184
+ const isFolder = !item.fileFields;
185
+ // An unknown answer keeps Save: the server still decides.
186
+ const canSave = !isFolder && (!access.known || access.auth.items.get(item.id!)?.has("DOWNLOAD") === true);
187
+ return {
188
+ id: item.id!,
189
+ name: item.name!,
190
+ isFolder,
191
+ subtitle: subtitleOf(item, searching),
192
+ icon: iconOf(item),
193
+ sizeBytes: sizeOf(item),
194
+ saveHidden: !canSave,
195
+ };
196
+ });
197
+ }
198
+
199
+ function shown(state: FileShareState, rows: Row[], nextCursor: string, canUpload: boolean): FileShareState {
200
+ known = new Map([...known, ...rows.map((row) => [row.id, row] as const)]);
201
+ const searching = state.query.trim() !== "";
202
+ return {
203
+ ...state,
204
+ status: "ready",
205
+ rows,
206
+ nextCursor,
207
+ canUpload,
208
+ moreBusy: false,
209
+ emptyText: searching
210
+ ? copyParam("fileShare.noResults", "No files match your search.")
211
+ : state.folderId
212
+ ? copyParam("fileShare.emptyFolder", "This folder is empty.")
213
+ : copyParam("fileShare.emptyLibrary", "No documents have been shared yet."),
214
+ loadingHidden: true,
215
+ contentHidden: rows.length === 0,
216
+ emptyHidden: rows.length > 0,
217
+ errorHidden: true,
218
+ signInHidden: true,
219
+ forbiddenHidden: true,
220
+ notInstalledHidden: true,
221
+ moreHidden: !nextCursor,
222
+ backHidden: state.trail.length === 0,
223
+ uploadHidden: !canUpload || searching,
224
+ };
225
+ }
226
+
227
+ function failedState(state: FileShareState, next: Exclude<Status, "loading" | "ready">): FileShareState {
228
+ return {
229
+ ...state,
230
+ status: next,
231
+ rows: [],
232
+ nextCursor: "",
233
+ canUpload: false,
234
+ moreBusy: false,
235
+ loadingHidden: true,
236
+ contentHidden: true,
237
+ emptyHidden: true,
238
+ errorHidden: next !== "error",
239
+ signInHidden: next !== "signIn",
240
+ forbiddenHidden: next !== "forbidden",
241
+ notInstalledHidden: next !== "notInstalled",
242
+ moreHidden: true,
243
+ backHidden: state.trail.length === 0,
244
+ uploadHidden: true,
245
+ };
246
+ }
247
+
248
+ /** Why a read failed, as the screen says it. Sign in helps only a visitor: a signed-in member who
249
+ * is refused (401 or 403) lacks the folder's permission or plan, or their session is broken, and
250
+ * the sign-in screen leads nowhere for them. */
251
+ async function failureOf(error: unknown): Promise<Exclude<Status, "loading" | "ready">> {
252
+ const status = httpStatus(error);
253
+ if (status === 428) return "notInstalled";
254
+ if (status === 401 || status === 403) {
255
+ const signedIn = await readAccess().then((a) => !!a.member.email).catch(() => false);
256
+ return signedIn ? "forbidden" : "signIn";
257
+ }
258
+ return "error";
259
+ }
260
+
261
+ async function authorizationFor(items: WixLibraryItem[], folderId: string): Promise<Permissions> {
262
+ const files = items.filter((item) => item.id && item.fileFields).map((item) => item.id!);
263
+ if (!files.length && !folderId) return { known: false };
264
+ try {
265
+ return { known: true, auth: await authorize(files, folderId) };
266
+ } catch (error) {
267
+ // Save stays (the server refuses it if it must) and Upload stays hidden.
268
+ console.warn("[file-share] authorize-actions failed", error);
269
+ return { known: false };
270
+ }
271
+ }
272
+
273
+ /** What one read produced. Plain data: it crosses `svc.settleRead`. */
274
+ interface ReadResult {
275
+ generation: number;
276
+ cursor: string;
277
+ rows?: Row[];
278
+ nextCursor?: string;
279
+ canUpload?: boolean;
280
+ failure?: Exclude<Status, "loading" | "ready">;
281
+ /** The account changed while the read was in flight. */
282
+ readerChanged?: boolean;
283
+ }
284
+
285
+ /** Read one page for `snapshot` (its folder or its search). Never throws. */
286
+ async function fetchPage(snapshot: FileShareState, cursor: string, mine: number, given?: ReadAccess): Promise<ReadResult> {
287
+ try {
288
+ const access = given ?? await readAccess();
289
+ const searching = snapshot.query.trim() !== "";
290
+ // The root id and the page do not depend on each other: read them together.
291
+ const [root, page] = await Promise.all([
292
+ rootFolderId ? Promise.resolve(rootFolderId) : appSettings().then((s) => s.rootFolderId).catch(() => ""),
293
+ searching ? searchLibrary(snapshot.query, snapshot.folderId, cursor) : queryFolder(snapshot.folderId, cursor),
294
+ ]);
295
+ // The root has an id of its own, and every root item names it as its parent.
296
+ const authFolder = searching ? "" : snapshot.folderId || root || (page.items.find((item) => item.parentFolderId)?.parentFolderId ?? "");
297
+ const auth = await authorizationFor(page.items, authFolder);
298
+ await assertReadAccess(access);
299
+ if (root && mine === generation) rootFolderId = root;
300
+ return {
301
+ generation: mine,
302
+ cursor,
303
+ rows: rowsOf(page.items, auth, searching),
304
+ nextCursor: page.nextCursor,
305
+ canUpload: !searching && auth.known && auth.auth.folder.has("UPLOAD_FILE"),
306
+ };
307
+ } catch (error) {
308
+ if ((error as { name?: string })?.name === "MemberAccessChanged") return { generation: mine, cursor, readerChanged: true };
309
+ return { generation: mine, cursor, failure: await failureOf(error) };
310
+ }
311
+ }
312
+
313
+ /** Put a read's answer on `state` — unless a newer read started since. */
314
+ async function applyRead(state: FileShareState, result: ReadResult): Promise<FileShareState> {
315
+ if (result.generation !== generation) return state;
316
+ // Start over as whoever is signed in now, at the root.
317
+ if (result.readerChanged) return load(state);
318
+ if (result.failure) {
319
+ // A failed "Show more" keeps the rows already on screen and offers the page again.
320
+ if (result.cursor) {
321
+ return { ...state, moreBusy: false, message: copyParam("fileShare.moreFailed", "More files couldn't be loaded. Try again."), messageHidden: false };
322
+ }
323
+ return failedState(state, result.failure);
324
+ }
325
+ const rows = result.rows ?? [];
326
+ return shown(
327
+ state,
328
+ result.cursor ? [...state.rows, ...rows] : rows,
329
+ result.nextCursor ?? "",
330
+ result.cursor ? state.canUpload || result.canUpload === true : result.canUpload === true,
331
+ );
332
+ }
333
+
334
+ /** Start a read of `next` in the background and show `next` (its loading state) now. */
335
+ function startRead(next: FileShareState, cursor = ""): FileShareState {
336
+ const mine = ++generation;
337
+ void fetchPage(next, cursor, mine).then((result) => svc.settleRead(result));
338
+ return next;
339
+ }
340
+
341
+ function loading(state: FileShareState, patch: Partial<FileShareState>): FileShareState {
342
+ return {
343
+ ...state,
344
+ ...patch,
345
+ status: "loading",
346
+ rows: [],
347
+ nextCursor: "",
348
+ canUpload: false,
349
+ moreBusy: false,
350
+ loadingHidden: false,
351
+ contentHidden: true,
352
+ emptyHidden: true,
353
+ errorHidden: true,
354
+ signInHidden: true,
355
+ forbiddenHidden: true,
356
+ notInstalledHidden: true,
357
+ moreHidden: true,
358
+ uploadHidden: true,
359
+ message: "",
360
+ messageHidden: true,
361
+ backHidden: (patch.trail ?? state.trail).length === 0,
362
+ };
363
+ }
364
+
365
+ function titleFor(trail: Crumb[]): string {
366
+ return trail.length ? trail[trail.length - 1]!.name : "";
367
+ }
368
+
369
+ const ROOT_POSITION = { folderId: "", trail: [] as Crumb[], folderTitle: "", query: "" };
370
+
371
+ /** onAppear. The same reader keeps the folder and search on screen, read again; a different
372
+ * reader (sign-in, sign-out, another account or site) starts at the root with nothing of the
373
+ * previous reader's kept. Awaited, because the host paints the state onAppear returns. */
374
+ async function load(state: FileShareState, arg?: unknown): Promise<FileShareState> {
375
+ if (arg !== undefined) stashCopy(arg);
376
+ const access = await readAccess().catch(() => undefined);
377
+ const key = access ? readerKey(access) : "";
378
+ const same = key !== "" && key === reader;
379
+ reader = key;
380
+ if (!same) {
381
+ rootFolderId = "";
382
+ known = new Map();
383
+ }
384
+ // `busy` belongs to an action of this run, or to none.
385
+ const next = { ...loading(state, same ? {} : ROOT_POSITION), busy: actionInFlight };
386
+ const mine = ++generation;
387
+ const result = await fetchPage(next, "", mine, access);
388
+ return applyRead(result.generation === generation ? next : current(next), result);
389
+ }
390
+
391
+ function retry(state: FileShareState): FileShareState {
392
+ return startRead(loading(state, {}));
393
+ }
394
+
395
+ function openFolder(state: FileShareState, id: string, name: string): FileShareState {
396
+ const trail = [...state.trail, { id, name }];
397
+ return startRead(loading(state, { folderId: id, trail, folderTitle: titleFor(trail), query: "" }));
398
+ }
399
+
400
+ function back(state: FileShareState): FileShareState {
401
+ if (!state.trail.length || state.busy) return state;
402
+ const trail = state.trail.slice(0, -1);
403
+ return startRead(loading(state, { folderId: trail.length ? trail[trail.length - 1]!.id : "", trail, folderTitle: titleFor(trail), query: "" }));
404
+ }
405
+
406
+ function search(state: FileShareState, arg?: { value?: unknown }): FileShareState {
407
+ const query = String(arg?.value ?? "").slice(0, 50);
408
+ if (query.trim() === state.query.trim()) return { ...state, query };
409
+ return startRead(loading(state, { query }));
410
+ }
411
+
412
+ function loadMore(state: FileShareState): FileShareState {
413
+ if (!state.nextCursor || state.status !== "ready" || state.moreBusy) return state;
414
+ return startRead({ ...state, moreBusy: true, message: "", messageHidden: true }, state.nextCursor);
415
+ }
416
+
417
+ /** An open, save or upload refusal, as the screen says it. Like a read refusal, "Sign in" is
418
+ * only for a visitor: a signed-in member refused with 401 or 403 has no access. */
419
+ async function actionError(error: unknown, fallback: string): Promise<string> {
420
+ const status = httpStatus(error);
421
+ if (status === 401 || status === 403) {
422
+ const signedIn = await readAccess().then((a) => !!a.member.email).catch(() => false);
423
+ return signedIn
424
+ ? copyParam("fileShare.noAccess", "You don't have access to this file.")
425
+ : copyParam("fileShare.signInToOpen", "Sign in to open this file.");
426
+ }
427
+ if (status === 404) return copyParam("fileShare.gone", "This file is no longer in the library.");
428
+ return fallback;
429
+ }
430
+
431
+ /** Finish an open, save or upload: say how it went, and read the folder again after an upload
432
+ * (without the loading skeleton) when it is still the one on screen. */
433
+ function settle(state: FileShareState, arg?: { message?: unknown; refreshFolder?: unknown }): FileShareState {
434
+ const message = typeof arg?.message === "string" ? arg.message : "";
435
+ const next = { ...state, busy: false, message, messageHidden: !message };
436
+ const folder = typeof arg?.refreshFolder === "string" ? arg.refreshFolder : undefined;
437
+ return folder !== undefined && folder === state.folderId && !state.query.trim() && state.status === "ready" ? startRead(next) : next;
438
+ }
439
+
440
+ /** A running upload's progress line. */
441
+ function progress(state: FileShareState, arg?: { message?: unknown }): FileShareState {
442
+ const message = typeof arg?.message === "string" ? arg.message : "";
443
+ return { ...state, message, messageHidden: !message };
444
+ }
445
+
446
+ /** Run one open, save or upload in the background, one at a time; `settle` always ends it. */
447
+ function runAction(state: FileShareState, startMessage: string, work: () => Promise<{ message: string; refreshFolder?: string } | "reload">): FileShareState {
448
+ actionInFlight = true;
449
+ // The reader the action started for. When the screen was loaded for another reader meanwhile
450
+ // (sign-out, account or site switch), the completion says nothing about the old reader's file.
451
+ const startedFor = reader;
452
+ void work()
453
+ .catch((error) => ((error as { name?: string })?.name === "MemberAccessChanged"
454
+ ? "reload" as const
455
+ : { message: copyParam("fileShare.actionFailed", "That didn't work. Try again.") }))
456
+ .then(async (outcome) => {
457
+ actionInFlight = false;
458
+ if (reader !== startedFor) {
459
+ await svc.settle({ message: "" });
460
+ return;
461
+ }
462
+ if (outcome === "reload") {
463
+ await svc.settle({ message: "" });
464
+ await svc.load();
465
+ return;
466
+ }
467
+ await svc.settle(outcome);
468
+ });
469
+ return { ...state, busy: true, message: startMessage, messageHidden: !startMessage };
470
+ }
471
+
472
+ /** Tap on a row: a folder opens; a file opens in the browser from a fresh inline link. */
473
+ function openItem(state: FileShareState, arg?: { id?: unknown }): FileShareState {
474
+ const id = String(arg?.id ?? "");
475
+ const row = state.rows.find((candidate) => candidate.id === id);
476
+ if (!row || state.busy || actionInFlight) return state;
477
+ if (row.isFolder) return openFolder(state, row.id, row.name);
478
+ const failedText = copyParam("fileShare.openFailed", "This file couldn't be opened. Try Save instead.");
479
+ return runAction(state, "", async () => {
480
+ const access = await readAccess();
481
+ try {
482
+ const url = await viewUrl(row.id);
483
+ // The link is the reader's own: never open it for whoever is signed in now.
484
+ await assertReadAccess(access);
485
+ const { opened } = await openUrl(url, "in_app_browser");
486
+ return { message: opened ? "" : failedText };
487
+ } catch (error) {
488
+ if ((error as { name?: string })?.name === "MemberAccessChanged") return "reload";
489
+ return { message: await actionError(error, failedText) };
490
+ }
491
+ });
492
+ }
493
+
494
+ function safeName(name: string): string {
495
+ const cleaned = name.replace(/[\\/:*?"<>|\u0000-\u001f]+/g, "_").replace(/^\.+/, "").slice(0, 120);
496
+ return cleaned || "file";
497
+ }
498
+
499
+ /** A sandbox copy is only a hand-off: deleted once the save picker or the upload is done with it,
500
+ * so a reader's file does not stay on the device for the next account. */
501
+ async function discard(handle: FileHandle | undefined): Promise<void> {
502
+ if (handle) await removeFile(handle).catch(() => undefined);
503
+ }
504
+
505
+ /** Save: a fresh attachment link, streamed into the sandbox, handed to the OS save picker. An
506
+ * expired link (410) is fetched again once. */
507
+ function saveItem(state: FileShareState, arg?: { id?: unknown }): FileShareState {
508
+ const id = String(arg?.id ?? "");
509
+ const row = state.rows.find((candidate) => candidate.id === id) ?? known.get(id);
510
+ if (!row || row.isFolder || state.busy || actionInFlight) return state;
511
+ const tooLarge = copyParam("fileShare.tooLargeToSave", "This file is larger than 100 MB. Open it to view it in the browser.");
512
+ if (row.sizeBytes > SAVE_MAX_BYTES) return { ...state, message: tooLarge, messageHidden: false };
513
+ return runAction(state, copyParam("fileShare.saving", "Preparing the file…"), async () => {
514
+ const access = await readAccess();
515
+ let handle: FileHandle | undefined;
516
+ // The link and the file are the reader's own: never fetched or exported for another reader.
517
+ const fetchFile = async () => {
518
+ const url = await downloadUrl(row.id);
519
+ await assertReadAccess(access);
520
+ return downloadFile(url, { name: `file-share/${row.id}/${safeName(row.name)}` });
521
+ };
522
+ try {
523
+ try {
524
+ handle = await fetchFile();
525
+ } catch (error) {
526
+ if (!(isFilesError(error) && error.code === "http_error" && error.status === 410)) throw error;
527
+ handle = await fetchFile();
528
+ }
529
+ await assertReadAccess(access);
530
+ const { exported } = await exportFile(handle);
531
+ return { message: exported ? copyTemplate("fileShare.saved", "Saved {name}.", { name: row.name }) : "" };
532
+ } catch (error) {
533
+ if ((error as { name?: string })?.name === "MemberAccessChanged") return "reload";
534
+ if (isFilesError(error)) {
535
+ if (error.code === "too_large") return { message: tooLarge };
536
+ if (error.code === "unavailable") return { message: copyParam("fileShare.saveUnavailable", "Saving files isn't available on this device. Open the file instead.") };
537
+ return { message: copyParam("fileShare.saveFailed", "The file couldn't be saved. Try again.") };
538
+ }
539
+ return { message: await actionError(error, copyParam("fileShare.saveFailed", "The file couldn't be saved. Try again.")) };
540
+ } finally {
541
+ await discard(handle);
542
+ }
543
+ });
544
+ }
545
+
546
+ function refusalText(refusal: UploadRefusal): string {
547
+ if (refusal.kind === "tooBig") {
548
+ return refusal.maxSize
549
+ ? copyTemplate("fileShare.uploadTooBigFor", "This file is too large for the library. The limit is {size}.", { size: formatSize(refusal.maxSize) })
550
+ : copyParam("fileShare.uploadTooBig", "This file is too large for the library.");
551
+ }
552
+ if (refusal.kind === "extension") return copyParam("fileShare.uploadType", "The library doesn't accept this type of file.");
553
+ if (refusal.kind === "quota") return copyParam("fileShare.uploadQuota", "The library is out of storage. Contact the business.");
554
+ if (refusal.kind === "video") return copyParam("fileShare.uploadVideo", "The library doesn't accept videos.");
555
+ return copyParam("fileShare.uploadFailed", "The upload didn't finish. Nothing was added. Try again.");
556
+ }
557
+
558
+ let uploadSeq = 0;
559
+
560
+ const UPLOAD_FAILED = () => copyParam("fileShare.uploadFailed", "The upload didn't finish. Nothing was added. Try again.");
561
+
562
+ /** Upload one file into the folder on screen, only where the server allows UPLOAD_FILE there.
563
+ * It is reported as added only after `complete-upload` returns the new library item. */
564
+ function upload(state: FileShareState): FileShareState {
565
+ if (!state.canUpload || state.busy || actionInFlight || state.query.trim()) return state;
566
+ const folderId = state.folderId;
567
+ return runAction(state, "", async () => {
568
+ const access = await readAccess();
569
+ const picked = await pickDetailed({ maxBytes: UPLOAD_MAX_BYTES, maxItems: 1 }).catch(() => ({ items: [], rejected: [] }));
570
+ const file = picked.items[0];
571
+ if (!file) {
572
+ const reason = picked.rejected[0]?.reason;
573
+ if (!reason) return { message: "" };
574
+ return {
575
+ message: reason === "size"
576
+ ? copyParam("fileShare.uploadAppLimit", "Files over 7 MB can't be uploaded from the app. Upload them from the website.")
577
+ : copyParam("fileShare.uploadOne", "Pick one file at a time."),
578
+ };
579
+ }
580
+ try {
581
+ if (file.sizeBytes > UPLOAD_MAX_BYTES) {
582
+ return { message: copyParam("fileShare.uploadAppLimit", "Files over 7 MB can't be uploaded from the app. Upload them from the website.") };
583
+ }
584
+ await svc.progress({ message: copyTemplate("fileShare.uploading", "Uploading {name}…", { name: file.name }) });
585
+ const actionId = `himi-upload-${Date.now().toString(36)}-${(uploadSeq += 1)}`;
586
+ const started = await startUpload({ name: file.name, sizeBytes: file.sizeBytes }, folderId, actionId);
587
+ if (!started.target) return { message: refusalText(started.refusal ?? { kind: "unknown" }) };
588
+ const boundary = `----himi${actionId.replace(/[^A-Za-z0-9]/g, "")}`;
589
+ const body = multipartBase64(started.target.requestParameters, { name: file.name, mimeType: file.mimeType, base64: await readBase64(file) }, boundary);
590
+ const sent = await uploadPut(started.target.url, { base64: body }, { method: "POST", contentType: `multipart/form-data; boundary=${boundary}` });
591
+ if (!sent.ok || !sent.body || sent.body.length > UPLOAD_RESPONSE_MAX) return { message: UPLOAD_FAILED() };
592
+ // The upload was made as one account; it is registered only for that same account.
593
+ await assertReadAccess(access);
594
+ const done = await completeUpload(sent.body, folderId, actionId);
595
+ if (!done.item) return { message: refusalText(done.refusal ?? { kind: "unknown" }) };
596
+ return { message: copyTemplate("fileShare.uploaded", "Added {name}.", { name: done.item.name ?? file.name }), refreshFolder: folderId };
597
+ } catch (error) {
598
+ if ((error as { name?: string })?.name === "MemberAccessChanged") return "reload";
599
+ // presigned_upload refuses an upload host outside its allowlist before sending anything.
600
+ if (/presigned_upload/i.test(String((error as { message?: unknown })?.message ?? ""))) {
601
+ return { message: copyParam("fileShare.uploadUnsupported", "Uploading to this library isn't available in the app yet. Upload from the website.") };
602
+ }
603
+ return { message: await actionError(error, UPLOAD_FAILED()) };
604
+ } finally {
605
+ await discard(file);
606
+ }
607
+ });
608
+ }
609
+
610
+ /** Every key: a cold boot starts from INITIAL. The flags (`busy`, `moreBusy`) describe actions
611
+ * of a run that is gone, and the rows, folder and search are a reader's restricted listing,
612
+ * which is read again for whoever is signed in rather than kept on the device. */
613
+ const RUN_ONLY_KEYS = Object.keys(INITIAL) as (keyof FileShareState)[];
614
+
615
+ const svc = defineService("himiBrandedFileShare", {
616
+ state: INITIAL,
617
+ notHydrated: RUN_ONLY_KEYS,
618
+ notPersisted: RUN_ONLY_KEYS,
619
+ actions: {
620
+ load,
621
+ retry,
622
+ back,
623
+ search,
624
+ loadMore,
625
+ open: openItem,
626
+ save: saveItem,
627
+ upload,
628
+ // Background completions (see STATE above), not UI actions.
629
+ settleRead: applyRead,
630
+ settle,
631
+ progress,
632
+ },
633
+ });
634
+
635
+ export { svc, rowsOf, subtitleOf };