@deot/docs-playground 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,98 +0,0 @@
1
- import { transform } from "sucrase";
2
- import * as VueCompiler from "@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js";
3
- //#region packages/playground/src/core/runtime/local/compile/script.ts
4
- var { babelParse, walkIdentifiers, MagicString } = VueCompiler;
5
- var rewriteJsxAttributes = (code) => {
6
- const replacements = [];
7
- for (const match of code.matchAll(/\b([\w-]+:[\w-]+)\s*=\s*\{/g)) {
8
- let depth = 1;
9
- let quote = "";
10
- const start = match.index + match[0].length;
11
- let end = start;
12
- for (; end < code.length; end += 1) {
13
- const character = code[end];
14
- if (quote) {
15
- if (character === "\\") end += 1;
16
- else if (character === quote) quote = "";
17
- } else if ("\"'`".includes(character)) quote = character;
18
- else if (character === "{") depth += 1;
19
- else if (character === "}" && --depth === 0) break;
20
- }
21
- replacements.push({
22
- start: match.index,
23
- end: end + 1,
24
- text: `{...{${JSON.stringify(match[1])}: ${code.slice(start, end)}}}`
25
- });
26
- }
27
- for (const item of replacements.reverse()) code = code.slice(0, item.start) + item.text + code.slice(item.end);
28
- return code;
29
- };
30
- var removeImportedTypeExports = (code) => {
31
- const types = /* @__PURE__ */ new Set();
32
- for (const match of code.matchAll(/\bimport\s+type\s*\{([^}]+)\}\s*from\s*['"][^'"]+['"]/g)) for (const item of match[1].split(",")) types.add(item.trim().split(/\s+as\s+/).pop());
33
- return code.replace(/\bexport\s*\{([^}]+)\}(?!\s*from)/g, (_statement, names) => `export {${names.split(",").filter((item) => !types.has(item.trim().split(/\s+as\s+/)[0])).join(",")}}`);
34
- };
35
- /**
36
- * files 里的 `import.meta.env` 没有 Vite 注入,接到开发态占位对象上。
37
- * @param code 源码文本。
38
- * @param filename 当前虚拟文件名。
39
- * @returns 替换 `import.meta` 之后的源码。
40
- */
41
- var rewriteImportMeta = (code, filename) => {
42
- if (!code.includes("process") && !code.includes("import.meta")) return code;
43
- const source = new MagicString(code);
44
- let hasMeta = false;
45
- walkIdentifiers(babelParse(code, { sourceType: "module" }), (id, parent, parents) => {
46
- if (id.name === "import" && parent?.type === "MetaProperty") {
47
- source.overwrite(parent.start, parent.end, "import_meta");
48
- hasMeta = true;
49
- }
50
- const outer = parents[parents.length - 2];
51
- if (id.name === "process" && parent?.type === "MemberExpression" && parent.object === id && !parent.computed && parent.property.type === "Identifier" && parent.property.name === "env" && outer?.type === "MemberExpression" && outer.object === parent && !outer.computed && outer.property.type === "Identifier" && outer.property.name === "NODE_ENV") source.overwrite(outer.start, outer.end, JSON.stringify("development"));
52
- }, true);
53
- if (!hasMeta) return source.toString();
54
- const meta = {
55
- url: `playground://${filename}`,
56
- env: {
57
- MODE: "development",
58
- DEV: true,
59
- PROD: false,
60
- SSR: false
61
- }
62
- };
63
- return `var import_meta = ${JSON.stringify(meta)};\n${source}`;
64
- };
65
- /**
66
- * 将 TS / ESM 转成可被 `new Function('require','module','exports', code)` 执行的 CJS。
67
- * @param code 源码文本。
68
- * @param filename 当前虚拟文件名,用来判断是否按 TypeScript 转换。
69
- * @param options 转换选项。
70
- * @param options.typescript 是否启用 TypeScript 转换。
71
- * @param options.jsx 是否转换 Vue JSX。
72
- * @param options.esm 是否保留 ESM 导入导出供 iframe 使用。
73
- * @returns 可执行的 CJS 文本。
74
- */
75
- var transformScript = (code, filename, options = {}) => {
76
- const transforms = options.esm ? [] : ["imports"];
77
- const wantTs = options.typescript === true || options.typescript !== false && (filename.endsWith(".ts") || filename.endsWith(".tsx"));
78
- if (wantTs) transforms.unshift("typescript");
79
- if (options.jsx) transforms.unshift("jsx");
80
- try {
81
- const script = wantTs ? removeImportedTypeExports(code) : code;
82
- const source = options.jsx ? `import { h as __docs_h, Fragment as __docs_Fragment } from 'vue';\n${rewriteJsxAttributes(script)}` : script;
83
- return `${rewriteImportMeta(transform(source, {
84
- transforms,
85
- disableESTransforms: true,
86
- production: true,
87
- jsxRuntime: "classic",
88
- jsxPragma: "__docs_h",
89
- jsxFragmentPragma: "__docs_Fragment",
90
- filePath: filename
91
- }).code, filename)}\n//# sourceURL=playground://${filename}`;
92
- } catch (error) {
93
- const message = error instanceof Error ? error.message : String(error);
94
- throw new Error(`[Playground] 脚本转换失败 ${filename}: ${message}`, { cause: error });
95
- }
96
- };
97
- //#endregion
98
- export { transformScript as n, rewriteImportMeta as t };
@@ -1,251 +0,0 @@
1
- const require_cdn = require("./cdn-BoYKnGD3.cjs");
2
- let vue = require("vue");
3
- //#region packages/playground/src/core/scss.ts
4
- var SCHEME = "docs-playground";
5
- var STYLE_EXTS = [".scss", ".sass"];
6
- var VUE_SCSS_STYLE_RE = /<style\b[^>]*\blang\s*=\s*(['"]?)s[ac]ss\1/i;
7
- var LANG_ATTR_RE = /\s*lang\s*=\s*(['"]?)s[ac]ss\1/i;
8
- var SCSS_ERROR_MARK = "[playground-sass]";
9
- var INJECT_START = "/* docs-playground-scss-start */";
10
- var INJECT_END = "/* docs-playground-scss-end */";
11
- var boundStores = /* @__PURE__ */ new WeakSet();
12
- var wrappedCompilers = /* @__PURE__ */ new WeakSet();
13
- var testLoader;
14
- var loadedSass;
15
- var loadPromise;
16
- var fileCode = (value) => typeof value === "string" ? value : value.code;
17
- var playgroundPath = (url) => decodeURIComponent(url.pathname.replace(/^\/+/u, ""));
18
- var toPlaygroundUrl = (filename) => new URL(`${SCHEME}:///${filename.replace(/^\/+/u, "")}`);
19
- var basename = (path) => path.split("/").pop() || path;
20
- var scssSyntax = (filename, lang) => lang === "sass" || /\.sass$/i.test(filename) ? "indented" : "scss";
21
- var errorText = (item) => item instanceof Error ? item.message : String(item);
22
- var isScssFile = (filename) => /\.s[ac]ss$/i.test(filename);
23
- var vueSourceNeedsScss = (source) => VUE_SCSS_STYLE_RE.test(source);
24
- var resolveSassModule = async (url) => {
25
- const mod = await import(
26
- /* @vite-ignore */
27
- url
28
- );
29
- const sass = typeof mod.compileString === "function" ? mod : mod.default;
30
- if (typeof sass?.compileString !== "function") throw new Error(`Sass module at ${url} does not export compileString`);
31
- return sass;
32
- };
33
- var loadSass = () => {
34
- loadPromise ??= (testLoader ?? (() => resolveSassModule(require_cdn.SASS_CDN_URL)))().then((sass) => {
35
- loadedSass = sass;
36
- return sass;
37
- });
38
- return loadPromise;
39
- };
40
- var isScssPartial = (filename) => isScssFile(filename) && basename(filename).startsWith("_");
41
- var filesNeedScss = (files) => Object.entries(files).some(([filename, value]) => isScssFile(filename) || /\.vue$/i.test(filename) && vueSourceNeedsScss(fileCode(value)));
42
- var whenSassReady = (files, run) => {
43
- if (!filesNeedScss(files) || loadedSass) run();
44
- else loadSass().then(run);
45
- };
46
- var toPlaygroundFileMap = (files) => Object.fromEntries(Object.entries(files).map(([filename, value]) => [filename, fileCode(value)]));
47
- var formatScssError = (filename, message) => `${SCSS_ERROR_MARK} ${filename}: ${message}`;
48
- var scssFail = (filename, error) => formatScssError(filename, errorText(error));
49
- var withUnderscore = (path) => {
50
- const base = basename(path);
51
- if (base.startsWith("_")) return path;
52
- return `${path.slice(0, -base.length)}_${base}`;
53
- };
54
- var matchFileKey = (files, path) => [
55
- path,
56
- path.startsWith("src/") ? path : `src/${path}`,
57
- path.replace(/^src\//u, "")
58
- ].find((key) => files[key] !== void 0);
59
- var stylesheetCandidates = (requestPath) => {
60
- if (isScssFile(requestPath)) return [requestPath, withUnderscore(requestPath)];
61
- return STYLE_EXTS.flatMap((ext) => [
62
- `${requestPath}${ext}`,
63
- withUnderscore(`${requestPath}${ext}`),
64
- `${requestPath}/index${ext}`,
65
- withUnderscore(`${requestPath}/index${ext}`)
66
- ]);
67
- };
68
- var resolvePlaygroundStylesheet = (files, requestPath) => {
69
- const found = [...new Set(stylesheetCandidates(requestPath).map((path) => matchFileKey(files, path)).filter((key) => Boolean(key)))];
70
- if (found.length > 1) throw new Error(`Ambiguous Sass import "${requestPath}": ${found.join(", ")}`);
71
- return found[0] ?? null;
72
- };
73
- var createPlaygroundImporter = (getFiles) => ({
74
- canonicalize(url, context) {
75
- if (/^[a-zA-Z][\w+.-]*:/u.test(url) && !url.startsWith(`${SCHEME}:`)) return null;
76
- try {
77
- const resolved = resolvePlaygroundStylesheet(getFiles(), playgroundPath(new URL(url, context.containingUrl ?? toPlaygroundUrl(""))));
78
- return resolved ? toPlaygroundUrl(resolved) : null;
79
- } catch {
80
- return null;
81
- }
82
- },
83
- load(canonicalUrl) {
84
- const files = getFiles();
85
- const key = playgroundPath(canonicalUrl);
86
- return files[key] === void 0 ? null : {
87
- contents: files[key],
88
- syntax: scssSyntax(key)
89
- };
90
- }
91
- });
92
- var compileScssSource = (source, filename, sass, files, lang) => {
93
- const importer = createPlaygroundImporter(() => files);
94
- return sass.compileString(source, {
95
- syntax: scssSyntax(filename, lang),
96
- url: toPlaygroundUrl(filename),
97
- importer,
98
- importers: [importer]
99
- }).css;
100
- };
101
- var rewriteVueSfcStyles = (source, filename, parse, sass, files) => {
102
- const scssStyles = parse(source, { filename }).descriptor.styles.filter((style) => style.lang === "scss" || style.lang === "sass");
103
- if (!scssStyles.length) return {
104
- code: source,
105
- errors: []
106
- };
107
- const errors = [];
108
- let code = source;
109
- for (const style of [...scssStyles].sort((left, right) => right.loc.start.offset - left.loc.start.offset)) {
110
- const before = code.slice(0, style.loc.start.offset);
111
- const after = code.slice(style.loc.end.offset);
112
- const openStart = before.lastIndexOf("<style");
113
- if (openStart < 0) {
114
- errors.push(formatScssError(filename, "unable to locate <style> opening tag"));
115
- continue;
116
- }
117
- try {
118
- const css = compileScssSource(style.content, filename, sass, files, style.lang);
119
- code = `${before.slice(0, openStart)}${before.slice(openStart).replace(LANG_ATTR_RE, "")}${css}${after}`;
120
- } catch (error) {
121
- errors.push(scssFail(filename, error));
122
- }
123
- }
124
- return {
125
- code,
126
- errors
127
- };
128
- };
129
- var appendParseErrors = (result, errors) => errors.length ? {
130
- ...result,
131
- errors: [...result.errors, ...errors.map((item) => new Error(item))]
132
- } : result;
133
- var wrapCompiler = (compiler, getFiles) => {
134
- if (wrappedCompilers.has(compiler)) return compiler;
135
- const originalParse = compiler.parse.bind(compiler);
136
- const wrapped = { ...compiler };
137
- wrapped.parse = ((source, options) => {
138
- const filename = options?.filename || "anonymous.vue";
139
- if (!vueSourceNeedsScss(source)) return originalParse(source, options);
140
- const rewritten = loadedSass ? rewriteVueSfcStyles(source, filename, originalParse, loadedSass, getFiles()) : {
141
- code: source,
142
- errors: [formatScssError(filename, "compiler is not loaded")]
143
- };
144
- return appendParseErrors(originalParse(rewritten.errors.length ? source : rewritten.code, options), rewritten.errors);
145
- });
146
- wrappedCompilers.add(wrapped);
147
- return wrapped;
148
- };
149
- var withInjectedCss = (css, extra) => {
150
- const start = css.indexOf(INJECT_START);
151
- const end = start < 0 ? -1 : css.indexOf(INJECT_END, start);
152
- const base = (start < 0 ? css : `${css.slice(0, start)}${end >= 0 ? css.slice(end + 30) : ""}`).trimEnd();
153
- if (!extra.trim()) return base;
154
- const block = `${INJECT_START}\n${extra.trim()}\n${INJECT_END}`;
155
- return base ? `${base}\n${block}` : block;
156
- };
157
- var isStandaloneScssError = (item) => {
158
- const text = errorText(item);
159
- return text.startsWith(SCSS_ERROR_MARK) && /\.s[ac]ss:/i.test(text);
160
- };
161
- var syncScssErrors = (store, scssErrors) => {
162
- const next = [...scssErrors, ...store.errors.filter((item) => !isStandaloneScssError(item))];
163
- if (next.map(String).join("\0") === store.errors.map(String).join("\0")) return;
164
- store.errors = next;
165
- };
166
- var extractScssExports = (css, filename) => {
167
- const exports = {};
168
- if (/\.module\.(?:scss|sass)$/.test(filename)) css = css.replace(/:export\s*\{([^}]*)\}/g, (_block, declarations) => {
169
- for (const declaration of declarations.split(";")) {
170
- const colon = declaration.indexOf(":");
171
- if (colon >= 0) exports[declaration.slice(0, colon).trim()] = declaration.slice(colon + 1).trim();
172
- }
173
- return "";
174
- });
175
- return {
176
- css,
177
- exports
178
- };
179
- };
180
- var applyStandaloneScss = (store, sass = loadedSass) => {
181
- if (!sass) return [];
182
- const fileMap = toPlaygroundFileMap(store.files);
183
- const errors = [];
184
- const injected = [];
185
- for (const [filename, file] of Object.entries(store.files)) {
186
- if (!isScssFile(filename) || !file.compiled) continue;
187
- try {
188
- const { css, exports } = extractScssExports(compileScssSource(file.code, filename, sass, fileMap), filename);
189
- file.compiled.css = css;
190
- file.compiled.js = file.compiled.ssr = `export default ${JSON.stringify(exports)};\n`;
191
- if (!isScssPartial(filename) && css.trim()) injected.push(css);
192
- } catch (error) {
193
- errors.push(scssFail(filename, error));
194
- }
195
- }
196
- const main = store.files[store.mainFile];
197
- if (main?.compiled) {
198
- const next = withInjectedCss(main.compiled.css || "", injected.join("\n"));
199
- if (next !== (main.compiled.css || "")) main.compiled.css = next;
200
- }
201
- syncScssErrors(store, errors);
202
- return errors;
203
- };
204
- var bindPlaygroundScss = (store) => {
205
- if (boundStores.has(store)) return;
206
- boundStores.add(store);
207
- const getFiles = () => toPlaygroundFileMap(store.files);
208
- const installCompiler = () => {
209
- if (typeof store.compiler?.parse === "function") store.compiler = wrapCompiler(store.compiler, getFiles);
210
- };
211
- installCompiler();
212
- (0, vue.watch)(() => store.compiler, installCompiler);
213
- (0, vue.watch)(() => [
214
- store.mainFile,
215
- store.files[store.mainFile]?.compiled?.css,
216
- store.errors.map(String).join("\0"),
217
- Object.entries(store.files).filter(([filename]) => isScssFile(filename)).map(([filename, file]) => `${filename}:${file.code}`).join("\n")
218
- ].join("\0"), () => {
219
- if (loadedSass) applyStandaloneScss(store);
220
- });
221
- const originalSetFiles = store.setFiles.bind(store);
222
- store.setFiles = async (newFiles, mainFile) => {
223
- if (filesNeedScss(newFiles) && !loadedSass) await loadSass();
224
- return originalSetFiles(newFiles, mainFile);
225
- };
226
- };
227
- //#endregion
228
- Object.defineProperty(exports, "bindPlaygroundScss", {
229
- enumerable: true,
230
- get: function() {
231
- return bindPlaygroundScss;
232
- }
233
- });
234
- Object.defineProperty(exports, "compileScssSource", {
235
- enumerable: true,
236
- get: function() {
237
- return compileScssSource;
238
- }
239
- });
240
- Object.defineProperty(exports, "extractScssExports", {
241
- enumerable: true,
242
- get: function() {
243
- return extractScssExports;
244
- }
245
- });
246
- Object.defineProperty(exports, "whenSassReady", {
247
- enumerable: true,
248
- get: function() {
249
- return whenSassReady;
250
- }
251
- });
@@ -1,227 +0,0 @@
1
- import { t as SASS_CDN_URL } from "./cdn-DQoETju_.js";
2
- import { watch } from "vue";
3
- //#region packages/playground/src/core/scss.ts
4
- var SCHEME = "docs-playground";
5
- var STYLE_EXTS = [".scss", ".sass"];
6
- var VUE_SCSS_STYLE_RE = /<style\b[^>]*\blang\s*=\s*(['"]?)s[ac]ss\1/i;
7
- var LANG_ATTR_RE = /\s*lang\s*=\s*(['"]?)s[ac]ss\1/i;
8
- var SCSS_ERROR_MARK = "[playground-sass]";
9
- var INJECT_START = "/* docs-playground-scss-start */";
10
- var INJECT_END = "/* docs-playground-scss-end */";
11
- var boundStores = /* @__PURE__ */ new WeakSet();
12
- var wrappedCompilers = /* @__PURE__ */ new WeakSet();
13
- var loadedSass;
14
- var loadPromise;
15
- var fileCode = (value) => typeof value === "string" ? value : value.code;
16
- var playgroundPath = (url) => decodeURIComponent(url.pathname.replace(/^\/+/u, ""));
17
- var toPlaygroundUrl = (filename) => new URL(`${SCHEME}:///${filename.replace(/^\/+/u, "")}`);
18
- var basename = (path) => path.split("/").pop() || path;
19
- var scssSyntax = (filename, lang) => lang === "sass" || /\.sass$/i.test(filename) ? "indented" : "scss";
20
- var errorText = (item) => item instanceof Error ? item.message : String(item);
21
- var isScssFile = (filename) => /\.s[ac]ss$/i.test(filename);
22
- var vueSourceNeedsScss = (source) => VUE_SCSS_STYLE_RE.test(source);
23
- var resolveSassModule = async (url) => {
24
- const mod = await import(
25
- /* @vite-ignore */
26
- url
27
- );
28
- const sass = typeof mod.compileString === "function" ? mod : mod.default;
29
- if (typeof sass?.compileString !== "function") throw new Error(`Sass module at ${url} does not export compileString`);
30
- return sass;
31
- };
32
- var loadSass = () => {
33
- loadPromise ??= (() => resolveSassModule(SASS_CDN_URL))().then((sass) => {
34
- loadedSass = sass;
35
- return sass;
36
- });
37
- return loadPromise;
38
- };
39
- var isScssPartial = (filename) => isScssFile(filename) && basename(filename).startsWith("_");
40
- var filesNeedScss = (files) => Object.entries(files).some(([filename, value]) => isScssFile(filename) || /\.vue$/i.test(filename) && vueSourceNeedsScss(fileCode(value)));
41
- var whenSassReady = (files, run) => {
42
- if (!filesNeedScss(files) || loadedSass) run();
43
- else loadSass().then(run);
44
- };
45
- var toPlaygroundFileMap = (files) => Object.fromEntries(Object.entries(files).map(([filename, value]) => [filename, fileCode(value)]));
46
- var formatScssError = (filename, message) => `${SCSS_ERROR_MARK} ${filename}: ${message}`;
47
- var scssFail = (filename, error) => formatScssError(filename, errorText(error));
48
- var withUnderscore = (path) => {
49
- const base = basename(path);
50
- if (base.startsWith("_")) return path;
51
- return `${path.slice(0, -base.length)}_${base}`;
52
- };
53
- var matchFileKey = (files, path) => [
54
- path,
55
- path.startsWith("src/") ? path : `src/${path}`,
56
- path.replace(/^src\//u, "")
57
- ].find((key) => files[key] !== void 0);
58
- var stylesheetCandidates = (requestPath) => {
59
- if (isScssFile(requestPath)) return [requestPath, withUnderscore(requestPath)];
60
- return STYLE_EXTS.flatMap((ext) => [
61
- `${requestPath}${ext}`,
62
- withUnderscore(`${requestPath}${ext}`),
63
- `${requestPath}/index${ext}`,
64
- withUnderscore(`${requestPath}/index${ext}`)
65
- ]);
66
- };
67
- var resolvePlaygroundStylesheet = (files, requestPath) => {
68
- const found = [...new Set(stylesheetCandidates(requestPath).map((path) => matchFileKey(files, path)).filter((key) => Boolean(key)))];
69
- if (found.length > 1) throw new Error(`Ambiguous Sass import "${requestPath}": ${found.join(", ")}`);
70
- return found[0] ?? null;
71
- };
72
- var createPlaygroundImporter = (getFiles) => ({
73
- canonicalize(url, context) {
74
- if (/^[a-zA-Z][\w+.-]*:/u.test(url) && !url.startsWith(`${SCHEME}:`)) return null;
75
- try {
76
- const resolved = resolvePlaygroundStylesheet(getFiles(), playgroundPath(new URL(url, context.containingUrl ?? toPlaygroundUrl(""))));
77
- return resolved ? toPlaygroundUrl(resolved) : null;
78
- } catch {
79
- return null;
80
- }
81
- },
82
- load(canonicalUrl) {
83
- const files = getFiles();
84
- const key = playgroundPath(canonicalUrl);
85
- return files[key] === void 0 ? null : {
86
- contents: files[key],
87
- syntax: scssSyntax(key)
88
- };
89
- }
90
- });
91
- var compileScssSource = (source, filename, sass, files, lang) => {
92
- const importer = createPlaygroundImporter(() => files);
93
- return sass.compileString(source, {
94
- syntax: scssSyntax(filename, lang),
95
- url: toPlaygroundUrl(filename),
96
- importer,
97
- importers: [importer]
98
- }).css;
99
- };
100
- var rewriteVueSfcStyles = (source, filename, parse, sass, files) => {
101
- const scssStyles = parse(source, { filename }).descriptor.styles.filter((style) => style.lang === "scss" || style.lang === "sass");
102
- if (!scssStyles.length) return {
103
- code: source,
104
- errors: []
105
- };
106
- const errors = [];
107
- let code = source;
108
- for (const style of [...scssStyles].sort((left, right) => right.loc.start.offset - left.loc.start.offset)) {
109
- const before = code.slice(0, style.loc.start.offset);
110
- const after = code.slice(style.loc.end.offset);
111
- const openStart = before.lastIndexOf("<style");
112
- if (openStart < 0) {
113
- errors.push(formatScssError(filename, "unable to locate <style> opening tag"));
114
- continue;
115
- }
116
- try {
117
- const css = compileScssSource(style.content, filename, sass, files, style.lang);
118
- code = `${before.slice(0, openStart)}${before.slice(openStart).replace(LANG_ATTR_RE, "")}${css}${after}`;
119
- } catch (error) {
120
- errors.push(scssFail(filename, error));
121
- }
122
- }
123
- return {
124
- code,
125
- errors
126
- };
127
- };
128
- var appendParseErrors = (result, errors) => errors.length ? {
129
- ...result,
130
- errors: [...result.errors, ...errors.map((item) => new Error(item))]
131
- } : result;
132
- var wrapCompiler = (compiler, getFiles) => {
133
- if (wrappedCompilers.has(compiler)) return compiler;
134
- const originalParse = compiler.parse.bind(compiler);
135
- const wrapped = { ...compiler };
136
- wrapped.parse = ((source, options) => {
137
- const filename = options?.filename || "anonymous.vue";
138
- if (!vueSourceNeedsScss(source)) return originalParse(source, options);
139
- const rewritten = loadedSass ? rewriteVueSfcStyles(source, filename, originalParse, loadedSass, getFiles()) : {
140
- code: source,
141
- errors: [formatScssError(filename, "compiler is not loaded")]
142
- };
143
- return appendParseErrors(originalParse(rewritten.errors.length ? source : rewritten.code, options), rewritten.errors);
144
- });
145
- wrappedCompilers.add(wrapped);
146
- return wrapped;
147
- };
148
- var withInjectedCss = (css, extra) => {
149
- const start = css.indexOf(INJECT_START);
150
- const end = start < 0 ? -1 : css.indexOf(INJECT_END, start);
151
- const base = (start < 0 ? css : `${css.slice(0, start)}${end >= 0 ? css.slice(end + 30) : ""}`).trimEnd();
152
- if (!extra.trim()) return base;
153
- const block = `${INJECT_START}\n${extra.trim()}\n${INJECT_END}`;
154
- return base ? `${base}\n${block}` : block;
155
- };
156
- var isStandaloneScssError = (item) => {
157
- const text = errorText(item);
158
- return text.startsWith(SCSS_ERROR_MARK) && /\.s[ac]ss:/i.test(text);
159
- };
160
- var syncScssErrors = (store, scssErrors) => {
161
- const next = [...scssErrors, ...store.errors.filter((item) => !isStandaloneScssError(item))];
162
- if (next.map(String).join("\0") === store.errors.map(String).join("\0")) return;
163
- store.errors = next;
164
- };
165
- var extractScssExports = (css, filename) => {
166
- const exports = {};
167
- if (/\.module\.(?:scss|sass)$/.test(filename)) css = css.replace(/:export\s*\{([^}]*)\}/g, (_block, declarations) => {
168
- for (const declaration of declarations.split(";")) {
169
- const colon = declaration.indexOf(":");
170
- if (colon >= 0) exports[declaration.slice(0, colon).trim()] = declaration.slice(colon + 1).trim();
171
- }
172
- return "";
173
- });
174
- return {
175
- css,
176
- exports
177
- };
178
- };
179
- var applyStandaloneScss = (store, sass = loadedSass) => {
180
- if (!sass) return [];
181
- const fileMap = toPlaygroundFileMap(store.files);
182
- const errors = [];
183
- const injected = [];
184
- for (const [filename, file] of Object.entries(store.files)) {
185
- if (!isScssFile(filename) || !file.compiled) continue;
186
- try {
187
- const { css, exports } = extractScssExports(compileScssSource(file.code, filename, sass, fileMap), filename);
188
- file.compiled.css = css;
189
- file.compiled.js = file.compiled.ssr = `export default ${JSON.stringify(exports)};\n`;
190
- if (!isScssPartial(filename) && css.trim()) injected.push(css);
191
- } catch (error) {
192
- errors.push(scssFail(filename, error));
193
- }
194
- }
195
- const main = store.files[store.mainFile];
196
- if (main?.compiled) {
197
- const next = withInjectedCss(main.compiled.css || "", injected.join("\n"));
198
- if (next !== (main.compiled.css || "")) main.compiled.css = next;
199
- }
200
- syncScssErrors(store, errors);
201
- return errors;
202
- };
203
- var bindPlaygroundScss = (store) => {
204
- if (boundStores.has(store)) return;
205
- boundStores.add(store);
206
- const getFiles = () => toPlaygroundFileMap(store.files);
207
- const installCompiler = () => {
208
- if (typeof store.compiler?.parse === "function") store.compiler = wrapCompiler(store.compiler, getFiles);
209
- };
210
- installCompiler();
211
- watch(() => store.compiler, installCompiler);
212
- watch(() => [
213
- store.mainFile,
214
- store.files[store.mainFile]?.compiled?.css,
215
- store.errors.map(String).join("\0"),
216
- Object.entries(store.files).filter(([filename]) => isScssFile(filename)).map(([filename, file]) => `${filename}:${file.code}`).join("\n")
217
- ].join("\0"), () => {
218
- if (loadedSass) applyStandaloneScss(store);
219
- });
220
- const originalSetFiles = store.setFiles.bind(store);
221
- store.setFiles = async (newFiles, mainFile) => {
222
- if (filesNeedScss(newFiles) && !loadedSass) await loadSass();
223
- return originalSetFiles(newFiles, mainFile);
224
- };
225
- };
226
- //#endregion
227
- export { whenSassReady as i, compileScssSource as n, extractScssExports as r, bindPlaygroundScss as t };