url-parser.ts
2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Parsed Figma URL information.
*
* Shared between the orchestration backend (apps/server) and the web UI so both
* validate Figma links with the exact same logic. The implementation is pure
* (only `URL` / `decodeURIComponent`) and has no dependency on the `coderio`
* engine, so it is safe to bundle into the browser without leaking native deps.
*/
export interface FigmaUrlInfo {
/** The ID of the Figma file */
fileId: string | null;
/** The name of the Figma file */
name: string;
/** The ID of the Figma node */
nodeId: string | null;
/** The name of the project */
projectName: string | null;
}
/**
* Parse Figma URL and extract fileId, name, and nodeId in one pass.
* @example
* parseFigmaUrl('https://www.figma.com/design/aONcu8L82l1PdcT304Q8Za/Intern?node-id=0-495')
* // Returns: { fileId: 'aONcu8L82l1PdcT304Q8Za', name: 'intern', nodeId: '0-495' }
*/
export const parseFigmaUrl = (url: string): FigmaUrlInfo => {
let fileId: string | null = null;
let name = 'untitled';
let nodeId: string | null = null;
try {
const urlObj = new URL(decodeURIComponent(url));
const pathParts = urlObj.pathname.split('/').filter(Boolean);
if (pathParts.length >= 3) {
fileId = pathParts[pathParts.length - 2] || null;
const fileName = pathParts[pathParts.length - 1];
name = slugifyFigmaName(fileName ?? 'untitled');
name = name.length > 20 ? name.substring(0, 20) : name;
}
nodeId = urlObj.searchParams.get('node-id') || null;
nodeId = nodeId ? nodeId.replace(/-/g, ':') : null;
} catch {}
if (!fileId || !nodeId) {
throw new Error('Invalid Figma URL');
}
return { fileId, name, nodeId, projectName: `${name}_${nodeId.replace(/:/g, '_')}` };
};
/**
* Turn a Figma file name into a filesystem / package-safe slug.
*
* The Figma URL is already percent-decoded once by `new URL(decodeURIComponent(url))`,
* but some URLs are double-encoded (e.g. `%25E3%2580%2590` instead of `%E3%80%90`).
* We fully decode the name first, then keep unicode letters/digits and replace every
* other character (spaces, brackets, `%`, etc.) with a single underscore.
*/
function slugifyFigmaName(raw: string): string {
let decoded = raw;
try {
let prev: string;
do {
prev = decoded;
decoded = decodeURIComponent(prev);
} while (decoded !== prev);
} catch {
/* leave as the last successfully decoded value */
}
const slug = decoded
.normalize('NFKC')
.replace(/[^\p{L}\p{N}]+/gu, '_')
.replace(/^_+|_+$/g, '')
.toLowerCase();
return slug || 'untitled';
}