Skip to content

Commit

Permalink
feat: open headless
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianJiang2021 authored and CarlLiu2023 committed Sep 8, 2023
1 parent 7370644 commit 8b15d3b
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 57 deletions.
163 changes: 110 additions & 53 deletions apps/storefront/src/buyerPortal.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,123 @@
// const str = '<script>
// window.b3CheckoutConfig = {
// routes: {
// dashboard: '/account.php?action=order_status'
// }
// }
// window.B3 = {
// setting: {
// 'store_hash': `{{settings.store_hash}}`,
// 'b2b_url': 'https://staging-v2.bundleb2b.net',
// 'captcha_setkey': '6LdGN_sgAAAAAGYFg1lmVoakQ8QXxbhWqZ1GpYaJ',
// },
// 'dom.checkoutRegisterParentElement': '#checkout-app',
// 'dom.registerElement': '[href^="/login.php"], #checkout-customer-login',
// 'dom.openB3Checkout': 'checkout-customer-continue',
// 'before_login_goto_page': '/account.php?action=order_status',
// 'checkout_super_clear_session': 'true',
// 'dom.navUserLoginElement': '.navUser-item.navUser-item--account',
const mode: string = import.meta.env.MODE

// }
// </script>
interface ScriptNodeChildren extends HTMLScriptElement {
dataSrc?: string
crossorigin?: string | boolean
}

interface GraphqlOriginProps {
[key: string]: string
}

// <script crossorigin src="https://cdn.bundleb2b.net/b2b/staging/storefront/polyfills-legacy.158d896b.js"></script>
// <script crossorigin src="https://cdn.bundleb2b.net/b2b/staging/storefront/index-legacy.40470c56.js"></script>
// '
const graphqlOrigin: GraphqlOriginProps = {
development: 'https://staging-v2.bundleb2b.net',
staging: 'https://staging-v2.bundleb2b.net',
production: 'https://api.bundleb2b.net',
}

function init() {
const insertScript = (scriptString: string) => {
// const scriptElement = document.createElement('script');
// scriptElement.innerHTML = scriptString;

// const {body} = document;
const doc = new DOMParser().parseFromString(scriptString, 'text/html')
const scriptNodes = doc.querySelectorAll('script')

// body.appendChild(scriptElement);
if (scriptNodes.length) {
const body: HTMLBodyElement | null = document.querySelector('body')

document.body.innerHTML += scriptString
}
async function getScriptContent(originurl: string) {
console.log(originurl)
const xxx = `<script>console.log('test123')</script>
<script>console.log('test456')</script>
`
const oldScriptNodes = document.querySelectorAll(
'.headless-buyerPortal-id'
)
if (oldScriptNodes.length > 0) {
oldScriptNodes.forEach((oldNode) => {
oldNode.parentNode?.removeChild(oldNode)
})
}
scriptNodes.forEach((node: ScriptNodeChildren, index: number) => {
const nodeInnerHTML = node?.innerHTML || ''
const nodeSrc = node?.src || ''
const dataSrc = node?.dataSrc || ''
const type = node?.type || ''
const crossorigin = node?.crossorigin || ''
const id = node?.id || ''
const scriptElement = document.createElement('script')
scriptElement.innerHTML = nodeInnerHTML
scriptElement.className = 'headless-buyerPortal-id'
if (nodeSrc) scriptElement.setAttribute('src', nodeSrc)
if (dataSrc) scriptElement.setAttribute('data-src', dataSrc)
if (type) {
scriptElement.setAttribute('type', 'module')
} else if (index !== 0) {
scriptElement.noModule = true
}
if (id) scriptElement.setAttribute('id', id)

insertScript(xxx)
// const queryParams = new URLSearchParams({
// url: originurl,
// });
if (crossorigin) scriptElement.setAttribute('crossorigin', 'true')

// const url = `https://api.example.com/data?${queryParams}`;
// fetch(url).then(response => {
// if (!response.ok) {
// throw new Error('Network response was not ok');
// }
// return response.json();
// })
// .then(data => {
// console.log(data);
if (body) {
body.appendChild(scriptElement)
}
})
}
}

// insertScript(data)
// })
// .catch(error => {
// console.error('There was a problem with the fetch operation:', error);
// });
async function getScriptContent(originUrl: string) {
const params: {
siteUrl: string
storehash: string
channelId: string | number
} = {
siteUrl: originUrl,
storehash: '',
channelId: '',
}
const scriptNodes = document.querySelectorAll('script')
if (scriptNodes && scriptNodes.length > 0) {
scriptNodes.forEach((node) => {
if (node.src.includes('/headless.js')) {
if (node.dataset) {
const data = node.dataset
params.storehash = data.storehash || ''
params.channelId = data.channelid || ''
}
}
})
}
const data = {
query: `
{
storefrontScript(
storeHash: "${params.storehash}"
channelId: ${params.channelId}
siteUrl: "${params.siteUrl}"
) {
script
storeHash
channelId
}
}`,
}
const init = {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify(data),
}
fetch(`${graphqlOrigin[mode]}/graphql`, init)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
})
.then((data) => {
const {
data: { storefrontScript },
} = data
insertScript(storefrontScript.script)
})
.catch((error) => {
console.error('There was a problem with the fetch operation:', error)
})
}

async function analyzeScript() {
Expand Down
6 changes: 2 additions & 4 deletions apps/storefront/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,12 @@ export default defineConfig(({ mode }) => {
rollupOptions: {
input: {
index: 'src/main.ts',
buyerPortal: 'src/buyerPortal.ts',
headless: 'src/buyerPortal.ts',
},
output: {
entryFileNames(info) {
const { name } = info
return name.includes('buyerPortal')
? '[name].js'
: '[name].[hash].js'
return name.includes('headless') ? '[name].js' : '[name].[hash].js'
},
},
onwarn(warning, warn) {
Expand Down

0 comments on commit 8b15d3b

Please sign in to comment.