5cbbb20c2ee389c09459b349cd0f743d.json 13.2 KB
{"ast":null,"code":"var _interopRequireDefault=require(\"@babel/runtime/helpers/interopRequireDefault\");Object.defineProperty(exports,\"__esModule\",{value:true});exports.guardPermission=guardPermission;exports.getExponentPushTokenAsync=getExponentPushTokenAsync;exports.getDevicePushTokenAsync=getDevicePushTokenAsync;var _regenerator=_interopRequireDefault(require(\"@babel/runtime/regenerator\"));var _core=require(\"@unimodules/core\");var _expoConstants=_interopRequireDefault(require(\"expo-constants\"));var _Platform=_interopRequireDefault(require(\"react-native-web/dist/exports/Platform\"));function guardPermission(){if(!('Notification'in window)){throw new Error('The Notification API is not available on this device.');}if(!navigator.serviceWorker){throw new Error('Notifications cannot be used because the service worker API is not supported on this device. This might also happen because your web page does not support HTTPS.');}if(Notification.permission!=='granted'){throw new Error('Cannot use Notifications without permissions. Please request permissions with `expo-permissions`');}}function getExponentPushTokenAsync(){var data,experienceId,tokenArguments,response;return _regenerator.default.async(function getExponentPushTokenAsync$(_context){while(1){switch(_context.prev=_context.next){case 0:if(!(!_expoConstants.default.manifest.owner||!_expoConstants.default.manifest.slug)){_context.next=2;break;}throw new _core.CodedError('E_NOTIFICATIONS_PUSH_WEB_MISSING_CONFIG','You must provide `owner` and `slug` in `app.json` to use push notifications on web. Learn more: https://docs.expo.io/versions/latest/guides/using-vapid/.');case 2:_context.next=4;return _regenerator.default.awrap(_subscribeUserToPushAsync());case 4:data=_context.sent;experienceId=\"@\"+_expoConstants.default.manifest.owner+\"/\"+_expoConstants.default.manifest.slug;tokenArguments={deviceId:_expoConstants.default.installationId,experienceId:experienceId,appId:experienceId,deviceToken:JSON.stringify(data),type:'web'};_context.next=9;return _regenerator.default.awrap(fetch('https://exp.host/--/api/v2/push/getExpoPushToken',{method:'POST',body:JSON.stringify(tokenArguments)}).then(function(response){if(!response.ok){throw new Error(response.statusText);}return response;}).then(function(response){return response.json();}).catch(function(error){throw new _core.CodedError('E_NOTIFICATIONS_TOKEN_REGISTRATION_FAILED','The device was unable to register for remote notifications with Expo. ('+error+')');}));case 9:response=_context.sent;return _context.abrupt(\"return\",response.data.expoPushToken);case 11:case\"end\":return _context.stop();}}});}function getDevicePushTokenAsync(){var data;return _regenerator.default.async(function getDevicePushTokenAsync$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return _regenerator.default.awrap(_subscribeUserToPushAsync());case 2:data=_context2.sent;return _context2.abrupt(\"return\",{type:_Platform.default.OS,data:data});case 4:case\"end\":return _context2.stop();}}});}function _subscribeUserToPushAsync(){var registration,subscribeOptions,pushSubscription,pushSubscriptionJson,subscriptionObject,notificationIcon;return _regenerator.default.async(function _subscribeUserToPushAsync$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:if(!(!_expoConstants.default.manifest.notification||!_expoConstants.default.manifest.notification.vapidPublicKey)){_context3.next=2;break;}throw new _core.CodedError('E_NOTIFICATIONS_PUSH_WEB_MISSING_CONFIG','You must provide `notification.vapidPublicKey` in `app.json` to use push notifications on web. Learn more: https://docs.expo.io/versions/latest/guides/using-vapid/.');case 2:guardPermission();_context3.next=5;return _regenerator.default.awrap(navigator.serviceWorker.register('/expo-service-worker.js'));case 5:registration=_context3.sent;_context3.next=8;return _regenerator.default.awrap(navigator.serviceWorker.ready);case 8:if(registration.active){_context3.next=10;break;}throw new Error('Notifications might not be working because the service worker API is not active.');case 10:subscribeOptions={userVisibleOnly:true,applicationServerKey:_urlBase64ToUint8Array(_expoConstants.default.manifest.notification.vapidPublicKey)};_context3.next=13;return _regenerator.default.awrap(registration.pushManager.subscribe(subscribeOptions).catch(function(error){throw new _core.CodedError('E_NOTIFICATIONS_PUSH_WEB_TOKEN_REGISTRATION_FAILED','The device was unable to register for remote notifications with the browser endpoint. ('+error+')');}));case 13:pushSubscription=_context3.sent;pushSubscriptionJson=pushSubscription.toJSON();subscriptionObject={endpoint:pushSubscriptionJson.endpoint,keys:{p256dh:pushSubscriptionJson.keys.p256dh,auth:pushSubscriptionJson.keys.auth}};notificationIcon=(_expoConstants.default.manifest.notification||{}).icon;_context3.next=19;return _regenerator.default.awrap(registration.active.postMessage(JSON.stringify({fromExpoWebClient:{notificationIcon:notificationIcon}})));case 19:return _context3.abrupt(\"return\",subscriptionObject);case 20:case\"end\":return _context3.stop();}}});}function _urlBase64ToUint8Array(base64String){var padding='='.repeat((4-base64String.length%4)%4);var base64=(base64String+padding).replace(/-/g,'+').replace(/_/g,'/');var rawData=window.atob(base64);var outputArray=new Uint8Array(rawData.length);for(var i=0;i<rawData.length;++i){outputArray[i]=rawData.charCodeAt(i);}return outputArray;}","map":{"version":3,"sources":["../../src/Notifications/ExponentNotificationsHelper.web.ts"],"names":[],"mappings":"uXAAA,sCACA,qE,wFAGM,QAAU,CAAA,eAAV,EAAyB,CAC7B,GAAI,EAAE,gBAAkB,CAAA,MAApB,CAAJ,CAAiC,CAC/B,KAAM,IAAI,CAAA,KAAJ,CAAU,uDAAV,CAAN,CACD,CACD,GAAI,CAAC,SAAS,CAAC,aAAf,CAA8B,CAC5B,KAAM,IAAI,CAAA,KAAJ,CACJ,mKADI,CAAN,CAGD,CACD,GAAI,YAAY,CAAC,UAAb,GAA4B,SAAhC,CAA2C,CACzC,KAAM,IAAI,CAAA,KAAJ,CACJ,kGADI,CAAN,CAGD,CACF,CAEM,QAAe,CAAA,yBAAf,0LACD,CAAC,uBAAU,QAAV,CAAmB,KAApB,EAA6B,CAAC,uBAAU,QAAV,CAAmB,IADhD,+BAEG,IAAI,iBAAJ,CACJ,yCADI,CAEJ,2JAFI,CAFH,0DAQc,yBAAyB,EARvC,SAQC,IARD,eASC,YATD,KASoB,uBAAU,QAAV,CAAmB,KATvC,KASgD,uBAAU,QAAV,CAAmB,IATnE,CAUC,cAVD,CAU6C,CAChD,QAAQ,CAAE,uBAAU,cAD4B,CAEhD,YAAY,CAAZ,YAFgD,CAIhD,KAAK,CAAE,YAJyC,CAKhD,WAAW,CAAE,IAAI,CAAC,SAAL,CAAe,IAAf,CALmC,CAMhD,IAAI,CAAE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,CAAb,CAAgB,CAAC,CAAG,OAAO,CAAC,MAA5B,CAAoC,EAAE,CAAtC,CAAyC,CACvC,WAAW,CAAC,CAAD,CAAX,CAAiB,OAAO,CAAC,UAAR,CAAmB,CAAnB,CAAjB,CACD,CACD,MAAO,CAAA,WAAP,CACD","sourcesContent":["import { CodedError } from '@unimodules/core';\nimport Constants from 'expo-constants';\nimport { Platform } from 'react-native';\n\nexport function guardPermission() {\n  if (!('Notification' in window)) {\n    throw new Error('The Notification API is not available on this device.');\n  }\n  if (!navigator.serviceWorker) {\n    throw new Error(\n      'Notifications cannot be used because the service worker API is not supported on this device. This might also happen because your web page does not support HTTPS.'\n    );\n  }\n  if (Notification.permission !== 'granted') {\n    throw new Error(\n      'Cannot use Notifications without permissions. Please request permissions with `expo-permissions`'\n    );\n  }\n}\n\nexport async function getExponentPushTokenAsync(): Promise<string> {\n  if (!Constants.manifest.owner || !Constants.manifest.slug) {\n    throw new CodedError(\n      'E_NOTIFICATIONS_PUSH_WEB_MISSING_CONFIG',\n      'You must provide `owner` and `slug` in `app.json` to use push notifications on web. Learn more: https://docs.expo.io/versions/latest/guides/using-vapid/.'\n    );\n  }\n\n  const data = await _subscribeUserToPushAsync();\n  const experienceId = `@${Constants.manifest.owner}/${Constants.manifest.slug}`;\n  const tokenArguments: { [key: string]: string } = {\n    deviceId: Constants.installationId,\n    experienceId,\n    // Also uses `experienceId` for `appId` because there's no `appId` for web.\n    appId: experienceId,\n    deviceToken: JSON.stringify(data),\n    type: 'web',\n  };\n\n  const response = await fetch('https://exp.host/--/api/v2/push/getExpoPushToken', {\n    method: 'POST',\n    body: JSON.stringify(tokenArguments),\n  })\n    .then(response => {\n      if (!response.ok) {\n        throw new Error(response.statusText);\n      }\n      return response;\n    })\n    .then(response => response.json())\n    .catch(error => {\n      throw new CodedError(\n        'E_NOTIFICATIONS_TOKEN_REGISTRATION_FAILED',\n        'The device was unable to register for remote notifications with Expo. (' + error + ')'\n      );\n    });\n\n  return response.data.expoPushToken;\n}\n\nexport async function getDevicePushTokenAsync(): Promise<{ type: string; data: Object }> {\n  const data = await _subscribeUserToPushAsync();\n  return { type: Platform.OS, data };\n}\n\nasync function _subscribeUserToPushAsync(): Promise<Object> {\n  if (!Constants.manifest.notification || !Constants.manifest.notification.vapidPublicKey) {\n    throw new CodedError(\n      'E_NOTIFICATIONS_PUSH_WEB_MISSING_CONFIG',\n      'You must provide `notification.vapidPublicKey` in `app.json` to use push notifications on web. Learn more: https://docs.expo.io/versions/latest/guides/using-vapid/.'\n    );\n  }\n  guardPermission();\n\n  const registration = await navigator.serviceWorker.register('/expo-service-worker.js');\n  await navigator.serviceWorker.ready;\n\n  if (!registration.active) {\n    throw new Error(\n      'Notifications might not be working because the service worker API is not active.'\n    );\n  }\n\n  const subscribeOptions = {\n    userVisibleOnly: true,\n    applicationServerKey: _urlBase64ToUint8Array(Constants.manifest.notification.vapidPublicKey),\n  };\n  const pushSubscription = await registration.pushManager\n    .subscribe(subscribeOptions)\n    .catch(error => {\n      throw new CodedError(\n        'E_NOTIFICATIONS_PUSH_WEB_TOKEN_REGISTRATION_FAILED',\n        'The device was unable to register for remote notifications with the browser endpoint. (' +\n          error +\n          ')'\n      );\n    });\n  const pushSubscriptionJson = pushSubscription.toJSON();\n\n  const subscriptionObject = {\n    endpoint: pushSubscriptionJson.endpoint,\n    keys: {\n      p256dh: pushSubscriptionJson.keys!.p256dh,\n      auth: pushSubscriptionJson.keys!.auth,\n    },\n  };\n\n  // Store notification icon string in service worker.\n  // This message is received by `/expo-service-worker.js`.\n  // We wrap it with `fromExpoWebClient` to make sure other message\n  // will not override content such as `notificationIcon`.\n  // https://stackoverflow.com/a/35729334/2603230\n  let notificationIcon = (Constants.manifest.notification || {}).icon;\n  await registration.active.postMessage(\n    JSON.stringify({ fromExpoWebClient: { notificationIcon } })\n  );\n\n  return subscriptionObject;\n}\n\n// https://github.com/web-push-libs/web-push#using-vapid-key-for-applicationserverkey\nfunction _urlBase64ToUint8Array(base64String: string): Uint8Array {\n  const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');\n\n  const rawData = window.atob(base64);\n  const outputArray = new Uint8Array(rawData.length);\n\n  for (let i = 0; i < rawData.length; ++i) {\n    outputArray[i] = rawData.charCodeAt(i);\n  }\n  return outputArray;\n}\n"],"sourceRoot":""},"metadata":{},"sourceType":"script"}