@vocab/vite 0.0.0-vite-virtual-resource-improvement-20250509051109

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ ### MIT License
2
+
3
+ Copyright (c) 2020 SEEK
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ export * from "../../dist/declarations/src/chunks.js";
2
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidm9jYWItdml0ZS1jaHVua3MuY2pzLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9kaXN0L2RlY2xhcmF0aW9ucy9zcmMvY2h1bmtzLmQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEifQ==
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var logger = require('../../dist/logger-3e3dccee.cjs.dev.js');
6
+ require('picocolors');
7
+ require('debug');
8
+
9
+ function getChunkName(lang) {
10
+ return `${lang}-translations`;
11
+ }
12
+
13
+ const trace = logger.trace.extend('create-vocab-chunks');
14
+
15
+ /**
16
+ * Gets vocab virtual module details and creates chunks for each language
17
+ */
18
+ const createVocabChunks = (id, {
19
+ getModuleInfo
20
+ }) => {
21
+ const match = /virtual:vocab-(\w+)/.exec(id);
22
+ if (!match) {
23
+ return;
24
+ }
25
+ const language = match[1];
26
+ const dependentEntryPoints = [];
27
+ const rootModuleInfo = getModuleInfo(id);
28
+ if (!rootModuleInfo) {
29
+ trace(`No module info found for ${id}`);
30
+ return;
31
+ }
32
+ const idsToHandle = new Set(rootModuleInfo.dynamicImporters);
33
+ for (const moduleId of idsToHandle) {
34
+ const moduleInfo = getModuleInfo(moduleId);
35
+ if (!moduleInfo) {
36
+ trace(`No module info found for ${moduleId}`);
37
+ continue;
38
+ }
39
+ const {
40
+ isEntry,
41
+ dynamicImporters,
42
+ importers
43
+ } = moduleInfo;
44
+ if (isEntry || dynamicImporters.length > 0) {
45
+ dependentEntryPoints.push(moduleId);
46
+ }
47
+ for (const importerId of importers) idsToHandle.add(importerId);
48
+ }
49
+ if (dependentEntryPoints.length > 0) {
50
+ return getChunkName(language);
51
+ }
52
+ };
53
+
54
+ exports.createVocabChunks = createVocabChunks;
55
+ exports.getChunkName = getChunkName;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./vocab-vite-chunks.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./vocab-vite-chunks.cjs.dev.js");
7
+ }
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var logger = require('../../dist/logger-0d92b2c5.cjs.prod.js');
6
+ require('picocolors');
7
+ require('debug');
8
+
9
+ function getChunkName(lang) {
10
+ return `${lang}-translations`;
11
+ }
12
+
13
+ const trace = logger.trace.extend('create-vocab-chunks');
14
+
15
+ /**
16
+ * Gets vocab virtual module details and creates chunks for each language
17
+ */
18
+ const createVocabChunks = (id, {
19
+ getModuleInfo
20
+ }) => {
21
+ const match = /virtual:vocab-(\w+)/.exec(id);
22
+ if (!match) {
23
+ return;
24
+ }
25
+ const language = match[1];
26
+ const dependentEntryPoints = [];
27
+ const rootModuleInfo = getModuleInfo(id);
28
+ if (!rootModuleInfo) {
29
+ trace(`No module info found for ${id}`);
30
+ return;
31
+ }
32
+ const idsToHandle = new Set(rootModuleInfo.dynamicImporters);
33
+ for (const moduleId of idsToHandle) {
34
+ const moduleInfo = getModuleInfo(moduleId);
35
+ if (!moduleInfo) {
36
+ trace(`No module info found for ${moduleId}`);
37
+ continue;
38
+ }
39
+ const {
40
+ isEntry,
41
+ dynamicImporters,
42
+ importers
43
+ } = moduleInfo;
44
+ if (isEntry || dynamicImporters.length > 0) {
45
+ dependentEntryPoints.push(moduleId);
46
+ }
47
+ for (const importerId of importers) idsToHandle.add(importerId);
48
+ }
49
+ if (dependentEntryPoints.length > 0) {
50
+ return getChunkName(language);
51
+ }
52
+ };
53
+
54
+ exports.createVocabChunks = createVocabChunks;
55
+ exports.getChunkName = getChunkName;
@@ -0,0 +1,50 @@
1
+ import { t as trace$1 } from '../../dist/logger-e3a4b043.esm.js';
2
+ import 'picocolors';
3
+ import 'debug';
4
+
5
+ function getChunkName(lang) {
6
+ return `${lang}-translations`;
7
+ }
8
+
9
+ const trace = trace$1.extend('create-vocab-chunks');
10
+
11
+ /**
12
+ * Gets vocab virtual module details and creates chunks for each language
13
+ */
14
+ const createVocabChunks = (id, {
15
+ getModuleInfo
16
+ }) => {
17
+ const match = /virtual:vocab-(\w+)/.exec(id);
18
+ if (!match) {
19
+ return;
20
+ }
21
+ const language = match[1];
22
+ const dependentEntryPoints = [];
23
+ const rootModuleInfo = getModuleInfo(id);
24
+ if (!rootModuleInfo) {
25
+ trace(`No module info found for ${id}`);
26
+ return;
27
+ }
28
+ const idsToHandle = new Set(rootModuleInfo.dynamicImporters);
29
+ for (const moduleId of idsToHandle) {
30
+ const moduleInfo = getModuleInfo(moduleId);
31
+ if (!moduleInfo) {
32
+ trace(`No module info found for ${moduleId}`);
33
+ continue;
34
+ }
35
+ const {
36
+ isEntry,
37
+ dynamicImporters,
38
+ importers
39
+ } = moduleInfo;
40
+ if (isEntry || dynamicImporters.length > 0) {
41
+ dependentEntryPoints.push(moduleId);
42
+ }
43
+ for (const importerId of importers) idsToHandle.add(importerId);
44
+ }
45
+ if (dependentEntryPoints.length > 0) {
46
+ return getChunkName(language);
47
+ }
48
+ };
49
+
50
+ export { createVocabChunks, getChunkName };
@@ -0,0 +1,4 @@
1
+ {
2
+ "main": "dist/vocab-vite-chunks.cjs.js",
3
+ "module": "dist/vocab-vite-chunks.esm.js"
4
+ }
@@ -0,0 +1,2 @@
1
+ export { createVocabChunks } from "./create-vocab-chunks.js";
2
+ export { getChunkName } from "./get-chunk-name.js";
@@ -0,0 +1,2 @@
1
+ import type { TranslationModule } from '@vocab/core';
2
+ export declare const createLanguage: (loadImport: () => Promise<any>) => TranslationModule<any>;
@@ -0,0 +1,5 @@
1
+ import type { Rollup } from 'vite';
2
+ /**
3
+ * Gets vocab virtual module details and creates chunks for each language
4
+ */
5
+ export declare const createVocabChunks: (id: string, { getModuleInfo }: Rollup.ManualChunkMeta) => string | undefined;
@@ -0,0 +1 @@
1
+ export declare function getChunkName(lang: string): string;
@@ -0,0 +1,6 @@
1
+ import type { Plugin as VitePlugin } from 'vite';
2
+ import type { UserConfig } from '@vocab/core';
3
+ export type VocabPluginOptions = {
4
+ vocabConfig: UserConfig;
5
+ };
6
+ export default function vitePluginVocab({ vocabConfig, }: VocabPluginOptions): VitePlugin;
@@ -0,0 +1,2 @@
1
+ export { createTranslationFile } from '@vocab/core/translation-file';
2
+ export { createLanguage } from "./create-language.js";
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ require('picocolors');
4
+ var debug = require('debug');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
7
+
8
+ var debug__default = /*#__PURE__*/_interopDefault(debug);
9
+
10
+ const trace = debug__default["default"](`vocab:vite`);
11
+
12
+ exports.trace = trace;
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ require('picocolors');
4
+ var debug = require('debug');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
7
+
8
+ var debug__default = /*#__PURE__*/_interopDefault(debug);
9
+
10
+ const trace = debug__default["default"](`vocab:vite`);
11
+
12
+ exports.trace = trace;
@@ -0,0 +1,6 @@
1
+ import 'picocolors';
2
+ import debug from 'debug';
3
+
4
+ const trace = debug(`vocab:vite`);
5
+
6
+ export { trace as t };
@@ -0,0 +1,3 @@
1
+ export * from "./declarations/src/index.js";
2
+ export { default } from "./declarations/src/index.js";
3
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidm9jYWItdml0ZS5janMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4vZGVjbGFyYXRpb25zL3NyYy9pbmRleC5kLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIn0=
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var core = require('@vocab/core');
6
+ var esModuleLexer = require('es-module-lexer');
7
+ var cjsModuleLexer = require('cjs-module-lexer');
8
+ var logger = require('./logger-3e3dccee.cjs.dev.js');
9
+ require('picocolors');
10
+ require('debug');
11
+
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule) return e;
14
+ var n = Object.create(null);
15
+ if (e) {
16
+ Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default') {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ }
26
+ n["default"] = e;
27
+ return Object.freeze(n);
28
+ }
29
+
30
+ var esModuleLexer__namespace = /*#__PURE__*/_interopNamespace(esModuleLexer);
31
+ var cjsModuleLexer__namespace = /*#__PURE__*/_interopNamespace(cjsModuleLexer);
32
+
33
+ const compiledVocabFileFilter = /\.vocab[\\/]index\.(?:ts|js|cjs|mjs)$/;
34
+ const virtualModuleId = 'virtual:vocab';
35
+ const sourceQueryKey = '?source=';
36
+
37
+ const trace = logger.trace.extend('transform');
38
+ function findExportNames(source, mode) {
39
+ if (mode === 'esm') {
40
+ const [, exports] = esModuleLexer__namespace.parse(source);
41
+ return exports;
42
+ }
43
+ const {
44
+ exports
45
+ } = cjsModuleLexer__namespace.parse(source);
46
+ return exports;
47
+ }
48
+ const transformVocabFile = async (code, id, config) => {
49
+ trace('Transforming vocab file', id);
50
+ let result = code;
51
+ const devJsonFilePath = core.getDevLanguageFileFromTsFile(id);
52
+ const loadedTranslation = core.loadTranslation({
53
+ filePath: devJsonFilePath,
54
+ fallbacks: 'all'
55
+ }, config);
56
+ const renderLanguageLoader = renderLanguageLoaderAsync(loadedTranslation);
57
+ const translations = /* ts */`
58
+ const translations = createTranslationFile({
59
+ ${Object.keys(loadedTranslation.languages).map(lang => `${JSON.stringify(lang)}: ${renderLanguageLoader(lang)}`).join(',\n')}
60
+ });
61
+ `;
62
+ await esModuleLexer__namespace.init;
63
+ const esmExports = findExportNames(code, 'esm');
64
+ if (esmExports.length > 0) {
65
+ const exportName = esmExports[0];
66
+ trace(`Found ESM export '${exportName.n}' in ${id}`);
67
+ result = /* ts */`
68
+ import { createLanguage, createTranslationFile } from '@vocab/vite/runtime';
69
+ ${translations}
70
+ export { translations as ${exportName.n} };
71
+ `;
72
+ } else {
73
+ // init needs to be called and waited upon
74
+ await cjsModuleLexer__namespace.init();
75
+ const exportName = findExportNames(code, 'cjs')[0];
76
+ trace(`Found CJS export '${exportName}' in ${id}`);
77
+ result = /* ts */`
78
+ import { createLanguage, createTranslationFile } from '@vocab/vite/runtime';
79
+ ${translations}
80
+ exports.${exportName} = translations;
81
+ `;
82
+ }
83
+ trace('Created translation file', result);
84
+ return result;
85
+ };
86
+ const renderLanguageLoaderAsync = loadedTranslation => lang => {
87
+ const identifier = JSON.stringify(createIdentifier(lang, loadedTranslation));
88
+ return /* ts */`createLanguage(() => import(${identifier}))`.trim();
89
+ };
90
+ const createIdentifier = (lang, loadedTranslation) => {
91
+ var _loadedTranslation$la;
92
+ const languageTranslations = (_loadedTranslation$la = loadedTranslation.languages[lang]) !== null && _loadedTranslation$la !== void 0 ? _loadedTranslation$la : {};
93
+ const langJson = {};
94
+ for (const key of loadedTranslation.keys) {
95
+ langJson[key] = languageTranslations[key].message;
96
+ }
97
+ const base64 = Buffer.from(JSON.stringify(langJson), 'utf-8').toString('base64');
98
+ const encodedResource = `${sourceQueryKey}${base64}`;
99
+ return `${virtualModuleId}-${lang}.json${encodedResource}`;
100
+ };
101
+
102
+ const virtualResourceLoader = path => Buffer.from(path.split(sourceQueryKey)[1], 'base64').toString('utf-8');
103
+
104
+ function vitePluginVocab({
105
+ vocabConfig
106
+ }) {
107
+ let isSSR = false;
108
+ logger.trace(`Creating Vocab plugin${vocabConfig ? ` with config file ${vocabConfig}` : ''}`);
109
+ return {
110
+ name: 'vite-plugin-vocab',
111
+ apply: 'build',
112
+ enforce: 'pre',
113
+ configResolved(config) {
114
+ // Check if the build is for SSR. This plugin should not run for SSR builds.
115
+ isSSR = Boolean(config.build.ssr);
116
+ },
117
+ resolveId(id) {
118
+ if (isSSR) return null;
119
+ if (id.includes(virtualModuleId)) {
120
+ return `\0${id}`;
121
+ }
122
+ },
123
+ load(id) {
124
+ if (isSSR) return null;
125
+ if (id.includes(`\0${virtualModuleId}`)) {
126
+ return virtualResourceLoader(id);
127
+ }
128
+ },
129
+ async transform(code, id) {
130
+ if (isSSR) return null;
131
+ if (compiledVocabFileFilter.test(id)) {
132
+ const transformedCode = await transformVocabFile(code, id, vocabConfig);
133
+ return {
134
+ code: transformedCode,
135
+ map: null // provide source map if available
136
+ };
137
+ }
138
+ }
139
+ };
140
+ }
141
+
142
+ exports["default"] = vitePluginVocab;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./vocab-vite.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./vocab-vite.cjs.dev.js");
7
+ }
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var core = require('@vocab/core');
6
+ var esModuleLexer = require('es-module-lexer');
7
+ var cjsModuleLexer = require('cjs-module-lexer');
8
+ var logger = require('./logger-0d92b2c5.cjs.prod.js');
9
+ require('picocolors');
10
+ require('debug');
11
+
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule) return e;
14
+ var n = Object.create(null);
15
+ if (e) {
16
+ Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default') {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ }
26
+ n["default"] = e;
27
+ return Object.freeze(n);
28
+ }
29
+
30
+ var esModuleLexer__namespace = /*#__PURE__*/_interopNamespace(esModuleLexer);
31
+ var cjsModuleLexer__namespace = /*#__PURE__*/_interopNamespace(cjsModuleLexer);
32
+
33
+ const compiledVocabFileFilter = /\.vocab[\\/]index\.(?:ts|js|cjs|mjs)$/;
34
+ const virtualModuleId = 'virtual:vocab';
35
+ const sourceQueryKey = '?source=';
36
+
37
+ const trace = logger.trace.extend('transform');
38
+ function findExportNames(source, mode) {
39
+ if (mode === 'esm') {
40
+ const [, exports] = esModuleLexer__namespace.parse(source);
41
+ return exports;
42
+ }
43
+ const {
44
+ exports
45
+ } = cjsModuleLexer__namespace.parse(source);
46
+ return exports;
47
+ }
48
+ const transformVocabFile = async (code, id, config) => {
49
+ trace('Transforming vocab file', id);
50
+ let result = code;
51
+ const devJsonFilePath = core.getDevLanguageFileFromTsFile(id);
52
+ const loadedTranslation = core.loadTranslation({
53
+ filePath: devJsonFilePath,
54
+ fallbacks: 'all'
55
+ }, config);
56
+ const renderLanguageLoader = renderLanguageLoaderAsync(loadedTranslation);
57
+ const translations = /* ts */`
58
+ const translations = createTranslationFile({
59
+ ${Object.keys(loadedTranslation.languages).map(lang => `${JSON.stringify(lang)}: ${renderLanguageLoader(lang)}`).join(',\n')}
60
+ });
61
+ `;
62
+ await esModuleLexer__namespace.init;
63
+ const esmExports = findExportNames(code, 'esm');
64
+ if (esmExports.length > 0) {
65
+ const exportName = esmExports[0];
66
+ trace(`Found ESM export '${exportName.n}' in ${id}`);
67
+ result = /* ts */`
68
+ import { createLanguage, createTranslationFile } from '@vocab/vite/runtime';
69
+ ${translations}
70
+ export { translations as ${exportName.n} };
71
+ `;
72
+ } else {
73
+ // init needs to be called and waited upon
74
+ await cjsModuleLexer__namespace.init();
75
+ const exportName = findExportNames(code, 'cjs')[0];
76
+ trace(`Found CJS export '${exportName}' in ${id}`);
77
+ result = /* ts */`
78
+ import { createLanguage, createTranslationFile } from '@vocab/vite/runtime';
79
+ ${translations}
80
+ exports.${exportName} = translations;
81
+ `;
82
+ }
83
+ trace('Created translation file', result);
84
+ return result;
85
+ };
86
+ const renderLanguageLoaderAsync = loadedTranslation => lang => {
87
+ const identifier = JSON.stringify(createIdentifier(lang, loadedTranslation));
88
+ return /* ts */`createLanguage(() => import(${identifier}))`.trim();
89
+ };
90
+ const createIdentifier = (lang, loadedTranslation) => {
91
+ var _loadedTranslation$la;
92
+ const languageTranslations = (_loadedTranslation$la = loadedTranslation.languages[lang]) !== null && _loadedTranslation$la !== void 0 ? _loadedTranslation$la : {};
93
+ const langJson = {};
94
+ for (const key of loadedTranslation.keys) {
95
+ langJson[key] = languageTranslations[key].message;
96
+ }
97
+ const base64 = Buffer.from(JSON.stringify(langJson), 'utf-8').toString('base64');
98
+ const encodedResource = `${sourceQueryKey}${base64}`;
99
+ return `${virtualModuleId}-${lang}.json${encodedResource}`;
100
+ };
101
+
102
+ const virtualResourceLoader = path => Buffer.from(path.split(sourceQueryKey)[1], 'base64').toString('utf-8');
103
+
104
+ function vitePluginVocab({
105
+ vocabConfig
106
+ }) {
107
+ let isSSR = false;
108
+ logger.trace(`Creating Vocab plugin${vocabConfig ? ` with config file ${vocabConfig}` : ''}`);
109
+ return {
110
+ name: 'vite-plugin-vocab',
111
+ apply: 'build',
112
+ enforce: 'pre',
113
+ configResolved(config) {
114
+ // Check if the build is for SSR. This plugin should not run for SSR builds.
115
+ isSSR = Boolean(config.build.ssr);
116
+ },
117
+ resolveId(id) {
118
+ if (isSSR) return null;
119
+ if (id.includes(virtualModuleId)) {
120
+ return `\0${id}`;
121
+ }
122
+ },
123
+ load(id) {
124
+ if (isSSR) return null;
125
+ if (id.includes(`\0${virtualModuleId}`)) {
126
+ return virtualResourceLoader(id);
127
+ }
128
+ },
129
+ async transform(code, id) {
130
+ if (isSSR) return null;
131
+ if (compiledVocabFileFilter.test(id)) {
132
+ const transformedCode = await transformVocabFile(code, id, vocabConfig);
133
+ return {
134
+ code: transformedCode,
135
+ map: null // provide source map if available
136
+ };
137
+ }
138
+ }
139
+ };
140
+ }
141
+
142
+ exports["default"] = vitePluginVocab;
@@ -0,0 +1,117 @@
1
+ import { getDevLanguageFileFromTsFile, loadTranslation } from '@vocab/core';
2
+ import * as esModuleLexer from 'es-module-lexer';
3
+ import * as cjsModuleLexer from 'cjs-module-lexer';
4
+ import { t as trace$1 } from './logger-e3a4b043.esm.js';
5
+ import 'picocolors';
6
+ import 'debug';
7
+
8
+ const compiledVocabFileFilter = /\.vocab[\\/]index\.(?:ts|js|cjs|mjs)$/;
9
+ const virtualModuleId = 'virtual:vocab';
10
+ const sourceQueryKey = '?source=';
11
+
12
+ const trace = trace$1.extend('transform');
13
+ function findExportNames(source, mode) {
14
+ if (mode === 'esm') {
15
+ const [, exports] = esModuleLexer.parse(source);
16
+ return exports;
17
+ }
18
+ const {
19
+ exports
20
+ } = cjsModuleLexer.parse(source);
21
+ return exports;
22
+ }
23
+ const transformVocabFile = async (code, id, config) => {
24
+ trace('Transforming vocab file', id);
25
+ let result = code;
26
+ const devJsonFilePath = getDevLanguageFileFromTsFile(id);
27
+ const loadedTranslation = loadTranslation({
28
+ filePath: devJsonFilePath,
29
+ fallbacks: 'all'
30
+ }, config);
31
+ const renderLanguageLoader = renderLanguageLoaderAsync(loadedTranslation);
32
+ const translations = /* ts */`
33
+ const translations = createTranslationFile({
34
+ ${Object.keys(loadedTranslation.languages).map(lang => `${JSON.stringify(lang)}: ${renderLanguageLoader(lang)}`).join(',\n')}
35
+ });
36
+ `;
37
+ await esModuleLexer.init;
38
+ const esmExports = findExportNames(code, 'esm');
39
+ if (esmExports.length > 0) {
40
+ const exportName = esmExports[0];
41
+ trace(`Found ESM export '${exportName.n}' in ${id}`);
42
+ result = /* ts */`
43
+ import { createLanguage, createTranslationFile } from '@vocab/vite/runtime';
44
+ ${translations}
45
+ export { translations as ${exportName.n} };
46
+ `;
47
+ } else {
48
+ // init needs to be called and waited upon
49
+ await cjsModuleLexer.init();
50
+ const exportName = findExportNames(code, 'cjs')[0];
51
+ trace(`Found CJS export '${exportName}' in ${id}`);
52
+ result = /* ts */`
53
+ import { createLanguage, createTranslationFile } from '@vocab/vite/runtime';
54
+ ${translations}
55
+ exports.${exportName} = translations;
56
+ `;
57
+ }
58
+ trace('Created translation file', result);
59
+ return result;
60
+ };
61
+ const renderLanguageLoaderAsync = loadedTranslation => lang => {
62
+ const identifier = JSON.stringify(createIdentifier(lang, loadedTranslation));
63
+ return /* ts */`createLanguage(() => import(${identifier}))`.trim();
64
+ };
65
+ const createIdentifier = (lang, loadedTranslation) => {
66
+ var _loadedTranslation$la;
67
+ const languageTranslations = (_loadedTranslation$la = loadedTranslation.languages[lang]) !== null && _loadedTranslation$la !== void 0 ? _loadedTranslation$la : {};
68
+ const langJson = {};
69
+ for (const key of loadedTranslation.keys) {
70
+ langJson[key] = languageTranslations[key].message;
71
+ }
72
+ const base64 = Buffer.from(JSON.stringify(langJson), 'utf-8').toString('base64');
73
+ const encodedResource = `${sourceQueryKey}${base64}`;
74
+ return `${virtualModuleId}-${lang}.json${encodedResource}`;
75
+ };
76
+
77
+ const virtualResourceLoader = path => Buffer.from(path.split(sourceQueryKey)[1], 'base64').toString('utf-8');
78
+
79
+ function vitePluginVocab({
80
+ vocabConfig
81
+ }) {
82
+ let isSSR = false;
83
+ trace$1(`Creating Vocab plugin${vocabConfig ? ` with config file ${vocabConfig}` : ''}`);
84
+ return {
85
+ name: 'vite-plugin-vocab',
86
+ apply: 'build',
87
+ enforce: 'pre',
88
+ configResolved(config) {
89
+ // Check if the build is for SSR. This plugin should not run for SSR builds.
90
+ isSSR = Boolean(config.build.ssr);
91
+ },
92
+ resolveId(id) {
93
+ if (isSSR) return null;
94
+ if (id.includes(virtualModuleId)) {
95
+ return `\0${id}`;
96
+ }
97
+ },
98
+ load(id) {
99
+ if (isSSR) return null;
100
+ if (id.includes(`\0${virtualModuleId}`)) {
101
+ return virtualResourceLoader(id);
102
+ }
103
+ },
104
+ async transform(code, id) {
105
+ if (isSSR) return null;
106
+ if (compiledVocabFileFilter.test(id)) {
107
+ const transformedCode = await transformVocabFile(code, id, vocabConfig);
108
+ return {
109
+ code: transformedCode,
110
+ map: null // provide source map if available
111
+ };
112
+ }
113
+ }
114
+ };
115
+ }
116
+
117
+ export { vitePluginVocab as default };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@vocab/vite",
3
+ "version": "0.0.0-vite-virtual-resource-improvement-20250509051109",
4
+ "author": "SEEK",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/seek-oss/vocab.git",
9
+ "directory": "packages/vite"
10
+ },
11
+ "main": "dist/vocab-vite.cjs.js",
12
+ "module": "dist/vocab-vite.esm.js",
13
+ "exports": {
14
+ "./package.json": "./package.json",
15
+ ".": {
16
+ "module": "./dist/vocab-vite.esm.js",
17
+ "default": "./dist/vocab-vite.cjs.js"
18
+ },
19
+ "./runtime": {
20
+ "module": "./runtime/dist/vocab-vite-runtime.esm.js",
21
+ "default": "./runtime/dist/vocab-vite-runtime.cjs.js"
22
+ },
23
+ "./chunks": {
24
+ "module": "./chunks/dist/vocab-vite-chunks.esm.js",
25
+ "default": "./chunks/dist/vocab-vite-chunks.cjs.js"
26
+ }
27
+ },
28
+ "preconstruct": {
29
+ "entrypoints": [
30
+ "index.ts",
31
+ "runtime.ts",
32
+ "chunks.ts"
33
+ ]
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "runtime",
38
+ "chunks"
39
+ ],
40
+ "dependencies": {
41
+ "cjs-module-lexer": "^1.2.2",
42
+ "debug": "^4.3.1",
43
+ "es-module-lexer": "^1.0.0",
44
+ "picocolors": "^1.0.0",
45
+ "@vocab/core": "^1.6.3"
46
+ },
47
+ "devDependencies": {
48
+ "@types/debug": "^4.1.5",
49
+ "vite": "^5.4.8"
50
+ },
51
+ "peerDependencies": {
52
+ "vite": "^5.4.8"
53
+ }
54
+ }
@@ -0,0 +1,2 @@
1
+ export * from "../../dist/declarations/src/runtime.js";
2
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidm9jYWItdml0ZS1ydW50aW1lLmNqcy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vZGlzdC9kZWNsYXJhdGlvbnMvc3JjL3J1bnRpbWUuZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSJ9
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var translationFile = require('@vocab/core/translation-file');
6
+ var icuHandler = require('@vocab/core/icu-handler');
7
+
8
+ const createLanguage = loadImport => {
9
+ let promiseValue;
10
+ let resolvedValue;
11
+ return {
12
+ getValue: locale => {
13
+ if (!resolvedValue) {
14
+ return undefined;
15
+ }
16
+ return icuHandler.getParsedICUMessages(resolvedValue, locale);
17
+ },
18
+ load: () => {
19
+ if (!promiseValue) {
20
+ promiseValue = loadImport();
21
+ promiseValue.then(value => {
22
+ resolvedValue = value.default;
23
+ });
24
+ }
25
+ return promiseValue;
26
+ }
27
+ };
28
+ };
29
+
30
+ Object.defineProperty(exports, 'createTranslationFile', {
31
+ enumerable: true,
32
+ get: function () { return translationFile.createTranslationFile; }
33
+ });
34
+ exports.createLanguage = createLanguage;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./vocab-vite-runtime.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./vocab-vite-runtime.cjs.dev.js");
7
+ }
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var translationFile = require('@vocab/core/translation-file');
6
+ var icuHandler = require('@vocab/core/icu-handler');
7
+
8
+ const createLanguage = loadImport => {
9
+ let promiseValue;
10
+ let resolvedValue;
11
+ return {
12
+ getValue: locale => {
13
+ if (!resolvedValue) {
14
+ return undefined;
15
+ }
16
+ return icuHandler.getParsedICUMessages(resolvedValue, locale);
17
+ },
18
+ load: () => {
19
+ if (!promiseValue) {
20
+ promiseValue = loadImport();
21
+ promiseValue.then(value => {
22
+ resolvedValue = value.default;
23
+ });
24
+ }
25
+ return promiseValue;
26
+ }
27
+ };
28
+ };
29
+
30
+ Object.defineProperty(exports, 'createTranslationFile', {
31
+ enumerable: true,
32
+ get: function () { return translationFile.createTranslationFile; }
33
+ });
34
+ exports.createLanguage = createLanguage;
@@ -0,0 +1,26 @@
1
+ export { createTranslationFile } from '@vocab/core/translation-file';
2
+ import { getParsedICUMessages } from '@vocab/core/icu-handler';
3
+
4
+ const createLanguage = loadImport => {
5
+ let promiseValue;
6
+ let resolvedValue;
7
+ return {
8
+ getValue: locale => {
9
+ if (!resolvedValue) {
10
+ return undefined;
11
+ }
12
+ return getParsedICUMessages(resolvedValue, locale);
13
+ },
14
+ load: () => {
15
+ if (!promiseValue) {
16
+ promiseValue = loadImport();
17
+ promiseValue.then(value => {
18
+ resolvedValue = value.default;
19
+ });
20
+ }
21
+ return promiseValue;
22
+ }
23
+ };
24
+ };
25
+
26
+ export { createLanguage };
@@ -0,0 +1,4 @@
1
+ {
2
+ "main": "dist/vocab-vite-runtime.cjs.js",
3
+ "module": "dist/vocab-vite-runtime.esm.js"
4
+ }