diff options
| author | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
|---|---|---|
| committer | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
| commit | bce557cc2dc767628bed6aac87301a1be7c5431b (patch) | |
| tree | b51a051228d01fe3306cd7626d4a96768aadb944 /shared/components/src/utils/sanitize.ts | |
init commit
Diffstat (limited to 'shared/components/src/utils/sanitize.ts')
| -rw-r--r-- | shared/components/src/utils/sanitize.ts | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/shared/components/src/utils/sanitize.ts b/shared/components/src/utils/sanitize.ts new file mode 100644 index 0000000..107a543 --- /dev/null +++ b/shared/components/src/utils/sanitize.ts @@ -0,0 +1,32 @@ +// Take care with < (which has special meaning inside script tags) +// See: https://github.com/sveltejs/kit/blob/ff9a27b4/packages/kit/src/runtime/server/page/serialize_data.js#L4-L28 +const replacements = { + '<': '\\u003C', + '\u2028': '\\u2028', + '\u2029': '\\u2029', +}; + +const pattern = new RegExp(`[${Object.keys(replacements).join('')}]`, 'g'); + +/** + * Serializes a POJO into a HTML <script> tag that can be read clientside by + * `deserializeServerData`. + * + * Use this to share data between serverside and clientside. Include the + * returned HTML in the response to a client to allow it to read this data. + * + * @param data data to serialize + * @returns serialized data (or empty string if serialization fails) + */ +export function serializeJSONData(data: object): string { + try { + return JSON.stringify(data).replace( + pattern, + (match) => replacements[match], + ); + } catch (e) { + // Don't let recursive data (or other non-serializable things) throw. + // We'd rather just let the serialize no-op to avoid breaking consumers. + return ''; + } +} |
