Skip to content

Conversation

@zhiyuanliang-ms
Copy link
Member

@zhiyuanliang-ms zhiyuanliang-ms commented Aug 17, 2024

Why this PR?

node:crypto is not recognizable in browser environment.

image

Visible changes

The evaluate method of targeting filter becomes async because crypto.subtle.digest is async.

Add testcase for browser scenario. Use playwright to simulate browser and build the package to umd style so that user can consume the package through

<script src="https://unpkg.com/@microsoft/[email protected]/dist/umd/index.js"></script>
<script>
const fm = new FeatureManagement.FeatureManager();
</script>

@Eskibear
Copy link
Member

something like below would possibly make the code compatible with browser and nodejs:

async function sha256(message) {
    let crypto;

    // Check for browser environment
    if (typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
        crypto = window.crypto;
    } 
    // Check for Node.js environment
    else if (typeof global !== 'undefined' && global.crypto) {
        crypto = global.crypto;
    } 
    // Fallback to native Node.js crypto module
    else {
        crypto = require('crypto'); // maybe wrap with try-catch in case of uncovered runtimes... or you maybe want to fail the program because there's no way to calc hash then
    }

    // In the browser, use crypto.subtle.digest
    if (crypto.subtle) {
        const encoder = new TextEncoder();
        const data = encoder.encode(message);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        return hashHex;
    } 
    // In Node.js, use the crypto module's hash function
    else {
        return crypto.createHash('sha256').update(message).digest('hex');
    }
}

// Example usage:
sha256('Hello, world!').then(hash => {
    console.log('SHA-256 hash:', hash);
});

@zhiyuanliang-ms zhiyuanliang-ms merged commit 85db328 into main Aug 26, 2024
@zhiyuanliang-ms zhiyuanliang-ms deleted the zhiyuanliang/update-targeting-filter branch August 26, 2024 05:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants