Skip to content

Commit f7fd803

Browse files
committed
feat: improve rewrite rules
1 parent b2cba32 commit f7fd803

File tree

2 files changed

+57
-14
lines changed

2 files changed

+57
-14
lines changed

rewrite/config.ts

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,30 @@
1-
export const SRC_PATTERN = /\/figma_app/
2-
3-
export const REWRITE_PATTERN = /\.appModel\.isReadOnly/g
4-
5-
export const REWRITE_REPLACER = '.appModel.__isReadOnly__'
6-
7-
const MARKERS = ['.appModel.isReadOnly']
1+
export type Replacement = {
2+
pattern: string | RegExp
3+
replacer: string | ((...args: any[]) => string)
4+
}
85

9-
export function matchFile(src: string, content: string) {
10-
return SRC_PATTERN.test(src) && MARKERS.every((marker) => content.includes(marker))
6+
export type Group = {
7+
markers?: string[]
8+
replacements: Replacement[]
119
}
10+
11+
export const GROUPS: Group[] = [
12+
{
13+
markers: ['.appModel.isReadOnly'],
14+
replacements: [
15+
{
16+
pattern: /\.appModel\.isReadOnly/g,
17+
replacer: '.appModel.__isReadOnly__'
18+
}
19+
]
20+
},
21+
{
22+
markers: ['dispnf.fyufotjpo;00', 'np{.fyufotjpo;00'],
23+
replacements: [
24+
{
25+
pattern: /dispnf\.fyufotjpo;00|np{\.fyufotjpo;00/g,
26+
replacer: 'FIGMA_PLEASE_STOP'
27+
}
28+
]
29+
}
30+
]

rewrite/figma.ts

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { matchFile, REWRITE_PATTERN, REWRITE_REPLACER } from './config'
1+
import type { Group } from './config'
2+
import { GROUPS } from './config'
23

34
async function rewriteScript() {
45
const current = document.currentScript as HTMLScriptElement
@@ -13,15 +14,38 @@ async function rewriteScript() {
1314
current.replaceWith(script)
1415
}
1516

17+
function applyGroup(content: string, group: Group) {
18+
const markers = group.markers || []
19+
20+
if (!markers.every((marker) => content.includes(marker))) {
21+
return content
22+
}
23+
24+
let out = content
25+
for (const { pattern, replacer } of group.replacements) {
26+
if (typeof pattern === 'string') {
27+
// @ts-ignore
28+
out = out.replaceAll(pattern, replacer)
29+
} else {
30+
// @ts-ignore
31+
out = out.replace(pattern, replacer)
32+
}
33+
}
34+
return out
35+
}
36+
1637
try {
17-
let content = await (await fetch(src)).text()
38+
const original = await (await fetch(src)).text()
39+
let content = original
40+
41+
for (const group of GROUPS) {
42+
content = applyGroup(content, group)
43+
}
1844

19-
if (matchFile(src, content)) {
20-
content = content.replace(REWRITE_PATTERN, REWRITE_REPLACER)
45+
if (content !== original) {
2146
console.log(`Rewrote script: ${src}`)
2247
}
2348

24-
// delete window.figma may throw Error in strict mode
2549
content = content.replaceAll('delete window.figma', 'window.figma = undefined')
2650

2751
Object.defineProperty(document, 'currentScript', {

0 commit comments

Comments
 (0)