posthog-react-native 4.11.0 → 4.12.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.
package/LICENSE CHANGED
@@ -219,7 +219,7 @@ limitations under the License.
219
219
 
220
220
  ---
221
221
 
222
- Some files in this codebase contain code from getsentry/sentry-javascript by Software, Inc. dba Sentry.
222
+ Some files in this codebase contain code from getsentry/sentry-javascript or getsentry/sentry-react-native by Software, Inc. dba Sentry.
223
223
  In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases.
224
224
 
225
225
  MIT License
@@ -242,4 +242,58 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
242
242
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
243
243
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
244
244
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
245
- SOFTWARE.
245
+ SOFTWARE.
246
+
247
+ ---
248
+
249
+ Some files in this codebase contain code from facebook/metro by Meta Platforms, Inc. and affiliates.
250
+ In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases.
251
+
252
+ MIT License
253
+
254
+ Copyright (c) Meta Platforms, Inc. and affiliates.
255
+
256
+ Permission is hereby granted, free of charge, to any person obtaining a copy
257
+ of this software and associated documentation files (the "Software"), to deal
258
+ in the Software without restriction, including without limitation the rights
259
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
260
+ copies of the Software, and to permit persons to whom the Software is
261
+ furnished to do so, subject to the following conditions:
262
+
263
+ The above copyright notice and this permission notice shall be included in all
264
+ copies or substantial portions of the Software.
265
+
266
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
267
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
268
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
269
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
270
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
271
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
272
+ SOFTWARE.
273
+
274
+ ---
275
+
276
+ Some files in this codebase contain code from expo/expo by 650 Industries, Inc. (aka Expo).
277
+ In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases.
278
+
279
+ The MIT License (MIT)
280
+
281
+ Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
282
+
283
+ Permission is hereby granted, free of charge, to any person obtaining a copy
284
+ of this software and associated documentation files (the "Software"), to deal
285
+ in the Software without restriction, including without limitation the rights
286
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
287
+ copies of the Software, and to permit persons to whom the Software is
288
+ furnished to do so, subject to the following conditions:
289
+
290
+ The above copyright notice and this permission notice shall be included in all
291
+ copies or substantial portions of the Software.
292
+
293
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
294
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
295
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
296
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
297
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
298
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
299
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ import type { MetroConfig } from 'metro';
2
+ import type { DefaultConfigOptions } from './vendor/expo/expoconfig';
3
+ export * from './posthogMetroSerializer';
4
+ export interface PostHogMetroConfigOptions {
5
+ }
6
+ export interface PostHogExpoConfigOptions {
7
+ /**
8
+ * Pass a custom `getDefaultConfig` function to override the default Expo configuration getter.
9
+ */
10
+ getDefaultConfig?: (projectRoot: string, options?: Record<string, unknown>) => Record<string, unknown>;
11
+ }
12
+ /**
13
+ * This function returns Default Expo configuration with PostHog plugins.
14
+ */
15
+ export declare function getPostHogExpoConfig(projectRoot: string, options?: DefaultConfigOptions & PostHogExpoConfigOptions & PostHogMetroConfigOptions): MetroConfig;
@@ -0,0 +1 @@
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={getPostHogExpoConfig:true};exports.getPostHogExpoConfig=getPostHogExpoConfig;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _posthogMetroSerializer=require("./posthogMetroSerializer");Object.keys(_posthogMetroSerializer).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_posthogMetroSerializer[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _posthogMetroSerializer[key];}});});function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}function getPostHogExpoConfig(projectRoot){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var getDefaultConfig=options.getDefaultConfig||loadExpoMetroConfigModule().getDefaultConfig;var config=getDefaultConfig(projectRoot,_objectSpread(_objectSpread({},options),{},{unstable_beforeAssetSerializationPlugins:[].concat((0,_toConsumableArray2["default"])(options.unstable_beforeAssetSerializationPlugins||[]),[_posthogMetroSerializer.unstableBeforeAssetSerializationDebugIdPlugin])}));return config;}function loadExpoMetroConfigModule(){try{return require('expo/metro-config');}catch(e){throw new Error('Unable to load `expo/metro-config`. Make sure you have Expo installed.');}}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metroconfig.js","sourceRoot":"","sources":["../../src/tooling/metroconfig.ts"],"names":[],"mappings":"AAAA,uJAAuJ;AAGvJ,OAAO,EAAE,6CAA6C,EAAE,MAAM,0BAA0B,CAAA;AAGxF,cAAc,0BAA0B,CAAA;AAWxC;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAClC,WAAmB,EACnB,UAAuF,EAAE;IAEzF,MAAM,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,IAAI,yBAAyB,EAAE,CAAC,gBAAgB,CAAA;IACjG,MAAM,MAAM,GAAG,gBAAgB,CAAC,WAAW,EAAE;QAC3C,GAAG,OAAO;QACV,wCAAwC,EAAE;YACxC,GAAG,CAAC,OAAO,CAAC,wCAAwC,IAAI,EAAE,CAAC;YAC3D,6CAA6C;SAC9C;KACF,CAAC,CAAA;IAEF,OAAO,MAAM,CAAA;AACf,CAAC;AAED,SAAS,yBAAyB;IAYhC,IAAI,CAAC;QACH,8DAA8D;QAC9D,OAAO,OAAO,CAAC,mBAAmB,CAAC,CAAA;IACrC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAA;IAC3F,CAAC;AACH,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { MixedOutput, Module, ReadOnlyGraph } from 'metro';
2
+ import type { MetroSerializer } from './utils';
3
+ /**
4
+ * Adds PostHog Chunk ID polyfill module to the bundle.
5
+ */
6
+ export declare function unstableBeforeAssetSerializationDebugIdPlugin({ premodules, debugId, }: {
7
+ graph: ReadOnlyGraph<MixedOutput>;
8
+ premodules: Module[];
9
+ debugId?: string;
10
+ }): Module[];
11
+ /**
12
+ * Creates a Metro serializer that adds Chunk ID module to the plain bundle.
13
+ * The Chunk ID module is a virtual module that provides a Chunk ID in runtime.
14
+ *
15
+ * RAM Bundles do not support custom serializers.
16
+ */
17
+ export declare const createPostHogMetroSerializer: (customSerializer?: MetroSerializer) => MetroSerializer;
@@ -0,0 +1 @@
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.createPostHogMetroSerializer=void 0;exports.unstableBeforeAssetSerializationDebugIdPlugin=unstableBeforeAssetSerializationDebugIdPlugin;var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _utils=require("./utils");var _utils2=require("./vendor/metro/utils");function _regeneratorRuntime(){"use strict";_regeneratorRuntime=function _regeneratorRuntime(){return r;};var t,r={},e=Object.prototype,n=e.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(t,r,e,n){return Object.defineProperty(t,r,{value:e,enumerable:!n,configurable:!n,writable:!n});}try{c({},"");}catch(t){c=function c(t,r,e){return t[r]=e;};}function h(r,e,n,o){var i=e&&e.prototype instanceof Generator?e:Generator,a=Object.create(i.prototype);return c(a,"_invoke",function(r,e,n){var o=1;return function(i,a){if(3===o)throw Error("Generator is already running");if(4===o){if("throw"===i)throw a;return{value:t,done:!0};}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var c=d(u,n);if(c){if(c===f)continue;return c;}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(1===o)throw o=4,n.arg;n.dispatchException(n.arg);}else"return"===n.method&&n.abrupt("return",n.arg);o=3;var h=s(r,e,n);if("normal"===h.type){if(o=n.done?4:2,h.arg===f)continue;return{value:h.arg,done:n.done};}"throw"===h.type&&(o=4,n.method="throw",n.arg=h.arg);}};}(r,n,new Context(o||[])),!0),a;}function s(t,r,e){try{return{type:"normal",arg:t.call(r,e)};}catch(t){return{type:"throw",arg:t};}}r.wrap=h;var f={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var l={};c(l,i,function(){return this;});var p=Object.getPrototypeOf,y=p&&p(p(x([])));y&&y!==e&&n.call(y,i)&&(l=y);var v=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(l);function g(t){["next","throw","return"].forEach(function(r){c(t,r,function(t){return this._invoke(r,t);});});}function AsyncIterator(t,r){function e(o,i,a,u){var c=s(t[o],t,i);if("throw"!==c.type){var h=c.arg,f=h.value;return f&&"object"==_typeof(f)&&n.call(f,"__await")?r.resolve(f.__await).then(function(t){e("next",t,a,u);},function(t){e("throw",t,a,u);}):r.resolve(f).then(function(t){h.value=t,a(h);},function(t){return e("throw",t,a,u);});}u(c.arg);}var o;c(this,"_invoke",function(t,n){function i(){return new r(function(r,o){e(t,n,r,o);});}return o=o?o.then(i,i):i();},!0);}function d(r,e){var n=e.method,o=r.i[n];if(o===t)return e.delegate=null,"throw"===n&&r.i["return"]&&(e.method="return",e.arg=t,d(r,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),f;var i=s(o,r.i,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,f;var a=i.arg;return a?a.done?(e[r.r]=a.value,e.next=r.n,"return"!==e.method&&(e.method="next",e.arg=t),e.delegate=null,f):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,f);}function w(t){this.tryEntries.push(t);}function m(r){var e=r[4]||{};e.type="normal",e.arg=t,r[4]=e;}function Context(t){this.tryEntries=[[-1]],t.forEach(w,this),this.reset(!0);}function x(r){if(null!=r){var e=r[i];if(e)return e.call(r);if("function"==typeof r.next)return r;if(!isNaN(r.length)){var o=-1,a=function e(){for(;++o<r.length;)if(n.call(r,o))return e.value=r[o],e.done=!1,e;return e.value=t,e.done=!0,e;};return a.next=a;}}throw new TypeError(_typeof(r)+" is not iterable");}return GeneratorFunction.prototype=GeneratorFunctionPrototype,c(v,"constructor",GeneratorFunctionPrototype),c(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName=c(GeneratorFunctionPrototype,u,"GeneratorFunction"),r.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===GeneratorFunction||"GeneratorFunction"===(r.displayName||r.name));},r.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,GeneratorFunctionPrototype):(t.__proto__=GeneratorFunctionPrototype,c(t,u,"GeneratorFunction")),t.prototype=Object.create(v),t;},r.awrap=function(t){return{__await:t};},g(AsyncIterator.prototype),c(AsyncIterator.prototype,a,function(){return this;}),r.AsyncIterator=AsyncIterator,r.async=function(t,e,n,o,i){void 0===i&&(i=Promise);var a=new AsyncIterator(h(t,e,n,o),i);return r.isGeneratorFunction(e)?a:a.next().then(function(t){return t.done?t.value:a.next();});},g(v),c(v,u,"Generator"),c(v,i,function(){return this;}),c(v,"toString",function(){return"[object Generator]";}),r.keys=function(t){var r=Object(t),e=[];for(var n in r)e.unshift(n);return function t(){for(;e.length;)if((n=e.pop())in r)return t.value=n,t.done=!1,t;return t.done=!0,t;};},r.values=x,Context.prototype={constructor:Context,reset:function reset(r){if(this.prev=this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(m),!r)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=t);},stop:function stop(){this.done=!0;var t=this.tryEntries[0][4];if("throw"===t.type)throw t.arg;return this.rval;},dispatchException:function dispatchException(r){if(this.done)throw r;var e=this;function n(t){a.type="throw",a.arg=r,e.next=t;}for(var o=e.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i[4],u=this.prev,c=i[1],h=i[2];if(-1===i[0])return n("end"),!1;if(!c&&!h)throw Error("try statement without catch or finally");if(null!=i[0]&&i[0]<=u){if(u<c)return this.method="next",this.arg=t,n(c),!0;if(u<h)return n(h),!1;}}},abrupt:function abrupt(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n[0]>-1&&n[0]<=this.prev&&this.prev<n[2]){var o=n;break;}}o&&("break"===t||"continue"===t)&&o[0]<=r&&r<=o[2]&&(o=null);var i=o?o[4]:{};return i.type=t,i.arg=r,o?(this.method="next",this.next=o[2],f):this.complete(i);},complete:function complete(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),f;},finish:function finish(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e[2]===t)return this.complete(e[4],e[3]),m(e),f;}},"catch":function _catch(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e[0]===t){var n=e[4];if("throw"===n.type){var o=n.arg;m(e);}return o;}}throw Error("illegal catch attempt");},delegateYield:function delegateYield(r,e,n){return this.delegate={i:x(r),r:e,n:n},"next"===this.method&&(this.arg=t),f;}},r;}var DEBUG_ID_PLACE_HOLDER='__POSTHOG_CHUNK_ID__';var DEBUG_ID_MODULE_PATH='__chunkid__';var SOURCE_MAP_COMMENT='//# sourceMappingURL=';var DEBUG_ID_COMMENT='//# chunkId=';function unstableBeforeAssetSerializationDebugIdPlugin(_ref){var premodules=_ref.premodules,debugId=_ref.debugId;if(!debugId){return premodules;}var debugIdModuleExists=premodules.some(function(module){return module.path===DEBUG_ID_MODULE_PATH;});if(debugIdModuleExists){console.warn('\n\nChunk ID module found. Skipping PostHog Chunk ID module...\n\n');return premodules;}var debugIdModule=createDebugIdModule(debugId);return(0,_utils.prependModule)(premodules,debugIdModule);}var createPostHogMetroSerializer=exports.createPostHogMetroSerializer=function createPostHogMetroSerializer(customSerializer){var serializer=customSerializer||(0,_utils2.createDefaultMetroSerializer)();return function(){var _ref2=(0,_asyncToGenerator2["default"])(_regeneratorRuntime().mark(function _callee(entryPoint,premodules,graph,options){var debugIdModuleExists,debugIdModule,modifiedPremodules,serializerResult,_yield$extractSeriali,bundleCode,bundleMapString,debugId,debugIdComment,indexOfSourceMapComment,bundleCodeWithDebugId,bundleMap;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(!graph.transformOptions.hot){_context.next=2;break;}return _context.abrupt("return",serializer(entryPoint,premodules,graph,options));case 2:debugIdModuleExists=premodules.some(function(module){return module.path===DEBUG_ID_MODULE_PATH;});if(!debugIdModuleExists){_context.next=6;break;}console.warn('Chunk ID module found. Skipping PostHog Chunk ID module...');return _context.abrupt("return",serializer(entryPoint,premodules,graph,options));case 6:debugIdModule=createDebugIdModule(DEBUG_ID_PLACE_HOLDER);modifiedPremodules=(0,_utils.prependModule)(premodules,debugIdModule);serializerResult=serializer(entryPoint,modifiedPremodules,graph,options);_context.next=11;return extractSerializerResult(serializerResult);case 11:_yield$extractSeriali=_context.sent;bundleCode=_yield$extractSeriali.code;bundleMapString=_yield$extractSeriali.map;debugId=(0,_utils.determineDebugIdFromBundleSource)(bundleCode);if(debugId){_context.next=17;break;}throw new Error('Chunk ID was not found in the bundle.');case 17:console.log('info '+"Bundle Chunk ID: ".concat(debugId));debugIdComment="".concat(DEBUG_ID_COMMENT).concat(debugId);indexOfSourceMapComment=bundleCode.lastIndexOf(SOURCE_MAP_COMMENT);bundleCodeWithDebugId=indexOfSourceMapComment===-1?"".concat(bundleCode,"\n").concat(debugIdComment):"".concat(bundleCode.substring(0,indexOfSourceMapComment)+debugIdComment,"\n").concat(bundleCode.substring(indexOfSourceMapComment));bundleMap=JSON.parse(bundleMapString);bundleMap['chunkId']=debugId;return _context.abrupt("return",{code:bundleCodeWithDebugId,map:JSON.stringify(bundleMap)});case 24:case"end":return _context.stop();}},_callee);}));return function(_x,_x2,_x3,_x4){return _ref2.apply(this,arguments);};}();};function extractSerializerResult(_x5){return _extractSerializerResult.apply(this,arguments);}function _extractSerializerResult(){_extractSerializerResult=(0,_asyncToGenerator2["default"])(_regeneratorRuntime().mark(function _callee2(serializerResult){var awaitedResult;return _regeneratorRuntime().wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!(typeof serializerResult==='string')){_context2.next=2;break;}return _context2.abrupt("return",{code:serializerResult,map:'{}'});case 2:if(!('map'in serializerResult)){_context2.next=4;break;}return _context2.abrupt("return",{code:serializerResult.code,map:serializerResult.map});case 4:_context2.next=6;return serializerResult;case 6:awaitedResult=_context2.sent;if(!(typeof awaitedResult==='string')){_context2.next=9;break;}return _context2.abrupt("return",{code:awaitedResult,map:'{}'});case 9:return _context2.abrupt("return",{code:awaitedResult.code,map:awaitedResult.map});case 10:case"end":return _context2.stop();}},_callee2);}));return _extractSerializerResult.apply(this,arguments);}function createDebugIdModule(debugId){return(0,_utils.createVirtualJSModule)(DEBUG_ID_MODULE_PATH,(0,_utils.createDebugIdSnippet)(debugId));}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthogMetroSerializer.js","sourceRoot":"","sources":["../../src/tooling/posthogMetroSerializer.ts"],"names":[],"mappings":"AAAA,iKAAiK;AAKjK,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACtH,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAA;AAInE,MAAM,qBAAqB,GAAG,sBAAsB,CAAA;AACpD,MAAM,oBAAoB,GAAG,aAAa,CAAA;AAE1C,MAAM,kBAAkB,GAAG,uBAAuB,CAAA;AAClD,MAAM,gBAAgB,G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B,CAAA;IACH,CAAC,CAAA;AACH,CAAC,CAAA;AAED,KAAK,UAAU,uBAAuB,CAAC,gBAAuC;IAC5E,IAAI,OAAO,gBAAgB,KAAK,QAAQ,EAAE,CAAC;QACzC,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,GAAG,EAAE,IAAI,EAAE,CAAA;IAC9C,CAAC;IAED,IAAI,KAAK,IAAI,gBAAgB,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,gBAAgB,CAAC,GAAG,EAAE,CAAA;IACnE,CAAC;IAED,MAAM,aAAa,GAAG,MAAM,gBAAgB,CAAA;IAC5C,IAAI,OAAO,aAAa,KAAK,QAAQ,EAAE,CAAC;QACtC,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,GAAG,EAAE,IAAI,EAAE,CAAA;IAC3C,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,aAAa,CAAC,IAAI,EAAE,GAAG,EAAE,aAAa,CAAC,GAAG,EAAE,CAAA;AAC7D,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAe;IAC1C,OAAO,qBAAqB,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAA;AACnF,CAAC"}
@@ -0,0 +1,58 @@
1
+ import type { MixedOutput, Module, ReadOnlyGraph, SerializerOptions } from 'metro';
2
+ import type CountingSet from 'metro/src/lib/CountingSet';
3
+ export type VirtualJSOutput = {
4
+ type: 'js/script/virtual';
5
+ data: {
6
+ code: string;
7
+ lineCount: number;
8
+ map: [];
9
+ };
10
+ };
11
+ export type Bundle = {
12
+ modules: Array<[id: number, code: string]>;
13
+ post: string;
14
+ pre: string;
15
+ };
16
+ export type SerializedBundle = {
17
+ code: string;
18
+ map: string;
19
+ };
20
+ export type MetroSerializerOutput = string | SerializedBundle | Promise<string | SerializedBundle>;
21
+ export type MetroSerializer = (entryPoint: string, premodules: ReadonlyArray<Module>, graph: ReadOnlyGraph, options: SerializerOptions) => MetroSerializerOutput;
22
+ /**
23
+ * Returns minified Chunk ID code snippet.
24
+ */
25
+ export declare function createDebugIdSnippet(debugId: string): string;
26
+ /**
27
+ * Deterministically hashes a string and turns the hash into a uuid.
28
+ *
29
+ * https://github.com/getsentry/sentry-javascript-bundler-plugins/blob/58271f1af2ade6b3e64d393d70376ae53bc5bd2f/packages/bundler-plugin-core/src/utils.ts#L174
30
+ */
31
+ export declare function stringToUUID(str: string): string;
32
+ /**
33
+ * Looks for an injected `_posthogChunkIds[n] = "debugId"` pattern
34
+ * in the bundle source and extracts the `debugId` value from it.
35
+ *
36
+ * Matches both string and numeric keys for `n`, e.g.:
37
+ * _posthogChunkIds["abc"] = "1234"
38
+ * _posthogChunkIds[42] = "1234"
39
+ */
40
+ export declare function determineDebugIdFromBundleSource(code: string): string | undefined;
41
+ export declare const createSet: () => CountingSet<string>;
42
+ /**
43
+ * Prepends the module after default required prelude modules.
44
+ */
45
+ export declare function prependModule(modules: readonly Module<MixedOutput>[], module: Module<VirtualJSOutput>): Module<MixedOutput>[];
46
+ /**
47
+ * Creates a virtual JS module with the given path and code.
48
+ */
49
+ export declare function createVirtualJSModule(modulePath: string, moduleCode: string): Module<VirtualJSOutput> & {
50
+ setSource: (code: string) => void;
51
+ };
52
+ /**
53
+ * Tries to load Expo config using `@expo/config` package.
54
+ */
55
+ export declare function getExpoConfig(projectRoot: string): Partial<{
56
+ name: string;
57
+ version: string;
58
+ }>;
@@ -0,0 +1 @@
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.createDebugIdSnippet=createDebugIdSnippet;exports.createSet=void 0;exports.createVirtualJSModule=createVirtualJSModule;exports.determineDebugIdFromBundleSource=determineDebugIdFromBundleSource;exports.getExpoConfig=getExpoConfig;exports.prependModule=prependModule;exports.stringToUUID=stringToUUID;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var crypto=_interopRequireWildcard(require("crypto"));var _countLines=_interopRequireDefault(require("./vendor/metro/countLines"));function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap(),n=new WeakMap();return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f);}for(var _t2 in e)"default"!==_t2&&{}.hasOwnProperty.call(e,_t2)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t2))&&(i.get||i.set)?o(f,_t2,i):f[_t2]=e[_t2]);return f;})(e,t);}function createDebugIdSnippet(debugId){return"!function(){try{var e=\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]=\"".concat(debugId,"\")}catch(e){}}();");}function stringToUUID(str){var md5sum=crypto.createHash('md5');md5sum.update(str);var md5Hash=md5sum.digest('hex');var v4variant=['8','9','a','b'][md5Hash.substring(16,17).charCodeAt(0)%4];return"".concat(md5Hash.substring(0,8),"-").concat(md5Hash.substring(8,12),"-4").concat(md5Hash.substring(13,16),"-").concat(v4variant).concat(md5Hash.substring(17,20),"-").concat(md5Hash.substring(20)).toLowerCase();}function determineDebugIdFromBundleSource(code){var match=code.match(/_posthogChunkIds\[\s*(?:(?:"[^"]*")|(?:'[^']*')|\d+)\s*\]\s*=\s*"([^"]+)"/);return match?match[1]:undefined;}function resolveSetCreator(){var CountingSetFromPrivate=safeRequireCountingSetFromPrivate();if(CountingSetFromPrivate){return function(){return new CountingSetFromPrivate["default"]();};}var CountingSetFromSrc=safeRequireCountingSetFromSrc();if(CountingSetFromSrc){return function(){return new CountingSetFromSrc["default"]();};}return function(){return new Set();};}function safeRequireCountingSetFromSrc(){try{return require('metro/src/lib/CountingSet');}catch(e){return undefined;}}function safeRequireCountingSetFromPrivate(){try{return require('metro/private/lib/CountingSet');}catch(e){return undefined;}}var createSet=exports.createSet=resolveSetCreator();var PRELUDE_MODULE_PATH='__prelude__';function prependModule(modules,module){var modifiedPremodules=(0,_toConsumableArray2["default"])(modules);if(modifiedPremodules.length>0&&modifiedPremodules[0]!==undefined&&modifiedPremodules[0].path===PRELUDE_MODULE_PATH){modifiedPremodules.unshift(modules[0]);modifiedPremodules[1]=module;}else{modifiedPremodules.unshift(module);}return modifiedPremodules;}function createVirtualJSModule(modulePath,moduleCode){var sourceCode=moduleCode;return{setSource:function setSource(code){sourceCode=code;},dependencies:new Map(),getSource:function getSource(){return Buffer.from(sourceCode);},inverseDependencies:createSet(),path:modulePath,output:[{type:'js/script/virtual',data:{code:sourceCode,lineCount:(0,_countLines["default"])(sourceCode),map:[]}}]};}function getExpoConfig(projectRoot){try{var expoConfig=require('@expo/config');if(expoConfig.getConfig){var _expoConfig$getConfig=expoConfig.getConfig(projectRoot),exp=_expoConfig$getConfig.exp;return{name:typeof exp.name==='string'&&exp.name?exp.name:undefined,version:typeof exp.version==='string'&&exp.version?exp.version:undefined};}}catch(_a){}return{};}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/tooling/utils.ts"],"names":[],"mappings":"AAAA,iJAAiJ;AAEjJ,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAA;AAIhC,OAAO,UAAU,MAAM,2BAA2B,CAAA;AA8BlD;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAe;IAClD,OAAO,mQAAmQ,OAAO,mBAAmB,CAAA;AACtS,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAA;IACvC,MAAM,CAAC,MAAM,CAAC,GAA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UAAU,GAAG,IAAI,CAAA;QACnB,CAAC;QACD,YAAY,EAAE,IAAI,GAAG,EAAE;QACvB,SAAS,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC;QACxC,mBAAmB,EAAE,SAAS,EAAE;QAChC,IAAI,EAAE,UAAU;QAChB,MAAM,EAAE;YACN;gBACE,IAAI,EAAE,mBAAmB;gBACzB,IAAI,EAAE;oBACJ,IAAI,EAAE,UAAU;oBAChB,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC;oBACjC,GAAG,EAAE,EAAE;iBACR;aACF;SACF;KACF,CAAA;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,WAAmB;IAI/C,IAAI,CAAC;QACH,iGAAiG;QACjG,MAAM,UAAU,GAAG,OAAO,CAAC,cAAc,CAExC,CAAA;QACD,IAAI,UAAU,CAAC,SAAS,EAAE,CAAC;YACzB,MAAM,EAAE,GAAG,EAAE,GAAG,UAAU,CAAC,SAAS,CAAC,WAAW,CAAC,CAAA;YACjD,OAAO;gBACL,IAAI,EAAE,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;gBACrE,OAAO,EAAE,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;aAClF,CAAA;QACH,CAAC;IACH,CAAC;IAAC,WAAM,CAAC;QACP,yCAAyC;IAC3C,CAAC;IAED,OAAO,EAAE,CAAA;AACX,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { MixedOutput, Module, ReadOnlyGraph } from 'metro';
2
+ export interface DefaultConfigOptions {
3
+ /** @deprecated */
4
+ mode?: 'exotic';
5
+ /**
6
+ * **Experimental:** Enable CSS support for Metro web, and shim on native.
7
+ *
8
+ * This is an experimental feature and may change in the future. The underlying implementation
9
+ * is subject to change, and native support for CSS Modules may be added in the future during a non-major SDK release.
10
+ */
11
+ isCSSEnabled?: boolean;
12
+ /**
13
+ * **Experimental:** Modify premodules before a code asset is serialized
14
+ *
15
+ * This is an experimental feature and may change in the future. The underlying implementation
16
+ * is subject to change.
17
+ */
18
+ unstable_beforeAssetSerializationPlugins?: ((serializationInput: {
19
+ graph: ReadOnlyGraph<MixedOutput>;
20
+ premodules: Module[];
21
+ debugId?: string;
22
+ }) => Module[])[];
23
+ }
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expoconfig.js","sourceRoot":"","sources":["../../../../src/tooling/vendor/expo/expoconfig.ts"],"names":[],"mappings":"AAAA,wBAAwB"}
@@ -0,0 +1,2 @@
1
+ declare const _default: (string: string) => number;
2
+ export default _default;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var newline=/\r\n?|\n|\u2028|\u2029/g;var _default=exports["default"]=function _default(string){return(string.match(newline)||[]).length+1;};
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countLines.js","sourceRoot":"","sources":["../../../../src/tooling/vendor/metro/countLines.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAEhC,uHAAuH;AAEvH,cAAc;AAEd,qDAAqD;AAErD,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAE3D,iFAAiF;AACjF,kDAAkD;AAElD,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ,4FAA4F;AAC5F,oGAAoG;AACpG,8CAA8C;AAE9C,MAAM,OAAO,GAAG,yBAAyB,CAAA;AAEzC,eAAe,CAAC,MAAc,EAAU,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAA"}
@@ -0,0 +1,22 @@
1
+ import type { Module, ReadOnlyGraph } from 'metro';
2
+ import type { MetroSerializer } from '../../utils';
3
+ /**
4
+ * This function ensures that modules in source maps are sorted in the same
5
+ * order as in a plain JS bundle.
6
+ *
7
+ * https://github.com/facebook/metro/blob/9b85f83c9cc837d8cd897aa7723be7da5b296067/packages/metro/src/Server.js#L984
8
+ */
9
+ export declare const getSortedModules: (graph: ReadOnlyGraph, { createModuleId, }: {
10
+ createModuleId: (file: string) => number;
11
+ }) => readonly Module[];
12
+ /**
13
+ * Creates the default Metro plain bundle serializer.
14
+ * Because Metro exports only the intermediate serializer functions, we need to
15
+ * assemble the final serializer ourselves. We have to work with the modules the same as Metro does
16
+ * to avoid unexpected changes in the final bundle.
17
+ *
18
+ * This is used when the user does not provide a custom serializer.
19
+ *
20
+ * https://github.com/facebook/metro/blob/9b85f83c9cc837d8cd897aa7723be7da5b296067/packages/metro/src/Server.js#L244-L277
21
+ */
22
+ export declare const createDefaultMetroSerializer: () => MetroSerializer;
@@ -0,0 +1 @@
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.getSortedModules=exports.createDefaultMetroSerializer=void 0;var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _a,_b;var baseJSBundleModule;try{baseJSBundleModule=require('metro/private/DeltaBundler/Serializers/baseJSBundle');}catch(_c){baseJSBundleModule=require('metro/src/DeltaBundler/Serializers/baseJSBundle');}var baseJSBundle=typeof baseJSBundleModule==='function'?baseJSBundleModule:(_a=baseJSBundleModule===null||baseJSBundleModule===void 0?void 0:baseJSBundleModule.baseJSBundle)!==null&&_a!==void 0?_a:baseJSBundleModule===null||baseJSBundleModule===void 0?void 0:baseJSBundleModule["default"];var sourceMapString;try{var sourceMapStringModule=require('metro/private/DeltaBundler/Serializers/sourceMapString');sourceMapString=sourceMapStringModule.sourceMapString;}catch(e){sourceMapString=require('metro/src/DeltaBundler/Serializers/sourceMapString');if('sourceMapString'in sourceMapString){sourceMapString=sourceMapString.sourceMapString;}}var bundleToStringModule;try{bundleToStringModule=require('metro/private/lib/bundleToString');}catch(_d){bundleToStringModule=require('metro/src/lib/bundleToString');}var bundleToString=typeof bundleToStringModule==='function'?bundleToStringModule:(_b=bundleToStringModule===null||bundleToStringModule===void 0?void 0:bundleToStringModule.bundleToString)!==null&&_b!==void 0?_b:bundleToStringModule===null||bundleToStringModule===void 0?void 0:bundleToStringModule["default"];var getSortedModules=exports.getSortedModules=function getSortedModules(graph,_ref){var createModuleId=_ref.createModuleId;var modules=(0,_toConsumableArray2["default"])(graph.dependencies.values());return modules.sort(function(a,b){return createModuleId(a.path)-createModuleId(b.path);});};var createDefaultMetroSerializer=exports.createDefaultMetroSerializer=function createDefaultMetroSerializer(){return function(entryPoint,premodules,graph,options){var bundle=(baseJSBundle["default"]||baseJSBundle)(entryPoint,premodules,graph,options);var _ref2=(bundleToString["default"]||bundleToString)(bundle),code=_ref2.code;if(graph.transformOptions.hot){return code;}var sourceMapStringFunction;if(typeof sourceMapString==='function'){sourceMapStringFunction=sourceMapString;}else if((0,_typeof2["default"])(sourceMapString)==='object'&&sourceMapString!=null&&'sourceMapString'in sourceMapString&&typeof sourceMapString['sourceMapString']==='function'){sourceMapStringFunction=sourceMapString.sourceMapString;}else{throw new Error("\n[posthog-react-native/metro] Can't find sourceMapString function in 'metro/src/DeltaBundler/Serializers/sourceMapString'.\nPlease check the version of Metro you are using and report the issue at https://github.com/postHog/posthog-js\n");}var map=(sourceMapStringFunction["default"]||sourceMapStringFunction)([].concat((0,_toConsumableArray2["default"])(premodules),(0,_toConsumableArray2["default"])(getSortedModules(graph,options))),{processModuleFilter:options.processModuleFilter,shouldAddToIgnoreList:options.shouldAddToIgnoreList||function(){return false;}});return{code:code,map:map};};};
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/tooling/vendor/metro/utils.ts"],"names":[],"mappings":"AAAA,2CAA2C;;AAiC3C,IAAI,kBAAuB,CAAA;AAC3B,IAAI,CAAC;IACH,iEAAiE;IACjE,kBAAkB,GAAG,OAAO,CAAC,qDAAqD,CAAC,CAAA;AACrF,CAAC;AAAC,WAAM,CAAC;IACP,iEAAiE;IACjE,kBAAkB,GAAG,OAAO,CAAC,iDAAiD,CAAC,CAAA;AACjF,CAAC;AAED,MAAM,YAAY,GAChB,OAAO,kBAAkB,KAAK,UAAU;IACtC,CAAC,CAAC,kBAAkB;IACpB,CAAC,CAAC,sEAAsE;QACtE,CAAC,MAAA,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,CAAE,YAAY,mCAAI,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,CAAE,OAAO,CAAC,CAAA;AAEvE,IAAI,eAA2C,CAAA;AAC/C,IAAI,CAAC;IACH,8DAA8D;IAC9D,MAAM,qBAAqB,GAAG,OAAO,CAAC,wDAAwD,CAAC,CAAA;IAC/F,eAAe,GAAI,qBAAyE,CAAC,eAAe,CAAA;AAC9G,CAAC;AAAC,OAAO,CAAC,EAAE,CAAC;IACX,eAAe,GAAG,OAAO,CAAC,oDAAoD,CAAC,CAAA;IAC/E,IAAI,iBAAiB,IAAI,eAAe,EAAE,CAAC;QACzC,+GAA+G;QAC/G,iCAAiC;QACjC,eAAe,GAAI,eAAmE,CAAC,eAAe,CAAA;IACxG,CAAC;AACH,CAAC;AAED,IAAI,oBAAyB,CAAA;AAC7B,IAAI,CAAC;IACH,oBAAoB,GAAG,OAAO,CAAC,kCAAkC,CAAC,CAAA;AACpE,CAAC;AAAC,WAAM,CAAC;IACP,oBAAoB,GAAG,OAAO,CAAC,8BAA8B,CAAC,CAAA;AAChE,CAAC;AAED,MAAM,cAAc,GAClB,OAA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O,eAAe,KAAK,QAAQ;YACnC,eAAe,IAAI,IAAI;YACvB,iBAAiB,IAAI,eAAe;YACpC,OAAO,eAAe,CAAC,iBAAiB,CAAC,KAAK,UAAU,EACxD,CAAC;YACD,uBAAuB,GAAI,eAA4C,CAAC,eAAe,CAAA;QACzF,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC;;;CAGrB,CAAC,CAAA;QACE,CAAC;QAED,8BAA8B;QAC9B,MAAM,GAAG,GAAG,CAAC,uBAAuB,CAAC,OAAO,IAAI,uBAAuB,CAAC,CACtE,CAAC,GAAG,UAAU,EAAE,GAAG,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,EACpD;YACE,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;YAChD,qBAAqB,EAAE,OAAO,CAAC,qBAAqB,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC;SACtE,CACF,CAAA;QACD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAA;IACtB,CAAC,CAAA;AACH,CAAC,CAAA"}
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "4.11.0";
1
+ export declare const version = "4.12.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.version=void 0;var version=exports.version="4.11.0";
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.version=void 0;var version=exports.version="4.12.0";
package/package.json CHANGED
@@ -1,11 +1,22 @@
1
1
  {
2
2
  "name": "posthog-react-native",
3
- "version": "4.11.0",
3
+ "version": "4.12.0",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./metro": {
13
+ "types": "./dist/tooling/metroconfig.d.ts",
14
+ "default": "./dist/tooling/metroconfig.js"
15
+ }
16
+ },
7
17
  "files": [
8
- "dist/"
18
+ "dist/",
19
+ "tooling/"
9
20
  ],
10
21
  "repository": {
11
22
  "type": "git",
@@ -31,6 +42,8 @@
31
42
  "jest": "^29.7.0",
32
43
  "jest-environment-node": "^29.7.0",
33
44
  "jest-expo": "^47.0.1",
45
+ "metro": "0.83.1",
46
+ "@expo/metro-config": "~0.20.0",
34
47
  "posthog-react-native-session-replay": "^1.2.0",
35
48
  "react": "18.2.0",
36
49
  "react-native": "^0.69.1",
@@ -0,0 +1,111 @@
1
+ # adapted from https://github.com/getsentry/sentry-react-native/blob/e76d0d388228437e82f235546de00f4e748fcbda/packages/core/scripts/sentry-xcode.sh
2
+
3
+ #!/bin/bash
4
+ # Bundle React Native code and images
5
+ # PWD=ios
6
+
7
+ # print commands before executing them and stop on first error
8
+ set -x -e
9
+
10
+ # WITH_ENVIRONMENT is executed by React Native
11
+
12
+ REACT_NATIVE_XCODE_DEFAULT="../node_modules/react-native/scripts/react-native-xcode.sh"
13
+ REACT_NATIVE_XCODE="${1:-$REACT_NATIVE_XCODE_DEFAULT}"
14
+
15
+ # Check if DERIVED_FILE_DIR exists, defined by Xcode
16
+ if [ ! -d "$DERIVED_FILE_DIR" ]; then
17
+ echo "error: DERIVED_FILE_DIR does not exist: $DERIVED_FILE_DIR"
18
+ exit 1
19
+ fi
20
+
21
+ # RN/users can define a BUNDLE_NAME, or fallback to main
22
+ SOURCEMAP_NAME="${BUNDLE_NAME:-main}.jsbundle.map"
23
+
24
+ [ -z "$SOURCEMAP_FILE" ] && export SOURCEMAP_FILE="$DERIVED_FILE_DIR/$SOURCEMAP_NAME"
25
+
26
+ # Check if CONFIGURATION_BUILD_DIR exists, defined by Xcode
27
+ if [ ! -d "$CONFIGURATION_BUILD_DIR" ]; then
28
+ echo "error: CONFIGURATION_BUILD_DIR does not exist: $CONFIGURATION_BUILD_DIR"
29
+ exit 1
30
+ fi
31
+
32
+ # Check for posthog-cli using installer environment variables
33
+ # TODO: provide a config that users can force the location
34
+ # Xcode starts with a very limited $PATH so using whereis does not work
35
+ if [ -n "$POSTHOG_CLI_INSTALL_DIR" ]; then
36
+ PH_CLI_PATH="$POSTHOG_CLI_INSTALL_DIR/posthog-cli"
37
+ elif [ -n "$CARGO_DIST_FORCE_INSTALL_DIR" ]; then
38
+ PH_CLI_PATH="$CARGO_DIST_FORCE_INSTALL_DIR/posthog-cli"
39
+ elif [ -f "$HOME/.posthog/posthog-cli" ]; then
40
+ PH_CLI_PATH="$HOME/.posthog/posthog-cli"
41
+ else
42
+ # Check if installed via npm -g @posthog/cli
43
+ NPM_GLOBAL_PATH=$(npm root -g 2>/dev/null)
44
+ if [ -n "$NPM_GLOBAL_PATH" ] && [ -f "$NPM_GLOBAL_PATH/@posthog/cli/bin/posthog-cli" ]; then
45
+ PH_CLI_PATH="$NPM_GLOBAL_PATH/@posthog/cli/bin/posthog-cli"
46
+ else
47
+ # Check if installed as local dependency
48
+ NPM_LOCAL_BIN=$(npm bin 2>/dev/null)
49
+ if [ -n "$NPM_LOCAL_BIN" ] && [ -f "$NPM_LOCAL_BIN/posthog-cli" ]; then
50
+ PH_CLI_PATH="$NPM_LOCAL_BIN/posthog-cli"
51
+ else
52
+ # Fallback to searching common locations
53
+ export PATH="/usr/local/bin:/opt/homebrew/bin:$HOME/.cargo/bin:$HOME/.local/bin:$HOME/.posthog:$PATH"
54
+ PH_CLI_PATH=$(command -v posthog-cli 2>/dev/null)
55
+ fi
56
+ fi
57
+ fi
58
+
59
+ if [ -z "$PH_CLI_PATH" ] || [ ! -x "$PH_CLI_PATH" ]; then
60
+ echo "error: posthog-cli not found"
61
+ exit 1
62
+ fi
63
+
64
+ # mimics how the file is defined in node_modules/react-native/scripts/react-native-xcode.sh (PACKAGER_SOURCEMAP_FILE)
65
+ SOURCEMAP_PACKAGER_FILE="$CONFIGURATION_BUILD_DIR/$SOURCEMAP_NAME"
66
+
67
+ # RN deletes the PACKAGER_SOURCEMAP_FILE file after execution but we need it
68
+ # lets patch the script to comment out this part if not yet
69
+ if grep -q '^[[:space:]]*rm.*PACKAGER_SOURCEMAP_FILE' "$REACT_NATIVE_XCODE"; then
70
+ echo "Patching React Native script to preserve sourcemap file..."
71
+ sed -i '' 's/^[[:space:]]*rm.*PACKAGER_SOURCEMAP_FILE/#&/' "$REACT_NATIVE_XCODE"
72
+ echo "Patched: commented out rm PACKAGER_SOURCEMAP_FILE line"
73
+ fi
74
+
75
+ # Execute React Native Xcode script and check exit code
76
+ set +x +e # disable printing commands and allow continuing on error
77
+ RN_XCODE_OUTPUT=$(/bin/sh -c "$REACT_NATIVE_XCODE" 2>&1)
78
+ RN_XCODE_EXIT_CODE=$?
79
+ if [ $RN_XCODE_EXIT_CODE -eq 0 ]; then
80
+ echo "$RN_XCODE_OUTPUT" | awk '{print "output: react-native-xcode - " $0}'
81
+ else
82
+ echo "error: react-native-xcode - $RN_XCODE_OUTPUT"
83
+ exit $RN_XCODE_EXIT_CODE
84
+ fi
85
+ set -x -e # re-enable
86
+
87
+ # Execute posthog cli clone
88
+ set +x +e
89
+ CLI_CLONE_OUTPUT=$(/bin/sh -c "$PH_CLI_PATH exp hermes clone --minified-map-path $SOURCEMAP_PACKAGER_FILE --composed-map-path $SOURCEMAP_FILE" 2>&1)
90
+ CLONE_EXIT_CODE=$?
91
+ if [ $CLONE_EXIT_CODE -eq 0 ]; then
92
+ echo "$CLI_CLONE_OUTPUT" | awk '{print "output: posthog-cli - " $0}'
93
+ else
94
+ echo "error: posthog-cli - $CLI_CLONE_OUTPUT"
95
+ exit $CLONE_EXIT_CODE
96
+ fi
97
+ set -x -e
98
+
99
+ # Execute posthog cli upload
100
+ set +x +e
101
+ CLI_UPLOAD_OUTPUT=$(/bin/sh -c "$PH_CLI_PATH exp hermes upload --directory $DERIVED_FILE_DIR" 2>&1)
102
+ UPLOAD_EXIT_CODE=$?
103
+ if [ $UPLOAD_EXIT_CODE -eq 0 ]; then
104
+ echo "$CLI_UPLOAD_OUTPUT" | awk '{print "output: posthog-cli - " $0}'
105
+ else
106
+ echo "error: posthog-cli - $CLI_UPLOAD_OUTPUT"
107
+ exit $UPLOAD_EXIT_CODE
108
+ fi
109
+ set -x -e
110
+
111
+ exit 0
@@ -0,0 +1,312 @@
1
+ // adapted from https://github.com/getsentry/sentry-react-native/blob/e76d0d388228437e82f235546de00f4e748fcbda/packages/core/sentry.gradle
2
+
3
+ import org.apache.tools.ant.taskdefs.condition.Os
4
+
5
+ import java.util.regex.Matcher
6
+ import java.util.regex.Pattern
7
+
8
+ interface InjectedExecOps {
9
+ @Inject //@javax.inject.Inject
10
+ ExecOperations getExecOps()
11
+ }
12
+
13
+ plugins.withId('com.android.application') {
14
+ def androidComponents = extensions.getByName("androidComponents")
15
+
16
+ androidComponents.onVariants(androidComponents.selector().all()) { v ->
17
+ if (!v.name.toLowerCase().contains("debug")) {
18
+ // separately we then hook into the bundle task of react native to inject
19
+ // sourcemap generation parameters. In case for whatever reason no release
20
+ // was found for the asset folder we just bail.
21
+ def bundleTasks = tasks.findAll { task -> (task.name.startsWith("createBundle") || task.name.startsWith("bundle")) && task.name.endsWith("JsAndAssets") && !task.name.contains("Debug") && task.enabled }
22
+ // this is the task that calls react-native bundle {params}
23
+ bundleTasks.each { bundleTask ->
24
+ def shouldCleanUp
25
+ def sourcemapOutput
26
+ def bundleOutput
27
+ def packagerSourcemapOutput
28
+ def bundleCommand
29
+ def props = bundleTask.getProperties()
30
+ def reactRoot = props.get("workingDir")
31
+ if (reactRoot == null) {
32
+ reactRoot = props.get("root").get() // RN 0.71 and above
33
+ }
34
+
35
+ (shouldCleanUp, bundleOutput, sourcemapOutput, packagerSourcemapOutput, bundleCommand) = forceSourceMapOutputFromBundleTask(bundleTask)
36
+
37
+ // Lets leave this here if we need to debug
38
+ // println bundleTask.properties
39
+ // .sort{it.key}
40
+ // .collect{it}
41
+ // .findAll{!['class', 'active'].contains(it.key)}
42
+ // .join('\n')
43
+
44
+ def currentVariants = extractCurrentVariants(bundleTask, v)
45
+ if (currentVariants == null) return
46
+
47
+ def previousCliTask = null
48
+ def applicationVariant = null
49
+
50
+ def nameCleanup = "${bundleTask.name}_PostHogUploadCleanUp"
51
+ // Upload the source map several times if necessary: once for each release and versionCode.
52
+ currentVariants.each { key, currentVariant ->
53
+ def variant = currentVariant[0]
54
+ def releaseName = currentVariant[1]
55
+ def versionCode = currentVariant[2]
56
+ applicationVariant = currentVariant[3]
57
+
58
+ try {
59
+ if (versionCode instanceof String) {
60
+ versionCode = Integer.parseInt(versionCode)
61
+ versionCode = Math.abs(versionCode)
62
+ }
63
+ } catch (NumberFormatException e) {
64
+ project.logger.info("versionCode: '$versionCode' isn't an Integer, using the plain value.")
65
+ }
66
+
67
+ def nameCliTask = "${bundleTask.name}_PostHogUpload_${releaseName}_${versionCode}"
68
+
69
+ // If several outputs have the same releaseName and versionCode, we'd do the exact same
70
+ // upload for each of them. No need to repeat.
71
+ try { tasks.named(nameCliTask); return } catch (Exception e) {}
72
+
73
+ /** Upload source map file to the PostHog server via CLI call. */
74
+ def cliTask = tasks.register(nameCliTask) {
75
+ description = "upload sourcemaps to PostHog"
76
+ group = 'posthog.com'
77
+
78
+ def extraArgs = []
79
+
80
+ def injected = project.objects.newInstance(InjectedExecOps)
81
+ doFirst {
82
+ injected.execOps.exec {
83
+ workingDir reactRoot
84
+
85
+ def cliPackage = "posthog-cli"
86
+ def args = [cliPackage]
87
+
88
+ args.addAll(["exp", "hermes", "clone",
89
+ "--minified-map-path", packagerSourcemapOutput, // The path to a sourcemap
90
+ "--composed-map-path", sourcemapOutput // The path of the composed source map
91
+ ])
92
+
93
+ args.addAll(extraArgs)
94
+
95
+ project.logger.info("posthog-cli clone arguments: ${args}")
96
+ def osCompatibility = Os.isFamily(Os.FAMILY_WINDOWS) ? ['cmd', '/c', 'node'] : []
97
+
98
+ commandLine(*osCompatibility, *args)
99
+ }
100
+ }
101
+
102
+ doLast {
103
+ injected.execOps.exec {
104
+ workingDir reactRoot
105
+
106
+ def cliPackage = "posthog-cli"
107
+ def args = [cliPackage]
108
+
109
+ def sourcemapDir = sourcemapOutput.getParent()
110
+ args.addAll(["exp", "hermes", "upload",
111
+ "--directory", sourcemapDir // The path to a sourcemap that should be uploaded.
112
+ ])
113
+
114
+ args.addAll(extraArgs)
115
+
116
+ project.logger.info("posthog-cli upload arguments: ${args}")
117
+ def osCompatibility = Os.isFamily(Os.FAMILY_WINDOWS) ? ['cmd', '/c', 'node'] : []
118
+
119
+ commandLine(*osCompatibility, *args)
120
+ }
121
+ }
122
+
123
+ enabled true
124
+ }
125
+
126
+ // chain the upload tasks so they run sequentially in order to run
127
+ // the cliCleanUpTask after the final upload task is run
128
+ if (previousCliTask != null) {
129
+ previousCliTask.configure { finalizedBy cliTask }
130
+ } else {
131
+ bundleTask.configure { finalizedBy cliTask }
132
+ }
133
+ previousCliTask = cliTask
134
+ }
135
+
136
+ /** Delete sourcemap files */
137
+ def cliCleanUpTask = tasks.register(nameCleanup, Delete) {
138
+ description = "clean up extra sourcemap"
139
+ group = 'posthog.com'
140
+
141
+ delete sourcemapOutput
142
+ delete "$buildDir/intermediates/assets/release/index.android.bundle.map"
143
+ // react native default bundle dir
144
+ }
145
+
146
+ // register clean task extension
147
+ cliCleanUpTask.configure { onlyIf { shouldCleanUp } }
148
+ // due to chaining the last value of previousCliTask will be the final
149
+ // upload task, after which the cleanup can be done
150
+ previousCliTask.configure { finalizedBy cliCleanUpTask }
151
+
152
+ def packageTasks = tasks.matching {
153
+ task -> ("package${applicationVariant}".equalsIgnoreCase(task.name) || "package${applicationVariant}Bundle".equalsIgnoreCase(task.name)) && task.enabled
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ def resolvePostHogReactNativeSDKPath(reactRoot) {
161
+ def resolvedPath = null
162
+ try {
163
+ resolvedPath = new File(["node", "--print", "require.resolve('posthog-react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile();
164
+ } catch (Throwable ignored) {} // if the resolve fails we fallback to the default path
165
+ def packagePath = resolvedPath != null && resolvedPath.exists() ? resolvedPath.getAbsolutePath() : "$reactRoot/node_modules/posthog-react-native"
166
+ return packagePath
167
+ }
168
+
169
+ /** Extract from arguments collection bundle and sourcemap files output names. */
170
+ static extractBundleTaskArgumentsLegacy(cmdArgs, Project project) {
171
+ def bundleOutput = null
172
+ def sourcemapOutput = null
173
+ def packagerSourcemapOutput = null
174
+ // packagerBundleOutput doesn't exist, because packager output is overwritten by Hermes
175
+
176
+ cmdArgs.eachWithIndex { String arg, int i ->
177
+ if (arg == "--bundle-output") {
178
+ bundleOutput = cmdArgs[i + 1]
179
+ project.logger.info("--bundle-output: `${bundleOutput}`")
180
+ } else if (arg == "--sourcemap-output") {
181
+ sourcemapOutput = cmdArgs[i + 1]
182
+ packagerSourcemapOutput = sourcemapOutput
183
+ project.logger.info("--sourcemap-output param: `${sourcemapOutput}`")
184
+ }
185
+ }
186
+
187
+ // Best thing would be if we just had access to the local gradle variables here:
188
+ // https://github.com/facebook/react-native/blob/ff3b839e9a5a6c9e398a1327cde6dd49a3593092/react.gradle#L89-L97
189
+ // Now, the issue is that hermes builds have a different pipeline:
190
+ // `metro -> hermes -> compose-source-maps`, which then combines both intermediate sourcemaps into the final one.
191
+ // In this function here, we only grep through the first `metro` step, which only generates an intermediate sourcemap,
192
+ // which is wrong. We need the final one. Luckily, we can just generate the path from the `bundleOutput`, since
193
+ // the paths seem to be well defined.
194
+
195
+ // if sourcemapOutput is null, it means there's no source maps at all
196
+ // if hermes is enabled and has intermediates folder, we need to fix paths
197
+ // if hermes is disabled, sourcemapOutput is already ok
198
+ def enableHermes = project.ext.react.get("enableHermes", false);
199
+ project.logger.info("enableHermes: `${enableHermes}`")
200
+
201
+ if (bundleOutput != null && sourcemapOutput != null && enableHermes) {
202
+ // react-native < 0.60.1
203
+ def pattern = Pattern.compile("(/|\\\\)intermediates\\1sourcemaps\\1react\\1")
204
+ Matcher matcher = pattern.matcher(sourcemapOutput)
205
+ // if its intermediates/sourcemaps/react then it should be generated/sourcemaps/react
206
+ if (matcher.find()) {
207
+ project.logger.info("sourcemapOutput has the wrong path, let's fix it.")
208
+ // replacing from bundleOutput which is more reliable
209
+ sourcemapOutput = bundleOutput.replaceAll("(/|\\\\)generated\\1assets\\1react\\1", "\$1generated\$1sourcemaps\$1react\$1") + ".map"
210
+ project.logger.info("sourcemapOutput new path: `${sourcemapOutput}`")
211
+ }
212
+ }
213
+
214
+ // get the current bundle command, if not peresent use default plain "bundle"
215
+ // we use this later to decide how to upload source maps
216
+ def bundleCommand = project.ext.react.get("bundleCommand", "bundle")
217
+
218
+ return [bundleOutput, sourcemapOutput, packagerSourcemapOutput, bundleCommand]
219
+ }
220
+
221
+ /** Extract bundle and sourcemap paths from bundle task props.
222
+ * Based on https://github.com/facebook/react-native/blob/93c17cd0c43ba7fe3bc09f547b64771984992fbb/packages/gradle-plugin/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt
223
+ * Output source map path is the same for both Hermes and JSC.
224
+ */
225
+ static extractBundleTaskArgumentsRN71AndAbove(bundleTask, logger) {
226
+ def props = bundleTask.getProperties()
227
+ def bundleAssetName = props.bundleAssetName?.get()
228
+
229
+ if (bundleAssetName == null) {
230
+ return [null, null]
231
+ }
232
+
233
+ def bundleCommand = props.bundleCommand.get()
234
+ def bundleFile = new File(props.jsBundleDir.get().asFile.absolutePath, bundleAssetName)
235
+ def outputSourceMap = new File(props.jsSourceMapsDir.get().asFile.absolutePath, "${bundleAssetName}.map")
236
+ def packagerOutputSourceMap = new File(props.jsIntermediateSourceMapsDir.get().asFile.absolutePath, "${bundleAssetName}.packager.map")
237
+
238
+ logger.info("bundleFile: `${bundleFile}`")
239
+ logger.info("outputSourceMap: `${outputSourceMap}`")
240
+ logger.info("packagerOutputSourceMap: `${packagerOutputSourceMap}`")
241
+ return [bundleFile, outputSourceMap, packagerOutputSourceMap, bundleCommand]
242
+ }
243
+
244
+ /** Force Bundle task to produce sourcemap files if they are not pre-configured by user yet. */
245
+ def forceSourceMapOutputFromBundleTask(bundleTask) {
246
+ def props = bundleTask.getProperties()
247
+ def cmd = props.get("commandLine") as List<String>
248
+ def cmdArgs = props.get("args") as List<String>
249
+ def shouldCleanUp = false
250
+ def bundleOutput = null
251
+ def sourcemapOutput = null
252
+ def packagerSourcemapOutput = null
253
+ def bundleCommand = null
254
+
255
+ (bundleOutput, sourcemapOutput, packagerSourcemapOutput, bundleCommand) = extractBundleTaskArgumentsRN71AndAbove(bundleTask, logger)
256
+ if (bundleOutput == null) {
257
+ (bundleOutput, sourcemapOutput, packagerSourcemapOutput, bundleCommand) = extractBundleTaskArgumentsLegacy(cmdArgs, project)
258
+ }
259
+
260
+ if (sourcemapOutput == null) {
261
+ sourcemapOutput = bundleOutput + ".map"
262
+
263
+ cmd.addAll(["--sourcemap-output", sourcemapOutput])
264
+ cmdArgs.addAll(["--sourcemap-output", sourcemapOutput])
265
+
266
+ shouldCleanUp = true
267
+
268
+ bundleTask.setProperty("commandLine", cmd)
269
+ bundleTask.setProperty("args", cmdArgs)
270
+
271
+ project.logger.info("forced sourcemap file output for `${bundleTask.name}` task")
272
+ } else {
273
+ project.logger.info("Info: used pre-configured source map files: ${sourcemapOutput}")
274
+ }
275
+
276
+ return [shouldCleanUp, bundleOutput, sourcemapOutput, packagerSourcemapOutput, bundleCommand]
277
+ }
278
+
279
+ /** compose array with one item - current build flavor name */
280
+ static extractCurrentVariants(bundleTask, variant) {
281
+ // examples: bundleLocalReleaseJsAndAssets, createBundleYellowDebugJsAndAssets
282
+ def pattern = Pattern.compile("(?:create)?(?:B|b)undle([A-Z][A-Za-z0-9_]+)JsAndAssets")
283
+
284
+ def currentRelease = ""
285
+
286
+ Matcher matcher = pattern.matcher(bundleTask.name)
287
+ if (matcher.find()) {
288
+ def match = matcher.group(1)
289
+ currentRelease = match.substring(0, 1).toLowerCase() + match.substring(1)
290
+ }
291
+
292
+ def currentVariants = null
293
+ if (variant.name.equalsIgnoreCase(currentRelease)) {
294
+ currentVariants = [:]
295
+ def variantName = variant.name
296
+ variant.outputs.each { output ->
297
+ def defaultVersionCode = output.versionCode.getOrElse(0)
298
+ def versionCode = defaultVersionCode
299
+ def appId = variant.applicationId.get()
300
+ def versionName = output.versionName.getOrElse('') // may be empty if not set
301
+ def defaultReleaseName = "${appId}@${versionName}+${versionCode}"
302
+ def releaseName = defaultReleaseName
303
+
304
+ def outputName = output.baseName
305
+
306
+ if (currentVariants[outputName] == null) currentVariants[outputName] = []
307
+ currentVariants[outputName] = [outputName, releaseName, versionCode, variantName]
308
+ }
309
+ }
310
+
311
+ return currentVariants
312
+ }