@pitcher/js-api 1.21.0-beta.3 → 1.21.0-beta.4

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/js-api.esm.js CHANGED
@@ -2410,7 +2410,16 @@ function deleteCanvas(payload) {
2410
2410
  return this.API.request("delete_canvas", payload);
2411
2411
  }
2412
2412
  function updateCanvas$1(payload) {
2413
- return this.API.request("update_canvas", payload);
2413
+ let shouldDebug = false;
2414
+ if (typeof window !== "undefined") {
2415
+ const urlParams = new URLSearchParams(window.location.search);
2416
+ shouldDebug = urlParams.get("debug") === "true" || !!window.debug;
2417
+ }
2418
+ shouldDebug && console.info("JS API UPDATE CANVAS", payload);
2419
+ return this.API.request("update_canvas", payload).then((res) => {
2420
+ shouldDebug && console.info("JS API UPDATE CANVAS RESPONSE", res);
2421
+ return res;
2422
+ });
2414
2423
  }
2415
2424
  function getCanvas$1(payload) {
2416
2425
  return this.API.request("get_canvas", payload);
@@ -2661,6 +2670,51 @@ function v4(options, buf, offset) {
2661
2670
  return unsafeStringify(rnds);
2662
2671
  }
2663
2672
 
2673
+ const PITCHER_EVENT = "PITCHER_EVENT";
2674
+ var PitcherMessageType = /* @__PURE__ */ ((PitcherMessageType2) => {
2675
+ PitcherMessageType2["REQUEST"] = "PITCHER_REQUEST";
2676
+ PitcherMessageType2["RESPONSE"] = "PITCHER_RESPONSE";
2677
+ return PitcherMessageType2;
2678
+ })(PitcherMessageType || {});
2679
+ var PitcherResponseStatus = /* @__PURE__ */ ((PitcherResponseStatus2) => {
2680
+ PitcherResponseStatus2["OK"] = "ok";
2681
+ PitcherResponseStatus2["ERROR"] = "error";
2682
+ return PitcherResponseStatus2;
2683
+ })(PitcherResponseStatus || {});
2684
+ var PitcherEventName = /* @__PURE__ */ ((PitcherEventName2) => {
2685
+ PitcherEventName2["ENV_CHANGED"] = "env_changed";
2686
+ PitcherEventName2["PHOTOS_CAPTURED"] = "photos_captured";
2687
+ PitcherEventName2["FILE_DOWNLOADED"] = "file_downloaded";
2688
+ PitcherEventName2["FILE_UPLOAD_PROGRESS"] = "file_upload_progress";
2689
+ PitcherEventName2["UPDATE_LOCATION"] = "update_location";
2690
+ PitcherEventName2["CANVAS_UPDATED"] = "canvas_updated";
2691
+ PitcherEventName2["CANVAS_UPDATED_SUCCESS"] = "canvas_updated_success";
2692
+ PitcherEventName2["FILE_CLOSED"] = "file_closed";
2693
+ PitcherEventName2["APP_BACKGROUNDED"] = "app_backgrounded";
2694
+ PitcherEventName2["APP_FOREGROUNDED"] = "app_foregrounded";
2695
+ PitcherEventName2["NON_FILES_SYNC_FINISHED"] = "non_files_sync_finished";
2696
+ PitcherEventName2["CONTENT_LIST_REFRESH_REQUESTED"] = "content_list_refresh_requested";
2697
+ PitcherEventName2["NETWORK_CONNECTION_ESTABLISHED"] = "network_connection_established";
2698
+ PitcherEventName2["NETWORK_CONNECTION_LOST"] = "network_connection_lost";
2699
+ PitcherEventName2["ENTERED_FULLSCREEN"] = "entered_fullscreen";
2700
+ PitcherEventName2["EXITED_FULLSCREEN"] = "exited_fullscreen";
2701
+ PitcherEventName2["SUBMIT_POSTCALL_CLICKED"] = "submit_postcall_clicked";
2702
+ return PitcherEventName2;
2703
+ })(PitcherEventName || {});
2704
+ var PitcherBroadcastedEventName = /* @__PURE__ */ ((PitcherBroadcastedEventName2) => {
2705
+ PitcherBroadcastedEventName2["UI_SHOW_MODAL"] = "ui:show-modal";
2706
+ PitcherBroadcastedEventName2["UI_HIDE_MODAL"] = "ui:hide-modal";
2707
+ PitcherBroadcastedEventName2["FAVORITES_CHANGED"] = "favorites:changed";
2708
+ PitcherBroadcastedEventName2["FILE_DOWNLOAD"] = "file:download";
2709
+ return PitcherBroadcastedEventName2;
2710
+ })(PitcherBroadcastedEventName || {});
2711
+ var PitcherExternalEventName = /* @__PURE__ */ ((PitcherExternalEventName2) => {
2712
+ PitcherExternalEventName2["CREATE_AND_OPEN_CANVAS"] = "create_and_open_canvas";
2713
+ PitcherExternalEventName2["OPEN_CANVAS"] = "open_canvas";
2714
+ PitcherExternalEventName2["START_CALL"] = "start_call";
2715
+ return PitcherExternalEventName2;
2716
+ })(PitcherExternalEventName || {});
2717
+
2664
2718
  class AssertionError extends Error {
2665
2719
  }
2666
2720
  function assert(exp, message) {
@@ -2733,12 +2787,205 @@ function isOriginValid(event, allowedOrigins = [], isDev = ["development", "test
2733
2787
  return isValid;
2734
2788
  }
2735
2789
 
2790
+ const MAX_RETRIES = 5;
2791
+ const BASE_DELAY = 1e3;
2792
+ function paramsSerializer(params) {
2793
+ const searchParams = new URLSearchParams();
2794
+ for (const key in params) {
2795
+ if (Array.isArray(params[key])) {
2796
+ params[key].forEach((val) => searchParams.append(key, val));
2797
+ } else {
2798
+ searchParams.append(key, params[key]);
2799
+ }
2800
+ }
2801
+ return searchParams.toString();
2802
+ }
2803
+ async function fetchWithRetry(url, options, remainingRetries = MAX_RETRIES) {
2804
+ try {
2805
+ const response = await fetch(url, options);
2806
+ if (!response.ok) {
2807
+ if (response.status >= 500 && response.status < 600 && remainingRetries > 0) {
2808
+ const delay = BASE_DELAY * Math.pow(2, MAX_RETRIES - remainingRetries);
2809
+ await new Promise((resolve) => setTimeout(resolve, delay));
2810
+ return fetchWithRetry(url, options, remainingRetries - 1);
2811
+ }
2812
+ const errorData = await response.json();
2813
+ const error = new Error(
2814
+ `HTTP error! status: ${response.status}, message: ${errorData.message || response.statusText}`
2815
+ );
2816
+ error.status = response.status;
2817
+ throw error;
2818
+ }
2819
+ return response.json();
2820
+ } catch (error) {
2821
+ if (remainingRetries > 0) {
2822
+ const delay = BASE_DELAY * Math.pow(2, MAX_RETRIES - remainingRetries);
2823
+ await new Promise((resolve) => setTimeout(resolve, delay));
2824
+ return fetchWithRetry(url, options, remainingRetries - 1);
2825
+ }
2826
+ throw error;
2827
+ }
2828
+ }
2829
+ function createHttpClient(origin, token) {
2830
+ const headers = {
2831
+ "Content-Type": "application/json",
2832
+ Authorization: `Bearer ${token}`
2833
+ };
2834
+ const basePath = origin + "/api/v1";
2835
+ const baseCommon = { credentials: "include" };
2836
+ return {
2837
+ get: async (endpoint, options = {}) => {
2838
+ const url = new URL(`${basePath}${endpoint}`);
2839
+ if (options.params) {
2840
+ url.search = paramsSerializer(options.params);
2841
+ }
2842
+ const data = await fetchWithRetry(url.toString(), {
2843
+ ...baseCommon,
2844
+ ...options,
2845
+ method: "GET",
2846
+ headers
2847
+ });
2848
+ return data;
2849
+ },
2850
+ post: async (endpoint, body, options = {}) => {
2851
+ const url = new URL(`${basePath}${endpoint}`);
2852
+ if (options.params) {
2853
+ url.search = paramsSerializer(options.params);
2854
+ }
2855
+ const data = await fetchWithRetry(url.toString(), {
2856
+ ...baseCommon,
2857
+ ...options,
2858
+ method: "POST",
2859
+ headers,
2860
+ body: JSON.stringify(body)
2861
+ });
2862
+ return data;
2863
+ },
2864
+ put: async (endpoint, body, options = {}) => {
2865
+ const url = new URL(`${basePath}${endpoint}`);
2866
+ if (options.params) {
2867
+ url.search = paramsSerializer(options.params);
2868
+ }
2869
+ const data = await fetchWithRetry(url.toString(), {
2870
+ ...baseCommon,
2871
+ ...options,
2872
+ method: "PUT",
2873
+ headers,
2874
+ body: JSON.stringify(body)
2875
+ });
2876
+ return data;
2877
+ },
2878
+ delete: async (endpoint, options = {}) => {
2879
+ const url = new URL(`${basePath}${endpoint}`);
2880
+ if (options.params) {
2881
+ url.search = paramsSerializer(options.params);
2882
+ }
2883
+ const data = await fetchWithRetry(url.toString(), {
2884
+ ...baseCommon,
2885
+ ...options,
2886
+ method: "DELETE",
2887
+ headers
2888
+ });
2889
+ return data;
2890
+ },
2891
+ patch: async (endpoint, body, options = {}) => {
2892
+ const url = new URL(`${basePath}${endpoint}`);
2893
+ if (options.params) {
2894
+ url.search = paramsSerializer(options.params);
2895
+ }
2896
+ const data = await fetchWithRetry(url.toString(), {
2897
+ ...baseCommon,
2898
+ ...options,
2899
+ method: "PATCH",
2900
+ headers,
2901
+ body: JSON.stringify(body)
2902
+ });
2903
+ return data;
2904
+ }
2905
+ };
2906
+ }
2907
+
2908
+ let env;
2909
+ let http;
2910
+ const logInfo = (msg, ...rest) => console.info(`[online handlers]: ${msg}`, ...rest);
2911
+ const check = () => {
2912
+ if (!env) throw new Error("Missing env");
2913
+ if (!http) throw new Error("Missing http");
2914
+ };
2915
+ const setEnv = (e) => {
2916
+ env = e;
2917
+ http = createHttpClient(
2918
+ env.pitcher.token_claims["https://pitcher.com/claims/urls"].custom_domain,
2919
+ env.pitcher.access_token
2920
+ );
2921
+ };
2922
+ const onlineRestApiHandlers = {
2923
+ get_canvases: async (params) => {
2924
+ logInfo("online handler get_canvases called with:", params);
2925
+ check();
2926
+ const { api_base_url, ...restParams } = params;
2927
+ const res = await http.get("/canvases", { params: { ...restParams, instance_id: env.pitcher.instance.id } });
2928
+ return res;
2929
+ },
2930
+ get_canvas: async (params) => {
2931
+ logInfo("online handler get_canvas called with:", params);
2932
+ check();
2933
+ const { id, ...restParams } = params;
2934
+ const res = await http.get(`/canvases/${params.id}`, { params: restParams });
2935
+ return res;
2936
+ },
2937
+ create_canvas: async (params) => {
2938
+ logInfo("online handler create_canvas called with:", params);
2939
+ check();
2940
+ const res = await http.post("/canvases", { ...params, instance_id: env.pitcher.instance.id });
2941
+ return res;
2942
+ },
2943
+ update_canvas: async (params) => {
2944
+ logInfo("online handler update_canvas called with:", params);
2945
+ check();
2946
+ const { id, ...restParams } = params;
2947
+ const res = await http.patch(`/canvases/${params.id}`, restParams);
2948
+ return res;
2949
+ },
2950
+ delete_canvas: async (params) => {
2951
+ logInfo("online handler delete_canvas called with:", params);
2952
+ check();
2953
+ const res = await http.delete(`/canvases/${params.id}`);
2954
+ return res;
2955
+ },
2956
+ share_canvas: async (params) => {
2957
+ logInfo("online handler share_canvas called with:", params);
2958
+ check();
2959
+ let link;
2960
+ try {
2961
+ link = await http.get(`/shared-links/canvas/${params.id}`);
2962
+ } catch (e) {
2963
+ if (e?.status === 404) {
2964
+ link = await http.post("/shared-links", {
2965
+ canvas_id: params.id
2966
+ });
2967
+ } else {
2968
+ throw e;
2969
+ }
2970
+ }
2971
+ return link;
2972
+ }
2973
+ };
2974
+
2975
+ function updateOnlineHandlersEnv(env) {
2976
+ env && setEnv(env);
2977
+ }
2736
2978
  class LowLevelApi extends EventEmitter {
2737
2979
  constructor(options) {
2738
2980
  super();
2739
2981
  this.callbacks = {};
2740
- this.options = options ?? { casing: "snake", logLevel: "off", errorLogger: () => {
2741
- } };
2982
+ this.options = options ?? {
2983
+ casing: "snake",
2984
+ logLevel: "off",
2985
+ errorLogger: () => {
2986
+ },
2987
+ fetchMode: "postmessage"
2988
+ };
2742
2989
  if (typeof window !== "undefined") {
2743
2990
  window.addEventListener("message", (event) => {
2744
2991
  if (!isOriginValid(event)) return;
@@ -2768,6 +3015,7 @@ class LowLevelApi extends EventEmitter {
2768
3015
  this.emit("event", event);
2769
3016
  }
2770
3017
  request(type, body = null) {
3018
+ const fetchMode = this.options.fetchMode ?? "postmessage";
2771
3019
  return new Promise((resolve, reject) => {
2772
3020
  const id = v4();
2773
3021
  const callback = (res) => {
@@ -2776,6 +3024,7 @@ class LowLevelApi extends EventEmitter {
2776
3024
  resolve(
2777
3025
  this.options.casing === "camel" ? camelCaseKeys(res.response.body) : res.response.body
2778
3026
  );
3027
+ if (type === "get_env") updateOnlineHandlersEnv(res.response.body);
2779
3028
  } else if (res.response.status === "error") {
2780
3029
  this.options.errorLogger?.({
2781
3030
  message: `Pitcher JS API call failure: ${res.request.type}`,
@@ -2793,18 +3042,40 @@ class LowLevelApi extends EventEmitter {
2793
3042
  payload: payload ?? {},
2794
3043
  callback
2795
3044
  };
2796
- if (typeof window !== "undefined" && window.top) {
2797
- window.top.postMessage(
2798
- {
2799
- type: "PITCHER_REQUEST",
2800
- request: {
2801
- type,
2802
- id,
2803
- body: payload
2804
- }
2805
- },
2806
- "*"
2807
- );
3045
+ if (fetchMode === "prefer-online" && type && onlineRestApiHandlers[type]) {
3046
+ onlineRestApiHandlers[type](payload).then((data) => {
3047
+ if (this.callbacks[id]) {
3048
+ this.callbacks[id].callback({
3049
+ type: PitcherMessageType.RESPONSE,
3050
+ request: { id, type },
3051
+ response: { status: PitcherResponseStatus.OK, body: data }
3052
+ });
3053
+ delete this.callbacks[id];
3054
+ }
3055
+ }).catch((error) => {
3056
+ if (this.callbacks[id]) {
3057
+ this.callbacks[id].callback({
3058
+ type: PitcherMessageType.RESPONSE,
3059
+ request: { id, type },
3060
+ response: { status: PitcherResponseStatus.ERROR, body: error }
3061
+ });
3062
+ delete this.callbacks[id];
3063
+ }
3064
+ });
3065
+ } else {
3066
+ if (typeof window !== "undefined" && window.top) {
3067
+ window.top.postMessage(
3068
+ {
3069
+ type: "PITCHER_REQUEST",
3070
+ request: {
3071
+ type,
3072
+ id,
3073
+ body: payload
3074
+ }
3075
+ },
3076
+ "*"
3077
+ );
3078
+ }
2808
3079
  }
2809
3080
  });
2810
3081
  }
@@ -3128,51 +3399,6 @@ const dsr = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
3128
3399
  on
3129
3400
  }, Symbol.toStringTag, { value: 'Module' }));
3130
3401
 
3131
- const PITCHER_EVENT = "PITCHER_EVENT";
3132
- var PitcherMessageType = /* @__PURE__ */ ((PitcherMessageType2) => {
3133
- PitcherMessageType2["REQUEST"] = "PITCHER_REQUEST";
3134
- PitcherMessageType2["RESPONSE"] = "PITCHER_RESPONSE";
3135
- return PitcherMessageType2;
3136
- })(PitcherMessageType || {});
3137
- var PitcherResponseStatus = /* @__PURE__ */ ((PitcherResponseStatus2) => {
3138
- PitcherResponseStatus2["OK"] = "ok";
3139
- PitcherResponseStatus2["ERROR"] = "error";
3140
- return PitcherResponseStatus2;
3141
- })(PitcherResponseStatus || {});
3142
- var PitcherEventName = /* @__PURE__ */ ((PitcherEventName2) => {
3143
- PitcherEventName2["ENV_CHANGED"] = "env_changed";
3144
- PitcherEventName2["PHOTOS_CAPTURED"] = "photos_captured";
3145
- PitcherEventName2["FILE_DOWNLOADED"] = "file_downloaded";
3146
- PitcherEventName2["FILE_UPLOAD_PROGRESS"] = "file_upload_progress";
3147
- PitcherEventName2["UPDATE_LOCATION"] = "update_location";
3148
- PitcherEventName2["CANVAS_UPDATED"] = "canvas_updated";
3149
- PitcherEventName2["CANVAS_UPDATED_SUCCESS"] = "canvas_updated_success";
3150
- PitcherEventName2["FILE_CLOSED"] = "file_closed";
3151
- PitcherEventName2["APP_BACKGROUNDED"] = "app_backgrounded";
3152
- PitcherEventName2["APP_FOREGROUNDED"] = "app_foregrounded";
3153
- PitcherEventName2["NON_FILES_SYNC_FINISHED"] = "non_files_sync_finished";
3154
- PitcherEventName2["CONTENT_LIST_REFRESH_REQUESTED"] = "content_list_refresh_requested";
3155
- PitcherEventName2["NETWORK_CONNECTION_ESTABLISHED"] = "network_connection_established";
3156
- PitcherEventName2["NETWORK_CONNECTION_LOST"] = "network_connection_lost";
3157
- PitcherEventName2["ENTERED_FULLSCREEN"] = "entered_fullscreen";
3158
- PitcherEventName2["EXITED_FULLSCREEN"] = "exited_fullscreen";
3159
- PitcherEventName2["SUBMIT_POSTCALL_CLICKED"] = "submit_postcall_clicked";
3160
- return PitcherEventName2;
3161
- })(PitcherEventName || {});
3162
- var PitcherBroadcastedEventName = /* @__PURE__ */ ((PitcherBroadcastedEventName2) => {
3163
- PitcherBroadcastedEventName2["UI_SHOW_MODAL"] = "ui:show-modal";
3164
- PitcherBroadcastedEventName2["UI_HIDE_MODAL"] = "ui:hide-modal";
3165
- PitcherBroadcastedEventName2["FAVORITES_CHANGED"] = "favorites:changed";
3166
- PitcherBroadcastedEventName2["FILE_DOWNLOAD"] = "file:download";
3167
- return PitcherBroadcastedEventName2;
3168
- })(PitcherBroadcastedEventName || {});
3169
- var PitcherExternalEventName = /* @__PURE__ */ ((PitcherExternalEventName2) => {
3170
- PitcherExternalEventName2["CREATE_AND_OPEN_CANVAS"] = "create_and_open_canvas";
3171
- PitcherExternalEventName2["OPEN_CANVAS"] = "open_canvas";
3172
- PitcherExternalEventName2["START_CALL"] = "start_call";
3173
- return PitcherExternalEventName2;
3174
- })(PitcherExternalEventName || {});
3175
-
3176
3402
  let highLevelApi;
3177
3403
  function usePitcherApi(options) {
3178
3404
  if (!highLevelApi) highLevelApi = createHighLevelApi(options);