Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(core&api)!: hide internal functions and reuse them in api.js & rename tauri module to primitives #7942

Merged
merged 18 commits into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changes/api-primitives.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tauri-apps/api': 'major:breaking'
---

Changed `tauri` module to `primitives` and removed the undocumented `invoke` export from the root module.
5 changes: 5 additions & 0 deletions .changes/invoke-system-refactor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri": patch:breaking
---

The initialization script for `Builder::invoke_system` now must initialize the `window.__TAURI_INTERNALS__.postMessage` function instead of `window.__TAURI_POST_MESSAGE__`.
2 changes: 1 addition & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
node_modules
target
dist
/core/tauri/scripts
/core/tauri/scripts/bundle.global.js
/tooling/cli/templates
/tooling/cli/node
/tooling/cli/schema.json
Expand Down
3 changes: 1 addition & 2 deletions core/tauri-utils/src/pattern/isolation.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
* isolation frame -> main frame = isolation message
*/

;
(async function () {
;(async function () {
/**
* Sends the message to the isolation frame.
* @param {any} message
Expand Down
2 changes: 1 addition & 1 deletion core/tauri/scripts/bundle.global.js

Large diffs are not rendered by default.

125 changes: 64 additions & 61 deletions core/tauri/scripts/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,48 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

; (function () {
;(function () {
function uid() {
return window.crypto.getRandomValues(new Uint32Array(1))[0]
}

if (!window.__TAURI__) {
Object.defineProperty(window, '__TAURI__', {
value: {}
})
}

const osName = __TEMPLATE_os_name__

window.__TAURI__.convertFileSrc = function convertFileSrc(filePath, protocol = 'asset') {
const path = encodeURIComponent(filePath)
return osName === 'windows' || osName === 'android'
? `http://${protocol}.localhost/${path}`
: `${protocol}://localhost/${path}`
}
Object.defineProperty(window.__TAURI_INTERNALS__, 'convertFileSrc', {
value: function (filePath, protocol = 'asset') {
const path = encodeURIComponent(filePath)
return osName === 'windows' || osName === 'android'
? `http://${protocol}.localhost/${path}`
: `${protocol}://localhost/${path}`
}
})

window.__TAURI__.transformCallback = function transformCallback(
callback,
once
) {
var identifier = uid()
var prop = `_${identifier}`
Object.defineProperty(window.__TAURI_INTERNALS__, 'transformCallback', {
value: function transformCallback(callback, once) {
var identifier = uid()
var prop = `_${identifier}`

Object.defineProperty(window, prop, {
value: (result) => {
if (once) {
Reflect.deleteProperty(window, prop)
}
Object.defineProperty(window, prop, {
value: (result) => {
if (once) {
Reflect.deleteProperty(window, prop)
}

return callback && callback(result)
},
writable: false,
configurable: true
})
return callback && callback(result)
},
writable: false,
configurable: true
})

return identifier
}
return identifier
}
})

const ipcQueue = []
let isWaitingForIpc = false

function waitForIpc() {
if ('__TAURI_IPC__' in window) {
if ('ipc' in window.__TAURI_INTERNALS__) {
for (const action of ipcQueue) {
action()
}
Expand All @@ -57,35 +52,43 @@
}
}

window.__TAURI_INVOKE__ = function invoke(cmd, payload = {}, options) {
return new Promise(function (resolve, reject) {
const callback = window.__TAURI__.transformCallback(function (r) {
resolve(r)
delete window[`_${error}`]
}, true)
const error = window.__TAURI__.transformCallback(function (e) {
reject(e)
delete window[`_${callback}`]
}, true)
Object.defineProperty(window.__TAURI_INTERNALS__, 'invoke', {
value: function (cmd, payload = {}, options) {
return new Promise(function (resolve, reject) {
const callback = window.__TAURI_INTERNALS__.transformCallback(function (
r
) {
resolve(r)
delete window[`_${error}`]
},
true)
const error = window.__TAURI_INTERNALS__.transformCallback(function (
e
) {
reject(e)
delete window[`_${callback}`]
},
true)

const action = () => {
window.__TAURI_IPC__({
cmd,
callback,
error,
payload,
options
})
}
if (window.__TAURI_IPC__) {
action()
} else {
ipcQueue.push(action)
if (!isWaitingForIpc) {
waitForIpc()
isWaitingForIpc = true
const action = () => {
window.window.__TAURI_INTERNALS__.ipc({
cmd,
callback,
error,
payload,
options
})
}
}
})
}
if ('ipc' in window.__TAURI_INTERNALS__) {
action()
} else {
ipcQueue.push(action)
if (!isWaitingForIpc) {
waitForIpc()
isWaitingForIpc = true
}
}
})
}
})
})()
16 changes: 10 additions & 6 deletions core/tauri/scripts/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,29 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

; (function () {
;(function () {
__RAW_freeze_prototype__

__RAW_pattern_script__

__RAW_ipc_script__
; (function () {
__RAW_bundle_script__
})()

__RAW_core_script__

__RAW_event_initialization_script__
;(function () {
__RAW_bundle_script__
})()

if (window.ipc) {
window.__TAURI_INVOKE__('__initialized', { url: window.location.href })
window.__TAURI_INTERNALS__.invoke('__initialized', {
url: window.location.href
})
} else {
window.addEventListener('DOMContentLoaded', function () {
window.__TAURI_INVOKE__('__initialized', { url: window.location.href })
window.__TAURI_INTERNALS__.invoke('__initialized', {
url: window.location.href
})
})
}

Expand Down
72 changes: 34 additions & 38 deletions core/tauri/scripts/ipc-protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,9 @@
const fetchChannelDataCommand = __TEMPLATE_fetch_channel_data_command__
const useCustomProtocol = __TEMPLATE_use_custom_protocol__

Object.defineProperty(window, '__TAURI_POST_MESSAGE__', {
Object.defineProperty(window.__TAURI_INTERNALS__, 'postMessage', {
value: (message) => {
const {
cmd,
callback,
error,
payload,
options
} = message
const { cmd, callback, error, payload, options } = message

// use custom protocol for IPC if:
// - the flag is set to true or
Expand All @@ -25,18 +19,16 @@
// AND
// - when not on macOS with an https URL
if (
(
useCustomProtocol ||
(useCustomProtocol ||
cmd === fetchChannelDataCommand ||
!(osName === 'linux' || osName === 'android')
) &&
!((osName === 'macos' || osName === 'ios') && location.protocol === 'https:')
!(osName === 'linux' || osName === 'android')) &&
!(
(osName === 'macos' || osName === 'ios') &&
location.protocol === 'https:'
)
) {
const {
contentType,
data
} = processIpcMessage(payload)
fetch(window.__TAURI__.convertFileSrc(cmd, 'ipc'), {
const { contentType, data } = processIpcMessage(payload)
fetch(window.__TAURI_INTERNALS__.convertFileSrc(cmd, 'ipc'), {
method: 'POST',
body: data,
headers: {
Expand All @@ -45,29 +37,33 @@
'Tauri-Error': error,
...options?.headers
}
}).then((response) => {
const cb = response.ok ? callback : error
// we need to split here because on Android the content-type gets duplicated
switch ((response.headers.get('content-type') || '').split(',')[0]) {
case 'application/json':
return response.json().then((r) => [cb, r])
case 'text/plain':
return response.text().then((r) => [cb, r])
default:
return response.arrayBuffer().then((r) => [cb, r])
}
}).then(([cb, data]) => {
if (window[`_${cb}`]) {
window[`_${cb}`](data)
} else {
console.warn(`[TAURI] Couldn't find callback id {cb} in window. This might happen when the app is reloaded while Rust is running an asynchronous operation.`)
}
})
.then((response) => {
const cb = response.ok ? callback : error
// we need to split here because on Android the content-type gets duplicated
switch (
(response.headers.get('content-type') || '').split(',')[0]
) {
case 'application/json':
return response.json().then((r) => [cb, r])
case 'text/plain':
return response.text().then((r) => [cb, r])
default:
return response.arrayBuffer().then((r) => [cb, r])
}
})
.then(([cb, data]) => {
if (window[`_${cb}`]) {
window[`_${cb}`](data)
} else {
console.warn(
`[TAURI] Couldn't find callback id {cb} in window. This might happen when the app is reloaded while Rust is running an asynchronous operation.`
)
}
})
} else {
// otherwise use the postMessage interface
const {
data
} = processIpcMessage({
const { data } = processIpcMessage({
cmd,
callback,
error,
Expand Down
16 changes: 9 additions & 7 deletions core/tauri/scripts/ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
* @typedef {{callback: string, error: string, data: *}} IsolationPayload - a valid isolation payload
*/

;
(function () {
;(function () {
/**
* @type {string}
*/
const pattern = window.__TAURI_PATTERN__.pattern
const pattern = window.__TAURI_INTERNALS__.__TAURI_PATTERN__.pattern

/**
* @type {string}
Expand All @@ -33,7 +32,10 @@
* @return {boolean} - if the event was a valid isolation message
*/
function isIsolationMessage(event) {
if (typeof event.data === 'object' && typeof event.data.payload === 'object') {
if (
typeof event.data === 'object' &&
typeof event.data.payload === 'object'
) {
const keys = Object.keys(event.data.payload || {})
return (
keys.length > 0 &&
Expand Down Expand Up @@ -90,12 +92,12 @@
)
}

Object.defineProperty(window, '__TAURI_IPC__', {
Object.defineProperty(window.__TAURI_INTERNALS__, 'ipc', {
// todo: JSDoc this function
value: Object.freeze((message) => {
switch (pattern) {
case 'brownfield':
window.__TAURI_POST_MESSAGE__(message)
window.__TAURI_INTERNALS__.postMessage(message)
break

case 'isolation':
Expand Down Expand Up @@ -152,7 +154,7 @@
}

if (isIsolationMessage(event)) {
window.__TAURI_POST_MESSAGE__(event.data)
window.__TAURI_INTERNALS__.postMessage(event.data)
}
},
false
Expand Down
2 changes: 1 addition & 1 deletion core/tauri/scripts/pattern.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
return Object.freeze(object)
}

Object.defineProperty(window, '__TAURI_PATTERN__', {
Object.defineProperty(window.__TAURI_INTERNALS__, '__TAURI_PATTERN__', {
value: __tauriDeepFreeze(__TEMPLATE_pattern__)
})
})()
Loading