@behindthemusictree/app-kit 32.0.3 → 33.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{chunk-BVWRP6IK.js → chunk-4TE4OSOM.js} +55 -15
  2. package/dist/chunk-4TE4OSOM.js.map +1 -0
  3. package/dist/{chunk-5NTNMBJP.js → chunk-HLAKW2YJ.js} +1 -1
  4. package/dist/{chunk-OGTDTTHJ.js → chunk-I7NXFXV3.js} +2 -2
  5. package/dist/chunk-I7NXFXV3.js.map +1 -0
  6. package/dist/{chunk-XCOAWKF6.js → chunk-MAKY4YBN.js} +118 -24
  7. package/dist/chunk-MAKY4YBN.js.map +1 -0
  8. package/dist/{chunk-4EBHHVZI.js → chunk-PY3Y4E27.js} +105 -23
  9. package/dist/chunk-PY3Y4E27.js.map +1 -0
  10. package/dist/chunk-W4QTTNNA.js +94 -0
  11. package/dist/chunk-W4QTTNNA.js.map +1 -0
  12. package/dist/genre-tree/index.cjs +469 -331
  13. package/dist/genre-tree/index.cjs.map +1 -1
  14. package/dist/genre-tree/index.d.ts +19 -1
  15. package/dist/genre-tree/index.js +6 -3
  16. package/dist/index.cjs +741 -441
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +2 -2
  19. package/dist/index.js +15 -5
  20. package/dist/player/index.cjs +167 -60
  21. package/dist/player/index.cjs.map +1 -1
  22. package/dist/player/index.d.ts +8 -0
  23. package/dist/player/index.js +2 -1
  24. package/dist/popup/index.cjs +1 -1
  25. package/dist/popup/index.cjs.map +1 -1
  26. package/dist/popup/index.d.ts +1 -1
  27. package/dist/popup/index.js +1 -1
  28. package/dist/transport/index.cjs +177 -46
  29. package/dist/transport/index.cjs.map +1 -1
  30. package/dist/transport/index.d.ts +23 -3
  31. package/dist/transport/index.js +10 -2
  32. package/package.json +1 -1
  33. package/dist/chunk-4EBHHVZI.js.map +0 -1
  34. package/dist/chunk-BVWRP6IK.js.map +0 -1
  35. package/dist/chunk-OGTDTTHJ.js.map +0 -1
  36. package/dist/chunk-XCOAWKF6.js.map +0 -1
  37. /package/dist/{chunk-5NTNMBJP.js.map → chunk-HLAKW2YJ.js.map} +0 -0
@@ -34,6 +34,8 @@ __export(transport_exports, {
34
34
  InvalidInputError: () => InvalidInputError,
35
35
  NetworkError: () => NetworkError,
36
36
  PaginatedResponseSchema: () => PaginatedResponseSchema,
37
+ PlaybackContextProvider: () => PlaybackContextProvider,
38
+ PlaybackContextSchema: () => PlaybackContextSchema,
37
39
  ServiceError: () => ServiceError,
38
40
  buildBackendBaseUrl: () => buildBackendBaseUrl,
39
41
  buildSubdomainBaseUrl: () => buildSubdomainBaseUrl,
@@ -47,6 +49,7 @@ __export(transport_exports, {
47
49
  queryClient: () => queryClient,
48
50
  useConnectivityError: () => useConnectivityError,
49
51
  useFetchWrapper: () => useFetchWrapper,
52
+ usePlaybackContext: () => usePlaybackContext,
50
53
  useQueryWithParse: () => useQueryWithParse,
51
54
  useValidatedMutation: () => useValidatedMutation
52
55
  });
@@ -454,7 +457,8 @@ var assertWellFormedRequest = (url, options) => {
454
457
  throw Object.assign(createAppErrorFromErrorCode("CLI5000" /* CLIENT_INTERNAL_ERROR */), { cause: error });
455
458
  }
456
459
  };
457
- var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryParams, handleMissingRequiredSession, handleError, expectBinary = false, backendBaseUrl) => {
460
+ var isCallerAbort = (error, signal) => !!signal?.aborted && error?.name !== "TimeoutError";
461
+ var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryParams, handleMissingRequiredSession, handleError, expectBinary = false, backendBaseUrl, onResponse) => {
458
462
  const urlWithParams = queryParams ? `${url}${url.includes("?") ? "&" : "?"}${new URLSearchParams(
459
463
  Object.entries(queryParams).map(([key, value]) => [key, String(value)])
460
464
  ).toString()}` : url;
@@ -472,9 +476,16 @@ var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryPar
472
476
  handleMissingRequiredSession?.();
473
477
  return null;
474
478
  }
479
+ let responseHookFailed = false;
475
480
  try {
476
481
  assertWellFormedRequest(finalUrl, finalOptions);
477
482
  const result = await fetchWithNetworkRetry(finalUrl, finalOptions);
483
+ try {
484
+ await onResponse?.(result);
485
+ } catch (error) {
486
+ responseHookFailed = true;
487
+ throw error;
488
+ }
478
489
  if (!result.ok) {
479
490
  const appError = await createAppErrorFromResult(result, backendBaseUrl);
480
491
  throw appError;
@@ -488,6 +499,7 @@ var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryPar
488
499
  return result.json();
489
500
  }
490
501
  } catch (caughtError) {
502
+ if (responseHookFailed || isCallerAbort(caughtError, finalOptions.signal)) throw caughtError;
491
503
  let appError = null;
492
504
  if (caughtError instanceof AppError) {
493
505
  appError = caughtError;
@@ -502,22 +514,110 @@ var fetchWrapper = async (url, requiresAuth, options = {}, accessToken, queryPar
502
514
  }
503
515
  };
504
516
 
517
+ // src/transport/PlaybackContext.tsx
518
+ var import_react = require("react");
519
+ var import_zod = require("zod");
520
+ var import_jsx_runtime = require("react/jsx-runtime");
521
+ var PlaybackContextSchema = import_zod.z.object({ country: import_zod.z.string().regex(/^[A-Z]{2}$/).nullable() });
522
+ var unmanaged = {
523
+ country: null,
524
+ key: null,
525
+ ready: true,
526
+ error: null,
527
+ isCurrent: (_key) => true,
528
+ snapshot: () => ({ key: null, country: null }),
529
+ refresh: async (_force = false) => null
530
+ };
531
+ var PlaybackContext = (0, import_react.createContext)(unmanaged);
532
+ var usePlaybackContext = () => (0, import_react.useContext)(PlaybackContext);
533
+ function PlaybackContextProvider({ children, loadContext }) {
534
+ const [state, setState] = (0, import_react.useState)({
535
+ country: null,
536
+ ready: false,
537
+ revision: 0,
538
+ error: null
539
+ });
540
+ const current = (0, import_react.useRef)(state);
541
+ const checkedAt = (0, import_react.useRef)(0);
542
+ const pending = (0, import_react.useRef)(null);
543
+ const refresh = (0, import_react.useCallback)((force = false) => {
544
+ if (pending.current) return pending.current;
545
+ if (!force && current.current.ready && Date.now() - checkedAt.current < 6e4) {
546
+ return Promise.resolve(current.current.country);
547
+ }
548
+ pending.current = loadContext().then((raw) => {
549
+ const { country } = PlaybackContextSchema.parse(raw);
550
+ const previous = current.current;
551
+ const next = {
552
+ country,
553
+ ready: true,
554
+ error: null,
555
+ revision: previous.revision + (country !== previous.country ? 1 : 0)
556
+ };
557
+ current.current = next;
558
+ checkedAt.current = Date.now();
559
+ setState(next);
560
+ return country;
561
+ }).catch((error) => {
562
+ const next = {
563
+ ...current.current,
564
+ error: error instanceof Error ? error.message : "Unable to check playback location"
565
+ };
566
+ current.current = next;
567
+ setState(next);
568
+ throw error;
569
+ }).finally(() => {
570
+ pending.current = null;
571
+ });
572
+ return pending.current;
573
+ }, [loadContext]);
574
+ (0, import_react.useEffect)(() => {
575
+ const update = () => {
576
+ void refresh(true).catch(() => {
577
+ });
578
+ };
579
+ update();
580
+ window.addEventListener("focus", update);
581
+ window.addEventListener("online", update);
582
+ return () => {
583
+ window.removeEventListener("focus", update);
584
+ window.removeEventListener("online", update);
585
+ };
586
+ }, [refresh]);
587
+ const isCurrent = (0, import_react.useCallback)(
588
+ (key) => key === `${current.current.country ?? "unknown"}:${current.current.revision}`,
589
+ []
590
+ );
591
+ const snapshot = (0, import_react.useCallback)(() => ({
592
+ key: `${current.current.country ?? "unknown"}:${current.current.revision}`,
593
+ country: current.current.country
594
+ }), []);
595
+ const value = (0, import_react.useMemo)(() => ({
596
+ ...state,
597
+ isCurrent,
598
+ snapshot,
599
+ key: `${state.country ?? "unknown"}:${state.revision}`,
600
+ refresh
601
+ }), [state, refresh, isCurrent, snapshot]);
602
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PlaybackContext.Provider, { value, children });
603
+ }
604
+
505
605
  // src/transport/useFetchWrapper.ts
506
- var import_react3 = require("react");
606
+ var import_react4 = require("react");
507
607
 
508
608
  // src/transport/connectivity-error-context.tsx
509
- var import_react = require("react");
510
- var import_jsx_runtime = require("react/jsx-runtime");
511
- var ConnectivityErrorContext = (0, import_react.createContext)(void 0);
609
+ var import_react2 = require("react");
610
+ var import_jsx_runtime2 = require("react/jsx-runtime");
611
+ var ConnectivityErrorContext = (0, import_react2.createContext)(void 0);
512
612
  function ConnectivityErrorProvider({ children }) {
513
- const [connectivityError, setConnectivityError] = (0, import_react.useState)(null);
514
- const clearConnectivityError = (0, import_react.useCallback)(() => {
613
+ const [connectivityError, setConnectivityError] = (0, import_react2.useState)(null);
614
+ const clearConnectivityError = (0, import_react2.useCallback)(() => {
515
615
  setConnectivityError(null);
516
616
  }, []);
517
- const handleSetConnectivityError = (0, import_react.useCallback)((error) => {
617
+ const handleSetConnectivityError = (0, import_react2.useCallback)((error) => {
518
618
  setConnectivityError(error);
519
619
  }, []);
520
- const value = (0, import_react.useMemo)(
620
+ const value = (0, import_react2.useMemo)(
521
621
  () => ({
522
622
  connectivityError,
523
623
  setConnectivityError: handleSetConnectivityError,
@@ -525,10 +625,10 @@ function ConnectivityErrorProvider({ children }) {
525
625
  }),
526
626
  [connectivityError, handleSetConnectivityError, clearConnectivityError]
527
627
  );
528
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ConnectivityErrorContext.Provider, { value, children });
628
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ConnectivityErrorContext.Provider, { value, children });
529
629
  }
530
630
  function useConnectivityError() {
531
- const context = (0, import_react.useContext)(ConnectivityErrorContext);
631
+ const context = (0, import_react2.useContext)(ConnectivityErrorContext);
532
632
  if (context === void 0) {
533
633
  throw new Error("useConnectivityError must be used within a ConnectivityErrorProvider");
534
634
  }
@@ -536,7 +636,7 @@ function useConnectivityError() {
536
636
  }
537
637
 
538
638
  // src/auth/SessionContext.tsx
539
- var import_react2 = require("react");
639
+ var import_react3 = require("react");
540
640
 
541
641
  // src/transport/query-client.ts
542
642
  var import_react_query = require("@tanstack/react-query");
@@ -551,10 +651,10 @@ var queryClient = new import_react_query.QueryClient({
551
651
  });
552
652
 
553
653
  // src/auth/SessionContext.tsx
554
- var import_jsx_runtime2 = require("react/jsx-runtime");
555
- var SessionContext = (0, import_react2.createContext)(void 0);
654
+ var import_jsx_runtime3 = require("react/jsx-runtime");
655
+ var SessionContext = (0, import_react3.createContext)(void 0);
556
656
  function useSession() {
557
- const context = (0, import_react2.useContext)(SessionContext);
657
+ const context = (0, import_react3.useContext)(SessionContext);
558
658
  if (context === void 0) {
559
659
  throw new Error("useSession must be used within a SessionProvider");
560
660
  }
@@ -563,9 +663,10 @@ function useSession() {
563
663
 
564
664
  // src/transport/useFetchWrapper.ts
565
665
  var useFetchWrapper = (getBackendBaseUrl) => {
666
+ const playback = usePlaybackContext();
566
667
  const { setConnectivityError } = useConnectivityError();
567
668
  const { clearSession, session, sessionRestored } = useSession();
568
- const handleError = (0, import_react3.useCallback)((error) => {
669
+ const handleError = (0, import_react4.useCallback)((error) => {
569
670
  if (error instanceof ConnectivityError) {
570
671
  const authDetailErrors = [
571
672
  "BAC4011" /* BACKEND_GOOGLE_OAUTH_CODE_INVALID_OR_EXPIRED */,
@@ -592,25 +693,52 @@ var useFetchWrapper = (getBackendBaseUrl) => {
592
693
  if (!sessionRestored) return;
593
694
  setConnectivityError(createAppErrorFromErrorCode("SES4012" /* SESSION_REQUIRED */));
594
695
  };
595
- const fetch2 = (0, import_react3.useCallback)((backendEndpointOrUrl, fromBackend = true, requiresAuth = true, options = {}, queryParams, expectBinary = false, skipGlobalError = false) => {
696
+ const fetch2 = (0, import_react4.useCallback)((backendEndpointOrUrl, fromBackend = true, requiresAuth = true, options = {}, queryParams, expectBinary = false, skipGlobalError = false, acceptRefreshedContext = false) => {
596
697
  const baseUrl = getBackendBaseUrl().replace(/\/+$/, "");
597
698
  const endpointPath = String(backendEndpointOrUrl);
598
699
  if (fromBackend && endpointPath.startsWith("/")) {
599
700
  throw new Error(`Endpoint path must be relative (no leading slash). Got: "${endpointPath}".`);
600
701
  }
601
702
  const url = fromBackend ? endpointPath ? `${baseUrl}/${endpointPath}` : baseUrl : backendEndpointOrUrl;
602
- return fetchWrapper(
603
- url,
604
- requiresAuth,
605
- options,
606
- session?.accessToken || void 0,
607
- queryParams,
608
- handleMissingRequiredSession,
609
- skipGlobalError ? void 0 : handleError,
610
- expectBinary,
611
- baseUrl
612
- );
613
- }, [session?.accessToken, handleError, getBackendBaseUrl, sessionRestored, setConnectivityError]);
703
+ const perform = async (retryContextChange) => {
704
+ const contextual = playback.key !== null && fromBackend && /^(?:me\/)?(library\/songs|genre-playlists|playlists|manual-playlists)\//.test(endpointPath);
705
+ let requestContext = { key: playback.key, country: playback.country };
706
+ if (contextual) {
707
+ await playback.refresh();
708
+ if (acceptRefreshedContext) requestContext = playback.snapshot();
709
+ if (!playback.isCurrent(requestContext.key)) throw new DOMException("Playback context changed", "AbortError");
710
+ }
711
+ try {
712
+ const result = await fetchWrapper(
713
+ url,
714
+ requiresAuth,
715
+ options,
716
+ session?.accessToken || void 0,
717
+ queryParams,
718
+ handleMissingRequiredSession,
719
+ skipGlobalError ? void 0 : handleError,
720
+ expectBinary,
721
+ baseUrl,
722
+ contextual ? async (response) => {
723
+ const responseCountry = response.headers.get("x-playback-country");
724
+ if (responseCountry !== null && responseCountry !== (requestContext.country ?? "unknown")) {
725
+ await playback.refresh(true);
726
+ throw new DOMException("Playback context changed", "AbortError");
727
+ }
728
+ if (!playback.isCurrent(requestContext.key)) throw new DOMException("Playback context changed", "AbortError");
729
+ } : void 0
730
+ );
731
+ if (contextual && !playback.isCurrent(requestContext.key)) throw new DOMException("Playback context changed", "AbortError");
732
+ return result;
733
+ } catch (error) {
734
+ if (retryContextChange && contextual && error instanceof DOMException && error.name === "AbortError" && !playback.isCurrent(requestContext.key)) {
735
+ return perform(false);
736
+ }
737
+ throw error;
738
+ }
739
+ };
740
+ return perform(acceptRefreshedContext);
741
+ }, [session?.accessToken, handleError, getBackendBaseUrl, sessionRestored, setConnectivityError, playback]);
614
742
  return { fetch: fetch2 };
615
743
  };
616
744
 
@@ -635,7 +763,7 @@ function buildBackendBaseUrl(params) {
635
763
  }
636
764
 
637
765
  // src/transport/lib/parse-with-log.ts
638
- var import_zod = require("zod");
766
+ var import_zod2 = require("zod");
639
767
  function parseWithLog(schema, data, context) {
640
768
  const result = schema.safeParse(data);
641
769
  if (!result.success) {
@@ -643,22 +771,22 @@ function parseWithLog(schema, data, context) {
643
771
  if (data == null) {
644
772
  throw new Error(`${prefix} received null response before schema validation`);
645
773
  }
646
- console.error(`${prefix} schema validation failed`, import_zod.z.flattenError(result.error));
774
+ console.error(`${prefix} schema validation failed`, import_zod2.z.flattenError(result.error));
647
775
  throw result.error;
648
776
  }
649
777
  return result.data;
650
778
  }
651
779
 
652
780
  // src/transport/lib/paginated-response.ts
653
- var import_zod2 = require("zod");
654
- var PaginatedResponseSchema = (itemSchema) => import_zod2.z.object({
655
- overallTotal: import_zod2.z.number(),
656
- next: import_zod2.z.string().url().nullable(),
657
- previous: import_zod2.z.string().url().nullable(),
658
- results: import_zod2.z.array(itemSchema),
659
- page: import_zod2.z.number(),
660
- pageSize: import_zod2.z.number(),
661
- totalPages: import_zod2.z.number()
781
+ var import_zod3 = require("zod");
782
+ var PaginatedResponseSchema = (itemSchema) => import_zod3.z.object({
783
+ overallTotal: import_zod3.z.number(),
784
+ next: import_zod3.z.string().url().nullable(),
785
+ previous: import_zod3.z.string().url().nullable(),
786
+ results: import_zod3.z.array(itemSchema),
787
+ page: import_zod3.z.number(),
788
+ pageSize: import_zod3.z.number(),
789
+ totalPages: import_zod3.z.number()
662
790
  });
663
791
 
664
792
  // src/transport/lib/use-query-with-parse.ts
@@ -680,15 +808,15 @@ function useQueryWithParse({
680
808
 
681
809
  // src/transport/lib/use-validated-mutation.ts
682
810
  var import_react_query3 = require("@tanstack/react-query");
683
- var import_react4 = require("react");
684
- var import_zod3 = require("zod");
811
+ var import_react5 = require("react");
812
+ var import_zod4 = require("zod");
685
813
  function useValidatedMutation({
686
814
  inputSchema,
687
815
  outputSchema,
688
816
  mutationFn,
689
817
  ...options
690
818
  }) {
691
- const [formErrors, setFormErrors] = (0, import_react4.useState)([]);
819
+ const [formErrors, setFormErrors] = (0, import_react5.useState)([]);
692
820
  const validatedMutation = (0, import_react_query3.useMutation)({
693
821
  ...options,
694
822
  mutationFn: async (data) => {
@@ -714,9 +842,9 @@ function useValidatedMutation({
714
842
  } catch (error) {
715
843
  if (error instanceof Error && "json" in error) {
716
844
  try {
717
- const errorResponse = import_zod3.z.object({
718
- details: import_zod3.z.object({
719
- fieldErrors: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.array(import_zod3.z.object({ message: import_zod3.z.string() })))
845
+ const errorResponse = import_zod4.z.object({
846
+ details: import_zod4.z.object({
847
+ fieldErrors: import_zod4.z.record(import_zod4.z.string(), import_zod4.z.array(import_zod4.z.object({ message: import_zod4.z.string() })))
720
848
  })
721
849
  }).parse(error.json);
722
850
  setFormErrors(
@@ -754,6 +882,8 @@ function useValidatedMutation({
754
882
  InvalidInputError,
755
883
  NetworkError,
756
884
  PaginatedResponseSchema,
885
+ PlaybackContextProvider,
886
+ PlaybackContextSchema,
757
887
  ServiceError,
758
888
  buildBackendBaseUrl,
759
889
  buildSubdomainBaseUrl,
@@ -767,6 +897,7 @@ function useValidatedMutation({
767
897
  queryClient,
768
898
  useConnectivityError,
769
899
  useFetchWrapper,
900
+ usePlaybackContext,
770
901
  useQueryWithParse,
771
902
  useValidatedMutation
772
903
  });