RangerMauve / hyper-sdk

Make your own hyper apps!
https://www.youtube.com/watch?v=HyHk4aImd_I&list=PL7sG5SCUNyeYx8wnfMOUpsh7rM_g0w_cu&index=20
MIT License
292 stars 45 forks source link

ready() promises do not resolve in a mobile context when using browserified dat-sdk #68

Closed 4c656554 closed 2 years ago

4c656554 commented 3 years ago

The following html works in a desktop browser, but does not on the mobile browsers I tried (Safari, Brave).

The drive.ready() does not resolve, it appears.

<!DOCTYPE html><html>
<head>
  <script src="lib/dat-sdk-bundle.js"></script>
 <meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>

<script>

let hypersdk
let drive
let core

// Runs through initialisation of hyper core and hyperdrive, puts status messages in html doc.
;(async function(){

  await new Promise(resolve => document.addEventListener('DOMContentLoaded', resolve));
  document.getElementById('setup').innerHTML += 'dom loaded<br>'
  hypersdk = await window.datSDK();
  document.getElementById('setup').innerHTML += 'hypersdk loaded<br>'

  drive = await hypersdk.Hyperdrive('drive')
  document.getElementById('drive').innerHTML += 'drive created<br>' //+String(drive.ready()) Note adding this shows that mobile browser recognises ready() as promise obj
  await drive.ready()
  document.getElementById('drive').innerHTML += 'drive ready<br>'
  document.getElementById('drive').innerHTML += 'drive key = ' + drive.key.toString('hex') +'<br>'

  core = await hypersdk.Hypercore('core')
  document.getElementById('core').innerHTML += 'core created<br>' +String(core.ready())
  await core.ready()
  document.getElementById('core').innerHTML += 'core ready<br>'
  document.getElementById('core').innerHTML += 'core key = ' + core.key.toString('hex') +'<br>'

})();

</script>
<!-- main container div -->
<div id="main" style="width:100%;height:auto;display:grid;grid-template: auto auto auto/ auto;background-color:red;">
      <div id="setup" style="width:100%;height:auto;grid-area: 1 / 1 / 2 / 2;;background-color:lavender;">
        INIT:<br>
      </div>
      <div id="drive" style="width:100%;height:auto;grid-area: 2 / 1 / 3 / 2;transition: all 0.5s;background-color:lightgreen;">
        DRIVE:<br>
      </div>
      <div id="core" style="width:100%;height:auto;grid-area: 3 / 1 / 4 / 2;transition: all 0.5s;background-color:yellow;">
        CORE:<br>
      </div>
</div>

</body></html>

Thanks for creating this great library!

RangerMauve commented 3 years ago

Would you be able to open dev tools for your mobile device and post any errors you're seeing in the console?

4c656554 commented 3 years ago

tldr: No console messages are reported, the mobile browser just hangs at:

Promise { <state>: "pending" }

Re mobile dev tools, I think you need consistent OS ecosystems for that (?), which I don't have atm.

I have managed to override console.log and console.error so that I can put the logs into a div on the mobile device (based on this SO question/answer). The code is below.

I'm still attempting to figure out how to debug in more detail. Do you get the same behaviour on your device?

Override functions:

function promiseState(p) {
    const t = {};
    return Promise.race([p, t])
      .then(v => (v === t)? { state: "pending" } : { state: "fulfilled", value: v }, () => { state: "rejected" });
}

console.log = async function(...args) {
  divconsole.innerHTML += String(ccount) +' CONSOLE LOG' + ':  <br>';
  for (let arg of args) {
    if (arg instanceof Promise) {
      let state = await promiseState(arg);
      divconsole.innerHTML += ` Promise { &lt;state&gt;: "${ state.state }"${ state.state === "fulfilled" ? ', &lt;value&gt;: ' + state.value : '' } }<br>`;
    } else if (typeof arg === 'object') {
      divconsole.innerHTML += 'Object:  ' + JSON.stringify(arg) + '<br>';
    }
    else {
      divconsole.innerHTML += 'Other' +  JSON.stringify(arg) +':  <br>';
    }
    // add more else-ifs to handle strings, numbers, booleans, ... etc

  }
    ccount++
  divconsole.innerHTML += '<br>';

}
console.error = async function(...args) {
  divconsole.innerHTML += String(ccount) +' CONSOLE ERROR' + ':  <br>';
  for (let arg of args) {
    if (arg instanceof Promise) {
      let state = await promiseState(arg);
      divconsole.innerHTML += ` Promise { &lt;state&gt;: "${ state.state }"${ state.state === "fulfilled" ? ', &lt;value&gt;: ' + state.value : '' } }<br>`;
    } else if (typeof arg === 'object') {
      divconsole.innerHTML += 'Object:  ' + JSON.stringify(arg) + '<br>';
    }
    else {
      divconsole.innerHTML += 'Other' +  JSON.stringify(arg) +':  <br>';
    }
    // add more else-ifs to handle strings, numbers, booleans, ... etc

  }
  divconsole.innerHTML += '<br>';
  ccount++
}
console.warn = async function(...args) {
  divconsole.innerHTML += String(ccount) +' CONSOLE WARNING' + ':  <br>';
  for (let arg of args) {
    if (arg instanceof Promise) {
      let state = await promiseState(arg);
      divconsole.innerHTML += ` Promise { &lt;state&gt;: "${ state.state }"${ state.state === "fulfilled" ? ', &lt;value&gt;: ' + state.value : '' } }<br>`;
    } else if (typeof arg === 'object') {
      divconsole.innerHTML += 'Object:  ' + JSON.stringify(arg) + '<br>';
    }
    else {
      divconsole.innerHTML += 'Other' +  JSON.stringify(arg) +':  <br>';
    }
    // add more else-ifs to handle strings, numbers, booleans, ... etc
  }
  divconsole.innerHTML += '<br>';
  ccount++
}

After I peppered extra console.logs in the code, the desktop the full readout is:

0 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"err => {\n if (err) return reject(err);\n return resolve();\n }":
0 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"function() {\n [native code]\n}":
Object: {"_events":{},"_eventsCount":2,"opening":false,"opened":false,"closing":false,"closed":false,"actives":0,"opts":{"sparse":true},"_replicationStreams":[],"cache":{"maxSize":1000,"gcable":{"oldest":null,"latest":null,"length":0},"entries":{}},"_masterKey":null,"_id":{"type":"Buffer","data":[129,100,107,63,195,108,69,45]}}

1 CONSOLE LOG:
Other"inready func":
Other"function onReady(err) {\n if (err) return self.emit('error', err);\n self.emit('ready');\n if (self._contentStates.has(self.db.feed)) return;\n\n self._getContent(self.db.feed, noop);\n }":

2 CONSOLE LOG:
Other"InOPEN ":
Other"[object Object]":
Other"undefined":

3 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"function onReady(err) {\n if (err) return self.emit('error', err);\n self.emit('ready');\n if (self._contentStates.has(self.db.feed)) return;\n\n self._getContent(self.db.feed, noop);\n }":
3 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"err => {\n if (err) return reject(err);\n return resolve();\n }":
3 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"function() {\n [native code]\n}":
Object: {"_events":{"feed":[null,null],"error":[null,null]},"_eventsCount":2,"opening":false,"opened":true,"closing":false,"closed":false,"actives":0,"opts":{"sparse":true},"_replicationStreams":[],"cache":{"maxSize":1000,"gcable":{"oldest":null,"latest":null,"length":0},"entries":{}},"_masterKey":{"type":"Buffer","data":[49,245,17,59,92,60,145,222,131,191,186,4,183,83,226,14,87,37,205,210,42,209,21,102,190,98,0,252,235,210,244,101]},"_id":{"type":"Buffer","data":[129,100,107,63,195,108,69,45]}}

4 CONSOLE LOG:
Other"inready func":
Other"() => {\n const key = drive.key;\n const stringKey = key.toString('hex');\n drives.set(stringKey, wrappedDrive);\n }":

5 CONSOLE LOG:
Other"InOPEN ":
Other"[object Object]":
Other"undefined":

6 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"() => {\n const key = drive.key;\n const stringKey = key.toString('hex');\n drives.set(stringKey, wrappedDrive);\n }":
6 CONSOLE LOG:
Other"inready func":
Other"() => {\n const {\n discoveryKey = drive.discoveryKey,\n lookup = true,\n announce = true\n } = opts; // Don't advertise if we're not looking up or announcing\n\n if (!lookup && !announce) return;\n swarm.configure(discoveryKey, {\n lookup,\n announce\n });\n }":

7 CONSOLE LOG:
Other"InOPEN ":
Other"[object Object]":
Other"undefined":

8 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"() => {\n const {\n discoveryKey = drive.discoveryKey,\n lookup = true,\n announce = true\n } = opts; // Don't advertise if we're not looking up or announcing\n\n if (!lookup && !announce) return;\n swarm.configure(discoveryKey, {\n lookup,\n announce\n });\n }":
8 CONSOLE LOG:
Other"in HyperDrivePromiseGET":
Other"{\"_events\":{},\"_eventsCount\":1,\"opening\":true,\"opened\":false,\"closing\":false,\"closed\":false,\"actives\":0,\"opts\":{\"sparse\":true,\"persist\":true,\"namespace\":\"drive\"},\"key\":null,\"discoveryKey\":null,\"live\":true,\"sparse\":true,\"sparseMetadata\":true,\"subtype\":\"hyperdrive\",\"promises\":{},\"_namespace\":\"drive\",\"corestore\":{\"_events\":{},\"_eventsCount\":0,\"opening\":true,\"opened\":false,\"closing\":false,\"closed\":false,\"actives\":0,\"name\":\"drive\",\"inner\":{\"_events\":{\"feed\":[null,null],\"error\":[null,null]},\"_eventsCount\":2,\"opening\":false,\"opened\":true,\"closing\":false,\"closed\":false,\"actives\":0,\"opts\":{\"sparse\":true},\"_replicationStreams\":[],\"cache\":{\"maxSize\":1000,\"gcable\":{\"oldest\":null,\"latest\":null,\"length\":0},\"entries\":{}},\"_masterKey\":{\"type\":\"Buffer\",\"data\":[49,245,17,59,92,60,145,222,131,191,186,4,183,83,226,14,87,37,205,210,42,209,21,102,190,98,0,252,235,210,244,101]},\"_id\":{\"type\":\"Buffer\",\"data\":[129,100,107,63,195,108,69,45]}},\"_parent\":{\"_events\":{},\"_eventsCount\":0,\"opening\":false,\"opened\":true,\"closing\":false,\"closed\":false,\"actives\":0,\"name\":\"default\",\"_isNamespaced\":false,\"_openedCores\":{}},\"_isNamespaced\":true,\"_openedCores\":{}},\"metadata\":null,\"tags\":{},\"isCheckout\":false,\"_contentStates\":{\"loading\":{},\"cache\":{}},\"_fds\":[],\"_writingFds\":{},\"_unlistens\":[],\"_unmirror\":null,\"_metadataOpts\":{\"key\":null,\"sparse\":true}}":
Other"\"then\"":

9 CONSOLE LOG:
Other"in HyperDrivePromise typeof value is: undefined":

10 CONSOLE LOG:
Other"value":
Otherundefined:

drive created
11 CONSOLE LOG:
Other"in HyperDrivePromiseGET":
Other"{\"_events\":{},\"_eventsCount\":1,\"opening\":true,\"opened\":false,\"closing\":false,\"closed\":false,\"actives\":0,\"opts\":{\"sparse\":true,\"persist\":true,\"namespace\":\"drive\"},\"key\":null,\"discoveryKey\":null,\"live\":true,\"sparse\":true,\"sparseMetadata\":true,\"subtype\":\"hyperdrive\",\"promises\":{},\"_namespace\":\"drive\",\"corestore\":{\"_events\":{},\"_eventsCount\":0,\"opening\":true,\"opened\":false,\"closing\":false,\"closed\":false,\"actives\":0,\"name\":\"drive\",\"inner\":{\"_events\":{\"feed\":[null,null],\"error\":[null,null]},\"_eventsCount\":2,\"opening\":false,\"opened\":true,\"closing\":false,\"closed\":false,\"actives\":0,\"opts\":{\"sparse\":true},\"_replicationStreams\":[],\"cache\":{\"maxSize\":1000,\"gcable\":{\"oldest\":null,\"latest\":null,\"length\":0},\"entries\":{}},\"_masterKey\":{\"type\":\"Buffer\",\"data\":[49,245,17,59,92,60,145,222,131,191,186,4,183,83,226,14,87,37,205,210,42,209,21,102,190,98,0,252,235,210,244,101]},\"_id\":{\"type\":\"Buffer\",\"data\":[129,100,107,63,195,108,69,45]}},\"_parent\":{\"_events\":{},\"_eventsCount\":0,\"opening\":false,\"opened\":true,\"closing\":false,\"closed\":false,\"actives\":0,\"name\":\"default\",\"_isNamespaced\":false,\"_openedCores\":{}},\"_isNamespaced\":true,\"_openedCores\":{}},\"metadata\":null,\"tags\":{},\"isCheckout\":false,\"_contentStates\":{\"loading\":{},\"cache\":{}},\"_fds\":[],\"_writingFds\":{},\"_unlistens\":[],\"_unmirror\":null,\"_metadataOpts\":{\"key\":null,\"sparse\":true}}":
Other"\"ready\"":

12 CONSOLE LOG:
Other"in HyperDrivePromise typeof value is: function":

13 CONSOLE LOG:
Other"value":
Otherundefined:

14 CONSOLE LOG:
Other"in HyperDrivePromisevalue === function":
Other"ready":

15 CONSOLE LOG:
Other"in HyperDrivePromis._getMethod, propKey: ":
Other"ready":
Other"true":

16 CONSOLE LOG:
Other"in HyperDrivePromis._getMethod.method,returning":
Other"{}":
Other"(...args) => {\n // We keep suporting the callback style if we get a callback.\n console.log( 'In method ' + String(propKey) , JSON.stringify(args))\n if (typeof args[args.length - 1] === 'function') {\n return Reflect.apply(func, target, args);\n }\n\n return new Promise((resolve, reject) => {\n console.log('In Promise** '+String(args))\n args.push((err, ...result) => {\n console.log('In Promiseresolving 0 ' , String(err) ,String(result))\n if (err) return reject(err);\n if (result.length > 1) {\n console.log('In Promiseresolving i ' , String(err), String(result))\n resolve(result);\n } else {\n console.log( 'In Promiseresolving ii ',String(err),String(result))\n resolve(result[0]);//resolve(result[0]);\n }\n });\n console.log( 'applying args to func ' , String(args),JSON.stringify(target, getCircularReplacer()), 'func', String(func))\n Reflect.apply(func, target, args);\n });\n }":

17 CONSOLE LOG:
Object: {}

18 CONSOLE LOG:
Other"In method ready":
Other"[]":

19 CONSOLE LOG:
Other"In Promise** ":

20 CONSOLE LOG:
Other"applying args to func ":
Other"(err, ...result) => {\n console.log('In Promiseresolving 0 ' , String(err) ,String(result))\n if (err) return reject(err);\n if (result.length > 1) {\n console.log('In Promiseresolving i ' , String(err), String(result))\n resolve(result);\n } else {\n console.log( 'In Promiseresolving ii ',String(err),String(result))\n resolve(result[0]);//resolve(result[0]);\n }\n }":
Other"{\"_events\":{},\"_eventsCount\":1,\"opening\":true,\"opened\":false,\"closing\":false,\"closed\":false,\"actives\":0,\"opts\":{\"sparse\":true,\"persist\":true,\"namespace\":\"drive\"},\"key\":null,\"discoveryKey\":null,\"live\":true,\"sparse\":true,\"sparseMetadata\":true,\"subtype\":\"hyperdrive\",\"promises\":{},\"_namespace\":\"drive\",\"corestore\":{\"_events\":{},\"_eventsCount\":0,\"opening\":true,\"opened\":false,\"closing\":false,\"closed\":false,\"actives\":0,\"name\":\"drive\",\"inner\":{\"_events\":{\"feed\":[null,null],\"error\":[null,null]},\"_eventsCount\":2,\"opening\":false,\"opened\":true,\"closing\":false,\"closed\":false,\"actives\":0,\"opts\":{\"sparse\":true},\"_replicationStreams\":[],\"cache\":{\"maxSize\":1000,\"gcable\":{\"oldest\":null,\"latest\":null,\"length\":0},\"entries\":{}},\"_masterKey\":{\"type\":\"Buffer\",\"data\":[49,245,17,59,92,60,145,222,131,191,186,4,183,83,226,14,87,37,205,210,42,209,21,102,190,98,0,252,235,210,244,101]},\"_id\":{\"type\":\"Buffer\",\"data\":[129,100,107,63,195,108,69,45]}},\"_parent\":{\"_events\":{},\"_eventsCount\":0,\"opening\":false,\"opened\":true,\"closing\":false,\"closed\":false,\"actives\":0,\"name\":\"default\",\"_isNamespaced\":false,\"_openedCores\":{}},\"_isNamespaced\":true,\"_openedCores\":{}},\"metadata\":null,\"tags\":{},\"isCheckout\":false,\"_contentStates\":{\"loading\":{},\"cache\":{}},\"_fds\":[],\"_writingFds\":{},\"_unlistens\":[],\"_unmirror\":null,\"_metadataOpts\":{\"key\":null,\"sparse\":true}}":
Other"func":
Other"ready(cb) {\n console.log( 'inready func' ,String(cb))\n return this.open(cb);\n }":

21 CONSOLE LOG:
Other"inready func":
Other"(err, ...result) => {\n console.log('In Promiseresolving 0 ' , String(err) ,String(result))\n if (err) return reject(err);\n if (result.length > 1) {\n console.log('In Promiseresolving i ' , String(err), String(result))\n resolve(result);\n } else {\n console.log( 'In Promiseresolving ii ',String(err),String(result))\n resolve(result[0]);//resolve(result[0]);\n }\n }":

22 CONSOLE LOG:
Other"InOPEN ":
Other"[object Object]":
Other"undefined":

23 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"(err, ...result) => {\n console.log('In Promiseresolving 0 ' , String(err) ,String(result))\n if (err) return reject(err);\n if (result.length > 1) {\n console.log('In Promiseresolving i ' , String(err), String(result))\n resolve(result);\n } else {\n console.log( 'In Promiseresolving ii ',String(err),String(result))\n resolve(result[0]);//resolve(result[0]);\n }\n }":
23 CONSOLE LOG:
PROMISE{} Promise { <state>: "pending" }

24 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"function onerror(err) {\n if (err) self.emit('error', err);\n }":
24 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"err => {\n if (err) return done(err);\n /**\n * TODO: Update comment to reflect mounts.\n *\n * If a db is provided as input, ensure that a contentFeed is also provided, then return (this is a checkout).\n * If the metadata feed is writable:\n * If the metadata feed has length 0, then the db should be initialized with the content feed key as metadata.\n * Else, initialize the db without metadata and load the content feed key from the header.\n * If the metadata feed is readable:\n * Initialize the db without metadata and load the content feed key from the header.\n */\n\n if (self.metadata.writable && !self.metadata.length && !self.isCheckout) {\n initialize();\n } else {\n restore();\n }\n }":
24 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"err => {\n if (err) return done(err);\n self.metadata.has(0, (err, hasMetadataBlock) => {\n if (err) return done(err);\n if (hasMetadataBlock) self._getContent(self.db.feed, done);else done(null);\n });\n }":
24 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"err => {\n if (err) return reject(err);\n return resolve();\n }":
24 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"function (err) {\n if (err) return done(err);\n if (self.feed.length || !self.feed.writable) return done(null);\n self.feed.append(Header.encode({\n type: 'hypertrie',\n metadata: self.metadata,\n subtype: this.subtype\n }), done);\n\n function done(err) {\n if (err) return cb(err);\n if (self._checkout === -1) self._checkout = self.feed.length;\n self.id = self.feed.id;\n self.key = self.feed.key;\n self.discoveryKey = self.feed.discoveryKey;\n self.secretKey = self.feed.secretKey;\n self.opened = true;\n self.emit('ready');\n\n if (self.alwaysReconnect) {\n var from = self.feed.length;\n var active = null;\n self.feed.on('append', function () {\n if (!from) {\n from = self.feed.length;\n return;\n }\n\n if (active) active.destroy();\n self.emit('reconnecting');\n const r = active = self.reconnect(from);\n active.next(function loop(err, data) {\n if (r !== active) return;\n\n if (err || !data) {\n active = null;\n from = self.feed.length;\n if (!err) self.emit('reconnected');\n return;\n }\n\n active.next(loop);\n });\n });\n }\n\n cb(null);\n }\n }":
24 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"function onerror(err) {\n if (err) self.emit('error', err);\n }":
24 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"err => {\n if (err) return cb(err);\n this.emit('content-feed', feed);\n return cb(null, new ContentState(feed));\n }":
24 CONSOLE LOG:
Other"In Promiseresolving 0 ":
Other"null":
Other"":

25 CONSOLE LOG:
Other"In Promiseresolving ii ":
Other"null":
Other"":

26 CONSOLE LOG:
drive ready
drive key = b75f95066b2eba4b009e0d95ea0a1a4900c085f887aae304f16b43eefa19b861
29 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"function onerror(err) {\n if (err) self.emit('error', err);\n }":
29 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"() => {\n const key = core.key;\n const stringKey = key.toString('hex');\n cores.set(stringKey, wrappedCore);\n }":
29 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"() => {\n const {\n discoveryKey = core.discoveryKey,\n lookup = true,\n announce = true\n } = opts; // Don't advertise if we're not looking up or announcing\n\n if (!lookup && !announce) return;\n swarm.configure(discoveryKey, {\n announce,\n lookup\n });\n }":
29 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"(err, ...result) => {\n if (err) return reject(err);\n\n if (result.length > 1) {\n resolve(result);\n } else {\n resolve(result[0]);\n }\n }":
29 CONSOLE LOG:
Other"Nanoresource.prototype.open ":
Other"(err, ...result) => {\n if (err) return reject(err);\n\n if (result.length > 1) {\n resolve(result);\n } else {\n resolve(result[0]);\n }\n }":
Promise { <state>: "fulfilled", <value>: undefined }
4c656554 commented 3 years ago

An update.

The last thing I can get to log is the nanoresource's onopen function. My guess is with ready as a callback.

RangerMauve commented 3 years ago

Just to confirm, hypersdk = await window.datSDK({persist: false}); still results in a stuck promise, right?

4c656554 commented 3 years ago

Yes it does. Also, to confirm, it seems this problem is not present on Android (sample size = 1).

4c656554 commented 3 years ago

A further update. Someone wise suggested setting window.onerror, and I got:

"Message: TypeError: Underlying ArrayBuffer has been detached from the view - URL: http://url/lib/dat-sdk-bundle.js - Line: 61541 - Column: 19 - Error object: {\"line\":61541,\"column\":19,\"sourceURL\":\"http://url/new/lib/dat-sdk-bundle.js\"}":

line 61541 is this.wasm = wasm in the Sha512() function

(note this line no may be different to standard lib as I've added console.logs)

4c656554 commented 3 years ago

Here is the revised script with window.WebAssembly = undefined;

<!DOCTYPE html><html>
<head>
  <script src="lib/dat-sdk-bundle.js"></script>
 <meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>

<script>

window.WebAssembly = undefined;
const pause =  sec => new Promise(r => setTimeout(r, 1000 * sec))

let hypersdk
let drive
let core
let ccount = 0

//override console ops
;(async function(){
  await new Promise(resolve => document.addEventListener('DOMContentLoaded', resolve));

  let divconsole = document.getElementById('main');

  function promiseState(p) {
    const t = {};
    return Promise.race([p, t])
      .then(v => (v === t)? { state: "pending" } : { state: "fulfilled", value: v }, () => { state: "rejected" });
}

console.log = async function(...args) {
  divconsole.innerHTML += String(ccount) +' CONSOLE LOG' + ':  <br>';
  for (let arg of args) {
    if (arg instanceof Promise) {
      let state = await promiseState(arg);
      divconsole.innerHTML += ` Promise { &lt;state&gt;: "${ state.state }"${ state.state === "fulfilled" ? ', &lt;value&gt;: ' + state.value : '' } }<br>`;
    } else if (typeof arg === 'object') {
      divconsole.innerHTML += 'Object:  ' + JSON.stringify(arg, getCircularReplacer()) + '<br>';
    }
    else {
      divconsole.innerHTML += 'Other' +  JSON.stringify(arg) +':  <br>';
    }
    // add more else-ifs to handle strings, numbers, booleans, ... etc

  }
    ccount++
  divconsole.innerHTML += '<br>';

}
console.error = async function(...args) {
  divconsole.innerHTML += String(ccount) +' CONSOLE ERROR' + ':  <br>';
  for (let arg of args) {
    if (arg instanceof Promise) {
      let state = await promiseState(arg);
      divconsole.innerHTML += ` Promise { &lt;state&gt;: "${ state.state }"${ state.state === "fulfilled" ? ', &lt;value&gt;: ' + state.value : '' } }<br>`;
    } else if (typeof arg === 'object') {
      divconsole.innerHTML += 'Object:  ' + JSON.stringify(arg) + '<br>';
    }
    else {
      divconsole.innerHTML += 'Other' +  JSON.stringify(arg) +':  <br>';
    }
    // add more else-ifs to handle strings, numbers, booleans, ... etc

  }
  divconsole.innerHTML += '<br>';
  ccount++
}
console.warn = async function(...args) {
  divconsole.innerHTML += String(ccount) +' CONSOLE WARNING' + ':  <br>';
  for (let arg of args) {
    if (arg instanceof Promise) {
      let state = await promiseState(arg);
      divconsole.innerHTML += ` Promise { &lt;state&gt;: "${ state.state }"${ state.state === "fulfilled" ? ', &lt;value&gt;: ' + state.value : '' } }<br>`;
    } else if (typeof arg === 'object') {
      divconsole.innerHTML += 'Object:  ' + JSON.stringify(arg) + '<br>';
    }
    else {
      divconsole.innerHTML += 'Other' +  JSON.stringify(arg) +':  <br>';
    }
    // add more else-ifs to handle strings, numbers, booleans, ... etc
  }
  divconsole.innerHTML += '<br>';
  ccount++
}

  window.onerror = function (msg, url, lineNo, columnNo, error) {
  var string = msg.toLowerCase();
  var substring = "script error";
  if (string.indexOf(substring) > -1){
    alert('Script Error: See Browser Console for Detail');
  } else {
    var message = [
      'Message: ' + msg,
      'URL: ' + url,
      'Line: ' + lineNo,
      'Column: ' + columnNo,
      'Error object: ' + JSON.stringify(error)
    ].join(' - ');

    console.log(message);
  }

  return false;
};

// Runs through initialisation of hyper core and hyperdrive, puts status messages in html doc.
  document.getElementById('main').innerHTML += 'dom loaded<br>'

  hypersdk = await window.datSDK({persist: false} ).catch(e=>{document.getElementById('setup').innerHTML += 'Error on loading:<br>' + String(e)});
  document.getElementById('main').innerHTML += 'hypersdk loaded<br>'

  drive = await hypersdk.Hyperdrive('main')
  console.log('drive22',drive)
  document.getElementById('main').innerHTML += 'drive created<br>' //+String(drive.ready()) Note adding this shows that mobile browser recognises ready() as promise obj
  let readypromise = drive.ready().catch(error => console.log(error));
  console.log(readypromise)
  document.getElementById('main').innerHTML += 'PROMISE' + JSON.stringify(readypromise, getCircularReplacer())
  await pause(3)
  await readypromise//drive.ready()//.then((res,rej)=>{console.log('result:  ',res,rej)})//.catch(e=>{document.getElementById('setup').innerHTML += 'Error on awiating drive:<br>' + String(e)});

console.log(readypromise)
  document.getElementById('main').innerHTML += 'drive ready<br>'
  document.getElementById('main').innerHTML += 'drive key = ' + drive.key.toString('hex') +'<br>'

})();

</script>
<!-- main container div -->
<div id="main" style="width:100%;height:auto;display:grid;grid-template: auto auto auto/ auto;background-color:lavender;">
</div>

</body></html>
RangerMauve commented 3 years ago

Ah! You need to have a script tag getting rid of WASM before the script tag for the SDK. Something like this:

(If I'm correct that this is a WASM issue)

<!DOCTYPE html>
<script>window.WebAssembly = undefined;</script>
<script src="lib/dat-sdk-bundle.js"></script>
 <meta name="viewport" content="width=device-width, initial-scale=1">
4c656554 commented 3 years ago

hmmm, error has gone but promise still does not resolve :thinking:

RangerMauve commented 2 years ago

The SDK has changed a bunch since this happened, so it may be working again.