/ shared / components / src / utils / sanitize.ts
sanitize.ts
 1  // Take care with < (which has special meaning inside script tags)
 2  // See: https://github.com/sveltejs/kit/blob/ff9a27b4/packages/kit/src/runtime/server/page/serialize_data.js#L4-L28
 3  const replacements = {
 4      '<': '\\u003C',
 5      '\u2028': '\\u2028',
 6      '\u2029': '\\u2029',
 7  };
 8  
 9  const pattern = new RegExp(`[${Object.keys(replacements).join('')}]`, 'g');
10  
11  /**
12   * Serializes a POJO into a HTML <script> tag that can be read clientside by
13   * `deserializeServerData`.
14   *
15   * Use this to share data between serverside and clientside. Include the
16   * returned HTML in the response to a client to allow it to read this data.
17   *
18   * @param data data to serialize
19   * @returns serialized data (or empty string if serialization fails)
20   */
21  export function serializeJSONData(data: object): string {
22      try {
23          return JSON.stringify(data).replace(
24              pattern,
25              (match) => replacements[match],
26          );
27      } catch (e) {
28          // Don't let recursive data (or other non-serializable things) throw.
29          // We'd rather just let the serialize no-op to avoid breaking consumers.
30          return '';
31      }
32  }