@ttt-productions/upload-ui 0.7.15 → 0.7.17
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/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/react/guard/guarded-link.d.ts.map +1 -0
- package/dist/react/guard/guarded-link.js.map +1 -0
- package/dist/react/guard/index.d.ts +3 -3
- package/dist/react/guard/index.d.ts.map +1 -1
- package/dist/react/guard/index.js +3 -3
- package/dist/react/guard/index.js.map +1 -1
- package/dist/react/guard/local-upload-guard-provider.d.ts.map +1 -0
- package/dist/react/guard/local-upload-guard-provider.js.map +1 -0
- package/dist/react/guard/use-guarded-navigation.d.ts.map +1 -0
- package/dist/react/{use-guarded-navigation.js → guard/use-guarded-navigation.js} +1 -1
- package/dist/react/guard/use-guarded-navigation.js.map +1 -0
- package/dist/react/tray/in-flight-uploads-provider.d.ts.map +1 -0
- package/dist/react/{in-flight-uploads-provider.js → tray/in-flight-uploads-provider.js} +11 -8
- package/dist/react/tray/in-flight-uploads-provider.js.map +1 -0
- package/dist/react/tray/index.d.ts +4 -4
- package/dist/react/tray/index.d.ts.map +1 -1
- package/dist/react/tray/index.js +4 -4
- package/dist/react/tray/index.js.map +1 -1
- package/dist/react/tray/use-clear-upload-activity.d.ts.map +1 -0
- package/dist/react/tray/use-clear-upload-activity.js.map +1 -0
- package/dist/react/tray/use-mark-upload-activity-seen.d.ts +16 -0
- package/dist/react/tray/use-mark-upload-activity-seen.d.ts.map +1 -0
- package/dist/react/tray/use-mark-upload-activity-seen.js +65 -0
- package/dist/react/tray/use-mark-upload-activity-seen.js.map +1 -0
- package/dist/react/tray/use-upload-processing.d.ts.map +1 -0
- package/dist/react/{use-upload-processing.js → tray/use-upload-processing.js} +11 -3
- package/dist/react/tray/use-upload-processing.js.map +1 -0
- package/dist/react/{deferred-upload-form-shell.d.ts → upload/deferred-upload-form-shell.d.ts} +1 -1
- package/dist/react/upload/deferred-upload-form-shell.d.ts.map +1 -0
- package/dist/react/{deferred-upload-form-shell.js → upload/deferred-upload-form-shell.js} +5 -1
- package/dist/react/upload/deferred-upload-form-shell.js.map +1 -0
- package/dist/react/upload/index.d.ts +2 -2
- package/dist/react/upload/index.d.ts.map +1 -1
- package/dist/react/upload/index.js +2 -2
- package/dist/react/upload/index.js.map +1 -1
- package/dist/react/upload/use-guarded-upload.d.ts.map +1 -0
- package/dist/react/{use-guarded-upload.js → upload/use-guarded-upload.js} +2 -2
- package/dist/react/upload/use-guarded-upload.js.map +1 -0
- package/dist/upload-display.d.ts +39 -0
- package/dist/upload-display.d.ts.map +1 -0
- package/dist/upload-display.js +64 -0
- package/dist/upload-display.js.map +1 -0
- package/package.json +5 -5
- package/dist/react/deferred-upload-form-shell.d.ts.map +0 -1
- package/dist/react/deferred-upload-form-shell.js.map +0 -1
- package/dist/react/guarded-link.d.ts.map +0 -1
- package/dist/react/guarded-link.js.map +0 -1
- package/dist/react/in-flight-uploads-provider.d.ts.map +0 -1
- package/dist/react/in-flight-uploads-provider.js.map +0 -1
- package/dist/react/local-upload-guard-provider.d.ts.map +0 -1
- package/dist/react/local-upload-guard-provider.js.map +0 -1
- package/dist/react/use-clear-upload-activity.d.ts.map +0 -1
- package/dist/react/use-clear-upload-activity.js.map +0 -1
- package/dist/react/use-guarded-navigation.d.ts.map +0 -1
- package/dist/react/use-guarded-navigation.js.map +0 -1
- package/dist/react/use-guarded-upload.d.ts.map +0 -1
- package/dist/react/use-guarded-upload.js.map +0 -1
- package/dist/react/use-mark-upload-activity-seen.d.ts +0 -8
- package/dist/react/use-mark-upload-activity-seen.d.ts.map +0 -1
- package/dist/react/use-mark-upload-activity-seen.js +0 -29
- package/dist/react/use-mark-upload-activity-seen.js.map +0 -1
- package/dist/react/use-upload-processing.d.ts.map +0 -1
- package/dist/react/use-upload-processing.js.map +0 -1
- /package/dist/react/{guarded-link.d.ts → guard/guarded-link.d.ts} +0 -0
- /package/dist/react/{guarded-link.js → guard/guarded-link.js} +0 -0
- /package/dist/react/{local-upload-guard-provider.d.ts → guard/local-upload-guard-provider.d.ts} +0 -0
- /package/dist/react/{local-upload-guard-provider.js → guard/local-upload-guard-provider.js} +0 -0
- /package/dist/react/{use-guarded-navigation.d.ts → guard/use-guarded-navigation.d.ts} +0 -0
- /package/dist/react/{in-flight-uploads-provider.d.ts → tray/in-flight-uploads-provider.d.ts} +0 -0
- /package/dist/react/{use-clear-upload-activity.d.ts → tray/use-clear-upload-activity.d.ts} +0 -0
- /package/dist/react/{use-clear-upload-activity.js → tray/use-clear-upload-activity.js} +0 -0
- /package/dist/react/{use-upload-processing.d.ts → tray/use-upload-processing.d.ts} +0 -0
- /package/dist/react/{use-guarded-upload.d.ts → upload/use-guarded-upload.d.ts} +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { useGuardedUpload, type GuardedUploadArgs
|
|
2
|
-
export { DeferredUploadFormShell, type DeferredUploadFormShellHandle, type DeferredUploadFormShellProps, } from '
|
|
1
|
+
export { useGuardedUpload, type GuardedUploadArgs } from './use-guarded-upload.js';
|
|
2
|
+
export { DeferredUploadFormShell, type DeferredUploadFormShellHandle, type DeferredUploadFormShellProps, } from './deferred-upload-form-shell.js';
|
|
3
3
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/upload/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/upload/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EACL,uBAAuB,EACvB,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,GAClC,MAAM,iCAAiC,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { useGuardedUpload
|
|
2
|
-
export { DeferredUploadFormShell, } from '
|
|
1
|
+
export { useGuardedUpload } from './use-guarded-upload.js';
|
|
2
|
+
export { DeferredUploadFormShell, } from './deferred-upload-form-shell.js';
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/react/upload/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/react/upload/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAA0B,MAAM,yBAAyB,CAAC;AACnF,OAAO,EACL,uBAAuB,GAGxB,MAAM,iCAAiC,CAAC","sourcesContent":["export { useGuardedUpload, type GuardedUploadArgs } from './use-guarded-upload.js';\nexport {\n DeferredUploadFormShell,\n type DeferredUploadFormShellHandle,\n type DeferredUploadFormShellProps,\n} from './deferred-upload-form-shell.js';\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-guarded-upload.d.ts","sourceRoot":"","sources":["../../../src/react/upload/use-guarded-upload.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAGlE,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,eAAe,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,IAAI,CAAC;IACX,QAAQ,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IAClC,uGAAuG;IACvG,QAAQ,EAAE,MAAM,CAAC;IACjB,qHAAqH;IACrH,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,KAAK,IAAI,CAAC;IACjD;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACnC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,WAIf,iBAAiB,KAAG,OAAO,CAAC,IAAI,CAAC,CA+BjD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useCallback } from 'react';
|
|
2
2
|
import { uploadFileResumable } from '@ttt-productions/upload-core/browser';
|
|
3
|
-
import { useLocalUploadGuard } from '
|
|
3
|
+
import { useLocalUploadGuard } from '../guard/local-upload-guard-provider.js';
|
|
4
4
|
/**
|
|
5
5
|
* Wraps `uploadFileResumable` with the canonical local-upload guard + phase reporting.
|
|
6
6
|
*
|
|
@@ -17,7 +17,7 @@ import { useLocalUploadGuard } from './local-upload-guard-provider.js';
|
|
|
17
17
|
export function useGuardedUpload() {
|
|
18
18
|
const { registerUpload, unregisterUpload } = useLocalUploadGuard();
|
|
19
19
|
return useCallback(async (args) => {
|
|
20
|
-
const { uploadId, onProgress, storage, path, file, metadata, signal, allowNeutralContentType } = args;
|
|
20
|
+
const { uploadId, onProgress, storage, path, file, metadata, signal, allowNeutralContentType, } = args;
|
|
21
21
|
onProgress?.({ phase: 'preparing', percent: null });
|
|
22
22
|
registerUpload(uploadId);
|
|
23
23
|
try {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-guarded-upload.js","sourceRoot":"","sources":["../../../src/react/upload/use-guarded-upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAG3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AA6B9E;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,gBAAgB;IAC9B,MAAM,EAAE,cAAc,EAAE,gBAAgB,EAAE,GAAG,mBAAmB,EAAE,CAAC;IAEnE,OAAO,WAAW,CAChB,KAAK,EAAE,IAAuB,EAAiB,EAAE;QAC/C,MAAM,EACJ,QAAQ,EACR,UAAU,EACV,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,QAAQ,EACR,MAAM,EACN,uBAAuB,GACxB,GAAG,IAAI,CAAC;QAET,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;QACpD,cAAc,CAAC,QAAQ,CAAC,CAAC;QACzB,IAAI,CAAC;YACH,MAAM,mBAAmB,CAAC;gBACxB,OAAO;gBACP,IAAI;gBACJ,IAAI;gBACJ,QAAQ;gBACR,MAAM;gBACN,GAAG,CAAC,uBAAuB,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,uBAAuB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC9E,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;aAC3E,CAAC,CAAC;QACL,CAAC;gBAAS,CAAC;YACT,gBAAgB,CAAC,QAAQ,CAAC,CAAC;QAC7B,CAAC;QACD,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACvD,CAAC,EACD,CAAC,cAAc,EAAE,gBAAgB,CAAC,CACnC,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback } from 'react';\nimport { uploadFileResumable } from '@ttt-productions/upload-core/browser';\nimport type { FirebaseStorage } from 'firebase/storage';\nimport type { UploadState } from '@ttt-productions/media-schemas';\nimport { useLocalUploadGuard } from '../guard/local-upload-guard-provider.js';\n\nexport interface GuardedUploadArgs {\n storage: FirebaseStorage;\n path: string;\n file: File;\n metadata: { contentType: string };\n /** Stable identifier for the in-flight upload (used to register/unregister the local-upload guard). */\n uploadId: string;\n /** Optional progress callback. Fires with preparing → uploading (with percent) → finalizing → null on completion. */\n onProgress?: (state: UploadState | null) => void;\n /**\n * Optional cancellation signal. When aborted, the in-flight Storage upload\n * is canceled and `guardedUpload` rejects with the underlying AbortError.\n * Callers should treat AbortError as a user-initiated cancel (not a real\n * failure) — typically by checking `error.name === 'AbortError'` in the\n * mutation's onError and swallowing toasts/error UI for that case.\n */\n signal?: AbortSignal;\n /**\n * EXPLICIT opt-in for the NEUTRAL `application/octet-stream` content type\n * (canonical-upload-content-classification): only for advisory picker files\n * with unknown browser metadata, so the server byte inspector sees unknown\n * as unknown. Threaded verbatim to `uploadFileResumable`, whose media-only\n * default stays intact for every consumer that omits it.\n */\n allowNeutralContentType?: boolean;\n}\n\n/**\n * Wraps `uploadFileResumable` with the canonical local-upload guard + phase reporting.\n *\n * Every upload-capable mutation hook MUST use this helper instead of calling\n * `uploadFileResumable` directly. The helper owns:\n * - phase reporting: preparing → uploading (with percent) → finalizing\n * - beforeunload guard registration during the upload window only\n * - error safety: the guard is unregistered in a `finally` block\n *\n * The helper does NOT call `onProgress?.(null)` — callers do that from the\n * mutation's `onSuccess` and `onError` callbacks (because the upload window\n * ends when the upload completes, but the mutation may have more work after).\n */\nexport function useGuardedUpload() {\n const { registerUpload, unregisterUpload } = useLocalUploadGuard();\n\n return useCallback(\n async (args: GuardedUploadArgs): Promise<void> => {\n const {\n uploadId,\n onProgress,\n storage,\n path,\n file,\n metadata,\n signal,\n allowNeutralContentType,\n } = args;\n\n onProgress?.({ phase: 'preparing', percent: null });\n registerUpload(uploadId);\n try {\n await uploadFileResumable({\n storage,\n path,\n file,\n metadata,\n signal,\n ...(allowNeutralContentType === true ? { allowNeutralContentType: true } : {}),\n onProgress: ({ percent }) => onProgress?.({ phase: 'uploading', percent }),\n });\n } finally {\n unregisterUpload(uploadId);\n }\n onProgress?.({ phase: 'finalizing', percent: null });\n },\n [registerUpload, unregisterUpload],\n );\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** A byte count as a short size: `850 B`, `24 KB`, `1.2 MB`, `3 GB`. `null` for no usable count. */
|
|
2
|
+
export declare function formatFileSize(bytes: number | undefined): string | null;
|
|
3
|
+
/** The app's words for an upload row's time and file kind. */
|
|
4
|
+
export interface UploadDisplayCopy {
|
|
5
|
+
/** Under a minute old. */
|
|
6
|
+
justNow: string;
|
|
7
|
+
minutesAgo: (minutes: number) => string;
|
|
8
|
+
hoursAgo: (hours: number) => string;
|
|
9
|
+
/** Accepted on the previous calendar day, given the local clock time. */
|
|
10
|
+
yesterdayAt: (time: string) => string;
|
|
11
|
+
/** Accepted before yesterday, given the short local date and clock time. */
|
|
12
|
+
dateAt: (date: string, time: string) => string;
|
|
13
|
+
/** The file's kind, by its simplified media type; `other` for anything else. */
|
|
14
|
+
fileType: {
|
|
15
|
+
image: string;
|
|
16
|
+
video: string;
|
|
17
|
+
audio: string;
|
|
18
|
+
other: string;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export interface UploadDisplayConfig {
|
|
22
|
+
copy: UploadDisplayCopy;
|
|
23
|
+
/** How long a row's time reads as relative before it reads as a clock time. */
|
|
24
|
+
relativeTimeCutoffMs: number;
|
|
25
|
+
/** Locale for the clock time and date; the runtime's own when omitted. */
|
|
26
|
+
locale?: Intl.LocalesArgument;
|
|
27
|
+
}
|
|
28
|
+
export interface UploadDisplayFormatters {
|
|
29
|
+
/**
|
|
30
|
+
* An upload's accept time. Within the cutoff of now: just now, minutes ago, or hours ago. Older:
|
|
31
|
+
* the clock time for today, yesterday and the clock time, or the short date and the clock time —
|
|
32
|
+
* by local calendar day.
|
|
33
|
+
*/
|
|
34
|
+
formatUploadTimestamp: (createdAtMs: number, nowMs: number) => string;
|
|
35
|
+
/** The file's kind from its stored content type; `null` when it has none. */
|
|
36
|
+
getFileTypeLabel: (contentType: string | undefined) => string | null;
|
|
37
|
+
}
|
|
38
|
+
export declare function createUploadDisplayFormatters(config: UploadDisplayConfig): UploadDisplayFormatters;
|
|
39
|
+
//# sourceMappingURL=upload-display.d.ts.map
|
|
@@ -0,0 +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B"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// What an upload row shows besides its title: the file's size, its kind, and when it was accepted.
|
|
2
|
+
// The mechanics are shared; every word, the relative-time cutoff and the locale are the app's.
|
|
3
|
+
import { getSimplifiedMediaType } from '@ttt-productions/media-schemas';
|
|
4
|
+
/** A byte count as a short size: `850 B`, `24 KB`, `1.2 MB`, `3 GB`. `null` for no usable count. */
|
|
5
|
+
export function formatFileSize(bytes) {
|
|
6
|
+
if (bytes === undefined || !Number.isFinite(bytes) || bytes < 0)
|
|
7
|
+
return null;
|
|
8
|
+
if (bytes < 1024)
|
|
9
|
+
return `${bytes} B`;
|
|
10
|
+
if (bytes < 1024 * 1024)
|
|
11
|
+
return `${Math.round(bytes / 1024)} KB`;
|
|
12
|
+
if (bytes < 1024 * 1024 * 1024) {
|
|
13
|
+
const mb = bytes / (1024 * 1024);
|
|
14
|
+
return `${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`;
|
|
15
|
+
}
|
|
16
|
+
const gb = bytes / (1024 * 1024 * 1024);
|
|
17
|
+
return `${gb < 10 ? gb.toFixed(1) : Math.round(gb)} GB`;
|
|
18
|
+
}
|
|
19
|
+
function sameCalendarDay(a, b) {
|
|
20
|
+
return (a.getFullYear() === b.getFullYear() &&
|
|
21
|
+
a.getMonth() === b.getMonth() &&
|
|
22
|
+
a.getDate() === b.getDate());
|
|
23
|
+
}
|
|
24
|
+
export function createUploadDisplayFormatters(config) {
|
|
25
|
+
const { copy, relativeTimeCutoffMs, locale } = config;
|
|
26
|
+
const formatUploadTimestamp = (createdAtMs, nowMs) => {
|
|
27
|
+
const diffMs = Math.max(0, nowMs - createdAtMs);
|
|
28
|
+
if (diffMs < relativeTimeCutoffMs) {
|
|
29
|
+
if (diffMs < 60_000)
|
|
30
|
+
return copy.justNow;
|
|
31
|
+
const minutes = Math.floor(diffMs / 60_000);
|
|
32
|
+
if (minutes < 60)
|
|
33
|
+
return copy.minutesAgo(minutes);
|
|
34
|
+
return copy.hoursAgo(Math.floor(diffMs / 3_600_000));
|
|
35
|
+
}
|
|
36
|
+
const created = new Date(createdAtMs);
|
|
37
|
+
const now = new Date(nowMs);
|
|
38
|
+
const time = created.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' });
|
|
39
|
+
if (sameCalendarDay(created, now))
|
|
40
|
+
return time;
|
|
41
|
+
// The previous calendar day, found by stepping the date rather than subtracting 24 hours: a
|
|
42
|
+
// day that crosses a daylight-saving change is 23 or 25 hours long.
|
|
43
|
+
const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
|
|
44
|
+
if (sameCalendarDay(created, yesterday))
|
|
45
|
+
return copy.yesterdayAt(time);
|
|
46
|
+
return copy.dateAt(created.toLocaleDateString(locale, { month: 'short', day: 'numeric' }), time);
|
|
47
|
+
};
|
|
48
|
+
const getFileTypeLabel = (contentType) => {
|
|
49
|
+
if (!contentType)
|
|
50
|
+
return null;
|
|
51
|
+
switch (getSimplifiedMediaType(contentType)) {
|
|
52
|
+
case 'image':
|
|
53
|
+
return copy.fileType.image;
|
|
54
|
+
case 'video':
|
|
55
|
+
return copy.fileType.video;
|
|
56
|
+
case 'audio':
|
|
57
|
+
return copy.fileType.audio;
|
|
58
|
+
default:
|
|
59
|
+
return copy.fileType.other;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
return { formatUploadTimestamp, getFileTypeLabel };
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=upload-display.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"upload-display.js","sourceRoot":"","sources":["../src/upload-display.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,+FAA+F;AAE/F,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAExE,oGAAoG;AACpG,MAAM,UAAU,cAAc,CAAC,KAAyB;IACtD,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,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tE,IAAI,CACL,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,CAAC,WAA+B,EAAiB,EAAE;QAC1E,IAAI,CAAC,WAAW;YAAE,OAAO,IAAI,CAAC;QAC9B,QAAQ,sBAAsB,CAAC,WAAW,CAAC,EAAE,CAAC;YAC5C,KAAK,OAAO;gBACV,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YAC7B,KAAK,OAAO;gBACV,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YAC7B,KAAK,OAAO;gBACV,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YAC7B;gBACE,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAC/B,CAAC;IACH,CAAC,CAAC;IAEF,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,CAAC;AACrD,CAAC","sourcesContent":["// What an upload row shows besides its title: the file's size, its kind, and when it was accepted.\n// The mechanics are shared; every word, the relative-time cutoff and the locale are the app's.\n\nimport { getSimplifiedMediaType } from '@ttt-productions/media-schemas';\n\n/** A byte count as a short size: `850 B`, `24 KB`, `1.2 MB`, `3 GB`. `null` for no usable count. */\nexport function formatFileSize(bytes: number | undefined): string | null {\n if (bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return null;\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\n if (bytes < 1024 * 1024 * 1024) {\n const mb = bytes / (1024 * 1024);\n return `${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`;\n }\n const gb = bytes / (1024 * 1024 * 1024);\n return `${gb < 10 ? gb.toFixed(1) : Math.round(gb)} GB`;\n}\n\n/** The app's words for an upload row's time and file kind. */\nexport interface UploadDisplayCopy {\n /** Under a minute old. */\n justNow: string;\n minutesAgo: (minutes: number) => string;\n hoursAgo: (hours: number) => string;\n /** Accepted on the previous calendar day, given the local clock time. */\n yesterdayAt: (time: string) => string;\n /** Accepted before yesterday, given the short local date and clock time. */\n dateAt: (date: string, time: string) => string;\n /** The file's kind, by its simplified media type; `other` for anything else. */\n fileType: { image: string; video: string; audio: string; other: string };\n}\n\nexport interface UploadDisplayConfig {\n copy: UploadDisplayCopy;\n /** How long a row's time reads as relative before it reads as a clock time. */\n relativeTimeCutoffMs: number;\n /** Locale for the clock time and date; the runtime's own when omitted. */\n locale?: Intl.LocalesArgument;\n}\n\nexport interface UploadDisplayFormatters {\n /**\n * An upload's accept time. Within the cutoff of now: just now, minutes ago, or hours ago. Older:\n * the clock time for today, yesterday and the clock time, or the short date and the clock time —\n * by local calendar day.\n */\n formatUploadTimestamp: (createdAtMs: number, nowMs: number) => string;\n /** The file's kind from its stored content type; `null` when it has none. */\n getFileTypeLabel: (contentType: string | undefined) => string | null;\n}\n\nfunction sameCalendarDay(a: Date, b: Date): boolean {\n return (\n a.getFullYear() === b.getFullYear() &&\n a.getMonth() === b.getMonth() &&\n a.getDate() === b.getDate()\n );\n}\n\nexport function createUploadDisplayFormatters(\n config: UploadDisplayConfig,\n): UploadDisplayFormatters {\n const { copy, relativeTimeCutoffMs, locale } = config;\n\n const formatUploadTimestamp = (createdAtMs: number, nowMs: number): string => {\n const diffMs = Math.max(0, nowMs - createdAtMs);\n if (diffMs < relativeTimeCutoffMs) {\n if (diffMs < 60_000) return copy.justNow;\n const minutes = Math.floor(diffMs / 60_000);\n if (minutes < 60) return copy.minutesAgo(minutes);\n return copy.hoursAgo(Math.floor(diffMs / 3_600_000));\n }\n\n const created = new Date(createdAtMs);\n const now = new Date(nowMs);\n const time = created.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' });\n if (sameCalendarDay(created, now)) return time;\n\n // The previous calendar day, found by stepping the date rather than subtracting 24 hours: a\n // day that crosses a daylight-saving change is 23 or 25 hours long.\n const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);\n if (sameCalendarDay(created, yesterday)) return copy.yesterdayAt(time);\n\n return copy.dateAt(\n created.toLocaleDateString(locale, { month: 'short', day: 'numeric' }),\n time,\n );\n };\n\n const getFileTypeLabel = (contentType: string | undefined): string | null => {\n if (!contentType) return null;\n switch (getSimplifiedMediaType(contentType)) {\n case 'image':\n return copy.fileType.image;\n case 'video':\n return copy.fileType.video;\n case 'audio':\n return copy.fileType.audio;\n default:\n return copy.fileType.other;\n }\n };\n\n return { formatUploadTimestamp, getFileTypeLabel };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ttt-productions/upload-ui",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.17",
|
|
4
4
|
"description": "Upload UI primitives: local upload guard provider, useGuardedUpload helper, DeferredUploadFormShell for forms that defer Firebase Storage upload until form submit.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -40,10 +40,10 @@
|
|
|
40
40
|
"prepublishOnly": "npm run clean && npm run build"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@ttt-productions/file-input": "^0.11.
|
|
44
|
-
"@ttt-productions/media-schemas": "^0.14.
|
|
45
|
-
"@ttt-productions/ui-core": "^0.11.
|
|
46
|
-
"@ttt-productions/upload-core": "^0.7.
|
|
43
|
+
"@ttt-productions/file-input": "^0.11.16",
|
|
44
|
+
"@ttt-productions/media-schemas": "^0.14.11",
|
|
45
|
+
"@ttt-productions/ui-core": "^0.11.34",
|
|
46
|
+
"@ttt-productions/upload-core": "^0.7.6"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
49
|
"@tanstack/react-query": ">=5.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deferred-upload-form-shell.d.ts","sourceRoot":"","sources":["../../src/react/deferred-upload-form-shell.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,EAMZ,KAAK,SAAS,EACd,KAAK,GAAG,EACT,MAAM,OAAO,CAA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sourcesContent":["'use client';\n\nimport React, {\n useState,\n useRef,\n useCallback,\n useImperativeHandle,\n forwardRef,\n type ReactNode,\n type Ref,\n} from 'react';\nimport { MediaInput } from '@ttt-productions/file-input/react';\nimport type { MediaInputChangePayload } from '@ttt-productions/file-input';\nimport type { ClientMediaClaim, MediaOriginSpec, UploadState } from '@ttt-productions/media-schemas';\n\nexport interface DeferredUploadFormShellHandle {\n submit: () => void;\n}\n\nexport interface DeferredUploadFormShellProps<\n TVariables extends {\n onProgress?: (s: UploadState | null) => void;\n signal?: AbortSignal;\n },\n TResult = unknown,\n> {\n /** The media-origin spec describing accept patterns, size caps, and label.\n * Consumers pass this directly — the shell does not look it up from a registry. */\n spec: MediaOriginSpec;\n mutation: {\n mutateAsync: (vars: TVariables) => Promise<TResult>;\n isPending: boolean;\n };\n buildVariables: (\n file: File | null,\n onProgress: (s: UploadState | null) => void,\n signal: AbortSignal,\n /** The untrusted claim MediaInput emitted with the selected file (advisory;\n * the server byte inspection is the only classification authority). Rides\n * and clears with the file — additive 4th arg, existing callers unchanged. */\n claim?: ClientMediaClaim,\n ) => TVariables;\n onSuccess?: (result: TResult) => void;\n onError?: (err: unknown) => void;\n /**\n * Optional callback fired whenever the shell's internal selectedFile state\n * changes — on user select, on user clear, and on the post-success internal\n * reset. Forms typically use this to mirror selectedFile externally so they\n * can compute their own submit-button `disabled` flag (e.g. require-a-file\n * submit gating).\n */\n onFileChange?: (file: File | null) => void;\n /**\n * Optional guard forwarded to MediaInput, fired before the picker/capture\n * opens for any action. Return false (or a Promise resolving false) to abort\n * — e.g. an email-verification gate. See MediaInputProps.onBeforeSelect.\n */\n onBeforeSelect?: () => boolean | Promise<boolean>;\n children?: ReactNode;\n}\n\nfunction DeferredUploadFormShellInner<\n TVariables extends {\n onProgress?: (s: UploadState | null) => void;\n signal?: AbortSignal;\n },\n TResult = unknown,\n>(\n props: DeferredUploadFormShellProps<TVariables, TResult>,\n ref: Ref<DeferredUploadFormShellHandle>,\n) {\n const {\n spec,\n mutation,\n buildVariables,\n onSuccess,\n onError,\n onFileChange,\n onBeforeSelect,\n children,\n } = props;\n\n const [selectedFile, setSelectedFile] = useState<File | null>(null);\n const [selectedClaim, setSelectedClaim] = useState<ClientMediaClaim | undefined>(undefined);\n const [uploadState, setUploadState] = useState<UploadState | null>(null);\n const fileAreaRef = useRef<HTMLDivElement>(null);\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const handleMediaChange = useCallback((payload: MediaInputChangePayload) => {\n const next = payload.error ? null : (payload.file ?? null);\n setSelectedFile(next);\n setSelectedClaim(next ? payload.claim : undefined);\n onFileChange?.(next);\n }, [onFileChange]);\n\n const handleClear = useCallback(() => {\n setSelectedFile(null);\n setSelectedClaim(undefined);\n onFileChange?.(null);\n }, [onFileChange]);\n\n const handleCancel = useCallback(() => {\n abortControllerRef.current?.abort();\n }, []);\n\n const handleSubmit = useCallback(async () => {\n if (mutation.isPending) return;\n if (selectedFile) {\n fileAreaRef.current?.focus();\n }\n const controller = new AbortController();\n abortControllerRef.current = controller;\n try {\n const result = await mutation.mutateAsync(\n buildVariables(selectedFile, setUploadState, controller.signal, selectedClaim),\n );\n setUploadState(null);\n setSelectedFile(null);\n setSelectedClaim(undefined);\n onFileChange?.(null);\n onSuccess?.(result);\n } catch (err) {\n setUploadState(null);\n // User-initiated cancel: swallow the AbortError, reset selection, do not fire onError.\n if (err instanceof Error && err.name === 'AbortError') {\n setSelectedFile(null);\n setSelectedClaim(undefined);\n onFileChange?.(null);\n return;\n }\n onError?.(err);\n } finally {\n abortControllerRef.current = null;\n }\n }, [mutation, selectedFile, selectedClaim, buildVariables, onSuccess, onError, onFileChange]);\n\n useImperativeHandle(ref, () => ({ submit: () => { void handleSubmit(); } }), [handleSubmit]);\n\n return (\n <>\n {children}\n\n <div\n ref={fileAreaRef}\n tabIndex={-1}\n aria-live=\"polite\"\n className=\"outline-none\"\n >\n <MediaInput\n spec={spec}\n selectedFile={selectedFile}\n uploadState={uploadState}\n isLoading={mutation.isPending}\n disabled={mutation.isPending}\n onChange={handleMediaChange}\n onClear={handleClear}\n onCancel={handleCancel}\n onBeforeSelect={onBeforeSelect}\n />\n </div>\n </>\n );\n}\n\nexport const DeferredUploadFormShell = forwardRef(DeferredUploadFormShellInner) as <\n TVariables extends {\n onProgress?: (s: UploadState | null) => void;\n signal?: AbortSignal;\n },\n TResult = unknown,\n>(\n props: DeferredUploadFormShellProps<TVariables, TResult> & { ref?: Ref<DeferredUploadFormShellHandle> },\n) => React.ReactElement;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"guarded-link.d.ts","sourceRoot":"","sources":["../../src/react/guarded-link.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGnD,MAAM,WAAW,qBAAqB;IACpC,6EAA6E;IAC7E,OAAO,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,KAAK,IAAI,CAAC;IAClD,yEAAyE;IACzE,QAAQ,EAAE,SAAS,CAAC;CACrB;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,SAAS,CAAC;IACpB,UAAU,EAAE,CAAC,IAAI,EAAE,qBAAqB,KAAK,SAAS,CAAC;CACxD;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,+BAWlD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"guarded-link.js","sourceRoot":"","sources":["../../src/react/guarded-link.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AA6Bb,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAcvE,MAAM,UAAU,WAAW,CAAC,KAAuB;IACjD,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,EAAE,iBAAiB,EAAE,GAAG,mBAAmB,EAAE,CAAC;IAEpD,MAAM,OAAO,GAAG,CAAC,KAA8B,EAAE,EAAE;QACjD,IAAI,CAAC,iBAAiB,EAAE,EAAE,CAAC;YACzB,KAAK,CAAC,cAAc,EAAE,CAAC;QACzB,CAAC;IACH,CAAC,CAAC;IAEF,OAAO,4BAAG,UAAU,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,GAAI,CAAC;AAClD,CAAC","sourcesContent":["'use client';\n\n/**\n * Render-prop link wrapper that guards navigation while an upload or unsaved\n * work is registered. The consumer owns the actual navigator component (Next.js Link,\n * React Router Link, plain anchor, etc.) — this wrapper only injects the\n * onClick interceptor.\n *\n * Why render-prop and not `as={Link}`? Polymorphic `as` props create\n * notoriously bad TypeScript inference and force the wrapper to forward all\n * link-specific props. Render-prop keeps the consumer in full control of the\n * link API, costs one extra wrapper closure, and keeps upload-ui agnostic of\n * Next.js / React Router / etc.\n *\n * Design note: the design spec lists `<GuardedNavigationButton>` as a second\n * component. We deliberately don't ship it — buttons that navigate use\n * `useGuardedNavigation()` directly in one line. A second component would\n * split the same surface for no payoff.\n *\n * Usage:\n *\n * <GuardedLink renderLink={({ onClick, children }) => (\n * <Link href=\"/your/destination\" onClick={onClick}>{children}</Link>\n * )}>\n * View all uploads →\n * </GuardedLink>\n */\n\nimport type { MouseEvent, ReactNode } from 'react';\nimport { useLocalUploadGuard } from './local-upload-guard-provider.js';\n\nexport interface GuardedLinkRenderArgs {\n /** Click handler the consumer MUST attach to its underlying link element. */\n onClick: (event: MouseEvent<HTMLElement>) => void;\n /** The children passed to `<GuardedLink>` — forward them to the link. */\n children: ReactNode;\n}\n\nexport interface GuardedLinkProps {\n children: ReactNode;\n renderLink: (args: GuardedLinkRenderArgs) => ReactNode;\n}\n\nexport function GuardedLink(props: GuardedLinkProps) {\n const { children, renderLink } = props;\n const { confirmNavigation } = useLocalUploadGuard();\n\n const onClick = (event: MouseEvent<HTMLElement>) => {\n if (!confirmNavigation()) {\n event.preventDefault();\n }\n };\n\n return <>{renderLink({ onClick, children })}</>;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"in-flight-uploads-provider.d.ts","sourceRoot":"","sources":["../../src/react/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAQL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AACf,OAAO,EAGL,wBAAwB,EACxB,KAAK,6BAA6B,EAClC,KAAK,kBAAkB,EACxB,MAAM,gCAAgC,CAAC;AASxC,qEAAqE;AACrE,MAAM,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AAEtD;;;;;;;GAOG;AACH,MAAM,MAAM,kBAAkB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,IAAI;IACpE,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,WAAW,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,oBAAoB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,IAClE,kBAAkB,CAAC,WAAW,CAAC,GAAG;IAChC,MAAM,EAAE,6BAA6B,CAAC;CACvC,CAAC;AAEJ,MAAM,MAAM,uBAAuB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,IACrE,kBAAkB,CAAC,WAAW,CAAC,GAAG;IAChC,MAAM,EAAE,OAAO,wBAAwB,CAAC,IAAI,CAAC,SAAS,CAAC;IACvD,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAA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qB,IAAI,kBAAkB,CAM1D;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,IAAI,kBAAkB,CAM1D;AAMD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,EAClE,IAAI,EAAE,cAAc,CAAC,WAAW,CAAC,GAChC,IAAI,IAAI,OAAO,CAAC,cAAc,CAAC,WAAW,CAAC,EAAE;IAAE,MAAM,EAAE,6BAA6B,CAAA;CAAE,CAAC,CAEzF;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,KAAK,cAAc,CAAC,WAAW,CAAC,EAAE,CAU3G"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"in-flight-uploads-provider.js","sourceRoot":"","sources":["../../src/react/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,gFAAgF;AAChF,0EAA0E;AAC1E,iFAAiF;AACjF,+CAA+C;AAC/C,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,kFAAkF;AAClF,mEAAmE;AACnE,+EAA+E;AAC/E,yEAAyE;AACzE,gEAAgE;AAChE,gFAAgF;AAChF,4EAA4E;AAC5E,EAAE;AACF,mFAAmF;AACnF,gFAAgF;AAChF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EACL,aAAa,EACb,WAAW,EACX,UAAU,EACV,SAAS,EACT,OAAO,EACP,MAAM,EACN,QAAQ,GAET,MAAM,OAAO,CAAC;AACf,OAAO,EACL,+BAA+B,EAC/B,4BAA4B,EAC5B,wBAAwB,GAGzB,MAAM,gCAAgC,CAAC;AAExC,4DAA4D;AAC5D,MAAM,MAAM,GAAG,wBAAwB,CAAC,IA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C;AAChB,CAAC;AAED,gFAAgF;AAChF,gDAAgD;AAChD,gFAAgF;AAEhF;;;;;;;;;;;;;;;GAeG;AACH,MAAM,yBAAyB,GAAyB,CAAC,IAAI,EAAE,EAAE;IAC/D,MAAM,CAAC,GAAG,KAAK,CAEb,UAAU,CAAC,IAAI,CAAC,EAAS,EAAE,IAAI,CAAC,cAAc,CAAC,EAC/C,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAClC,KAAK,CAAC,WAAW,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,CAC7C,CAAC;IACF,sFAAsF;IACtF,uFAAuF;IACvF,OAAO,UAAU,CAAC,CAAC,EAAE,EAAE,sBAAsB,EAAE,IAAI,EAAE,EAAE,IAAI,CAAC,UAAmB,EAAE,IAAI,CAAC,OAAgB,CAAC,CAAC;AAC1G,CAAC,CAAC","sourcesContent":["'use client';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// SANCTIONED EXCEPTION to the \"packages read/write Firestore only through\n// @ttt-productions/query-core\" rule (see docs/packages/package-architecture.md →\n// \"Firestore access goes through query-core\").\n//\n// WHY this provider reads Firestore directly instead of via a query-core hook:\n// 1. It needs snapshot *transition events* — onSnapshot's `docChanges()` with\n// added / modified / removed — to fire one-shot terminal callbacks and to\n// suppress the initial snapshot. query-core's hooks return \"the current\n// list\", not per-doc transitions, so they cannot express this state machine.\n// 2. The subscription is already abstracted behind an injectable\n// `FirestoreSubscribeFn` (the `subscribe` prop); the direct firebase code\n// path lives ONLY in `defaultFirestoreSubscribe` below and is fully\n// swappable (tests / alternate backends inject their own).\n// 3. The static ESM `firebase/firestore` import is load-bearing for Next.js +\n// Turbopack module identity (see defaultFirestoreSubscribe's comment).\n//\n// Do NOT \"migrate\" this onto query-core without preserving docChanges() semantics.\n// ─────────────────────────────────────────────────────────────────────────────\nimport { collection, onSnapshot, query, where } from 'firebase/firestore';\n\n/**\n * Generic in-flight uploads provider.\n *\n * Provides a global Map of in-flight upload state by `pendingMediaId`, derived\n * from a Firestore listener over the consumer-supplied collection. On terminal\n * status transitions observed THIS SESSION, fires consumer-supplied success /\n * failure / rejection callbacks. Records monitoring breadcrumbs and parse\n * errors through the injected monitoring callback.\n *\n * EVERY app-specific value is supplied by the consumer:\n * - userId resolution\n * - Firestore `db` reference\n * - collection path\n * - listener time window (ms)\n * - parser/schema for raw Firestore doc → typed PendingMedia\n * - success copy per origin\n * - notification callback (cache invalidation, etc.)\n * - toast callback\n * - rejection callback (for the media-rejection dialog or equivalent)\n * - monitoring callback (breadcrumbs + captured errors)\n *\n * Read APIs:\n * - `useInFlightUploadsState()` — full Map.\n * - `useInFlightUpload(id)` — single doc, narrowable on status.\n * - `useUploadActivityState()` — tray-visible items, sorted newest-first.\n *\n * The package owns the deduplication, initial-snapshot suppression, and\n * non-terminal → terminal transition tracking. It does NOT own anything about\n * what a file-origin is or what message text appears in toasts.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {\n isPendingMediaNonTerminalStatus,\n isPendingMediaTerminalStatus,\n PendingMediaStatusSchema,\n type PendingMediaNonTerminalStatus,\n type PendingMediaStatus,\n} from '@ttt-productions/media-schemas';\n\n// Status values derive from media-schemas' one declaration.\nconst STATUS = PendingMediaStatusSchema.enum;\n\n// =============================================================================\n// Generic shape of the data the provider tracks\n// =============================================================================\n\n/** Generic pending-media status — media-schemas' one declaration. */\nexport type InFlightUploadStatus = PendingMediaStatus;\n\n/**\n * Generic in-flight upload record. The provider keeps a Map<id, InFlightUpload>\n * built from each parsed PendingMedia. Consumers parameterize the `fileOrigin`\n * type via the parser's return type (the provider treats it as opaque).\n *\n * `TFileOrigin` defaults to `string` so unannotated consumers get a permissive\n * shape; consuming apps bind it to their own `FileOrigin` union at the call site.\n */\nexport type InFlightUploadBase<TFileOrigin extends string = string> = {\n id: string;\n fileOrigin: TFileOrigin;\n surface: string;\n createdAt: number;\n targetIds?: string[];\n originalContentType?: string;\n originalSize?: number;\n};\n\nexport type InFlightUploadActive<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: PendingMediaNonTerminalStatus;\n };\n\nexport type InFlightUploadCompleted<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: typeof PendingMediaStatusSchema.enum.completed;\n completedAt: number;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n };\n\nexport type InFlightUploadFailed<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: typeof PendingMediaStatusSchema.enum.failed;\n failedAt: number;\n errorCategory: string;\n errorMessage: string;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n };\n\nexport type InFlightUploadRejected<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: typeof PendingMediaStatusSchema.enum.rejected;\n rejectedAt: number;\n rejectionType: 'text' | 'media';\n errorMessage: string;\n violationId?: string;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n };\n\nexport type InFlightUpload<TFileOrigin extends string = string> =\n | InFlightUploadActive<TFileOrigin>\n | InFlightUploadCompleted<TFileOrigin>\n | InFlightUploadFailed<TFileOrigin>\n | InFlightUploadRejected<TFileOrigin>;\n\n// =============================================================================\n// Adapter contract — every app-specific behavior is injected here\n// =============================================================================\n\n/**\n * Result of the consumer-supplied parser. The provider keeps the raw parsed\n * record for callbacks (so consumers can read domain events, target IDs, etc.)\n * AND derives the generic InFlightUpload from it for the public Map.\n *\n * The parser MUST throw if validation fails; the provider catches and routes\n * the error to the monitoring callback.\n */\nexport type ParsedPendingMedia<TFileOrigin extends string = string> = {\n id: string;\n userId: string;\n fileOrigin: TFileOrigin;\n status: InFlightUploadStatus;\n createdAt: number;\n surface: string;\n targetIds?: string[];\n originalContentType?: string;\n originalSize?: number;\n // Terminal-status fields (only meaningful for the matching status)\n completedAt?: number;\n failedAt?: number;\n rejectedAt?: number;\n errorCategory?: string;\n errorMessage?: string;\n rejectionType?: 'text' | 'media';\n violationId?: string;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n /**\n * Opaque consumer-controlled domain-event payload, surfaced to the\n * `onUploadCompleted` and `onUploadRejected` callbacks for cache\n * invalidation. The provider does not interpret it.\n */\n domainEvents?: unknown;\n};\n\nexport type InFlightUploadsAdapter<TFileOrigin extends string = string> = {\n /** Returns the current user's uid, or null if not signed in. */\n getCurrentUserId: () => string | null;\n\n /** Firestore database adapter (loose typing — `unknown` keeps zero firebase coupling at the type level). */\n db: unknown;\n\n /** Collection path holding pending-media docs (e.g. \"pendingMedia\"). */\n collectionPath: string;\n\n /** Listener window in milliseconds — only docs with `createdAt >= now - window` are tracked. */\n listenerWindowMs: number;\n\n /**\n * Parse a raw Firestore doc snapshot's `.data()` into the generic shape the\n * provider tracks. Throws on validation failure; the provider routes thrown\n * errors to `onMonitoringEvent`.\n */\n parsePendingMedia: (raw: unknown) => ParsedPendingMedia<TFileOrigin>;\n\n /** Called once per observed non-terminal → terminal completed transition. */\n onUploadCompleted: (parsed: ParsedPendingMedia<TFileOrigin>) => void;\n\n /** Called once per observed non-terminal → terminal failed transition. */\n onUploadFailed: (parsed: ParsedPendingMedia<TFileOrigin>) => void;\n\n /** Called once per observed non-terminal → terminal rejected transition. */\n onUploadRejected: (parsed: ParsedPendingMedia<TFileOrigin>) => void;\n\n /**\n * Monitoring callback. Receives:\n * - `breadcrumb`: informational, fired on every observed terminal transition.\n * - `parse-error`: when `parsePendingMedia` throws.\n * - `listener-error`: when the Firestore listener's error callback fires.\n *\n * Consumers wire this to Sentry, OpenTelemetry, or any other observability\n * provider. The provider does NOT import any monitoring SDK directly.\n */\n onMonitoringEvent: (event: InFlightUploadsMonitoringEvent<TFileOrigin>) => void;\n};\n\nexport type InFlightUploadsMonitoringEvent<TFileOrigin extends string = string> =\n | {\n type: 'breadcrumb';\n category: 'upload.terminal';\n level: 'info';\n message: string;\n data: {\n id: string;\n fileOrigin: TFileOrigin;\n status: InFlightUploadStatus;\n surface: string;\n };\n }\n | {\n type: 'parse-error';\n docId: string;\n error: unknown;\n data: unknown;\n }\n | {\n type: 'listener-error';\n error: unknown;\n };\n\n// =============================================================================\n// Firestore subscription contract — abstracted to avoid firebase coupling\n// =============================================================================\n\n/**\n * Minimal subscription contract used by the provider. The default\n * implementation lives in `firestore-subscribe.ts` and uses the standard\n * `firebase/firestore` `onSnapshot` + `query` + `where` builders.\n *\n * Tests inject a fake to drive the listener without spinning up Firestore.\n */\nexport type FirestoreSubscribeFn = (args: {\n db: unknown;\n collectionPath: string;\n userId: string;\n windowStartMs: number;\n onSnapshot: (snapshot: FirestoreLikeSnapshot) => void;\n onError: (error: unknown) => void;\n}) => () => void;\n\nexport type FirestoreLikeSnapshot = {\n docChanges: () => FirestoreLikeDocChange[];\n /**\n * Snapshot metadata. Present when the subscription is opened with\n * `{ includeMetadataChanges: true }` (the default firebase implementation does).\n * `fromCache === false` means a server-confirmed snapshot. Optional so injected\n * test fakes need not supply it (absent ⇒ treated as server-confirmed).\n */\n metadata?: { fromCache: boolean };\n};\n\n/**\n * Metadata-derived liveness of the uploads listener, mirroring query-core's\n * `FirestoreSourceState`. Firestore serves cached snapshots offline WITHOUT\n * firing the error callback, so the Files tray source needs this to show a\n * degraded indicator instead of a false \"all caught up\":\n * - `connecting` — no server-confirmed snapshot yet.\n * - `live` — at least one server-confirmed snapshot (`fromCache === false`).\n * - `offline` — only cached data after having been live.\n * - `error` — the listener error callback fired.\n */\nexport type UploadsSourceState = 'connecting' | 'live' | 'offline' | 'error';\n\nexport type FirestoreLikeDocChange = {\n type: 'added' | 'modified' | 'removed';\n doc: {\n id: string;\n data: () => unknown;\n };\n};\n\n// =============================================================================\n// Provider\n// =============================================================================\n\ninterface InFlightUploadsContextValue<TFileOrigin extends string = string> {\n uploads: Map<string, InFlightUpload<TFileOrigin>>;\n sourceState: UploadsSourceState;\n retry: () => void;\n retrying: boolean;\n}\n\n/** Restarting the uploads listener after it failed, and whether that restart is running. */\nexport interface UploadsSourceRetry {\n /**\n * Tear the listener down and subscribe again on a fresh retry ladder. While the restart runs the\n * source state stays as it was (an `error` stays `error`), so a failure shown on it stays on\n * screen with its control pending.\n */\n retry: () => void;\n /** A `retry` is running: true until the restarted listener answers or its ladder fails again. */\n retrying: boolean;\n}\n\nconst InFlightUploadsContext = createContext<InFlightUploadsContextValue | undefined>(undefined);\n\nexport interface InFlightUploadsProviderProps<TFileOrigin extends string = string> {\n adapter: InFlightUploadsAdapter<TFileOrigin>;\n /** Firestore subscription function. Defaults to the firebase/firestore implementation. */\n subscribe?: FirestoreSubscribeFn;\n children: ReactNode;\n}\n\nfunction fromParsed<TFileOrigin extends string>(\n parsed: ParsedPendingMedia<TFileOrigin>,\n): InFlightUpload<TFileOrigin> {\n const base: InFlightUploadBase<TFileOrigin> = {\n id: parsed.id,\n fileOrigin: parsed.fileOrigin,\n surface: parsed.surface,\n createdAt: parsed.createdAt,\n targetIds: parsed.targetIds,\n originalContentType: parsed.originalContentType,\n originalSize: parsed.originalSize,\n };\n if (isPendingMediaNonTerminalStatus(parsed.status)) {\n return { ...base, status: parsed.status };\n }\n if (parsed.status === STATUS.completed) {\n return {\n ...base,\n status: STATUS.completed,\n completedAt: parsed.completedAt ?? parsed.createdAt,\n uploadTrayClearedAt: parsed.uploadTrayClearedAt,\n uploadTrayClearedBy: parsed.uploadTrayClearedBy,\n uploadTraySeenAt: parsed.uploadTraySeenAt,\n uploadTraySeenBy: parsed.uploadTraySeenBy,\n };\n }\n if (parsed.status === STATUS.failed) {\n return {\n ...base,\n status: STATUS.failed,\n failedAt: parsed.failedAt ?? parsed.createdAt,\n errorCategory: parsed.errorCategory ?? 'system',\n errorMessage: parsed.errorMessage ?? '',\n uploadTrayClearedAt: parsed.uploadTrayClearedAt,\n uploadTrayClearedBy: parsed.uploadTrayClearedBy,\n uploadTraySeenAt: parsed.uploadTraySeenAt,\n uploadTraySeenBy: parsed.uploadTraySeenBy,\n };\n }\n // rejected\n return {\n ...base,\n status: STATUS.rejected,\n rejectedAt: parsed.rejectedAt ?? parsed.createdAt,\n rejectionType: parsed.rejectionType ?? 'media',\n errorMessage: parsed.errorMessage ?? '',\n violationId: parsed.violationId,\n uploadTrayClearedAt: parsed.uploadTrayClearedAt,\n uploadTrayClearedBy: parsed.uploadTrayClearedBy,\n // Carry the seen fields through (round-9 finding 9): dropping them on the\n // `rejected` branch — while `completed`/`failed` keep them — made a seen\n // rejected upload relight the Files dot forever, because the tray's\n // unseen-terminal check never saw `uploadTraySeenAt`.\n uploadTraySeenAt: parsed.uploadTraySeenAt,\n uploadTraySeenBy: parsed.uploadTraySeenBy,\n };\n}\n\nexport function InFlightUploadsProvider<TFileOrigin extends string = string>(\n props: InFlightUploadsProviderProps<TFileOrigin>,\n) {\n const { adapter, subscribe = defaultFirestoreSubscribe, children } = props;\n\n const [uploads, setUploads] = useState<Map<string, InFlightUpload<TFileOrigin>>>(new Map());\n const [sourceState, setSourceState] = useState<UploadsSourceState>('connecting');\n const [restarts, setRestarts] = useState(0);\n const [retrying, setRetrying] = useState(false);\n /** Set by `retry` for the subscription the restart opens; that run keeps the source state. */\n const restartRequestedRef = useRef(false);\n const seenTerminalIdsRef = useRef<Set<string>>(new Set());\n const statusByIdRef = useRef<Map<string, InFlightUploadStatus>>(new Map());\n const hasProcessedInitialSnapshotRef = useRef(false);\n /** The identity the dedup/tracking refs belong to — they outlive resubscribes\n * for the SAME user (auth-settling flaps) and reset only on a real identity\n * change. See the reset block in the subscription effect. */\n const trackedUserIdRef = useRef<string | null>(null);\n\n // Stable refs for adapter callbacks — read from latest adapter inside effect.\n const adapterRef = useRef(adapter);\n useEffect(() => {\n adapterRef.current = adapter;\n });\n\n const userId = adapter.getCurrentUserId();\n\n useEffect(() => {\n // The uploads map and source state rebuild from every subscription's initial\n // snapshot, so they reset on every effect run. The terminal-dedup and\n // status-tracking refs are IDENTITY-scoped, not subscription-scoped: an\n // auth-settling flap (uid → null → same uid re-subscribes) must neither\n // re-fire terminals the previous subscription already fired (seen set\n // persists) nor lose the observed non-terminal statuses that let the new\n // subscription's initial listing detect a transition that completed during\n // the gap. A real identity change — including UID-A → UID-B with no\n // intermediate null user — starts clean; never rely on an intermediate\n // sign-out to clear refs between two authenticated UIDs.\n // A restart the person asked for keeps the source state it had (a failure stays a failure\n // until the restarted listener answers); every other run starts over as `connecting`.\n // A restart belongs to the identity it was asked for: one that lands with a sign-out or a switch\n // of account is an ordinary new subscription, which starts over.\n let restarting = restartRequestedRef.current && userId !== null && userId === trackedUserIdRef.current;\n restartRequestedRef.current = false;\n setUploads(new Map());\n if (!restarting) {\n setSourceState('connecting');\n setRetrying(false);\n }\n if (userId !== null && userId !== trackedUserIdRef.current) {\n seenTerminalIdsRef.current = new Set();\n statusByIdRef.current = new Map();\n trackedUserIdRef.current = userId;\n }\n hasProcessedInitialSnapshotRef.current = false;\n\n if (!userId) {\n return;\n }\n\n const a = adapterRef.current;\n const windowStartMs = Date.now() - a.listenerWindowMs;\n\n const handleSnapshot = (snapshot: FirestoreLikeSnapshot) => {\n const updates: Array<{ id: string; upload: InFlightUpload<TFileOrigin> | null }> = [];\n const newlyTerminal: Array<ParsedPendingMedia<TFileOrigin>> = [];\n const isInitialSnapshot = !hasProcessedInitialSnapshotRef.current;\n\n for (const change of snapshot.docChanges()) {\n if (change.type === 'removed') {\n updates.push({ id: change.doc.id, upload: null });\n statusByIdRef.current.delete(change.doc.id);\n seenTerminalIdsRef.current.delete(change.doc.id);\n continue;\n }\n\n let parsed: ParsedPendingMedia<TFileOrigin>;\n try {\n parsed = adapterRef.current.parsePendingMedia(change.doc.data());\n } catch (error) {\n adapterRef.current.onMonitoringEvent({\n type: 'parse-error',\n docId: change.doc.id,\n error,\n data: change.doc.data(),\n });\n continue;\n }\n\n const upload = fromParsed(parsed);\n updates.push({ id: parsed.id, upload });\n\n const previousStatus = statusByIdRef.current.get(parsed.id);\n const currentStatus = parsed.status;\n const currentIsTerminal = isPendingMediaTerminalStatus(currentStatus);\n const previousWasNonTerminal = isPendingMediaNonTerminalStatus(previousStatus);\n\n if (isInitialSnapshot) {\n // A subscription's first snapshot is a (re-)listing of current state,\n // not a live event: already-terminal docs stay suppressed so a page\n // refresh never re-toasts. ONE exception — this provider instance\n // tracked the doc as non-terminal before (same-identity resubscribe\n // gap; the tracking refs survive those), so the terminal listing IS\n // the transition, observed across the gap, and must fire.\n if (currentIsTerminal) {\n if (previousWasNonTerminal && !seenTerminalIdsRef.current.has(parsed.id)) {\n newlyTerminal.push(parsed);\n }\n seenTerminalIdsRef.current.add(parsed.id);\n }\n } else if (currentIsTerminal && !seenTerminalIdsRef.current.has(parsed.id)) {\n // Any unseen terminal in a LIVE snapshot fires — including a doc whose\n // FIRST client-visible state is already terminal. A fast backend\n // outcome (moderation rejection in ~2s) can coalesce created→terminal\n // into one delivery, and the uploader is actively waiting on exactly\n // this callback; swallowing it silently loses a rejection dialog.\n seenTerminalIdsRef.current.add(parsed.id);\n newlyTerminal.push(parsed);\n }\n\n statusByIdRef.current.set(parsed.id, currentStatus);\n }\n\n hasProcessedInitialSnapshotRef.current = true;\n\n // Metadata-derived source state: stay `connecting` until a server-confirmed\n // snapshot, `offline` if only cached data arrives after being live.\n const fromCache = snapshot.metadata?.fromCache ?? false;\n // A restart ends on the server's answer: a cached snapshot during it keeps the failure on screen\n // (the server may refuse again). Otherwise a snapshot after a failed listener comes from a new\n // subscription: not yet live, never offline.\n if (!(restarting && fromCache)) {\n setSourceState((prev) =>\n fromCache ? (prev === 'connecting' || prev === 'error' ? 'connecting' : 'offline') : 'live',\n );\n restarting = false;\n setRetrying(false);\n }\n\n if (updates.length > 0) {\n setUploads((prev) => {\n const next = new Map(prev);\n for (const { id, upload } of updates) {\n if (upload === null) next.delete(id);\n else next.set(id, upload);\n }\n return next;\n });\n }\n\n for (const parsed of newlyTerminal) {\n handleTerminal(parsed);\n }\n };\n\n function handleTerminal(parsed: ParsedPendingMedia<TFileOrigin>) {\n adapterRef.current.onMonitoringEvent({\n type: 'breadcrumb',\n category: 'upload.terminal',\n level: 'info',\n message: `${parsed.fileOrigin}:${parsed.status}`,\n data: {\n id: parsed.id,\n fileOrigin: parsed.fileOrigin,\n status: parsed.status,\n surface: parsed.surface,\n },\n });\n\n if (parsed.status === STATUS.completed) {\n adapterRef.current.onUploadCompleted(parsed);\n } else if (parsed.status === STATUS.failed) {\n adapterRef.current.onUploadFailed(parsed);\n } else if (parsed.status === STATUS.rejected) {\n adapterRef.current.onUploadRejected(parsed);\n }\n }\n\n // Bounded RESUBSCRIBE on listener error: a cold-session race (e.g. Firestore\n // App Check enforcement rejecting the first attach before the token is\n // minted) must not kill the listener for the whole session — observed live:\n // one permission-denied at first login → sourceState 'error' forever, every\n // tray file status dead until reload. Retry on a short ladder; a snapshot\n // resets the ladder (healthy again); exhausting it goes terminal 'error'\n // (a real rules denial stays denied — retries are cheap and bounded).\n const RESUBSCRIBE_DELAYS_MS = [1_000, 3_000, 10_000, 30_000];\n let attempt = 0;\n let disposed = false;\n let retryTimer: ReturnType<typeof setTimeout> | undefined;\n let unsubscribe: (() => void) | undefined;\n\n const start = () => {\n unsubscribe = subscribe({\n db: a.db,\n collectionPath: a.collectionPath,\n userId,\n windowStartMs,\n onSnapshot: (snapshot) => {\n attempt = 0; // healthy — future errors get a fresh ladder\n handleSnapshot(snapshot);\n },\n onError: (error) => {\n adapterRef.current.onMonitoringEvent({ type: 'listener-error', error });\n unsubscribe?.();\n unsubscribe = undefined;\n if (disposed || attempt >= RESUBSCRIBE_DELAYS_MS.length) {\n setSourceState('error');\n setRetrying(false);\n return;\n }\n if (!restarting) setSourceState('connecting');\n retryTimer = setTimeout(() => {\n if (disposed) return;\n attempt += 1;\n start();\n }, RESUBSCRIBE_DELAYS_MS[attempt]);\n },\n });\n };\n start();\n\n return () => {\n disposed = true;\n if (retryTimer) clearTimeout(retryTimer);\n unsubscribe?.();\n };\n // adapter is intentionally NOT in the deps array — adapter is read via\n // adapterRef on every snapshot, so identity changes don't re-subscribe.\n\n }, [userId, subscribe, restarts]);\n\n const retry = useCallback(() => {\n restartRequestedRef.current = true;\n setRetrying(true);\n setRestarts((count) => count + 1);\n }, []);\n\n const value = useMemo<InFlightUploadsContextValue<TFileOrigin>>(\n () => ({ uploads, sourceState, retry, retrying }),\n [uploads, sourceState, retry, retrying],\n );\n\n return (\n <InFlightUploadsContext.Provider value={value as InFlightUploadsContextValue}>\n {children}\n </InFlightUploadsContext.Provider>\n );\n}\n\n// =============================================================================\n// Read APIs\n// =============================================================================\n\nexport function useInFlightUploadsState<TFileOrigin extends string = string>(): Map<\n string,\n InFlightUpload<TFileOrigin>\n> {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useInFlightUploadsState must be used within InFlightUploadsProvider');\n }\n return ctx.uploads as Map<string, InFlightUpload<TFileOrigin>>;\n}\n\nexport function useInFlightUpload<TFileOrigin extends string = string>(\n id: string | null | undefined,\n): InFlightUpload<TFileOrigin> | undefined {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useInFlightUpload must be used within InFlightUploadsProvider');\n }\n if (!id) return undefined;\n return ctx.uploads.get(id) as InFlightUpload<TFileOrigin> | undefined;\n}\n\n/**\n * Metadata-derived source state of the uploads listener\n * (`connecting | live | offline | error`). The Files tray uses this to show a\n * degraded indicator and never display \"all caught up\" while the source is\n * `offline`/`error`/`connecting`.\n */\nexport function useUploadsSourceState(): UploadsSourceState {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useUploadsSourceState must be used within InFlightUploadsProvider');\n }\n return ctx.sourceState;\n}\n\n/**\n * The uploads listener's restart — the Try again of a failure shown on `useUploadsSourceState` —\n * and whether it is running.\n */\nexport function useUploadsSourceRetry(): UploadsSourceRetry {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useUploadsSourceRetry must be used within InFlightUploadsProvider');\n }\n return { retry: ctx.retry, retrying: ctx.retrying };\n}\n\n// =============================================================================\n// Tray helpers\n// =============================================================================\n\n/**\n * `true` for `completed` / `failed` / `rejected`. Used by tray UI to decide\n * whether a Clear action is available for an item.\n */\nexport function isTerminalUpload<TFileOrigin extends string = string>(\n item: InFlightUpload<TFileOrigin>,\n): item is Exclude<InFlightUpload<TFileOrigin>, { status: PendingMediaNonTerminalStatus }> {\n return isPendingMediaTerminalStatus(item.status);\n}\n\n/**\n * Tray-visible items. Includes every pending/processing upload, plus terminal\n * uploads that have NOT been cleared from the tray. Sorted newest-first by\n * createdAt.\n *\n * The public selector name in upload-ui is `useUploadActivityState`. The\n * mutation hook is `useClearUploadActivity` (in a separate file).\n */\nexport function useUploadActivityState<TFileOrigin extends string = string>(): InFlightUpload<TFileOrigin>[] {\n const uploads = useInFlightUploadsState<TFileOrigin>();\n return useMemo(() => {\n return Array.from(uploads.values())\n .filter((item) => {\n if (!isTerminalUpload(item)) return true;\n return item.uploadTrayClearedAt === undefined;\n })\n .sort((a, b) => b.createdAt - a.createdAt);\n }, [uploads]);\n}\n\n// =============================================================================\n// Default Firestore subscription implementation\n// =============================================================================\n\n/**\n * Default Firestore subscription using the consumer's `firebase/firestore`\n * module instance (via static ESM import at the top of this file).\n *\n * Using static ESM import — NOT `require()` — is load-bearing. CommonJS\n * `require('firebase/firestore')` and ESM `import 'firebase/firestore'` resolve\n * to different module instances under Next.js + Turbopack. If the consumer\n * constructs `db` via ESM and we receive it here, but we then call\n * `collection()` from a CJS-loaded copy of firebase, the firebase runtime\n * does not recognize the db as a Firestore instance and throws\n * \"Expected first argument to collection() to be a CollectionReference,\n * a DocumentReference or FirebaseFirestore\".\n *\n * Consumers who want to skip the firebase code path entirely (tests, alt\n * backends) supply their own `subscribe` prop to `InFlightUploadsProvider`.\n */\nconst defaultFirestoreSubscribe: FirestoreSubscribeFn = (args) => {\n const q = query(\n\n collection(args.db as any, args.collectionPath),\n where('userId', '==', args.userId),\n where('createdAt', '>=', args.windowStartMs),\n );\n // includeMetadataChanges so the provider can derive a `connecting|live|offline|error`\n // source state from `snapshot.metadata.fromCache` (the Files tray degraded indicator).\n return onSnapshot(q, { includeMetadataChanges: true }, args.onSnapshot as never, args.onError as never);\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"local-upload-guard-provider.d.ts","sourceRoot":"","sources":["../../src/react/local-upload-guard-provider.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EASL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,MAAM,WAAW,wBAAwB;IACvC;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,UAAU,4BAA4B;IACpC,gCAAgC;IAChC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,yCAAyC;IACzC,gBAAgB,EAAE,MAAM,CAAC;IACzB,oGAAoG;IACpG,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,gBAAgB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,mBAAmB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IAC1C,qBAAqB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5C,qFAAqF;IACrF,uBAAuB,EAAE,MAAM,OAAO,CAAC;IACvC;;;;;;;;;OASG;IACH,iBAAiB,EAAE,CAAC,OAAO,CAAC,EAAE,wBAAwB,KAAK,OAAO,CAAC;CACpE;AAID,MAAM,WAAW,6BAA6B;IAC5C;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,4FAA4F;IAC5F,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,wFAAwF;IACxF,yBAAyB,CAAC,EAAE,MAAM,CAAC;IACnC,4FAA4F;IAC5F,kCAAkC,CAAC,EAAE,MAAM,CAAC;IAC5C,QAAQ,EAAE,SAAS,CAAC;CACrB;AAoCD,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,6BAA6B,+BAoH5E;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,IAAI,4BAA4B,CAQzE;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,IAAI,4BAA4B,GAAG,IAAI,CAEjF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,IAAI,4BAA4B,CAElE;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,cAAc,EAAE,OAAO,GAAG;IAAE,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CAUpF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"local-upload-guard-provider.js","sourceRoot":"","sources":["../../src/react/local-upload-guard-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EACL,aAAa,EACb,WAAW,EACX,UAAU,EACV,SAAS,EACT,KAAK,EACL,OAAO,EACP,MAAM,EACN,QAAQ,GAET,MAAM,OAAO,CAAC;AAuCf,MAAM,uBAAuB,GAAG,aAAa,CAA2C,SAAS,CAAC,CAAC;AAkBnG,MAAM,kCAAkC,GACtC,oGAAoG,CAAC;AACvG,MAAM,oCAAoC,GACxC,gFAAgF,CAAC;AACnF,MAAM,+CAA+C,GACnD,qJAAqJ,CAAC;AACxJ,MAAM,oCAAoC,GACxC,kFAAkF,CAAC;AACrF,MAAM,0CAA0C,GAC9C,yEAAyE,CAAC;AAE5E,SAAS,WAAW,CAAC,UAAsB;IACzC,MAAM,MAAM,GAAG,MAAM,CAAc,IAAI,GAAG,EAAE,CAAC,CAAC;IA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,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,cAAc;YAAE,OAAO;QAC5B,mBAAmB,CAAC,EAAE,CAAC,CAAC;QACxB,OAAO,GAAG,EAAE,CAAC,qBAAqB,CAAC,EAAE,CAAC,CAAC;IACzC,CAAC,EAAE,CAAC,cAAc,EAAE,EAAE,EAAE,mBAAmB,EAAE,qBAAqB,CAAC,CAAC,CAAC;IACrE,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,qBAAqB,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,qBAAqB,CAAC,CAAC,CAAC;IAC1F,OAAO,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;AACjD,CAAC","sourcesContent":["'use client';\n\n/**\n * The navigation and leave guard: warns before the user leaves while work that leaving would lose\n * is registered — a LOCAL byte upload in flight, or an editor's unsaved input.\n *\n * Uploads: phases `preparing` and `uploading` only. `finalizing` and backend `pendingMedia`\n * processing are safe to leave (the bytes are already in Storage), so they are not registered.\n * Unsaved work: an editor registers while it holds input its user has not saved, and unregisters\n * when the input is saved, discarded, or the editor unmounts.\n *\n * While anything is registered the provider installs ONE `beforeunload` listener (tab close,\n * reload, full-page navigation), and `confirmNavigation()` asks before an in-app navigation. It is\n * the one leave guard: an editor never installs its own `beforeunload` handler (FRONTEND-207).\n *\n * Consumers register with a stable id per piece of work; registering a registered id, or\n * unregistering an absent one, is a no-op. Uploads and unsaved work are counted separately, so the\n * same id may be both.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\n\nexport interface ConfirmNavigationOptions {\n /**\n * The caller leaves through a FULL-PAGE navigation (`location.assign` /\n * `location.replace`) once this returns true. The provider then lets that\n * navigation's next `beforeunload` pass without the browser's own\n * \"Leave site?\" prompt, because the user has just answered this one. Soft\n * (in-app router) navigations never pass it: they fire no `beforeunload`.\n */\n fullPageNavigation?: boolean;\n}\n\ninterface LocalUploadGuardContextValue {\n /** Registered local uploads. */\n activeUploadCount: number;\n /** Registered pieces of unsaved work. */\n unsavedWorkCount: number;\n /** Everything the guard warns about: uploads plus unsaved work. Zero means leaving asks nothing. */\n guardedWorkCount: number;\n registerUpload: (id: string) => void;\n unregisterUpload: (id: string) => void;\n registerUnsavedWork: (id: string) => void;\n unregisterUnsavedWork: (id: string) => void;\n /** Returns true iff an upload or unsaved work is currently registered. Pure read. */\n shouldConfirmNavigation: () => boolean;\n /**\n * Shows a confirm() dialog with the message for what is registered and returns the user's\n * choice. Safe to call when nothing is registered — returns true without prompting.\n *\n * With `{ fullPageNavigation: true }` and a result of true (confirmed, or nothing registered),\n * arms a ONE-SHOT bypass: the next `beforeunload` is not prevented, so a confirmed full-page\n * navigation does not prompt twice. A declined confirm never arms it; the bypass is cleared when\n * it is consumed, when new work (an upload or unsaved work) registers, and on `pageshow` (a\n * back/forward-cache return).\n */\n confirmNavigation: (options?: ConfirmNavigationOptions) => boolean;\n}\n\nconst LocalUploadGuardContext = createContext<LocalUploadGuardContextValue | undefined>(undefined);\n\nexport interface LocalUploadGuardProviderProps {\n /**\n * Message the browser is given when the user closes the tab, reloads, or leaves the page while\n * work is registered. Modern browsers show their own generic dialog and ignore it; when omitted,\n * the default for what is registered is used.\n */\n beforeUnloadMessage?: string;\n /** `confirmNavigation()`'s message while an upload is in progress (and no unsaved work). */\n navigationConfirmMessage?: string;\n /** `confirmNavigation()`'s message while unsaved work is registered (and no upload). */\n unsavedWorkConfirmMessage?: string;\n /** `confirmNavigation()`'s message while both an upload and unsaved work are registered. */\n uploadAndUnsavedWorkConfirmMessage?: string;\n children: ReactNode;\n}\n\nconst DEFAULT_NAVIGATION_CONFIRM_MESSAGE =\n 'An upload is currently in progress. If you leave this page, the upload will be canceled. Continue?';\nconst DEFAULT_UNSAVED_WORK_CONFIRM_MESSAGE =\n 'You have unsaved changes. If you leave this page, they will be lost. Continue?';\nconst DEFAULT_UPLOAD_AND_UNSAVED_WORK_CONFIRM_MESSAGE =\n 'An upload is in progress and you have unsaved changes. If you leave this page, the upload will be canceled and your changes will be lost. Continue?';\nconst DEFAULT_UPLOAD_BEFORE_UNLOAD_MESSAGE =\n 'File upload in progress. Are you sure you want to leave and end the file upload?';\nconst DEFAULT_UNSAVED_WORK_BEFORE_UNLOAD_MESSAGE =\n 'You have unsaved changes. Are you sure you want to leave and lose them?';\n\nfunction useRegistry(onRegister: () => void) {\n const idsRef = useRef<Set<string>>(new Set());\n const [count, setCount] = useState(0);\n\n const register = useCallback(\n (id: string) => {\n if (idsRef.current.has(id)) return;\n onRegister();\n idsRef.current.add(id);\n setCount(idsRef.current.size);\n },\n [onRegister],\n );\n\n const unregister = useCallback((id: string) => {\n if (!idsRef.current.has(id)) return;\n idsRef.current.delete(id);\n setCount(idsRef.current.size);\n }, []);\n\n return { idsRef, count, register, unregister };\n}\n\nexport function LocalUploadGuardProvider(props: LocalUploadGuardProviderProps) {\n const {\n children,\n beforeUnloadMessage,\n navigationConfirmMessage = DEFAULT_NAVIGATION_CONFIRM_MESSAGE,\n unsavedWorkConfirmMessage = DEFAULT_UNSAVED_WORK_CONFIRM_MESSAGE,\n uploadAndUnsavedWorkConfirmMessage = DEFAULT_UPLOAD_AND_UNSAVED_WORK_CONFIRM_MESSAGE,\n } = props;\n // One-shot: the user already confirmed the full-page navigation now unloading.\n const bypassNextUnloadRef = useRef(false);\n // Also run when work registers: work that starts after a confirmation was not covered by it.\n const clearBypass = useCallback(() => {\n bypassNextUnloadRef.current = false;\n }, []);\n\n const uploads = useRegistry(clearBypass);\n const unsavedWork = useRegistry(clearBypass);\n const uploadIdsRef = uploads.idsRef;\n const unsavedWorkIdsRef = unsavedWork.idsRef;\n const guardedWorkCount = uploads.count + unsavedWork.count;\n const hasGuardedWork = guardedWorkCount > 0;\n\n // Read at the moment of asking, so a message always matches what is registered right then.\n const confirmMessage = useCallback((): string => {\n const uploading = uploadIdsRef.current.size > 0;\n const unsaved = unsavedWorkIdsRef.current.size > 0;\n if (uploading && unsaved) return uploadAndUnsavedWorkConfirmMessage;\n return uploading ? navigationConfirmMessage : unsavedWorkConfirmMessage;\n }, [\n uploadIdsRef,\n unsavedWorkIdsRef,\n navigationConfirmMessage,\n unsavedWorkConfirmMessage,\n uploadAndUnsavedWorkConfirmMessage,\n ]);\n\n useEffect(() => {\n if (!hasGuardedWork) return;\n\n const handleBeforeUnload = (event: BeforeUnloadEvent) => {\n if (bypassNextUnloadRef.current) {\n bypassNextUnloadRef.current = false;\n return;\n }\n event.preventDefault();\n // Modern browsers may ignore the custom string and show their own generic confirmation;\n // what matters is that leaving is warned, not the exact text.\n event.returnValue =\n beforeUnloadMessage ??\n (uploadIdsRef.current.size > 0\n ? DEFAULT_UPLOAD_BEFORE_UNLOAD_MESSAGE\n : DEFAULT_UNSAVED_WORK_BEFORE_UNLOAD_MESSAGE);\n return event.returnValue;\n };\n\n window.addEventListener('beforeunload', handleBeforeUnload);\n return () => {\n window.removeEventListener('beforeunload', handleBeforeUnload);\n };\n }, [hasGuardedWork, beforeUnloadMessage, uploadIdsRef]);\n\n // A back/forward-cache return re-shows this page without reloading it: an\n // armed bypass from the navigation that left must never outlive that navigation.\n useEffect(() => {\n window.addEventListener('pageshow', clearBypass);\n return () => {\n window.removeEventListener('pageshow', clearBypass);\n };\n }, [clearBypass]);\n\n const shouldConfirmNavigation = useCallback(\n () => uploadIdsRef.current.size > 0 || unsavedWorkIdsRef.current.size > 0,\n [uploadIdsRef, unsavedWorkIdsRef],\n );\n\n const confirmNavigation = useCallback(\n (options?: ConfirmNavigationOptions): boolean => {\n // SSR / non-browser safety: if `window` isn't available, default to allow.\n if (typeof window === 'undefined') return true;\n const proceed = !shouldConfirmNavigation() || window.confirm(confirmMessage());\n if (proceed && options?.fullPageNavigation) bypassNextUnloadRef.current = true;\n return proceed;\n },\n [shouldConfirmNavigation, confirmMessage],\n );\n\n const value = useMemo<LocalUploadGuardContextValue>(\n () => ({\n activeUploadCount: uploads.count,\n unsavedWorkCount: unsavedWork.count,\n guardedWorkCount,\n registerUpload: uploads.register,\n unregisterUpload: uploads.unregister,\n registerUnsavedWork: unsavedWork.register,\n unregisterUnsavedWork: unsavedWork.unregister,\n shouldConfirmNavigation,\n confirmNavigation,\n }),\n [\n uploads.count,\n uploads.register,\n uploads.unregister,\n unsavedWork.count,\n unsavedWork.register,\n unsavedWork.unregister,\n guardedWorkCount,\n shouldConfirmNavigation,\n confirmNavigation,\n ],\n );\n\n return (\n <LocalUploadGuardContext.Provider value={value}>\n {children}\n </LocalUploadGuardContext.Provider>\n );\n}\n\n/**\n * Low-level accessor for the guard context. Throws if used outside a\n * `LocalUploadGuardProvider`. Most consumers should use `useLocalUploadGuard`\n * (the public re-export below) instead.\n */\nexport function useLocalUploadGuardContext(): LocalUploadGuardContextValue {\n const ctx = useContext(LocalUploadGuardContext);\n if (ctx === undefined) {\n throw new Error(\n 'useLocalUploadGuard must be used within LocalUploadGuardProvider',\n );\n }\n return ctx;\n}\n\n/**\n * Optional accessor: returns the guard context, or `null` when rendered\n * outside a `LocalUploadGuardProvider`. For package components (e.g. the\n * chat composer registering an in-flight send) that must degrade gracefully\n * in consumers that don't mount the provider, instead of throwing.\n */\nexport function useOptionalLocalUploadGuard(): LocalUploadGuardContextValue | null {\n return useContext(LocalUploadGuardContext) ?? null;\n}\n\n/**\n * Public hook for the navigation and leave guard.\n *\n * Typical usage in an upload flow:\n *\n * const { registerUpload, unregisterUpload } = useLocalUploadGuard();\n * useEffect(() => {\n * if (phase === 'preparing' || phase === 'uploading') {\n * registerUpload(uploadId);\n * return () => unregisterUpload(uploadId);\n * }\n * }, [phase, uploadId, registerUpload, unregisterUpload]);\n *\n * An editor holding input uses `useUnsavedWorkGuard(hasUnsavedWork)` instead.\n */\nexport function useLocalUploadGuard(): LocalUploadGuardContextValue {\n return useLocalUploadGuardContext();\n}\n\n/**\n * Registers the calling editor's unsaved input with the leave guard while `hasUnsavedWork` is\n * true, and unregisters it when that turns false or the editor unmounts. While registered, closing\n * the tab, reloading, a full-page navigation, and every guarded in-app navigation ask first.\n * Throws outside a `LocalUploadGuardProvider`.\n *\n * Returns `release`, which unregisters at once: an editor that saves and then navigates in the\n * same handler calls it after the save, because its dirty flag clears only on the next render.\n */\nexport function useUnsavedWorkGuard(hasUnsavedWork: boolean): { release: () => void } {\n const { registerUnsavedWork, unregisterUnsavedWork } = useLocalUploadGuardContext();\n const id = useId();\n useEffect(() => {\n if (!hasUnsavedWork) return;\n registerUnsavedWork(id);\n return () => unregisterUnsavedWork(id);\n }, [hasUnsavedWork, id, registerUnsavedWork, unregisterUnsavedWork]);\n const release = useCallback(() => unregisterUnsavedWork(id), [id, unregisterUnsavedWork]);\n return useMemo(() => ({ release }), [release]);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-clear-upload-activity.d.ts","sourceRoot":"","sources":["../../src/react/use-clear-upload-activity.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAe,KAAK,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEtE,MAAM,WAAW,0BAA0B;IACzC,sEAAsE;IACtE,OAAO,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,sFAAsF;IACtF,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,KAAK,IAAI,CAAC;IACzD;;;;OAIG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,0BAA0B,mFASzE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-clear-upload-activity.js","sourceRoot":"","sources":["../../src/react/use-clear-upload-activity.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,WAAW,EAAoB,MAAM,uBAAuB,CAAC;AAetE,MAAM,UAAU,sBAAsB,CAAC,OAAmC;IACxE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;IAClD,OAAO,WAAW,CAAsB;QACtC,WAAW;QACX,UAAU,EAAE,OAAO;QACnB,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,EAAE,EAAE;YACjC,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QACnC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["'use client';\n\n/**\n * Generic mutation hook to clear a terminal pendingMedia item from the tray.\n *\n * Pure adapter: the consumer supplies `clearFn` (typically a wrapped Firebase\n * callable in the consuming app, or a fetch call elsewhere). The package owns the\n * useMutation wiring and the optional `onError` toast hook; the consumer owns\n * the network call.\n *\n * The provider's Firestore listener observes the `uploadTrayClearedAt` write\n * and removes the item from the tray selector automatically — no optimistic\n * update is needed in this hook.\n *\n * The returned object is the standard `useMutation` result (`mutate`,\n * `mutateAsync`, `isPending`, …). Pass `mutationKey` to register the clear in\n * React Query's shared `MutationCache` under a stable key, so a consumer can\n * read per-item pending with `useMutationState` (the pendingMediaId is the\n * mutation variables) — pending that survives the clearing row unmounting.\n */\n\nimport { useMutation, type MutationKey } from '@tanstack/react-query';\n\nexport interface ClearUploadActivityOptions {\n /** Network call performing the clear. Receives the pendingMediaId. */\n clearFn: (pendingMediaId: string) => Promise<void>;\n /** Optional error callback. Receives the error and the pendingMediaId that failed. */\n onError?: (error: Error, pendingMediaId: string) => void;\n /**\n * Optional stable key for the underlying mutation, registering it in the\n * shared `MutationCache` so pending can be read with `useMutationState`.\n * Omitted ⇒ an unkeyed mutation (the prior behavior).\n */\n mutationKey?: MutationKey;\n}\n\nexport function useClearUploadActivity(options: ClearUploadActivityOptions) {\n const { clearFn, onError, mutationKey } = options;\n return useMutation<void, Error, string>({\n mutationKey,\n mutationFn: clearFn,\n onError: (error, pendingMediaId) => {\n onError?.(error, pendingMediaId);\n },\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-guarded-navigation.d.ts","sourceRoot":"","sources":["../../src/react/use-guarded-navigation.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAuB,KAAK,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAEtG;;;;;;GAMG;AACH,wBAAgB,oBAAoB,IAAI,CACtC,iBAAiB,EAAE,MAAM,IAAI,EAC7B,OAAO,CAAC,EAAE,wBAAwB,KAC/B,IAAI,CAUR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-guarded-navigation.js","sourceRoot":"","sources":["../../src/react/use-guarded-navigation.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAiC,MAAM,kCAAkC,CAAC;AAEtG;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB;IAIlC,MAAM,EAAE,iBAAiB,EAAE,GAAG,mBAAmB,EAAE,CAAC;IACpD,OAAO,WAAW,CAChB,CAAC,iBAA6B,EAAE,OAAkC,EAAE,EAAE;QACpE,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;YAC/B,iBAAiB,EAAE,CAAC;QACtB,CAAC;IACH,CAAC,EACD,CAAC,iBAAiB,CAAC,CACpB,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\n/**\n * Wraps a navigation action so it prompts the user while an upload or unsaved\n * work is registered. Returns a function that takes the consumer's actual navigation\n * call and either runs it immediately (nothing registered) or shows a confirm()\n * dialog first.\n *\n * Designed to be framework-agnostic — the consumer supplies the navigator\n * (Next.js router.push, React Router navigate, plain location.assign, etc.).\n * A FULL-PAGE navigator (`location.assign` / `location.replace`) passes\n * `{ fullPageNavigation: true }`, so the unload that follows a confirmed\n * navigation does not raise the browser's own \"Leave site?\" as a second prompt\n * (see `ConfirmNavigationOptions`). Router navigations pass nothing.\n *\n * Typical use inside a button:\n *\n * const guardedNav = useGuardedNavigation();\n * <Button onClick={() => guardedNav(() => router.push('/somewhere'))}>Go</Button>\n * <Button onClick={() => guardedNav(() => location.assign(url), { fullPageNavigation: true })}>Leave</Button>\n *\n * For links, use the `<GuardedLink>` render-prop wrapper.\n */\n\nimport { useCallback } from 'react';\nimport { useLocalUploadGuard, type ConfirmNavigationOptions } from './local-upload-guard-provider.js';\n\n/**\n * Returns a callable that wraps a navigation action. Calling the returned\n * function with `performNavigation` either invokes it immediately (when\n * nothing is registered) or shows a confirmation prompt; if the user confirms,\n * `performNavigation` is invoked. `options` passes through to\n * `confirmNavigation()`.\n */\nexport function useGuardedNavigation(): (\n performNavigation: () => void,\n options?: ConfirmNavigationOptions,\n) => void {\n const { confirmNavigation } = useLocalUploadGuard();\n return useCallback(\n (performNavigation: () => void, options?: ConfirmNavigationOptions) => {\n if (confirmNavigation(options)) {\n performNavigation();\n }\n },\n [confirmNavigation],\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-guarded-upload.d.ts","sourceRoot":"","sources":["../../src/react/use-guarded-upload.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAGlE,MAAM,WAAW,iBAAiB;IAC9B,OAAO,EAAE,eAAe,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,IAAI,CAAC;IACX,QAAQ,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IAClC,uGAAuG;IACvG,QAAQ,EAAE,MAAM,CAAC;IACjB,qHAAqH;IACrH,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,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E,CAAC,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC;aAC7E,CAAC,CAAC;QACP,CAAC;gBAAS,CAAC;YACP,gBAAgB,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;QACD,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACzD,CAAC,EAAE,CAAC,cAAc,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import { useCallback } from 'react';\nimport { uploadFileResumable } from '@ttt-productions/upload-core/browser';\nimport type { FirebaseStorage } from 'firebase/storage';\nimport type { UploadState } from '@ttt-productions/media-schemas';\nimport { useLocalUploadGuard } from './local-upload-guard-provider.js';\n\nexport interface GuardedUploadArgs {\n storage: FirebaseStorage;\n path: string;\n file: File;\n metadata: { contentType: string };\n /** Stable identifier for the in-flight upload (used to register/unregister the local-upload guard). */\n uploadId: string;\n /** Optional progress callback. Fires with preparing → uploading (with percent) → finalizing → null on completion. */\n onProgress?: (state: UploadState | null) => void;\n /**\n * Optional cancellation signal. When aborted, the in-flight Storage upload\n * is canceled and `guardedUpload` rejects with the underlying AbortError.\n * Callers should treat AbortError as a user-initiated cancel (not a real\n * failure) — typically by checking `error.name === 'AbortError'` in the\n * mutation's onError and swallowing toasts/error UI for that case.\n */\n signal?: AbortSignal;\n /**\n * EXPLICIT opt-in for the NEUTRAL `application/octet-stream` content type\n * (canonical-upload-content-classification): only for advisory picker files\n * with unknown browser metadata, so the server byte inspector sees unknown\n * as unknown. Threaded verbatim to `uploadFileResumable`, whose media-only\n * default stays intact for every consumer that omits it.\n */\n allowNeutralContentType?: boolean;\n}\n\n/**\n * Wraps `uploadFileResumable` with the canonical local-upload guard + phase reporting.\n *\n * Every upload-capable mutation hook MUST use this helper instead of calling\n * `uploadFileResumable` directly. The helper owns:\n * - phase reporting: preparing → uploading (with percent) → finalizing\n * - beforeunload guard registration during the upload window only\n * - error safety: the guard is unregistered in a `finally` block\n *\n * The helper does NOT call `onProgress?.(null)` — callers do that from the\n * mutation's `onSuccess` and `onError` callbacks (because the upload window\n * ends when the upload completes, but the mutation may have more work after).\n */\nexport function useGuardedUpload() {\n const { registerUpload, unregisterUpload } = useLocalUploadGuard();\n\n return useCallback(async (args: GuardedUploadArgs): Promise<void> => {\n const { uploadId, onProgress, storage, path, file, metadata, signal, allowNeutralContentType } = args;\n\n onProgress?.({ phase: 'preparing', percent: null });\n registerUpload(uploadId);\n try {\n await uploadFileResumable({\n storage,\n path,\n file,\n metadata,\n signal,\n ...(allowNeutralContentType === true ? { allowNeutralContentType: true } : {}),\n onProgress: ({ percent }) => onProgress?.({ phase: 'uploading', percent }),\n });\n } finally {\n unregisterUpload(uploadId);\n }\n onProgress?.({ phase: 'finalizing', percent: null });\n }, [registerUpload, unregisterUpload]);\n}\n"]}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
export interface MarkUploadActivitySeenOptions {
|
|
2
|
-
/** Network call performing the mark-seen. Receives the pendingMediaIds. */
|
|
3
|
-
markFn: (pendingMediaIds: string[]) => Promise<void>;
|
|
4
|
-
/** Optional error callback. Receives the error and the ids that failed. */
|
|
5
|
-
onError?: (error: Error, pendingMediaIds: string[]) => void;
|
|
6
|
-
}
|
|
7
|
-
export declare function useMarkUploadActivitySeen(options: MarkUploadActivitySeenOptions): import("@tanstack/react-query").UseMutationResult<void, Error, string[], unknown>;
|
|
8
|
-
//# sourceMappingURL=use-mark-upload-activity-seen.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-mark-upload-activity-seen.d.ts","sourceRoot":"","sources":["../../src/react/use-mark-upload-activity-seen.ts"],"names":[],"mappings":"AAsBA,MAAM,WAAW,6BAA6B;IAC5C,2EAA2E;IAC3E,MAAM,EAAE,CAAC,eAAe,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD,2EAA2E;IAC3E,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;CAC7D;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,6BAA6B,qFAQ/E"}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
'use client';
|
|
2
|
-
/**
|
|
3
|
-
* Generic mutation hook to mark terminal pendingMedia items as seen in the tray.
|
|
4
|
-
*
|
|
5
|
-
* Pure adapter: the consumer supplies `markFn` (typically a wrapped Firebase
|
|
6
|
-
* callable in the consuming app that writes `uploadTraySeenAt`/`uploadTraySeenBy` on the
|
|
7
|
-
* caller's own terminal pendingMedia docs). The package owns the useMutation
|
|
8
|
-
* wiring and the optional `onError` hook; the consumer owns the network call.
|
|
9
|
-
*
|
|
10
|
-
* The provider's Firestore listener observes the `uploadTraySeenAt` write and
|
|
11
|
-
* updates the in-flight upload records automatically — no optimistic update is
|
|
12
|
-
* needed in this hook. Marking seen is tray UX state, not a sensitive action,
|
|
13
|
-
* so it mirrors `useClearUploadActivity` exactly (no audit event).
|
|
14
|
-
*
|
|
15
|
-
* `markFn` receives the full batch of pendingMediaIds to mark seen at once
|
|
16
|
-
* (typically every currently-unseen terminal item when the File-status tab
|
|
17
|
-
* opens). An empty array is a no-op the consumer's callable can short-circuit.
|
|
18
|
-
*/
|
|
19
|
-
import { useMutation } from '@tanstack/react-query';
|
|
20
|
-
export function useMarkUploadActivitySeen(options) {
|
|
21
|
-
const { markFn, onError } = options;
|
|
22
|
-
return useMutation({
|
|
23
|
-
mutationFn: markFn,
|
|
24
|
-
onError: (error, pendingMediaIds) => {
|
|
25
|
-
onError?.(error, pendingMediaIds);
|
|
26
|
-
},
|
|
27
|
-
});
|
|
28
|
-
}
|
|
29
|
-
//# sourceMappingURL=use-mark-upload-activity-seen.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-mark-upload-activity-seen.js","sourceRoot":"","sources":["../../src/react/use-mark-upload-activity-seen.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AASpD,MAAM,UAAU,yBAAyB,CAAC,OAAsC;IAC9E,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACpC,OAAO,WAAW,CAAwB;QACxC,UAAU,EAAE,MAAM;QAClB,OAAO,EAAE,CAAC,KAAK,EAAE,eAAe,EAAE,EAAE;YAClC,OAAO,EAAE,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;QACpC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["'use client';\n\n/**\n * Generic mutation hook to mark terminal pendingMedia items as seen in the tray.\n *\n * Pure adapter: the consumer supplies `markFn` (typically a wrapped Firebase\n * callable in the consuming app that writes `uploadTraySeenAt`/`uploadTraySeenBy` on the\n * caller's own terminal pendingMedia docs). The package owns the useMutation\n * wiring and the optional `onError` hook; the consumer owns the network call.\n *\n * The provider's Firestore listener observes the `uploadTraySeenAt` write and\n * updates the in-flight upload records automatically — no optimistic update is\n * needed in this hook. Marking seen is tray UX state, not a sensitive action,\n * so it mirrors `useClearUploadActivity` exactly (no audit event).\n *\n * `markFn` receives the full batch of pendingMediaIds to mark seen at once\n * (typically every currently-unseen terminal item when the File-status tab\n * opens). An empty array is a no-op the consumer's callable can short-circuit.\n */\n\nimport { useMutation } from '@tanstack/react-query';\n\nexport interface MarkUploadActivitySeenOptions {\n /** Network call performing the mark-seen. Receives the pendingMediaIds. */\n markFn: (pendingMediaIds: string[]) => Promise<void>;\n /** Optional error callback. Receives the error and the ids that failed. */\n onError?: (error: Error, pendingMediaIds: string[]) => void;\n}\n\nexport function useMarkUploadActivitySeen(options: MarkUploadActivitySeenOptions) {\n const { markFn, onError } = options;\n return useMutation<void, Error, string[]>({\n mutationFn: markFn,\n onError: (error, pendingMediaIds) => {\n onError?.(error, pendingMediaIds);\n },\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-upload-processing.d.ts","sourceRoot":"","sources":["../../src/react/use-upload-processing.ts"],"names":[],"mappings":"AAqBA,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,YAAY,GAAG,SAAS,GAAG,QAAQ,GAAG,eAAe,GAAG,gBAAgB,CAAC;IACtG,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,OAAO,CAAC;IACtB,UAAU,EAAE,OAAO,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;CACrB;AAOD,MAAM,WAAW,0BAA0B;IACzC,6CAA6C;IAC7C,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,0CAA0C;IAC1C,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,yCAAyC;IACzC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2CAA2C;IAC3C,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAyED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,EACrE,cAAc,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACzC,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,qBAAqB,KAAK,IAAI,EACnD,OAAO,GAAE,0BAA+B,GACvC,qBAAqB,CAqBvB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-upload-processing.js","sourceRoot":"","sources":["../../src/react/use-upload-processing.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAE,+BAA+B,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,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QACxB,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,YAAY,CAAC,OAAO,GAAG,IAAI,CAAC;YAC5B,OAAO;QACT,CAAC;QACD,IAAI,KAAK,CAAC,UAAU,IAAI,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;YAC3D,MAAM,GAAG,GAAG,GAAG,cAAc,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;YAChD,IAAI,YAAY,CAAC,OAAO,KAAK,GAAG,EAAE,CAAC;gBACjC,YAAY,CAAC,OAAO,GAAG,GAAG,CAAC;gBAC3B,UAAU,CAAC,KAAK,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC,EAAE,CAAC,cAAc,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;IAE1G,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["'use client';\n\n/**\n * Adapter that maps `useInFlightUpload` state to the legacy\n * `{ isProcessing, message, isComplete, isRejected, isFailed }` shape used\n * by per-component spinners and overlays.\n *\n * Routing of toasts and rejection dialogs lives in `InFlightUploadsProvider`\n * via the consumer-supplied callbacks — `useUploadProcessing` only surfaces\n * local UI state. The `onTerminal` callback fires once per terminal status\n * (completed / failed / rejected) and is intended for local UI cleanup\n * (clearing form state, closing modals, etc.).\n */\n\nimport { useEffect, useRef } from 'react';\nimport { isPendingMediaNonTerminalStatus, PendingMediaStatusSchema } from '@ttt-productions/media-schemas';\nimport { useInFlightUpload, type InFlightUpload } from './in-flight-uploads-provider.js';\n\n// Pending-media status values derive from media-schemas' one declaration.\nconst STATUS = PendingMediaStatusSchema.enum;\n\nexport interface UploadProcessingState {\n status: 'idle' | 'pending' | 'processing' | 'success' | 'failed' | 'rejected-text' | 'rejected-media';\n message: string;\n errorMessage?: string;\n isProcessing: boolean;\n isComplete: boolean;\n isFailed: boolean;\n isRejected: boolean;\n}\n\nconst DEFAULT_PROCESSING_MESSAGE = 'Processing your content...';\nconst DEFAULT_SUCCESS_MESSAGE = 'Complete!';\nconst DEFAULT_FAILED_MESSAGE = 'Processing failed';\nconst DEFAULT_REJECTED_MESSAGE = 'Content rejected';\n\nexport interface UseUploadProcessingOptions {\n /** Override the processing-phase message. */\n processingMessage?: string;\n /** Override the success-phase message. */\n successMessage?: string;\n /** Override the failed-phase message. */\n failedMessage?: string;\n /** Override the rejected-phase message. */\n rejectedMessage?: string;\n}\n\nfunction buildState<TFileOrigin extends string>(\n upload: InFlightUpload<TFileOrigin> | undefined,\n opts: UseUploadProcessingOptions,\n): UploadProcessingState {\n const processingMessage = opts.processingMessage ?? DEFAULT_PROCESSING_MESSAGE;\n const successMessage = opts.successMessage ?? DEFAULT_SUCCESS_MESSAGE;\n const failedMessage = opts.failedMessage ?? DEFAULT_FAILED_MESSAGE;\n const rejectedMessage = opts.rejectedMessage ?? DEFAULT_REJECTED_MESSAGE;\n\n if (!upload) {\n return {\n status: 'idle',\n message: '',\n isProcessing: false,\n isComplete: false,\n isFailed: false,\n isRejected: false,\n };\n }\n if (isPendingMediaNonTerminalStatus(upload.status)) {\n return {\n status: upload.status,\n message: processingMessage,\n isProcessing: true,\n isComplete: false,\n isFailed: false,\n isRejected: false,\n };\n }\n if (upload.status === STATUS.completed) {\n return {\n status: 'success',\n message: successMessage,\n isProcessing: false,\n isComplete: true,\n isFailed: false,\n isRejected: false,\n };\n }\n if (upload.status === STATUS.failed) {\n return {\n status: 'failed',\n message: failedMessage,\n errorMessage: upload.errorMessage,\n isProcessing: false,\n isComplete: false,\n isFailed: true,\n isRejected: false,\n };\n }\n if (upload.status === STATUS.rejected) {\n return {\n status: upload.rejectionType === 'text' ? 'rejected-text' : 'rejected-media',\n message: rejectedMessage,\n errorMessage: upload.errorMessage,\n isProcessing: false,\n isComplete: false,\n isFailed: false,\n isRejected: true,\n };\n }\n return {\n status: 'processing',\n message: processingMessage,\n isProcessing: true,\n isComplete: false,\n isFailed: false,\n isRejected: false,\n };\n}\n\n/**\n * Returns local UI processing state for the given pendingMediaId. If the\n * `onTerminal` callback is provided, it fires once when the doc reaches a\n * terminal status (completed / failed / rejected). Use `onTerminal` for\n * local UI cleanup — global toast/dialog routing belongs in the provider.\n */\nexport function useUploadProcessing<TFileOrigin extends string = string>(\n pendingMediaId: string | null | undefined,\n onTerminal?: (state: UploadProcessingState) => void,\n options: UseUploadProcessingOptions = {},\n): UploadProcessingState {\n const upload = useInFlightUpload<TFileOrigin>(pendingMediaId);\n const state = buildState(upload, options);\n const lastFiredRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (!onTerminal) return;\n if (!pendingMediaId) {\n lastFiredRef.current = null;\n return;\n }\n if (state.isComplete || state.isFailed || state.isRejected) {\n const sig = `${pendingMediaId}:${state.status}`;\n if (lastFiredRef.current !== sig) {\n lastFiredRef.current = sig;\n onTerminal(state);\n }\n }\n }, [pendingMediaId, state.status, state.isComplete, state.isFailed, state.isRejected, state, onTerminal]);\n\n return state;\n}\n"]}
|
|
File without changes
|
|
File without changes
|
/package/dist/react/{local-upload-guard-provider.d.ts → guard/local-upload-guard-provider.d.ts}
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
/package/dist/react/{in-flight-uploads-provider.d.ts → tray/in-flight-uploads-provider.d.ts}
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|