@casual-simulation/aux-common 2.0.19-alpha.1523438944 → 2.0.22

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.
@@ -11,13 +11,13 @@ import { DEBUG_STRING, debugStringifyFunction, } from './AuxGlobalContext';
11
11
  import { hasValue, trimTag, isBot, BOT_SPACE_TAG, toast as toastMessage, showJoinCode as calcShowJoinCode, requestFullscreen, exitFullscreen, html as htmlMessage, hideHtml as hideHtmlMessage, setClipboard as calcSetClipboard, tweenTo as calcTweenTo, showChat as calcShowChat, hideChat as calcHideChat, runScript, enableAR as calcEnableAR, disableAR as calcDisableAR, enableVR as calcEnableVR, disableVR as calcDisableVR, showUploadAuxFile as calcShowUploadAuxFile, openQRCodeScanner as calcOpenQRCodeScanner, showQRCode as calcShowQRCode, openBarcodeScanner as calcOpenBarcodeScanner, showBarcode as calcShowBarcode, importAUX as calcImportAUX, showInputForTag as calcShowInputForTag, showInput as calcShowInput, replaceDragBot as calcReplaceDragBot, goToDimension as calcGoToDimension, goToURL as calcGoToURL, openURL as calcOpenURL, checkout as calcCheckout, playSound as calcPlaySound, bufferSound as calcBufferSound, cancelSound as calcCancelSound, setupServer as calcSetupServer, shell as calcShell, backupToGithub as calcBackupToGithub, backupAsDownload as calcBackupAsDownload, finishCheckout as calcFinishCheckout, markHistory as calcMarkHistory, browseHistory as calcBrowseHistory, restoreHistoryMark as calcRestoreHistoryMark, loadFile as calcLoadFile, saveFile as calcSaveFile, reject as calcReject, localFormAnimation as calcLocalFormAnimation, webhook as calcWebhook, superShout as calcSuperShout, share as calcShare, registerPrefix as calcRegisterPrefix, createCertificate as calcCreateCertificate, signTag as calcSignTag, revokeCertificate as calcRevokeCertificate, localPositionTween as calcLocalPositionTween, localRotationTween as calcLocalRotationTween, showUploadFiles as calcShowUploadFiles, download, loadSimulation, unloadSimulation, getUploadState, addState, getPortalTag, KNOWN_PORTALS, openConsole, tagsOnBot, getOriginalObject, getBotSpace, trimEvent, CREATE_ACTION_NAME, CREATE_ANY_ACTION_NAME, DESTROY_ACTION_NAME, ORIGINAL_OBJECT, unlockSpace, getRemoteCount, getServers, getRemotes, action, getServerStatuses, setSpacePassword, exportGpioPin, unexportGpioPin, setGpioPin, getGpioPin, rpioInitPin, rpioExitPin, rpioOpenPin, rpioModePin, rpioReadPin, rpioReadSequencePin, rpioWritePin, rpioWriteSequencePin, rpioReadpadPin, rpioWritepadPin, rpioPudPin, rpioPollPin, rpioClosePin, rpioI2CBeginPin, rpioI2CSetSlaveAddressPin, rpioI2CSetBaudRatePin, rpioI2CSetClockDividerPin, rpioI2CReadPin, rpioI2CWritePin,
12
12
  // rpioI2CReadRegisterRestartPin,
13
13
  // rpioI2CWriteReadRestartPin,
14
- rpioI2CEndPin, rpioPWMSetClockDividerPin, rpioPWMSetRangePin, rpioPWMSetDataPin, rpioSPIBeginPin, rpioSPIChipSelectPin, rpioSPISetCSPolarityPin, rpioSPISetClockDividerPin, rpioSPISetDataModePin, rpioSPITransferPin, rpioSPIWritePin, rpioSPIEndPin, serialConnectPin, serialOpenPin, serialStreamPin, serialUpdatePin, serialWritePin, serialReadPin, serialClosePin, serialFlushPin, serialDrainPin, serialPausePin, serialResumePin, calculateAnchorPoint, calculateAnchorPointOffset, getBotPosition as calcGetBotPosition, isRuntimeBot, SET_TAG_MASK_SYMBOL, CLEAR_TAG_MASKS_SYMBOL, getBotScale, EDIT_TAG_SYMBOL, EDIT_TAG_MASK_SYMBOL, circleWipe, addDropSnap as calcAddDropSnap, animateToPosition, beginAudioRecording as calcBeginAudioRecording, endAudioRecording as calcEndAudioRecording, beginRecording as calcBeginRecording, endRecording as calcEndRecording, speakText as calcSpeakText, getVoices as calcGetVoices, getGeolocation as calcGetGeolocation, cancelAnimation, disablePOV, enablePOV, enableCustomDragging as calcEnableCustomDragging, MINI_PORTAL, registerCustomApp, setAppOutput, unregisterCustomApp, requestAuthData as calcRequestAuthData, createBot, defineGlobalBot as calcDefineGlobalBot, TEMPORARY_BOT_PARTITION_ID, publishRecord as calcPublishRecord, DEFAULT_RECORD_SPACE, getRecords as calcGetRecords, requestPermanentAuthToken as calcRequestPermanentAuthToken, deleteRecord, convertToString, GET_TAG_MASKS_SYMBOL, isBotLink, parseBotLink, createBotLink, } from '../bots';
14
+ rpioI2CEndPin, rpioPWMSetClockDividerPin, rpioPWMSetRangePin, rpioPWMSetDataPin, rpioSPIBeginPin, rpioSPIChipSelectPin, rpioSPISetCSPolarityPin, rpioSPISetClockDividerPin, rpioSPISetDataModePin, rpioSPITransferPin, rpioSPIWritePin, rpioSPIEndPin, serialConnectPin, serialOpenPin, serialStreamPin, serialUpdatePin, serialWritePin, serialReadPin, serialClosePin, serialFlushPin, serialDrainPin, serialPausePin, serialResumePin, calculateAnchorPoint, calculateAnchorPointOffset, getBotPosition as calcGetBotPosition, isRuntimeBot, SET_TAG_MASK_SYMBOL, CLEAR_TAG_MASKS_SYMBOL, getBotScale, EDIT_TAG_SYMBOL, EDIT_TAG_MASK_SYMBOL, circleWipe, addDropSnap as calcAddDropSnap, animateToPosition, beginAudioRecording as calcBeginAudioRecording, endAudioRecording as calcEndAudioRecording, beginRecording as calcBeginRecording, endRecording as calcEndRecording, speakText as calcSpeakText, getVoices as calcGetVoices, getGeolocation as calcGetGeolocation, cancelAnimation, disablePOV, enablePOV, enableCustomDragging as calcEnableCustomDragging, MINI_PORTAL, registerCustomApp, setAppOutput, unregisterCustomApp, requestAuthData as calcRequestAuthData, createBot, defineGlobalBot as calcDefineGlobalBot, TEMPORARY_BOT_PARTITION_ID, convertToString, GET_TAG_MASKS_SYMBOL, isBotLink, parseBotLink, createBotLink, convertGeolocationToWhat3Words as calcConvertGeolocationToWhat3Words, getPublicRecordKey as calcGetPublicRecordKey, recordData as calcRecordData, getRecordData, recordFile as calcRecordFile, } from '../bots';
15
15
  import { sortBy, every, cloneDeep, union, isEqual, flatMap } from 'lodash';
16
16
  import { remote as calcRemote, } from '@casual-simulation/causal-trees';
17
17
  import { RanOutOfEnergyError } from './AuxResults';
18
18
  import '../polyfill/Array.first.polyfill';
19
19
  import '../polyfill/Array.last.polyfill';
20
- import { convertToCopiableValue, embedBase64InPdf, formatAuthToken, getEasing, getEmbeddedBase64FromPdf, } from './Utils';
20
+ import { convertToCopiableValue, embedBase64InPdf, getEasing, getEmbeddedBase64FromPdf, } from './Utils';
21
21
  import { sha256 as hashSha256, sha512 as hashSha512, hmac } from 'hash.js';
22
22
  import stableStringify from '@casual-simulation/fast-json-stable-stringify';
23
23
  import { encrypt as realEncrypt, decrypt as realDecrypt, keypair as realKeypair, sign as realSign, verify as realVerify, asymmetricKeypair as realAsymmetricKeypair, asymmetricEncrypt as realAsymmetricEncrypt, asymmetricDecrypt as realAsymmetricDecrypt, isAsymmetricKeypair, isAsymmetricEncrypted, isEncrypted, } from '@casual-simulation/crypto';
@@ -32,6 +32,7 @@ import { Fragment, h } from 'preact';
32
32
  import htm from 'htm';
33
33
  import { fromByteArray, toByteArray } from 'base64-js';
34
34
  import expect, { iterableEquality } from '@casual-simulation/expect';
35
+ import { parseRecordKey, isRecordKey as calcIsRecordKey, } from '@casual-simulation/aux-records';
35
36
  const _html = htm.bind(h);
36
37
  const html = ((...args) => {
37
38
  return _html(...args);
@@ -130,6 +131,14 @@ export function createDefaultLibrary(context) {
130
131
  };
131
132
  const webhookFunc = makeMockableFunction(webhook, 'webhook');
132
133
  webhookFunc.post = makeMockableFunction(webhook.post, 'webhook.post');
134
+ const shoutImpl = shout;
135
+ const shoutProxy = new Proxy(shoutImpl, {
136
+ get(target, name, reciever) {
137
+ return (arg) => {
138
+ return shout(name, arg);
139
+ };
140
+ },
141
+ });
133
142
  return {
134
143
  api: {
135
144
  getBots,
@@ -162,7 +171,7 @@ export function createDefaultLibrary(context) {
162
171
  updateBotLinks,
163
172
  superShout,
164
173
  priorityShout,
165
- shout,
174
+ shout: shoutProxy,
166
175
  whisper,
167
176
  byTag,
168
177
  byID,
@@ -175,10 +184,6 @@ export function createDefaultLibrary(context) {
175
184
  byCreator,
176
185
  either,
177
186
  not,
178
- byAuthID,
179
- byAddress,
180
- withAuthToken,
181
- byPrefix,
182
187
  remote,
183
188
  sendRemoteData: remoteWhisper,
184
189
  remoteWhisper,
@@ -285,16 +290,22 @@ export function createDefaultLibrary(context) {
285
290
  unregisterApp,
286
291
  compileApp: setAppContent,
287
292
  requestAuthBot,
288
- requestPermanentAuthToken: makeMockableFunction(requestPermanentAuthToken, 'os.requestPermanentAuthToken'),
289
- publishRecord: makeMockableFunction(publishRecord, 'os.publishRecord'),
290
- getRecords: makeMockableFunction(getRecords, 'os.getRecords'),
291
- destroyRecord: makeMockableFunction(destroyRecord, 'os.destroyRecord'),
293
+ getPublicRecordKey,
294
+ isRecordKey,
295
+ recordData,
296
+ getData,
297
+ recordFile,
298
+ getFile,
299
+ convertGeolocationToWhat3Words,
292
300
  setupInst: setupServer,
293
301
  remotes,
294
302
  instances: servers,
295
303
  remoteCount: serverRemoteCount,
296
304
  totalRemoteCount: totalRemoteCount,
297
305
  instStatuses: serverStatuses,
306
+ get vars() {
307
+ return context.global;
308
+ },
298
309
  },
299
310
  portal: {
300
311
  registerPrefix,
@@ -952,50 +963,6 @@ export function createDefaultLibrary(context) {
952
963
  function not(filter) {
953
964
  return (bot) => !filter(bot);
954
965
  }
955
- /**
956
- * Creates a record filter that retrieves records created by the given Auth ID.
957
- * @param authID The ID of the creator of the records.
958
- */
959
- function byAuthID(authID) {
960
- return {
961
- recordFilter: true,
962
- authID,
963
- [DEBUG_STRING]: debugStringifyFunction('byAuthID', [authID]),
964
- };
965
- }
966
- /**
967
- * Creates a record filter that retrieves records with the given address.
968
- * @param address The address that the record was stored at.
969
- */
970
- function byAddress(address) {
971
- return {
972
- recordFilter: true,
973
- address,
974
- [DEBUG_STRING]: debugStringifyFunction('byAddress', [address]),
975
- };
976
- }
977
- /**
978
- * Creates a record filter that retrieves records with the given address.
979
- * @param token The auth token that should be used to authenticate the getRecords() request.
980
- */
981
- function withAuthToken(token) {
982
- return {
983
- recordFilter: true,
984
- authToken: token,
985
- [DEBUG_STRING]: debugStringifyFunction('withAuthToken', [token]),
986
- };
987
- }
988
- /**
989
- * Creates a record filter that retrieves records with the given prefix in their address.
990
- * @param prefix The prefix that should be matched to record addresses.
991
- */
992
- function byPrefix(prefix) {
993
- return {
994
- recordFilter: true,
995
- prefix,
996
- [DEBUG_STRING]: debugStringifyFunction('byPrefix', [prefix]),
997
- };
998
- }
999
966
  /**
1000
967
  * Gets the value of the given tag stored in the given bot.
1001
968
  * @param bot The bot.
@@ -1984,8 +1951,6 @@ export function createDefaultLibrary(context) {
1984
1951
  let bot = getBot('id', data.userId);
1985
1952
  if (!bot) {
1986
1953
  bot = context.createBot(createBot(data.userId, {
1987
- authToken: formatAuthToken(data.token, data.service),
1988
- authBundle: data.service,
1989
1954
  avatarAddress: data.avatarUrl,
1990
1955
  name: data.name,
1991
1956
  }, TEMPORARY_BOT_PARTITION_ID));
@@ -2005,144 +1970,98 @@ export function createDefaultLibrary(context) {
2005
1970
  return addAsyncAction(task, event);
2006
1971
  }
2007
1972
  /**
2008
- * Requests an auth token that does not expire and can be used to authorize other app bundles to publish records for this app bundle.
1973
+ * Gets an access key for the given public record.
1974
+ * @param name The name of the record.
2009
1975
  */
2010
- function requestPermanentAuthToken() {
2011
- return __awaiter(this, void 0, void 0, function* () {
2012
- const task = context.createTask();
2013
- const event = calcRequestPermanentAuthToken(task.taskId);
2014
- const data = yield addAsyncAction(task, event);
2015
- return formatAuthToken(data.token, data.service);
2016
- });
1976
+ function getPublicRecordKey(name) {
1977
+ const task = context.createTask();
1978
+ const event = calcGetPublicRecordKey(name, task.taskId);
1979
+ return addAsyncAction(task, event);
2017
1980
  }
2018
1981
  /**
2019
- * Publishes a record that can be used across instances.
2020
- * @param recordDefinition The data that should be used to publish the record.
1982
+ * Determines if the given value is a record key.
1983
+ * @param key The value to check.
2021
1984
  */
2022
- function publishRecord(recordDefinition) {
2023
- var _a, _b, _c, _d, _e;
2024
- let address;
2025
- if ('address' in recordDefinition) {
2026
- if (!hasValue(recordDefinition.address)) {
2027
- throw new Error('A non-null or empty address must be used when specifying an address.');
2028
- }
2029
- address = recordDefinition.address;
2030
- }
2031
- else {
2032
- if (!hasValue(recordDefinition.prefix)) {
2033
- if (hasValue(recordDefinition.id)) {
2034
- throw new Error('A prefix must be specified when declaring an ID for the record.');
2035
- }
2036
- address = uuid();
2037
- }
2038
- else {
2039
- address = `${recordDefinition.prefix}-${(_a = recordDefinition.id) !== null && _a !== void 0 ? _a : uuid()}`;
2040
- }
2041
- }
2042
- const space = (_b = recordDefinition.space) !== null && _b !== void 0 ? _b : DEFAULT_RECORD_SPACE;
2043
- const token = (_c = recordDefinition.authToken) !== null && _c !== void 0 ? _c : (_e = (_d = context.global.authBot) === null || _d === void 0 ? void 0 : _d.tags) === null || _e === void 0 ? void 0 : _e.authToken;
2044
- if (!hasValue(token)) {
2045
- throw new Error('authToken is required when there is no authBot.');
2046
- }
2047
- if (!hasValue(recordDefinition.record)) {
2048
- throw new Error('The record property is required.');
2049
- }
1985
+ function isRecordKey(key) {
1986
+ return calcIsRecordKey(key);
1987
+ }
1988
+ /**
1989
+ * Records the given data to the given address inside the record for the given record key.
1990
+ * @param recordKey The key that should be used to access the record.
1991
+ * @param address The address that the data should be stored at inside the record.
1992
+ * @param data The data that should be stored.
1993
+ */
1994
+ function recordData(recordKey, address, data) {
2050
1995
  const task = context.createTask();
2051
- const event = calcPublishRecord(token, address, recordDefinition.record, space, task.taskId);
1996
+ const event = calcRecordData(recordKey, address, data, task.taskId);
2052
1997
  return addAsyncAction(task, event);
2053
1998
  }
2054
1999
  /**
2055
- * Retrives a list of records using the given filters.
2056
- * @param filters The list of filters that should be used to retrieve some records.
2057
- *
2058
- * @example
2059
- * // Get a record by address
2060
- * let result = await os.getRecords(byAuthID('myAuthID'), byAddress('myAddress'));
2061
- */
2062
- function getRecords(...filters) {
2063
- var _a, _b, _c, _d, _e;
2064
- let token = (_c = (_b = (_a = context.global.authBot) === null || _a === void 0 ? void 0 : _a.tags) === null || _b === void 0 ? void 0 : _b.authToken) !== null && _c !== void 0 ? _c : null;
2065
- let address;
2066
- let prefix;
2067
- let authID = (_e = (_d = context.global.authBot) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : null;
2068
- let id;
2069
- let space = 'tempRestricted';
2070
- for (let filter of filters) {
2071
- if ('address' in filter) {
2072
- address = filter.address;
2073
- }
2074
- if ('authID' in filter) {
2075
- authID = filter.authID;
2076
- }
2077
- if ('space' in filter) {
2078
- space = filter.space;
2079
- }
2080
- if ('authToken' in filter) {
2081
- token = filter.authToken;
2082
- }
2083
- if ('prefix' in filter) {
2084
- prefix = filter.prefix;
2085
- }
2086
- if ('id' in filter) {
2087
- id = filter.id;
2088
- }
2000
+ * Gets the data stored in the given record at the given address.
2001
+ * @param recordKeyOrName The record that the data should be retrieved from.
2002
+ * @param address The address that the data is stored at.
2003
+ */
2004
+ function getData(recordKeyOrName, address) {
2005
+ let recordName = isRecordKey(recordKeyOrName)
2006
+ ? parseRecordKey(recordKeyOrName)[0]
2007
+ : recordKeyOrName;
2008
+ const task = context.createTask();
2009
+ const event = getRecordData(recordName, address, task.taskId);
2010
+ return addAsyncAction(task, event);
2011
+ }
2012
+ /**
2013
+ * Records the given data as a file.
2014
+ * @param recordKey The record that the file should be recorded in.
2015
+ * @param data The data that should be recorded.
2016
+ * @param options The options that should be used to record the file.
2017
+ */
2018
+ function recordFile(recordKey, data, options) {
2019
+ if (!hasValue(recordKey)) {
2020
+ throw new Error('A recordKey must be provided.');
2089
2021
  }
2090
- if (!hasValue(authID)) {
2091
- throw new Error('An authID must be specified as a filter when there is no authBot.');
2092
- }
2093
- if (!hasValue(address) && !hasValue(prefix) && !hasValue(id)) {
2094
- throw new Error('An address, prefix, or ID must be specified as a filter.');
2095
- }
2096
- if (!hasValue(address) && hasValue(prefix) && hasValue(id)) {
2097
- address = prefix + id;
2098
- }
2099
- else if (!hasValue(address) && hasValue(id)) {
2100
- address = id;
2101
- }
2102
- let query = hasValue(address) ? { address } : { prefix };
2103
- return issueEvent(query);
2104
- function issueEvent(query) {
2105
- return __awaiter(this, void 0, void 0, function* () {
2106
- const task = context.createTask();
2107
- const event = calcGetRecords(token, authID, space, query, task.taskId);
2108
- const result = yield addAsyncAction(task, event);
2109
- return {
2110
- records: result.records,
2111
- hasMoreRecords: result.hasMoreRecords,
2112
- totalCount: result.totalCount,
2113
- getMoreRecords: () => __awaiter(this, void 0, void 0, function* () {
2114
- if (result.hasMoreRecords && hasValue(result.cursor)) {
2115
- return issueEvent(Object.assign(Object.assign({}, query), { cursor: result.cursor }));
2116
- }
2117
- else {
2118
- throw new Error('No more records to retrieve.');
2119
- }
2120
- }),
2121
- };
2122
- });
2022
+ else if (typeof recordKey !== 'string') {
2023
+ throw new Error('recordKey must be a string.');
2024
+ }
2025
+ if (!hasValue(data)) {
2026
+ throw new Error('data must be provided.');
2123
2027
  }
2028
+ const task = context.createTask();
2029
+ const event = calcRecordFile(recordKey, data, options === null || options === void 0 ? void 0 : options.description, options === null || options === void 0 ? void 0 : options.mimeType, task.taskId);
2030
+ return addAsyncAction(task, event);
2124
2031
  }
2125
2032
  /**
2126
- * Requests that the given record be destroyed.
2127
- * @param record The record that should be deleted.
2033
+ * Gets the data stored in the given file.
2034
+ * @param urlOrRecordFileResult The URL or the successful result of the record file operation.
2128
2035
  */
2129
- function destroyRecord(record) {
2130
- var _a, _b, _c;
2131
- let address;
2132
- if (!hasValue(record.address)) {
2133
- throw new Error('the address property is required in order to delete a record.');
2036
+ function getFile(urlOrRecordFileResult) {
2037
+ if (!hasValue(urlOrRecordFileResult)) {
2038
+ throw new Error('A url or successful os.recordFile() result must be provided.');
2134
2039
  }
2135
- address = record.address;
2136
- if (!hasValue(record.space)) {
2137
- throw new Error('the space property is required in order to delete a record.');
2040
+ let url;
2041
+ if (typeof urlOrRecordFileResult === 'string') {
2042
+ url = urlOrRecordFileResult;
2138
2043
  }
2139
- const space = record.space;
2140
- const token = (_a = record.authToken) !== null && _a !== void 0 ? _a : (_c = (_b = context.global.authBot) === null || _b === void 0 ? void 0 : _b.tags) === null || _c === void 0 ? void 0 : _c.authToken;
2141
- if (!hasValue(token)) {
2142
- throw new Error('authToken is required when there is no authBot.');
2044
+ else {
2045
+ if (!urlOrRecordFileResult.success) {
2046
+ throw new Error('The result must be a successful os.recordFile() result.');
2047
+ }
2048
+ url = urlOrRecordFileResult.url;
2143
2049
  }
2050
+ let promise = webGet(url);
2051
+ let action = promise[ORIGINAL_OBJECT];
2052
+ let final = promise.then((result) => {
2053
+ return result.data;
2054
+ });
2055
+ final[ORIGINAL_OBJECT] = action;
2056
+ return final;
2057
+ }
2058
+ /**
2059
+ * Converts the given geolocation to a what3words (https://what3words.com/) address.
2060
+ * @param location The latitude and longitude that should be converted to a 3 word address.
2061
+ */
2062
+ function convertGeolocationToWhat3Words(location) {
2144
2063
  const task = context.createTask();
2145
- const event = deleteRecord(token, address, space, task.taskId);
2064
+ const event = calcConvertGeolocationToWhat3Words(location, task.taskId);
2146
2065
  return addAsyncAction(task, event);
2147
2066
  }
2148
2067
  /**