snack-sdk 3.6.0 → 3.9.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/CHANGELOG.md +27 -0
- package/build/DependencyResolver.d.ts +2 -1
- package/build/DependencyResolver.js +6 -5
- package/build/DependencyResolver.js.map +1 -1
- package/build/FileUploader.d.ts +2 -1
- package/build/FileUploader.js.map +1 -1
- package/build/Session.d.ts +6 -1
- package/build/Session.js +16 -7
- package/build/Session.js.map +1 -1
- package/build/State.js +2 -2
- package/build/State.js.map +1 -1
- package/build/WantedVersions.d.ts +30 -6
- package/build/WantedVersions.js +86 -26
- package/build/WantedVersions.js.map +1 -1
- package/build/defaultConfig.d.ts +2 -3
- package/build/defaultConfig.js +4 -4
- package/build/defaultConfig.js.map +1 -1
- package/build/index.d.ts +2 -2
- package/build/index.js +8 -8
- package/build/index.js.map +1 -1
- package/build/transports/CodeMessageBuilder.d.ts +1 -1
- package/build/transports/CodeMessageBuilder.js +2 -2
- package/build/transports/CodeMessageBuilder.js.map +1 -1
- package/build/transports/Protocol.d.ts +1 -1
- package/build/transports/Protocol.js.map +1 -1
- package/build/transports/Transport.d.ts +1 -0
- package/build/transports/Transport.js +6 -1
- package/build/transports/Transport.js.map +1 -1
- package/build/transports/types.d.ts +1 -1
- package/build/transports/types.js.map +1 -1
- package/build/transports/webPlayer.d.ts +2 -1
- package/build/transports/webPlayer.js.map +1 -1
- package/build/types.d.ts +10 -75
- package/build/types.js.map +1 -1
- package/build/utils.d.ts +2 -1
- package/build/utils.js.map +1 -1
- package/package.json +12 -4
- package/build/sdk.d.ts +0 -34
- package/build/sdk.js +0 -139
- package/build/sdk.js.map +0 -1
- package/build/sdks/features.d.ts +0 -9
- package/build/sdks/features.js +0 -13
- package/build/sdks/features.js.map +0 -1
- package/build/sdks/index.d.ts +0 -5
- package/build/sdks/index.js +0 -124
- package/build/sdks/index.js.map +0 -1
- package/build/sdks/types.d.ts +0 -21
- package/build/sdks/types.js +0 -3
- package/build/sdks/types.js.map +0 -1
- package/src/DependencyResolver.ts +0 -214
- package/src/DevSession.ts +0 -159
- package/src/FileUploader.ts +0 -133
- package/src/Logger.ts +0 -33
- package/src/Session.ts +0 -1280
- package/src/State.ts +0 -98
- package/src/WantedVersions.ts +0 -56
- package/src/defaultConfig.ts +0 -33
- package/src/index.ts +0 -31
- package/src/sdk.ts +0 -135
- package/src/sdks/features.ts +0 -11
- package/src/sdks/index.ts +0 -159
- package/src/sdks/types.ts +0 -49
- package/src/transports/CodeMessageBuilder.ts +0 -221
- package/src/transports/Protocol.ts +0 -78
- package/src/transports/Transport.ts +0 -270
- package/src/transports/index.ts +0 -8
- package/src/transports/types.ts +0 -88
- package/src/transports/webPlayer.ts +0 -91
- package/src/types.ts +0 -287
- package/src/utils.ts +0 -70
- package/tsconfig.json +0 -28
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WantedVersions.js","sourceRoot":"","sources":["../src/WantedVersions.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"WantedVersions.js","sourceRoot":"","sources":["../src/WantedVersions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAA0E;AAI1E,iCAAgC;AAehC;IAOE,kCAAY,OAAwC;QAClD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IACnC,CAAC;IAED,gDAAa,GAAb,UAAc,UAAsB;QAClC,IAAI,IAAI,CAAC,UAAU,KAAK,UAAU,EAAE;YAClC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;YAC7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,YAAY,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Y,4DAAwB","sourcesContent":["import { SDKVersion, SnackDependencyVersions, sdks } from 'snack-content';\n\nimport { Logger } from './Logger';\nimport { SnackError } from './types';\nimport { fetch } from './utils';\n\nexport type WantedDependencyVersionsCallback = (\n sdkVersion: SDKVersion,\n result?: SnackDependencyVersions,\n error?: SnackError\n) => any;\n\ninterface WantedDependencyVersionsOptions {\n /** The Expo API URL to fetch the remote versioned modules from */\n apiUrl: string;\n logger?: Logger;\n callback: WantedDependencyVersionsCallback;\n}\n\nexport class WantedDependencyVersions {\n private readonly callback: WantedDependencyVersionsCallback;\n private readonly logger?: Logger;\n private sdkVersion?: SDKVersion;\n private promise: Promise<any>;\n private apiUrl: string;\n\n constructor(options: WantedDependencyVersionsOptions) {\n this.apiUrl = options.apiUrl;\n this.logger = options.logger;\n this.callback = options.callback;\n this.promise = Promise.resolve();\n }\n\n setSDKVersion(sdkVersion: SDKVersion) {\n if (this.sdkVersion !== sdkVersion) {\n this.sdkVersion = sdkVersion;\n this.promise = this.fetchModules(sdkVersion);\n }\n }\n\n waitForCompletion() {\n return this.promise;\n }\n\n /**\n * Fetch all versioned modules from an SDK.\n * This is similar to the `getCombinedKnownVersionsAsync` method.\n * @see https://github.com/expo/expo/blob/0f1b5f0cd1caa86db3c01a001b14def93062a07e/packages/%40expo/cli/src/start/doctor/dependencies/getVersionedPackages.ts#L34\n */\n private async fetchModules(sdkVersion: SDKVersion): Promise<void> {\n if (this.sdkVersion !== sdkVersion) {\n return;\n }\n\n try {\n this.logger?.module('fetching versioned modules for SDK', sdkVersion, '...');\n\n // TODO(cedric): check why this is still necessary\n const sdkVersionString = sdks[sdkVersion]?.version || sdkVersion;\n const [remoteVersions, bundledVersions] = await Promise.all([\n this.fetchRemoteVersionedModules(sdkVersionString),\n this.fetchBundledNativeModules(sdkVersionString),\n ]);\n\n const versions = {\n ...remoteVersions,\n ...bundledVersions,\n };\n\n // Note(cedric): SDK could have changed during fetching\n if (this.sdkVersion === sdkVersion) {\n this.logger?.module('fetched versioned modules for SDK', sdkVersion, versions);\n this.callback(sdkVersion, versions);\n }\n } catch (error) {\n // Note(cedric): SDK could have changed during fetching\n if (this.sdkVersion === sdkVersion) {\n this.logger?.error(error);\n this.callback(sdkVersion, undefined, error);\n }\n }\n }\n\n /**\n * Fetch all bundled native modules from the `expo/bundledNativeModules.json` file.\n */\n private fetchBundledNativeModules(sdkVersion: string): Promise<Record<string, string>> {\n const urlVersion = encodeURIComponent(sdkVersion);\n return fetch(`https://cdn.jsdelivr.net/npm/expo@${urlVersion}/bundledNativeModules.json`)\n .then((response) => response.json())\n .then((data) => data || {});\n }\n\n /**\n * Fetch all remote versioned modules from the `/versions/latest` API endpoint.\n */\n private fetchRemoteVersionedModules(sdkVersion: string): Promise<Record<string, string>> {\n return fetch(`${this.apiUrl}/--/api/v2/versions/latest`)\n .then((response) => response.json())\n .then((data) => this.normalizeRemoteVersionResponse(sdkVersion, data));\n }\n\n /**\n * Normalize the versions response, and account for incorrect settings.\n * @see https://github.com/expo/expo/blob/0f1b5f0cd1caa86db3c01a001b14def93062a07e/packages/%40expo/cli/src/start/doctor/dependencies/getVersionedPackages.ts#L13-L31\n */\n private normalizeRemoteVersionResponse(sdkVersion: string, response: any = {}) {\n const sdkVersionSettings = response?.data?.sdkVersions?.[sdkVersion];\n\n if (!sdkVersionSettings) {\n return {};\n }\n\n const { relatedPackages, facebookReactVersion, facebookReactNativeVersion } =\n sdkVersionSettings;\n\n const reactVersion = facebookReactVersion\n ? {\n react: facebookReactVersion,\n 'react-dom': facebookReactVersion,\n }\n : undefined;\n\n // Adds `react-dom`, `react`, and `react-native` to the list of known package versions (`relatedPackages`)\n return {\n ...relatedPackages,\n ...reactVersion,\n 'react-native': facebookReactNativeVersion,\n };\n }\n}\n"]}
|
package/build/defaultConfig.d.ts
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { SnackState } from './types';
|
|
2
2
|
export declare const apiURL: string;
|
|
3
3
|
export declare const snackagerURL: string;
|
|
4
4
|
export declare const webPlayerURL: string;
|
|
5
|
-
export declare const sdkVersion: SDKVersion;
|
|
6
5
|
export declare const SnackIdentityState: SnackState;
|
|
7
6
|
declare const defaultConfig: {
|
|
8
7
|
apiURL: string;
|
|
9
8
|
snackagerURL: string;
|
|
10
|
-
sdkVersion: "
|
|
9
|
+
sdkVersion: import("snack-content").SDKVersion;
|
|
11
10
|
webPlayerURL: string;
|
|
12
11
|
};
|
|
13
12
|
export default defaultConfig;
|
package/build/defaultConfig.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SnackIdentityState = exports.
|
|
3
|
+
exports.SnackIdentityState = exports.webPlayerURL = exports.snackagerURL = exports.apiURL = void 0;
|
|
4
|
+
var snack_content_1 = require("snack-content");
|
|
4
5
|
exports.apiURL = 'https://exp.host';
|
|
5
6
|
exports.snackagerURL = 'https://snackager.expo.io';
|
|
6
7
|
exports.webPlayerURL = 'https://snack-web-player.s3.us-west-1.amazonaws.com/v2/%%SDK_VERSION%%';
|
|
7
|
-
exports.sdkVersion = '42.0.0';
|
|
8
8
|
exports.SnackIdentityState = {
|
|
9
|
-
sdkVersion:
|
|
9
|
+
sdkVersion: snack_content_1.defaultSdkVersion,
|
|
10
10
|
name: '',
|
|
11
11
|
description: '',
|
|
12
12
|
dependencies: {},
|
|
@@ -23,7 +23,7 @@ exports.SnackIdentityState = {
|
|
|
23
23
|
var defaultConfig = {
|
|
24
24
|
apiURL: exports.apiURL,
|
|
25
25
|
snackagerURL: exports.snackagerURL,
|
|
26
|
-
sdkVersion:
|
|
26
|
+
sdkVersion: snack_content_1.defaultSdkVersion,
|
|
27
27
|
webPlayerURL: exports.webPlayerURL,
|
|
28
28
|
};
|
|
29
29
|
exports.default = defaultConfig;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaultConfig.js","sourceRoot":"","sources":["../src/defaultConfig.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"defaultConfig.js","sourceRoot":"","sources":["../src/defaultConfig.ts"],"names":[],"mappings":";;;AAAA,+CAAkD;AAIrC,QAAA,MAAM,GAAW,kBAAkB,CAAC;AACpC,QAAA,YAAY,GAAW,2BAA2B,CAAC;AACnD,QAAA,YAAY,GACvB,wEAAwE,CAAC;AAE9D,QAAA,kBAAkB,GAAe;IAC5C,UAAU,EAAE,iCAAiB;IAC7B,IAAI,EAAE,EAAE;IACR,WAAW,EAAE,EAAE;IACf,YAAY,EAAE,EAAE;IAChB,mBAAmB,EAAE,EAAE;IACvB,KAAK,EAAE,EAAE;IACT,gBAAgB,EAAE,EAAE;IACpB,UAAU,EAAE,EAAE;IACd,QAAQ,EAAE,KAAK;IACf,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,KAAK;IACb,GAAG,EAAE,EAAE;IACP,OAAO,EAAE,EAAE;CACZ,CAAC;AAEF,IAAM,aAAa,GAAG;IACpB,MAAM,gBAAA;IACN,YAAY,sBAAA;IACZ,UAAU,EAAE,iCAAiB;IAC7B,YAAY,sBAAA;CACb,CAAC;AAEF,kBAAe,aAAa,CAAC","sourcesContent":["import { defaultSdkVersion } from 'snack-content';\n\nimport { SnackState } from './types';\n\nexport const apiURL: string = 'https://exp.host';\nexport const snackagerURL: string = 'https://snackager.expo.io';\nexport const webPlayerURL: string =\n 'https://snack-web-player.s3.us-west-1.amazonaws.com/v2/%%SDK_VERSION%%';\n\nexport const SnackIdentityState: SnackState = {\n sdkVersion: defaultSdkVersion,\n name: '',\n description: '',\n dependencies: {},\n missingDependencies: {},\n files: {},\n connectedClients: {},\n transports: {},\n disabled: false,\n unsaved: false,\n online: false,\n url: '',\n channel: '',\n};\n\nconst defaultConfig = {\n apiURL,\n snackagerURL,\n sdkVersion: defaultSdkVersion,\n webPlayerURL,\n};\n\nexport default defaultConfig;\n"]}
|
package/build/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { SDKFeature, SDKVersion, SnackAssetFile, SnackCodeFile, SnackFile, SnackFiles, SnackDependency, SnackDependencyVersions, SnackDependencies, SnackMissingDependency, SnackMissingDependencies, isModulePreloaded, getPreloadedModules, isValidSemver, getSupportedSDKVersions, isFeatureSupported, standardizeDependencies, getDeprecatedModule } from 'snack-content';
|
|
1
2
|
import Snack, { SnackOptions, SnackSaveOptions, SnackStateListener, SnackLogListener } from './Session';
|
|
2
3
|
import defaultConfig from './defaultConfig';
|
|
3
|
-
import { isModulePreloaded, getPreloadedModules, isValidSemver, getSupportedSDKVersions, isFeatureSupported, standardizeDependencies, getDeprecatedModule } from './sdk';
|
|
4
4
|
export * from './transports';
|
|
5
5
|
export * from './types';
|
|
6
|
-
export type { SnackOptions, SnackSaveOptions, SnackStateListener, SnackLogListener };
|
|
6
|
+
export type { SnackOptions, SnackSaveOptions, SnackStateListener, SnackLogListener, SDKFeature, SDKVersion, SnackAssetFile, SnackCodeFile, SnackFile, SnackFiles, SnackDependency, SnackDependencyVersions, SnackDependencies, SnackMissingDependency, SnackMissingDependencies, };
|
|
7
7
|
export { isModulePreloaded, getPreloadedModules, isValidSemver, getSupportedSDKVersions, isFeatureSupported, standardizeDependencies, getDeprecatedModule, defaultConfig, Snack, };
|
package/build/index.js
CHANGED
|
@@ -14,18 +14,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
14
14
|
};
|
|
15
15
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
16
|
exports.Snack = exports.defaultConfig = exports.getDeprecatedModule = exports.standardizeDependencies = exports.isFeatureSupported = exports.getSupportedSDKVersions = exports.isValidSemver = exports.getPreloadedModules = exports.isModulePreloaded = void 0;
|
|
17
|
+
var snack_content_1 = require("snack-content");
|
|
18
|
+
Object.defineProperty(exports, "isModulePreloaded", { enumerable: true, get: function () { return snack_content_1.isModulePreloaded; } });
|
|
19
|
+
Object.defineProperty(exports, "getPreloadedModules", { enumerable: true, get: function () { return snack_content_1.getPreloadedModules; } });
|
|
20
|
+
Object.defineProperty(exports, "isValidSemver", { enumerable: true, get: function () { return snack_content_1.isValidSemver; } });
|
|
21
|
+
Object.defineProperty(exports, "getSupportedSDKVersions", { enumerable: true, get: function () { return snack_content_1.getSupportedSDKVersions; } });
|
|
22
|
+
Object.defineProperty(exports, "isFeatureSupported", { enumerable: true, get: function () { return snack_content_1.isFeatureSupported; } });
|
|
23
|
+
Object.defineProperty(exports, "standardizeDependencies", { enumerable: true, get: function () { return snack_content_1.standardizeDependencies; } });
|
|
24
|
+
Object.defineProperty(exports, "getDeprecatedModule", { enumerable: true, get: function () { return snack_content_1.getDeprecatedModule; } });
|
|
17
25
|
var Session_1 = __importDefault(require("./Session"));
|
|
18
26
|
exports.Snack = Session_1.default;
|
|
19
27
|
var defaultConfig_1 = __importDefault(require("./defaultConfig"));
|
|
20
28
|
exports.defaultConfig = defaultConfig_1.default;
|
|
21
|
-
var sdk_1 = require("./sdk");
|
|
22
|
-
Object.defineProperty(exports, "isModulePreloaded", { enumerable: true, get: function () { return sdk_1.isModulePreloaded; } });
|
|
23
|
-
Object.defineProperty(exports, "getPreloadedModules", { enumerable: true, get: function () { return sdk_1.getPreloadedModules; } });
|
|
24
|
-
Object.defineProperty(exports, "isValidSemver", { enumerable: true, get: function () { return sdk_1.isValidSemver; } });
|
|
25
|
-
Object.defineProperty(exports, "getSupportedSDKVersions", { enumerable: true, get: function () { return sdk_1.getSupportedSDKVersions; } });
|
|
26
|
-
Object.defineProperty(exports, "isFeatureSupported", { enumerable: true, get: function () { return sdk_1.isFeatureSupported; } });
|
|
27
|
-
Object.defineProperty(exports, "standardizeDependencies", { enumerable: true, get: function () { return sdk_1.standardizeDependencies; } });
|
|
28
|
-
Object.defineProperty(exports, "getDeprecatedModule", { enumerable: true, get: function () { return sdk_1.getDeprecatedModule; } });
|
|
29
29
|
__exportStar(require("./transports"), exports);
|
|
30
30
|
__exportStar(require("./types"), exports);
|
|
31
31
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+CAmBuB;AA8BrB,kGArCA,iCAAiB,OAqCA;AACjB,oGArCA,mCAAmB,OAqCA;AACnB,8FArCA,6BAAa,OAqCA;AACb,wGArCA,uCAAuB,OAqCA;AACvB,mGArCA,kCAAkB,OAqCA;AAClB,wGArCA,uCAAuB,OAqCA;AACvB,oGArCA,mCAAmB,OAqCA;AAlCrB,sDAKmB;AA+BjB,gBApCK,iBAAK,CAoCL;AA9BP,kEAA4C;AA6B1C,wBA7BK,uBAAa,CA6BL;AA3Bf,+CAA6B;AAC7B,0CAAwB","sourcesContent":["import {\n SDKFeature,\n SDKVersion,\n SnackAssetFile,\n SnackCodeFile,\n SnackFile,\n SnackFiles,\n SnackDependency,\n SnackDependencyVersions,\n SnackDependencies,\n SnackMissingDependency,\n SnackMissingDependencies,\n isModulePreloaded,\n getPreloadedModules,\n isValidSemver,\n getSupportedSDKVersions,\n isFeatureSupported,\n standardizeDependencies,\n getDeprecatedModule,\n} from 'snack-content';\n\nimport Snack, {\n SnackOptions,\n SnackSaveOptions,\n SnackStateListener,\n SnackLogListener,\n} from './Session';\nimport defaultConfig from './defaultConfig';\n\nexport * from './transports';\nexport * from './types';\nexport type {\n SnackOptions,\n SnackSaveOptions,\n SnackStateListener,\n SnackLogListener,\n SDKFeature,\n SDKVersion,\n SnackAssetFile,\n SnackCodeFile,\n SnackFile,\n SnackFiles,\n SnackDependency,\n SnackDependencyVersions,\n SnackDependencies,\n SnackMissingDependency,\n SnackMissingDependencies,\n};\nexport {\n isModulePreloaded,\n getPreloadedModules,\n isValidSemver,\n getSupportedSDKVersions,\n isFeatureSupported,\n standardizeDependencies,\n getDeprecatedModule,\n defaultConfig,\n Snack,\n};\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { SnackFiles, SDKVersion, SnackDependencies } from 'snack-content';
|
|
1
2
|
import { Logger } from '../Logger';
|
|
2
|
-
import { SnackFiles, SDKVersion, SnackDependencies } from '../types';
|
|
3
3
|
import { ProtocolCodeMessage } from './Protocol';
|
|
4
4
|
export declare type SnackCode = {
|
|
5
5
|
files: SnackFiles;
|
|
@@ -16,10 +16,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.getFileDiff = void 0;
|
|
18
18
|
var diff_1 = require("diff");
|
|
19
|
+
var snack_content_1 = require("snack-content");
|
|
19
20
|
var ua_parser_js_1 = require("ua-parser-js");
|
|
20
21
|
var FileUploader_1 = __importDefault(require("../FileUploader"));
|
|
21
22
|
var defaultConfig_1 = require("../defaultConfig");
|
|
22
|
-
var sdk_1 = require("../sdk");
|
|
23
23
|
var SnackIdentityCode = {
|
|
24
24
|
files: defaultConfig_1.SnackIdentityState.files,
|
|
25
25
|
dependencies: defaultConfig_1.SnackIdentityState.dependencies,
|
|
@@ -160,7 +160,7 @@ var CodeMessageBuilder = /** @class */ (function () {
|
|
|
160
160
|
var deps = {};
|
|
161
161
|
for (var name_1 in dependencies) {
|
|
162
162
|
var dep = dependencies[name_1];
|
|
163
|
-
if (dep.handle && !
|
|
163
|
+
if (dep.handle && !snack_content_1.isModulePreloaded(name_1, sdkVersion)) {
|
|
164
164
|
deps[name_1] = {
|
|
165
165
|
version: dep.version,
|
|
166
166
|
handle: dep.handle,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeMessageBuilder.js","sourceRoot":"","sources":["../../src/transports/CodeMessageBuilder.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,6BAAmC;AACnC,6CAAwC;AAExC,iEAAqE;AAErE,kDAAsD;AACtD,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H;SACF;QAED,IAAM,QAAQ,GAAQ;YACpB,cAAc,EAAE,IAAI,CAAC,UAAU;SAGhC,CAAC;QACF,IAAI,OAAO,SAAS,KAAK,WAAW,IAAI,SAAS,CAAC,SAAS,EAAE;YAC3D,IAAM,EAAE,GAAG,IAAI,uBAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,SAAS,EAAE,CAAC;YACzD,QAAQ,CAAC,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAChD,QAAQ,CAAC,iBAAiB,GAAG,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC;YACjD,QAAQ,CAAC,WAAW,GAAG,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC;YAClC,QAAQ,CAAC,YAAY,GAAG,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC;YACtC,QAAQ,CAAC,eAAe,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC;YAC1C,QAAQ,CAAC,aAAa,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC;YACxC,QAAQ,CAAC,UAAU,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;YACtC,QAAQ,CAAC,iBAAiB,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC;SACjD;QAED,OAAO;YACL,IAAI,EAAE,MAAM;YACZ,IAAI,MAAA;YACJ,KAAK,OAAA;YACL,YAAY,EAAE,IAAI;YAClB,QAAQ,UAAA;SACT,CAAC;IACJ,CAAC;IAeH,yBAAC;AAAD,CAAC,AAtLD,IAsLC","sourcesContent":["import { createPatch } from 'diff';\nimport { UAParser } from 'ua-parser-js';\n\nimport FileUploader, { FileUploaderCallback } from '../FileUploader';\nimport { Logger } from '../Logger';\nimport { SnackIdentityState } from '../defaultConfig';\nimport { isModulePreloaded } from '../sdk';\nimport { SnackFiles, SDKVersion, SnackCodeFile, SnackDependencies } from '../types';\nimport { ProtocolCodeMessage, ProtocolCodeMessageDependencies } from './Protocol';\n\nexport type SnackCode = {\n files: SnackFiles;\n dependencies: SnackDependencies;\n sdkVersion: SDKVersion;\n};\n\nconst SnackIdentityCode: SnackCode = {\n files: SnackIdentityState.files,\n dependencies: SnackIdentityState.dependencies,\n sdkVersion: SnackIdentityState.sdkVersion,\n};\n\nexport type CodeMessageBuilderCallback = (codeMessage: ProtocolCodeMessage, code: SnackCode) => any;\n\nexport function getFileDiff(oldCode: string, newCode: string): string {\n const patch = createPatch('code', oldCode, newCode, '', '', {\n context: 0,\n });\n if (patch) {\n return patch;\n } else {\n throw new Error('Error creating a file diff');\n }\n}\n\nconst PLACEHOLDER_URL =\n 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';\n\nexport default class CodeMessageBuilder {\n private callback: CodeMessageBuilderCallback;\n private code: SnackCode = SnackIdentityCode;\n private codeMessage?: ProtocolCodeMessage;\n private logger?: Logger;\n private codeUploader?: FileUploader;\n private maxDiffPlaceholder?: string;\n private placeholderURLs: { [path: string]: string } = {};\n private uploadedURLs: { [path: string]: string } = {};\n private verifyCodeMessageSize: (message: ProtocolCodeMessage) => boolean;\n\n constructor(options: {\n callback: CodeMessageBuilderCallback;\n verifyCodeMessageSize: (message: ProtocolCodeMessage) => boolean;\n apiURL?: string;\n logger?: Logger;\n maxDiffPlaceholder?: string;\n }) {\n this.logger = options.logger;\n this.callback = options.callback;\n this.verifyCodeMessageSize = options.verifyCodeMessageSize;\n this.maxDiffPlaceholder = options.maxDiffPlaceholder;\n this.codeUploader = options.apiURL\n ? new FileUploader({\n apiURL: options.apiURL,\n logger: options.logger,\n callback: this.onFileUploaded,\n })\n : undefined;\n }\n\n setCode(code: SnackCode) {\n if (code === this.code) {\n return;\n }\n\n const prevCode = this.code;\n const { files } = code;\n this.code = code;\n\n // Cancel any uploads for files that were removed or changed\n for (const path in prevCode.files) {\n if (prevCode.files[path].contents !== files[path]?.contents) {\n delete this.placeholderURLs[path];\n delete this.uploadedURLs[path];\n this.codeUploader?.remove(path, prevCode.files[path]);\n }\n }\n\n // Generate code message\n const codeMessage = this.createCodeMessage(code, this.codeMessage, prevCode);\n this.codeMessage = codeMessage;\n\n // When the code message size is valid and there are no pending\n // uploads, then fire the callback immediately\n if (this.verifyCodeMessageSize(codeMessage)) {\n if (!Object.keys(this.placeholderURLs).length) {\n this.callback(codeMessage, code);\n }\n return;\n }\n\n // Upload files if the code message exceeds the limit\n // Sort code files by size\n if (this.codeUploader) {\n const paths = Object.keys(files)\n .filter((path) => files[path].type === 'CODE')\n // @ts-ignore\n .sort((a, b) => files[b].contents.length - files[a].contents.length);\n\n // Upload the largest file\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n if (!this.uploadedURLs[path] && !this.placeholderURLs[path]) {\n const file: SnackCodeFile = files[path] as any;\n this.placeholderURLs[path] = PLACEHOLDER_URL;\n // this.logger?.comm('Uploading file', path, `, ${file.contents.length} bytes ...`);\n this.codeUploader.add(path, file);\n codeMessage.diff[path] = '';\n codeMessage.s3url[path] = this.placeholderURLs[path];\n if (this.verifyCodeMessageSize(codeMessage)) {\n // Message size is now valid. When the upload completes, it\n // will try to call the callback\n return;\n }\n }\n }\n }\n\n // Message is still too large\n this.logger?.error('Message size is too large');\n }\n\n private createCodeMessage(\n code: SnackCode,\n prevCodeMessage?: ProtocolCodeMessage,\n prevCode?: SnackCode\n ): ProtocolCodeMessage {\n const { files, dependencies, sdkVersion } = code;\n\n const diff: any = { ...files };\n const s3url: any = {};\n for (const path in files) {\n const file = files[path];\n if (this.uploadedURLs[path] || this.placeholderURLs[path]) {\n diff[path] = '';\n s3url[path] = this.uploadedURLs[path] || this.placeholderURLs[path];\n } else {\n if (file.type === 'CODE') {\n if (\n prevCodeMessage?.diff[path] &&\n prevCode?.files[path].contents === code.files[path].contents\n ) {\n diff[path] = prevCodeMessage.diff[path];\n } else {\n if (this.maxDiffPlaceholder && file.contents.length >= this.maxDiffPlaceholder.length) {\n diff[path] = this.maxDiffPlaceholder;\n } else {\n diff[path] = getFileDiff('', file.contents);\n }\n }\n } else {\n diff[path] = '';\n }\n if (file.type === 'ASSET' && typeof file.contents === 'string') {\n s3url[path] = file.contents;\n }\n }\n }\n\n const deps: ProtocolCodeMessageDependencies = {};\n for (const name in dependencies) {\n const dep = dependencies[name];\n if (dep.handle && !isModulePreloaded(name, sdkVersion)) {\n deps[name] = {\n version: dep.version,\n handle: dep.handle,\n // Resolved has been replaced by handle. It is still needed for pre SDK 37 runtimes\n resolved: dep.handle.substring(dep.handle.lastIndexOf('@') + 1),\n };\n }\n }\n\n const metadata: any = {\n expoSDKVersion: code.sdkVersion,\n // TODO: restore sdk version field\n // webSnackSDKVersion: require('../../package.json').version,\n };\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const ua = new UAParser(navigator.userAgent).getResult();\n metadata.webHostName = window.location.hostname;\n metadata.webOSArchitecture = ua.cpu.architecture;\n metadata.webOSFamily = ua.os.name;\n metadata.webOSVersion = ua.os.version;\n metadata.webLayoutEngine = ua.engine.name;\n metadata.webDeviceType = ua.device.type;\n metadata.webBrowser = ua.browser.name;\n metadata.webBrowserVersion = ua.browser.version;\n }\n\n return {\n type: 'CODE',\n diff,\n s3url,\n dependencies: deps,\n metadata,\n };\n }\n\n private onFileUploaded: FileUploaderCallback = (request, resultURL, _error) => {\n const { path } = request;\n delete this.placeholderURLs[path];\n if (resultURL) {\n this.uploadedURLs[path] = resultURL;\n if (!Object.keys(this.placeholderURLs).length) {\n const codeMessage = this.createCodeMessage(this.code, this.codeMessage, this.code);\n if (this.verifyCodeMessageSize(codeMessage)) {\n this.callback(codeMessage, this.code);\n }\n }\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CodeMessageBuilder.js","sourceRoot":"","sources":["../../src/transports/CodeMessageBuilder.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,6BAAmC;AACnC,+CAMuB;AACvB,6CAAw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CAAC;iBAChE,CAAC;aACH;SACF;QAED,IAAM,QAAQ,GAAQ;YACpB,cAAc,EAAE,IAAI,CAAC,UAAU;SAGhC,CAAC;QACF,IAAI,OAAO,SAAS,KAAK,WAAW,IAAI,SAAS,CAAC,SAAS,EAAE;YAC3D,IAAM,EAAE,GAAG,IAAI,uBAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,SAAS,EAAE,CAAC;YACzD,QAAQ,CAAC,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAChD,QAAQ,CAAC,iBAAiB,GAAG,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC;YACjD,QAAQ,CAAC,WAAW,GAAG,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC;YAClC,QAAQ,CAAC,YAAY,GAAG,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC;YACtC,QAAQ,CAAC,eAAe,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC;YAC1C,QAAQ,CAAC,aAAa,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC;YACxC,QAAQ,CAAC,UAAU,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;YACtC,QAAQ,CAAC,iBAAiB,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC;SACjD;QAED,OAAO;YACL,IAAI,EAAE,MAAM;YACZ,IAAI,MAAA;YACJ,KAAK,OAAA;YACL,YAAY,EAAE,IAAI;YAClB,QAAQ,UAAA;SACT,CAAC;IACJ,CAAC;IAeH,yBAAC;AAAD,CAAC,AAtLD,IAsLC","sourcesContent":["import { createPatch } from 'diff';\nimport {\n SnackFiles,\n SDKVersion,\n SnackCodeFile,\n SnackDependencies,\n isModulePreloaded,\n} from 'snack-content';\nimport { UAParser } from 'ua-parser-js';\n\nimport FileUploader, { FileUploaderCallback } from '../FileUploader';\nimport { Logger } from '../Logger';\nimport { SnackIdentityState } from '../defaultConfig';\nimport { ProtocolCodeMessage, ProtocolCodeMessageDependencies } from './Protocol';\n\nexport type SnackCode = {\n files: SnackFiles;\n dependencies: SnackDependencies;\n sdkVersion: SDKVersion;\n};\n\nconst SnackIdentityCode: SnackCode = {\n files: SnackIdentityState.files,\n dependencies: SnackIdentityState.dependencies,\n sdkVersion: SnackIdentityState.sdkVersion,\n};\n\nexport type CodeMessageBuilderCallback = (codeMessage: ProtocolCodeMessage, code: SnackCode) => any;\n\nexport function getFileDiff(oldCode: string, newCode: string): string {\n const patch = createPatch('code', oldCode, newCode, '', '', {\n context: 0,\n });\n if (patch) {\n return patch;\n } else {\n throw new Error('Error creating a file diff');\n }\n}\n\nconst PLACEHOLDER_URL =\n 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';\n\nexport default class CodeMessageBuilder {\n private callback: CodeMessageBuilderCallback;\n private code: SnackCode = SnackIdentityCode;\n private codeMessage?: ProtocolCodeMessage;\n private logger?: Logger;\n private codeUploader?: FileUploader;\n private maxDiffPlaceholder?: string;\n private placeholderURLs: { [path: string]: string } = {};\n private uploadedURLs: { [path: string]: string } = {};\n private verifyCodeMessageSize: (message: ProtocolCodeMessage) => boolean;\n\n constructor(options: {\n callback: CodeMessageBuilderCallback;\n verifyCodeMessageSize: (message: ProtocolCodeMessage) => boolean;\n apiURL?: string;\n logger?: Logger;\n maxDiffPlaceholder?: string;\n }) {\n this.logger = options.logger;\n this.callback = options.callback;\n this.verifyCodeMessageSize = options.verifyCodeMessageSize;\n this.maxDiffPlaceholder = options.maxDiffPlaceholder;\n this.codeUploader = options.apiURL\n ? new FileUploader({\n apiURL: options.apiURL,\n logger: options.logger,\n callback: this.onFileUploaded,\n })\n : undefined;\n }\n\n setCode(code: SnackCode) {\n if (code === this.code) {\n return;\n }\n\n const prevCode = this.code;\n const { files } = code;\n this.code = code;\n\n // Cancel any uploads for files that were removed or changed\n for (const path in prevCode.files) {\n if (prevCode.files[path].contents !== files[path]?.contents) {\n delete this.placeholderURLs[path];\n delete this.uploadedURLs[path];\n this.codeUploader?.remove(path, prevCode.files[path]);\n }\n }\n\n // Generate code message\n const codeMessage = this.createCodeMessage(code, this.codeMessage, prevCode);\n this.codeMessage = codeMessage;\n\n // When the code message size is valid and there are no pending\n // uploads, then fire the callback immediately\n if (this.verifyCodeMessageSize(codeMessage)) {\n if (!Object.keys(this.placeholderURLs).length) {\n this.callback(codeMessage, code);\n }\n return;\n }\n\n // Upload files if the code message exceeds the limit\n // Sort code files by size\n if (this.codeUploader) {\n const paths = Object.keys(files)\n .filter((path) => files[path].type === 'CODE')\n // @ts-ignore\n .sort((a, b) => files[b].contents.length - files[a].contents.length);\n\n // Upload the largest file\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n if (!this.uploadedURLs[path] && !this.placeholderURLs[path]) {\n const file: SnackCodeFile = files[path] as any;\n this.placeholderURLs[path] = PLACEHOLDER_URL;\n // this.logger?.comm('Uploading file', path, `, ${file.contents.length} bytes ...`);\n this.codeUploader.add(path, file);\n codeMessage.diff[path] = '';\n codeMessage.s3url[path] = this.placeholderURLs[path];\n if (this.verifyCodeMessageSize(codeMessage)) {\n // Message size is now valid. When the upload completes, it\n // will try to call the callback\n return;\n }\n }\n }\n }\n\n // Message is still too large\n this.logger?.error('Message size is too large');\n }\n\n private createCodeMessage(\n code: SnackCode,\n prevCodeMessage?: ProtocolCodeMessage,\n prevCode?: SnackCode\n ): ProtocolCodeMessage {\n const { files, dependencies, sdkVersion } = code;\n\n const diff: any = { ...files };\n const s3url: any = {};\n for (const path in files) {\n const file = files[path];\n if (this.uploadedURLs[path] || this.placeholderURLs[path]) {\n diff[path] = '';\n s3url[path] = this.uploadedURLs[path] || this.placeholderURLs[path];\n } else {\n if (file.type === 'CODE') {\n if (\n prevCodeMessage?.diff[path] &&\n prevCode?.files[path].contents === code.files[path].contents\n ) {\n diff[path] = prevCodeMessage.diff[path];\n } else {\n if (this.maxDiffPlaceholder && file.contents.length >= this.maxDiffPlaceholder.length) {\n diff[path] = this.maxDiffPlaceholder;\n } else {\n diff[path] = getFileDiff('', file.contents);\n }\n }\n } else {\n diff[path] = '';\n }\n if (file.type === 'ASSET' && typeof file.contents === 'string') {\n s3url[path] = file.contents;\n }\n }\n }\n\n const deps: ProtocolCodeMessageDependencies = {};\n for (const name in dependencies) {\n const dep = dependencies[name];\n if (dep.handle && !isModulePreloaded(name, sdkVersion)) {\n deps[name] = {\n version: dep.version,\n handle: dep.handle,\n // Resolved has been replaced by handle. It is still needed for pre SDK 37 runtimes\n resolved: dep.handle.substring(dep.handle.lastIndexOf('@') + 1),\n };\n }\n }\n\n const metadata: any = {\n expoSDKVersion: code.sdkVersion,\n // TODO: restore sdk version field\n // webSnackSDKVersion: require('../../package.json').version,\n };\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const ua = new UAParser(navigator.userAgent).getResult();\n metadata.webHostName = window.location.hostname;\n metadata.webOSArchitecture = ua.cpu.architecture;\n metadata.webOSFamily = ua.os.name;\n metadata.webOSVersion = ua.os.version;\n metadata.webLayoutEngine = ua.engine.name;\n metadata.webDeviceType = ua.device.type;\n metadata.webBrowser = ua.browser.name;\n metadata.webBrowserVersion = ua.browser.version;\n }\n\n return {\n type: 'CODE',\n diff,\n s3url,\n dependencies: deps,\n metadata,\n };\n }\n\n private onFileUploaded: FileUploaderCallback = (request, resultURL, _error) => {\n const { path } = request;\n delete this.placeholderURLs[path];\n if (resultURL) {\n this.uploadedURLs[path] = resultURL;\n if (!Object.keys(this.placeholderURLs).length) {\n const codeMessage = this.createCodeMessage(this.code, this.codeMessage, this.code);\n if (this.verifyCodeMessageSize(codeMessage)) {\n this.callback(codeMessage, this.code);\n }\n }\n }\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Protocol.js","sourceRoot":"","sources":["../../src/transports/Protocol.ts"],"names":[],"mappings":"","sourcesContent":["import { SDKVersion } from '
|
|
1
|
+
{"version":3,"file":"Protocol.js","sourceRoot":"","sources":["../../src/transports/Protocol.ts"],"names":[],"mappings":"","sourcesContent":["import { SDKVersion } from 'snack-content';\n\nexport type Device = {\n name: string;\n id: string;\n platform: string;\n};\n\nexport type ProtocolConsoleMessage = {\n type: 'CONSOLE';\n device: Device;\n method: 'log' | 'error' | 'warn';\n payload: any[];\n};\n\nexport type ProtocolErrorMessage = {\n type: 'ERROR';\n error: string; // e.g. `{message: \"my error\", stack: \"...\"}`\n device: Device;\n};\n\nexport type ProtocolResendCodeMessage = {\n type: 'RESEND_CODE';\n device: Device;\n};\n\nexport type ProtocolCodeMessageDependencies = {\n [name: string]: {\n version: string; // original version\n resolved: string; // resolved version\n handle: string; // snackager handle\n };\n};\n\nexport type ProtocolCodeMessage = {\n type: 'CODE';\n diff: { [path: string]: string };\n s3url: { [path: string]: string };\n dependencies: ProtocolCodeMessageDependencies;\n metadata: {\n expoSDKVersion: SDKVersion;\n webSnackSDKVersion: string;\n webHostname?: string; // window.location.hostname,\n webOSArchitecture?: string; // os.architecture,\n webOSFamily?: string; // os.family,\n webOSVersion?: string; // os.version,\n webLayoutEngine?: string; // platformInfo.layout,\n webDeviceType?: string; // platformInfo.product,\n webBrowser?: string; // platformInfo.name,\n webBrowserVersion?: string; // platformInfo.version,\n webDescription?: string; // platformInfo.description,\n };\n};\n\nexport type ProtocolReloadMessage = {\n type: 'RELOAD_SNACK';\n};\n\nexport type ProtocolRequestStatusMessage = {\n type: 'REQUEST_STATUS';\n};\n\nexport type ProtocolStatusMessage = {\n type: 'STATUS_REPORT';\n previewLocation: string;\n status: 'FAILURE' | 'SUCCESS';\n};\n\nexport type ProtocolOutgoingMessage =\n | ProtocolCodeMessage\n | ProtocolReloadMessage\n | ProtocolRequestStatusMessage;\n\nexport type ProtocolIncomingMessage =\n | ProtocolConsoleMessage\n | ProtocolErrorMessage\n | ProtocolResendCodeMessage\n | ProtocolStatusMessage;\n"]}
|
|
@@ -163,13 +163,18 @@ var Transport = /** @class */ (function () {
|
|
|
163
163
|
Transport.prototype.start = function () {
|
|
164
164
|
var _a;
|
|
165
165
|
this.stop();
|
|
166
|
+
if (!this.pubNubClientId) {
|
|
167
|
+
// Keep track of the client ID per transport instance.
|
|
168
|
+
// See: https://support.pubnub.com/hc/en-us/articles/360051496532-How-do-I-set-the-UUID-
|
|
169
|
+
this.pubNubClientId = pubnub_1.default.generateUUID();
|
|
170
|
+
}
|
|
166
171
|
if (this.channel) {
|
|
167
172
|
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.comm('Starting channel...', this.channel, this.logSuffix);
|
|
168
173
|
this.pubNub = new pubnub_1.default({
|
|
169
174
|
publishKey: 'pub-c-2a7fd67b-333d-40db-ad2d-3255f8835f70',
|
|
170
175
|
subscribeKey: 'sub-c-0b655000-d784-11e6-b950-02ee2ddab7fe',
|
|
176
|
+
uuid: this.pubNubClientId,
|
|
171
177
|
ssl: true,
|
|
172
|
-
// uuid: TODO
|
|
173
178
|
presenceTimeout: 600,
|
|
174
179
|
heartbeatInterval: 60,
|
|
175
180
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Transport.js","sourceRoot":"","sources":["../../src/transports/Transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kDAA4B;AAE5B,oCAAiD;AACjD,4EAAsF;AAStF,SAAgB,yBAAyB,CAAC,OAAe,EAAE,WAAgC;IACzF,+GAA+G;IAC/G,OAAO,CACL,kBAAkB,CAChB,OAAO;QACL,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,OAAO,CACjC,WAAW,EACX,UAAC,CAAC,IAAK,OAAA,MAAI,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAI,EAAhD,CAAgD,CACxD,CACJ,CAAC,MAAM,GAAG,GAAG,CACf,CAAC;AACJ,CAAC;AAXD,8DA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ilder, { CodeMessageBuilderCallback } from './CodeMessageBuilder';\nimport { ProtocolOutgoingMessage, ProtocolIncomingMessage, ProtocolCodeMessage } from './Protocol';\nimport {\n SnackTransport,\n SnackTransportListener,\n SnackTransportMessage,\n SnackTransportOptions,\n} from './types';\n\nexport function calcPubNubCodeMessageSize(channel: string, codeMessage: ProtocolCodeMessage) {\n // https://support.pubnub.com/hc/en-us/articles/360051495932-Calculating-message-payload-size-before-publishing\n return (\n encodeURIComponent(\n channel +\n JSON.stringify(codeMessage).replace(\n /[!~*'()]/g,\n (x) => `%${x.charCodeAt(0).toString(16).toUpperCase()}`\n )\n ).length + 200\n );\n}\n\nexport default class Transport implements SnackTransport {\n private readonly channel: string;\n private readonly logger?: Logger;\n private callback?: SnackTransportListener;\n private pubNub?: PubNub;\n private codeMessageBuilder: CodeMessageBuilder;\n private codeMessage?: ProtocolCodeMessage;\n private connectionsCount: number = 0;\n private readonly logSuffix: string;\n\n constructor(options: SnackTransportOptions) {\n const { apiURL, channel, verbose } = options;\n this.channel = channel ?? '';\n this.logger = verbose ? createLogger(true) : undefined;\n this.logSuffix = options.name ? ` (${options.name})` : '';\n\n if (channel) {\n this.codeMessageBuilder = new CodeMessageBuilder({\n verifyCodeMessageSize: this.onPubNubVerifyCodeMessageSize,\n callback: this.onCodeMessageReady,\n apiURL,\n logger: this.logger,\n maxDiffPlaceholder: 'X'.repeat(32768),\n });\n } else {\n this.codeMessageBuilder = new CodeMessageBuilder({\n verifyCodeMessageSize: () => true,\n callback: this.onCodeMessageReady,\n logger: this.logger,\n });\n }\n }\n\n addEventListener(_type: 'message', callback: SnackTransportListener) {\n this.callback = callback;\n }\n\n removeEventListener(_type: 'message', _callback: SnackTransportListener) {\n this.callback = undefined;\n }\n\n postMessage(message: SnackTransportMessage) {\n switch (message.type) {\n case 'start':\n this.start();\n break;\n case 'stop':\n this.stop();\n break;\n case 'update_code':\n this.codeMessageBuilder.setCode(message.data);\n break;\n case 'protocol_message':\n this.publish(message.data);\n break;\n case 'synthetic_event':\n this.onSyntheticEvent(message.data);\n break;\n }\n }\n\n private start() {\n this.stop();\n\n if (this.channel) {\n this.logger?.comm('Starting channel...', this.channel, this.logSuffix);\n this.pubNub = new PubNub({\n publishKey: 'pub-c-2a7fd67b-333d-40db-ad2d-3255f8835f70',\n subscribeKey: 'sub-c-0b655000-d784-11e6-b950-02ee2ddab7fe',\n ssl: true,\n // uuid: TODO\n presenceTimeout: 600,\n heartbeatInterval: 60,\n });\n\n this.pubNub.addListener({\n presence: this.onPubNubPresence,\n message: this.onPubNubMessage,\n status: this.onPubNubStatus,\n });\n\n this.pubNub.subscribe({\n channels: [this.channel],\n withPresence: true,\n });\n }\n }\n\n private stop() {\n if (this.pubNub) {\n this.logger?.comm('Stopping...', this.logSuffix);\n this.pubNub.removeListener({\n presence: this.onPubNubPresence,\n message: this.onPubNubMessage,\n status: this.onPubNubStatus,\n });\n\n this.pubNub.unsubscribe({\n channels: [this.channel],\n });\n\n this.pubNub.stop();\n this.pubNub = undefined;\n }\n }\n\n private onProtocolMessage(connectionId: string, message: ProtocolIncomingMessage) {\n if (message.type === 'RESEND_CODE') {\n if (this.codeMessage) {\n this.logger?.comm('Resending code...', this.logSuffix);\n this.publish(this.codeMessage);\n }\n } else {\n this.callback?.({\n type: 'protocol_message',\n connectionId,\n data: message,\n });\n }\n }\n\n private async publish(message: ProtocolOutgoingMessage) {\n if (!this.connectionsCount) {\n return;\n }\n if (this.pubNub) {\n try {\n await this.pubNub.publish({\n channel: this.channel,\n message,\n });\n } catch (e) {\n this.logger?.error('Failed to publish message', message.type, e, this.logSuffix);\n }\n } else {\n this.callback?.({\n type: 'synthetic_event',\n data: message,\n });\n }\n this.callback?.({\n type: 'send_message',\n data: message,\n });\n }\n\n private onPubNubPresence = (event: PubNub.PresenceEvent) => {\n switch (event.action) {\n case 'join':\n try {\n const device = JSON.parse(event.uuid);\n this.connectionsCount++;\n this.callback?.({\n type: 'connect',\n connectionId: event.uuid,\n data: device,\n });\n if (this.codeMessage) {\n this.logger?.comm('Sending code...', this.logSuffix);\n this.publish(this.codeMessage);\n }\n } catch (e) {\n // Wasn't from the device\n }\n break;\n case 'timeout':\n case 'leave':\n this.connectionsCount = Math.max(this.connectionsCount - 1, 0);\n this.callback?.({\n type: 'disconnect',\n connectionId: event.uuid,\n data: {\n timedout: event.action === 'timeout',\n },\n });\n break;\n }\n };\n\n private onPubNubMessage = (event: PubNub.MessageEvent) => {\n const message: ProtocolIncomingMessage = event.message;\n this.onProtocolMessage(event.publisher, message);\n };\n\n private onPubNubStatus = (_event: PubNub.StatusEvent) => {\n // TODO: Do something here?\n };\n\n private onPubNubVerifyCodeMessageSize = (codeMessage: ProtocolCodeMessage) => {\n // Calculate unencoded size (quickly) and if that exceeds the limit\n // then don't bother calculating the exact size (which is more expensive)\n let approxSize = 0;\n for (const path in codeMessage.diff) {\n approxSize += path.length + codeMessage.diff[path].length;\n }\n if (approxSize >= 32768) {\n return false;\n }\n\n // Calculate exact size and check whether it exceeds the limit\n const size = calcPubNubCodeMessageSize(this.channel, codeMessage);\n return size < 32768;\n };\n\n private onSyntheticEvent(data: any) {\n if (typeof data !== 'string') {\n return;\n }\n\n try {\n const message = JSON.parse(data);\n switch (message.type) {\n case 'CONNECT':\n this.connectionsCount++;\n this.callback?.({\n type: 'connect',\n connectionId: JSON.stringify(message.device),\n data: message.device,\n });\n break;\n case 'DISCONNECT':\n this.connectionsCount = Math.max(this.connectionsCount - 1, 0);\n this.callback?.({\n type: 'disconnect',\n connectionId: JSON.stringify(message.device),\n data: {\n timedout: false,\n },\n });\n break;\n case 'MESSAGE':\n this.onProtocolMessage(JSON.stringify(message.message.device), message.message);\n break;\n }\n } catch (e) {\n this.logger?.error('Failed to parse postMessage', e, data, this.logSuffix);\n }\n }\n\n private onCodeMessageReady: CodeMessageBuilderCallback = (codeMessage) => {\n this.codeMessage = codeMessage;\n this.logger?.comm('Sending code...', this.logSuffix);\n this.publish(codeMessage);\n };\n}\n"]}
|
|
1
|
+
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AgB,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;oBAC/D,MAAA,IAAI,CAAC,QAAQ,+CAAb,IAAI,EAAY;wBACd,IAAI,EAAE,YAAY;wBAClB,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC;wBAC5C,IAAI,EAAE;4BACJ,QAAQ,EAAE,KAAK;yBAChB;qBACF,EAAE;oBACH,MAAM;gBACR,KAAK,SAAS;oBACZ,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;oBAChF,MAAM;aACT;SACF;QAAC,OAAO,CAAC,EAAE;YACV,MAAA,IAAI,CAAC,MAAM,0CAAE,KAAK,CAAC,6BAA6B,EAAE,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE;SAC5E;IACH,CAAC;IAOH,gBAAC;AAAD,CAAC,AA3PD,IA2PC","sourcesContent":["import PubNub from 'pubnub';\n\nimport { createLogger, Logger } from '../Logger';\nimport CodeMessageBuilder, { CodeMessageBuilderCallback } from './CodeMessageBuilder';\nimport { ProtocolOutgoingMessage, ProtocolIncomingMessage, ProtocolCodeMessage } from './Protocol';\nimport {\n SnackTransport,\n SnackTransportListener,\n SnackTransportMessage,\n SnackTransportOptions,\n} from './types';\n\nexport function calcPubNubCodeMessageSize(channel: string, codeMessage: ProtocolCodeMessage) {\n // https://support.pubnub.com/hc/en-us/articles/360051495932-Calculating-message-payload-size-before-publishing\n return (\n encodeURIComponent(\n channel +\n JSON.stringify(codeMessage).replace(\n /[!~*'()]/g,\n (x) => `%${x.charCodeAt(0).toString(16).toUpperCase()}`\n )\n ).length + 200\n );\n}\n\nexport default class Transport implements SnackTransport {\n private readonly channel: string;\n private readonly logger?: Logger;\n private callback?: SnackTransportListener;\n private pubNub?: PubNub;\n private pubNubClientId?: string;\n private codeMessageBuilder: CodeMessageBuilder;\n private codeMessage?: ProtocolCodeMessage;\n private connectionsCount: number = 0;\n private readonly logSuffix: string;\n\n constructor(options: SnackTransportOptions) {\n const { apiURL, channel, verbose } = options;\n this.channel = channel ?? '';\n this.logger = verbose ? createLogger(true) : undefined;\n this.logSuffix = options.name ? ` (${options.name})` : '';\n\n if (channel) {\n this.codeMessageBuilder = new CodeMessageBuilder({\n verifyCodeMessageSize: this.onPubNubVerifyCodeMessageSize,\n callback: this.onCodeMessageReady,\n apiURL,\n logger: this.logger,\n maxDiffPlaceholder: 'X'.repeat(32768),\n });\n } else {\n this.codeMessageBuilder = new CodeMessageBuilder({\n verifyCodeMessageSize: () => true,\n callback: this.onCodeMessageReady,\n logger: this.logger,\n });\n }\n }\n\n addEventListener(_type: 'message', callback: SnackTransportListener) {\n this.callback = callback;\n }\n\n removeEventListener(_type: 'message', _callback: SnackTransportListener) {\n this.callback = undefined;\n }\n\n postMessage(message: SnackTransportMessage) {\n switch (message.type) {\n case 'start':\n this.start();\n break;\n case 'stop':\n this.stop();\n break;\n case 'update_code':\n this.codeMessageBuilder.setCode(message.data);\n break;\n case 'protocol_message':\n this.publish(message.data);\n break;\n case 'synthetic_event':\n this.onSyntheticEvent(message.data);\n break;\n }\n }\n\n private start() {\n this.stop();\n\n if (!this.pubNubClientId) {\n // Keep track of the client ID per transport instance.\n // See: https://support.pubnub.com/hc/en-us/articles/360051496532-How-do-I-set-the-UUID-\n this.pubNubClientId = PubNub.generateUUID();\n }\n\n if (this.channel) {\n this.logger?.comm('Starting channel...', this.channel, this.logSuffix);\n this.pubNub = new PubNub({\n publishKey: 'pub-c-2a7fd67b-333d-40db-ad2d-3255f8835f70',\n subscribeKey: 'sub-c-0b655000-d784-11e6-b950-02ee2ddab7fe',\n uuid: this.pubNubClientId,\n ssl: true,\n presenceTimeout: 600,\n heartbeatInterval: 60,\n });\n\n this.pubNub.addListener({\n presence: this.onPubNubPresence,\n message: this.onPubNubMessage,\n status: this.onPubNubStatus,\n });\n\n this.pubNub.subscribe({\n channels: [this.channel],\n withPresence: true,\n });\n }\n }\n\n private stop() {\n if (this.pubNub) {\n this.logger?.comm('Stopping...', this.logSuffix);\n this.pubNub.removeListener({\n presence: this.onPubNubPresence,\n message: this.onPubNubMessage,\n status: this.onPubNubStatus,\n });\n\n this.pubNub.unsubscribe({\n channels: [this.channel],\n });\n\n this.pubNub.stop();\n this.pubNub = undefined;\n }\n }\n\n private onProtocolMessage(connectionId: string, message: ProtocolIncomingMessage) {\n if (message.type === 'RESEND_CODE') {\n if (this.codeMessage) {\n this.logger?.comm('Resending code...', this.logSuffix);\n this.publish(this.codeMessage);\n }\n } else {\n this.callback?.({\n type: 'protocol_message',\n connectionId,\n data: message,\n });\n }\n }\n\n private async publish(message: ProtocolOutgoingMessage) {\n if (!this.connectionsCount) {\n return;\n }\n if (this.pubNub) {\n try {\n await this.pubNub.publish({\n channel: this.channel,\n message,\n });\n } catch (e) {\n this.logger?.error('Failed to publish message', message.type, e, this.logSuffix);\n }\n } else {\n this.callback?.({\n type: 'synthetic_event',\n data: message,\n });\n }\n this.callback?.({\n type: 'send_message',\n data: message,\n });\n }\n\n private onPubNubPresence = (event: PubNub.PresenceEvent) => {\n switch (event.action) {\n case 'join':\n try {\n const device = JSON.parse(event.uuid);\n this.connectionsCount++;\n this.callback?.({\n type: 'connect',\n connectionId: event.uuid,\n data: device,\n });\n if (this.codeMessage) {\n this.logger?.comm('Sending code...', this.logSuffix);\n this.publish(this.codeMessage);\n }\n } catch (e) {\n // Wasn't from the device\n }\n break;\n case 'timeout':\n case 'leave':\n this.connectionsCount = Math.max(this.connectionsCount - 1, 0);\n this.callback?.({\n type: 'disconnect',\n connectionId: event.uuid,\n data: {\n timedout: event.action === 'timeout',\n },\n });\n break;\n }\n };\n\n private onPubNubMessage = (event: PubNub.MessageEvent) => {\n const message: ProtocolIncomingMessage = event.message;\n this.onProtocolMessage(event.publisher, message);\n };\n\n private onPubNubStatus = (_event: PubNub.StatusEvent) => {\n // TODO: Do something here?\n };\n\n private onPubNubVerifyCodeMessageSize = (codeMessage: ProtocolCodeMessage) => {\n // Calculate unencoded size (quickly) and if that exceeds the limit\n // then don't bother calculating the exact size (which is more expensive)\n let approxSize = 0;\n for (const path in codeMessage.diff) {\n approxSize += path.length + codeMessage.diff[path].length;\n }\n if (approxSize >= 32768) {\n return false;\n }\n\n // Calculate exact size and check whether it exceeds the limit\n const size = calcPubNubCodeMessageSize(this.channel, codeMessage);\n return size < 32768;\n };\n\n private onSyntheticEvent(data: any) {\n if (typeof data !== 'string') {\n return;\n }\n\n try {\n const message = JSON.parse(data);\n switch (message.type) {\n case 'CONNECT':\n this.connectionsCount++;\n this.callback?.({\n type: 'connect',\n connectionId: JSON.stringify(message.device),\n data: message.device,\n });\n break;\n case 'DISCONNECT':\n this.connectionsCount = Math.max(this.connectionsCount - 1, 0);\n this.callback?.({\n type: 'disconnect',\n connectionId: JSON.stringify(message.device),\n data: {\n timedout: false,\n },\n });\n break;\n case 'MESSAGE':\n this.onProtocolMessage(JSON.stringify(message.message.device), message.message);\n break;\n }\n } catch (e) {\n this.logger?.error('Failed to parse postMessage', e, data, this.logSuffix);\n }\n }\n\n private onCodeMessageReady: CodeMessageBuilderCallback = (codeMessage) => {\n this.codeMessage = codeMessage;\n this.logger?.comm('Sending code...', this.logSuffix);\n this.publish(codeMessage);\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SnackFiles, SnackDependencies, SDKVersion } from '
|
|
1
|
+
import { SnackFiles, SnackDependencies, SDKVersion } from 'snack-content';
|
|
2
2
|
import { ProtocolOutgoingMessage, ProtocolIncomingMessage } from './Protocol';
|
|
3
3
|
export declare type SnackTransportStartMessage = {
|
|
4
4
|
type: 'start';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/transports/types.ts"],"names":[],"mappings":"","sourcesContent":["import { SnackFiles, SnackDependencies, SDKVersion } from '
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/transports/types.ts"],"names":[],"mappings":"","sourcesContent":["import { SnackFiles, SnackDependencies, SDKVersion } from 'snack-content';\n\nimport { ProtocolOutgoingMessage, ProtocolIncomingMessage } from './Protocol';\n\nexport type SnackTransportStartMessage = {\n type: 'start';\n};\n\nexport type SnackTransportStopMessage = {\n type: 'stop';\n};\n\nexport type SnackTransportUpdateCodeMessage = {\n type: 'update_code';\n data: {\n files: SnackFiles;\n dependencies: SnackDependencies;\n sdkVersion: SDKVersion;\n };\n};\n\nexport type SnackTransportProtocolMessage = {\n type: 'protocol_message';\n data: ProtocolOutgoingMessage;\n};\n\nexport type SnackTransportSyntheticMessage = {\n type: 'synthetic_event';\n data: any;\n};\n\nexport type SnackTransportMessage =\n | SnackTransportStartMessage\n | SnackTransportStopMessage\n | SnackTransportUpdateCodeMessage\n | SnackTransportProtocolMessage\n | SnackTransportSyntheticMessage;\n\nexport type SnackTransportEventConnect = {\n type: 'connect';\n connectionId: string;\n data: any; // DeviceInfo\n};\n\nexport type SnackTransportEventDisconnect = {\n type: 'disconnect';\n connectionId: string;\n data: {\n timedout: boolean;\n };\n};\n\nexport type SnackTransportEventProtocolMessage = {\n type: 'protocol_message';\n connectionId: string;\n data: ProtocolIncomingMessage;\n};\n\nexport type SnackTransportEventSendMessage = {\n type: 'send_message';\n data: ProtocolOutgoingMessage;\n};\n\nexport type SnackTransportEventSyntheticMessage = {\n type: 'synthetic_event';\n data: any;\n};\n\nexport type SnackTransportEvent =\n | SnackTransportEventConnect\n | SnackTransportEventDisconnect\n | SnackTransportEventProtocolMessage\n | SnackTransportEventSendMessage\n | SnackTransportEventSyntheticMessage;\n\nexport type SnackTransportListener = (event: SnackTransportEvent) => void;\n\nexport interface SnackTransport {\n addEventListener(type: 'message', listener: SnackTransportListener): void;\n removeEventListener(type: 'message', listener: SnackTransportListener): void;\n postMessage(message: SnackTransportMessage): void;\n}\n\nexport type SnackTransportOptions = {\n channel?: string;\n apiURL?: string;\n verbose?: boolean;\n name?: string;\n};\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { SDKVersion
|
|
1
|
+
import { SDKVersion } from 'snack-content';
|
|
2
|
+
import { SnackWindowRef } from '../types';
|
|
2
3
|
import { SnackTransport, SnackTransportOptions } from './types';
|
|
3
4
|
export declare function createWebPlayerTransport(config: {
|
|
4
5
|
name?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webPlayer.js","sourceRoot":"","sources":["../../src/transports/webPlayer.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"webPlayer.js","sourceRoot":"","sources":["../../src/transports/webPlayer.ts"],"names":[],"mappings":";;;AAUA,SAAgB,wBAAwB,CAAC,MAOxC;IACC,IAAI,SAAS,GAA0B,IAAI,CAAC;IAC5C,SAAS,YAAY;;QACnB,SAAS,GACP,SAAS,aAAT,SAAS,cAAT,SAAS,GACT,MAAM,CAAC,eAAe,CAAC;YACrB,IAAI,QAAE,MAAM,CAAC,IAAI,mCAAI,WAAW;YAChC,OAAO,EAAE,MAAM,CAAC,OAAO;SACxB,CAAC,CAAC;QACL,OAAO,SAAS,CAAC;IACnB,CAAC;IAEK,IAAA,MAAM,GAAK,IAAI,GAAG,CAAC,MAAM,CAAC,YAAY,CAAC,OAAjC,CAAkC;IAE9C,IAAI,cAAkD,CAAC;IACvD,IAAI,iBAAqD,CAAC;IAC1D,OAAO;QACL,gBAAgB,EAAE,UAAC,IAAe,EAAE,QAAgC;;YAClE,IAAI,CAAC,cAAc,EAAE;gBACnB,cAAc,GAAG,UAAC,KAAU;oBAC1B,IAAI,KAAK,CAAC,MAAM,KAAK,MAAM,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;wBAC7D,IAAI,SAAS,EAAE;4BACb,SAAS,CAAC,WAAW,CAAC;gCACpB,IAAI,EAAE,iBAAiB;gCACvB,IAAI,EAAE,KAAK,CAAC,IAAI;6BACjB,CAAC,CAAC;yBACJ;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AU,GAAG,QAAQ,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAC1D,OAAO,SAAS,CAAC;KAClB;IAED,OAAU,YAAY,CAAC,OAAO,CAC5B,iBAAiB,EACjB,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACzB,+BAA0B,kBAAkB,CAAC,UAAU,CAAC,gBAAW,kBAAkB,CACpF,MAAM,CAAC,QAAQ,CAAC,MAAM,CACvB,iBAAY,OAAS,CAAC;AACzB,CAAC;AAhBD,sDAgBC","sourcesContent":["import { SDKVersion } from 'snack-content';\n\nimport { SnackWindowRef } from '../types';\nimport {\n SnackTransport,\n SnackTransportOptions,\n SnackTransportListener,\n SnackTransportMessage,\n} from './types';\n\nexport function createWebPlayerTransport(config: {\n name?: string;\n verbose?: boolean;\n webPlayerURL: string;\n window: Window;\n ref: SnackWindowRef;\n createTransport: (options: SnackTransportOptions) => SnackTransport;\n}): SnackTransport {\n let transport: SnackTransport | null = null;\n function getTransport(): SnackTransport {\n transport =\n transport ??\n config.createTransport({\n name: config.name ?? 'webplayer',\n verbose: config.verbose,\n });\n return transport;\n }\n\n let { origin } = new URL(config.webPlayerURL);\n\n let windowListener: ((event: any) => void) | undefined;\n let transportListener: ((event: any) => void) | undefined;\n return {\n addEventListener: (type: 'message', listener: SnackTransportListener) => {\n if (!windowListener) {\n windowListener = (event: any) => {\n if (event.origin === origin && typeof event.data === 'string') {\n if (transport) {\n transport.postMessage({\n type: 'synthetic_event',\n data: event.data,\n });\n }\n }\n };\n config.window?.addEventListener(type, windowListener);\n }\n if (!transportListener) {\n transportListener = (event: any) => {\n const message = event;\n if (message.type === 'synthetic_event') {\n config.ref.current?.postMessage(JSON.stringify(message.data), origin);\n } else {\n listener(message);\n }\n };\n }\n getTransport().addEventListener(type, transportListener);\n },\n removeEventListener: (type: 'message', _listener: SnackTransportListener) => {\n if (windowListener) {\n config.window?.removeEventListener(type, windowListener);\n windowListener = undefined;\n }\n if (transportListener) {\n transport?.removeEventListener(type, transportListener);\n transportListener = undefined;\n }\n },\n postMessage: (message: SnackTransportMessage) => getTransport().postMessage(message),\n // @ts-ignore: Dirty hack to allow snack web to to communicate with older web-players\n updateOrigin: (newOrigin: string) => (origin = newOrigin),\n };\n}\n\nexport function getWebPlayerIFrameURL(\n webPlayerURL: string,\n sdkVersion: SDKVersion,\n initialURL: string,\n verbose: boolean\n) {\n if (sdkVersion < '40.0.0' || typeof window === 'undefined') {\n return undefined;\n }\n\n return `${webPlayerURL.replace(\n '%%SDK_VERSION%%',\n sdkVersion.split('.')[0]\n )}/index.html?initialUrl=${encodeURIComponent(initialURL)}&origin=${encodeURIComponent(\n window.location.origin\n )}&verbose=${verbose}`;\n}\n"]}
|
package/build/types.d.ts
CHANGED
|
@@ -1,78 +1,5 @@
|
|
|
1
|
-
import { SDKVersion,
|
|
1
|
+
import { SDKVersion, SnackDependencies, SnackDependencyVersions, SnackFiles, SnackMissingDependencies } from 'snack-content';
|
|
2
2
|
import { SnackTransport } from './transports';
|
|
3
|
-
export type { SDKVersion, SDKFeature };
|
|
4
|
-
/**
|
|
5
|
-
* A non asset file that is included with the project.
|
|
6
|
-
* This can be either a code file (.js/.tsx) or a support
|
|
7
|
-
* file such as a markdown or json file.
|
|
8
|
-
*/
|
|
9
|
-
export declare type SnackCodeFile = {
|
|
10
|
-
type: 'CODE';
|
|
11
|
-
contents: string;
|
|
12
|
-
error?: Error;
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* An asset file that refers to externaly available
|
|
16
|
-
* content such as an image or font.
|
|
17
|
-
*
|
|
18
|
-
* When resolved, the `contents` field is an URL to the
|
|
19
|
-
* uploaded asset. A File, Blob or FormData object may
|
|
20
|
-
* also be provided after which it is automatically uploaded
|
|
21
|
-
* and converted into an URL.
|
|
22
|
-
*/
|
|
23
|
-
export declare type SnackAssetFile = {
|
|
24
|
-
type: 'ASSET';
|
|
25
|
-
contents: string | File | Blob | FormData;
|
|
26
|
-
error?: Error;
|
|
27
|
-
};
|
|
28
|
-
/**
|
|
29
|
-
* The content of a Snack code or asset file.
|
|
30
|
-
*/
|
|
31
|
-
export declare type SnackFile = SnackCodeFile | SnackAssetFile;
|
|
32
|
-
/**
|
|
33
|
-
* Dictionary of file-names and their content that make up
|
|
34
|
-
* the files of the Snack.
|
|
35
|
-
*/
|
|
36
|
-
export declare type SnackFiles = {
|
|
37
|
-
[path: string]: SnackFile;
|
|
38
|
-
};
|
|
39
|
-
/**
|
|
40
|
-
* Dictionary of dependencies and their version.
|
|
41
|
-
*/
|
|
42
|
-
export declare type SnackDependencyVersions = {
|
|
43
|
-
[name: string]: string;
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* The version, resolved handle, peer-dependencies and optional
|
|
47
|
-
* error of a dependency.
|
|
48
|
-
*/
|
|
49
|
-
export declare type SnackDependency = {
|
|
50
|
-
version: string;
|
|
51
|
-
handle?: string;
|
|
52
|
-
peerDependencies?: SnackDependencyVersions;
|
|
53
|
-
error?: Error;
|
|
54
|
-
wantedVersion?: string;
|
|
55
|
-
};
|
|
56
|
-
/**
|
|
57
|
-
* Dictionary of dependency names and their (resolved) versions.
|
|
58
|
-
*/
|
|
59
|
-
export declare type SnackDependencies = {
|
|
60
|
-
[name: string]: SnackDependency;
|
|
61
|
-
};
|
|
62
|
-
/**
|
|
63
|
-
* Wanted version of the dependency that is missing, including the
|
|
64
|
-
* dependents which have this dependency as a peer-dependency.
|
|
65
|
-
*/
|
|
66
|
-
export declare type SnackMissingDependency = {
|
|
67
|
-
dependents: string[];
|
|
68
|
-
wantedVersion?: string;
|
|
69
|
-
};
|
|
70
|
-
/**
|
|
71
|
-
* Dictionary of dependencies that are missing.
|
|
72
|
-
*/
|
|
73
|
-
export declare type SnackMissingDependencies = {
|
|
74
|
-
[name: string]: SnackMissingDependency;
|
|
75
|
-
};
|
|
76
3
|
/**
|
|
77
4
|
* An error that can optionally hold a file-name and line/column location.
|
|
78
5
|
*/
|
|
@@ -227,9 +154,17 @@ export declare type SnackState = {
|
|
|
227
154
|
*/
|
|
228
155
|
unsaved: boolean;
|
|
229
156
|
/**
|
|
230
|
-
*
|
|
157
|
+
* Full name of the saved Snack.
|
|
231
158
|
*/
|
|
232
159
|
id?: string;
|
|
160
|
+
/**
|
|
161
|
+
* Id of this version of the saved Snack. Each Snack can have many different versions or revisions, each revision has its own snackId.
|
|
162
|
+
*/
|
|
163
|
+
snackId?: string;
|
|
164
|
+
/**
|
|
165
|
+
* Id of a Snack saved to an account. This id points to the latest version of a Snack revision and associated user.
|
|
166
|
+
*/
|
|
167
|
+
accountSnackId?: string;
|
|
233
168
|
/**
|
|
234
169
|
* URL of the saved Snack.
|
|
235
170
|
* The URL is empty when no save "id" is available.
|
package/build/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n SDKVersion,\n SnackDependencies,\n SnackDependencyVersions,\n SnackFiles,\n SnackMissingDependencies,\n} from 'snack-content';\n\nimport { SnackTransport } from './transports';\n\n/**\n * An error that can optionally hold a file-name and line/column location.\n */\nexport interface SnackError extends Error {\n fileName?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\nexport type SnackConnectedClientStatus = 'ok' | 'error' | 'reloading';\n\n/**\n * Client which connected to the Snack.\n *\n * Clients are only able to connect when the Snack is `online`.\n */\nexport type SnackConnectedClient = {\n transport: string;\n id: string;\n name: string;\n platform: string;\n status: SnackConnectedClientStatus;\n error?: SnackError;\n previewURL?: string;\n previewTimestamp?: number;\n};\n\n/**\n * Collection of connected clients.\n */\nexport type SnackConnectedClients = {\n [key: string]: SnackConnectedClient;\n};\n\n/**\n * User that is used for communicating with the Expo servers.\n */\nexport type SnackUser = {\n sessionSecret?: string;\n accessToken?: string;\n};\n\n/**\n * Request data to be used with the `sendBeacon` API.\n */\nexport type SnackSendBeaconRequest = {\n url: string;\n data: any;\n};\n\nexport type SnackListenerSubscription = () => any;\n\n/**\n * Log data for when a connected client calls one of the\n * `console.[log,info,warn,error]` to log information to the\n * console.\n */\nexport type SnackLogEvent = {\n type: 'error' | 'warn' | 'log' | 'info';\n message: string;\n connectedClient?: SnackConnectedClient;\n error?: SnackError;\n};\n\nexport type SnackWindowRef = {\n current: Window | null;\n};\n\nexport type SnackState = {\n /**\n * Expo SDK version.\n */\n sdkVersion: SDKVersion;\n\n /**\n * Files that make up the content (code & assets) of the Snack. There should\n * always be a file called \"App.js\" or \"App.tsx\" as the main entry point.\n */\n files: SnackFiles;\n\n /**\n * Packages that can be used in the code files. Packages that are pre-loaded\n * by the sdk may be ommited, but it is recommended to add them anyway.\n */\n dependencies: SnackDependencies;\n\n /**\n * Optional name. The name is used when saving or downloading the Snack; and is used\n * for the onlineName property.\n */\n name: string;\n\n /**\n * Additional description of the Snack. The description is used when saving the Snack\n * and may also be used for searching purposes.\n */\n description: string;\n\n /**\n * Collection of dependencies that are missing but are required by one or more of\n * the dependencies.\n */\n missingDependencies: SnackMissingDependencies;\n\n /**\n * Collection of packages and versions that are compatible with the selected\n * SDK version. This is similar to using `expo install`, which ensures the latest\n * compatible version is installed.\n */\n wantedDependencyVersions?: SnackDependencyVersions;\n\n /**\n * Disabled state. When the Snack is disabled it will not resolve any dependencies\n * or upload any asset files. It also disables the ability to go online.\n */\n disabled: boolean;\n\n /**\n * When online is true, Expo clients can connect to the Snack and receive live updates\n * when code or dependencies are changed. It also makes the Snack visible in the\n * \"Recently in Development\" section of the Expo client.\n */\n online: boolean;\n\n /**\n * Communication channel (\"pubnub\") through which live updates are transferred.\n * The communication channel is only used when the Snack is \"online\".\n */\n channel: string;\n\n /**\n * Device-id of the Expo client. When set causes the Snack to be visible in the\n * \"Recently in Development\" section of the Expo client with that device-id.\n * The device-id is only used when the Snack is \"online\".\n */\n deviceId?: string;\n\n /**\n * Unique experience url which can be used to open the Expo client and connect\n * to the Snack (e.g. \"exp://exp.host/@snack/sdk.38.0.0-78173941\").\n */\n url: string;\n\n /**\n * Name of the Snack as shown in the \"Recently in Development\" section in the\n * Expo client. The online-name will be empty when the Snack is not \"online\".\n */\n onlineName?: string;\n\n /**\n * A close request that should be send using the browser `sendBeacon` API\n * whenever the browser session is unloaded. This gives the Snack a last opportunity\n * to gracefully close its connections so that the \"Recently in Development\"\n * section in the Expo client no longer shows the Snack.\n */\n sendBeaconCloseRequest?: SnackSendBeaconRequest;\n\n /**\n * @internal\n */\n transports: { [id: string]: SnackTransport };\n\n /**\n * Clients that are currently connected.\n */\n connectedClients: SnackConnectedClients;\n\n /**\n *\n */\n user?: SnackUser;\n\n /**\n * Unsaved status of the Snack. Becomes `true` when the Snack code is changed and\n * `false` whenever the Snack is saved.\n */\n unsaved: boolean;\n\n /**\n * Full name of the saved Snack.\n */\n id?: string;\n\n /**\n * Id of this version of the saved Snack. Each Snack can have many different versions or revisions, each revision has its own snackId.\n */\n snackId?: string;\n\n /**\n * Id of a Snack saved to an account. This id points to the latest version of a Snack revision and associated user.\n */\n accountSnackId?: string;\n\n /**\n * URL of the saved Snack.\n * The URL is empty when no save \"id\" is available.\n */\n saveURL?: string;\n\n /**\n * Last saved (non-draft) Expo SDK version.\n */\n savedSDKVersion?: string;\n\n /**\n * URL to use to when loading the web-preview in an iframe.\n *\n * Web-preview is supported from SDK 40 and higher.\n * To enable it, set the `webPreviewRef` to the contentWindow\n * of the iframe.\n */\n webPreviewURL?: string;\n};\n"]}
|
package/build/utils.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { SDKVersion
|
|
1
|
+
import { SDKVersion } from 'snack-content';
|
|
2
|
+
import { SnackError, SnackUser } from './types';
|
|
2
3
|
declare const fetch: typeof globalThis.fetch;
|
|
3
4
|
export { fetch };
|
|
4
5
|
export declare function createChannel(channel?: string): string;
|
package/build/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAAA,kEAA2C;AAC3C,iCAAwC;
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAAA,kEAA2C;AAC3C,iCAAwC;AAKhC,IAAA,KAAK,GAAK,wBAAa,EAAE,MAApB,CAAqB;AACzB,sBAAK;AAEd,6FAA6F;AAC7F,IAAM,mBAAmB,GAAG,kEAAkE,CAAC;AAC/F,IAAM,eAAe,GAAG,uBAAc,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC;AAEhE,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,eAAe,EAAE,CAAC;IAEvC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;QACtB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,KAAmB,UAAO,EAAP,mBAAO,EAAP,qBAAO,EAAP,IAAO,EAAE;QAAvB,IAAM,IAAI,gBAAA;QACb,IAAI,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;YACzC,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;SAC3D;KACF;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAdD,sCAcC;AAED,SAAgB,SAAS,CAAC,IAAY,EAAE,UAAsB,EAAE,OAAgB,EAAE,EAAW;IAC3F,IAAI,OAAO,EAAE;QACX,OAAO,EAAE;YACP,CAAC,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC;gBAClB,CAAC,CAAC,WAAS,IAAI,SAAI,EAAE,SAAI,OAAS;gBAClC,CAAC,CAAC,WAAS,IAAI,gBAAW,EAAE,SAAI,OAAS;YAC3C,CAAC,CAAC,WAAS,IAAI,oBAAe,UAAU,SAAI,OAAS,CAA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 'snack-content';\n\nimport { SnackError, SnackUser } from './types';\n\nconst { fetch } = fetchPonyfill();\nexport { fetch };\n\n// + and - are used as delimiters in the uri, ensure they do not appear in the channel itself\nconst VALID_CHANNEL_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!_';\nconst generateChannel = customAlphabet(VALID_CHANNEL_CHARS, 10);\n\nexport function createChannel(channel?: string): string {\n channel = channel ?? generateChannel();\n\n if (channel.length < 6) {\n throw new Error('Please use a channel id with more entropy');\n }\n\n for (const char of channel) {\n if (VALID_CHANNEL_CHARS.indexOf(char) < 0) {\n throw new Error('Channel id contains invalid characters');\n }\n }\n\n return channel;\n}\n\nexport function createURL(host: string, sdkVersion: SDKVersion, channel?: string, id?: string) {\n if (channel) {\n return id\n ? id.startsWith('@')\n ? `exp://${host}/${id}+${channel}`\n : `exp://${host}/@snack/${id}+${channel}`\n : `exp://${host}/@snack/sdk.${sdkVersion}-${channel}`;\n } else if (id) {\n return `exp://${host}/${id.match(/.*\\/.*/) ? id : `@snack/${id}`}`;\n } else {\n return '';\n }\n}\n\nexport function createError(config: {\n message: string;\n name?: string;\n fileName?: string;\n lineNumber?: number;\n columnNumber?: number;\n stack?: string;\n}): SnackError {\n const error: SnackError = new Error(config.message);\n if (config.name) error.name = config.name;\n if (config.fileName) error.fileName = config.fileName;\n if (config.lineNumber) error.lineNumber = config.lineNumber;\n if (config.columnNumber) error.columnNumber = config.columnNumber;\n if (config.stack) error.stack = config.stack;\n return error;\n}\n\nexport function createUserHeader(user?: SnackUser): { [key: string]: string } {\n if (user?.sessionSecret) {\n return { 'Expo-Session': user.sessionSecret };\n }\n\n if (user?.accessToken) {\n return { Authorization: `Bearer ${user.accessToken}` };\n }\n\n return {};\n}\n"]}
|