@linguanahq/vite 0.1.0 → 0.1.2

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/package.json CHANGED
@@ -1,51 +1,66 @@
1
1
  {
2
- "name": "@linguanahq/vite",
3
- "version": "0.1.0",
4
- "publishConfig": {
5
- "access": "public"
6
- },
7
- "type": "module",
8
- "exports": {
9
- ".": "./src/index.ts",
10
- "./react": "./src/react.ts",
11
- "./solid": "./src/solid.ts",
12
- "./vue": "./src/vue.ts",
13
- "./svelte": "./src/svelte.ts"
14
- },
15
- "imports": {
16
- "#shared": "./src/shared.ts"
17
- },
18
- "scripts": {
19
- "check-types": "tsc --noEmit",
20
- "test": "bun test"
21
- },
22
- "dependencies": {
23
- "@linguanahq/build-core": "0.1.0",
24
- "@linguanahq/catalog": "0.1.0",
25
- "@linguanahq/compiler": "0.1.0",
26
- "magic-string": "^0.30.21"
27
- },
28
- "devDependencies": {
29
- "@linguana/config": "0.0.0",
30
- "@types/bun": "^1.3.14",
31
- "@vue/compiler-dom": "^3.5.24",
32
- "@vue/compiler-sfc": "^3.5.24",
33
- "svelte": "^5.43.8",
34
- "typescript": "^6",
35
- "vite": "^8.1.3"
36
- },
37
- "peerDependencies": {
38
- "vite": ">=7 <9"
39
- },
40
- "peerDependenciesMeta": {
41
- "@vue/compiler-dom": {
42
- "optional": true
43
- },
44
- "@vue/compiler-sfc": {
45
- "optional": true
46
- },
47
- "svelte": {
48
- "optional": true
49
- }
50
- }
2
+ "name": "@linguanahq/vite",
3
+ "version": "0.1.2",
4
+ "type": "module",
5
+ "description": "Linguana vite integration",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./react": {
13
+ "types": "./dist/react.d.ts",
14
+ "import": "./dist/react.js",
15
+ "default": "./dist/react.js"
16
+ },
17
+ "./solid": {
18
+ "types": "./dist/solid.d.ts",
19
+ "import": "./dist/solid.js",
20
+ "default": "./dist/solid.js"
21
+ },
22
+ "./vue": {
23
+ "types": "./dist/vue.d.ts",
24
+ "import": "./dist/vue.js",
25
+ "default": "./dist/vue.js"
26
+ },
27
+ "./svelte": {
28
+ "types": "./dist/svelte.d.ts",
29
+ "import": "./dist/svelte.js",
30
+ "default": "./dist/svelte.js"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "engines": {
37
+ "node": ">=22.12.0"
38
+ },
39
+ "dependencies": {
40
+ "@linguanahq/build-core": "0.1.2",
41
+ "@linguanahq/catalog": "0.1.2",
42
+ "@linguanahq/compiler": "0.1.2",
43
+ "magic-string": "^0.30.21",
44
+ "@linguanahq/core": "0.1.2"
45
+ },
46
+ "peerDependencies": {
47
+ "vite": ">=7 <9",
48
+ "@vue/compiler-dom": ">=3.5 <4",
49
+ "@vue/compiler-sfc": ">=3.5 <4",
50
+ "svelte": ">=5 <6"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "@vue/compiler-dom": {
54
+ "optional": true
55
+ },
56
+ "@vue/compiler-sfc": {
57
+ "optional": true
58
+ },
59
+ "svelte": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "publishConfig": {
64
+ "access": "public"
65
+ }
51
66
  }
package/src/index.ts DELETED
@@ -1,173 +0,0 @@
1
- import { isAbsolute, relative, resolve } from "node:path";
2
-
3
- import {
4
- BuildSession,
5
- type SourceAdapter,
6
- type StrictPolicy,
7
- } from "@linguanahq/build-core";
8
- import {
9
- createFilter,
10
- normalizePath,
11
- type Plugin,
12
- type TransformResult,
13
- version as viteVersion,
14
- } from "vite";
15
-
16
- export type LinguanaViteAdapter = SourceAdapter;
17
- export type LinguanaViteOptions = {
18
- adapter: LinguanaViteAdapter;
19
- projectId: string;
20
- environment?: string;
21
- sourceLocale?: string;
22
- apiUrl?: string;
23
- token?: string;
24
- include?: string | string[];
25
- exclude?: string | string[];
26
- output?: string;
27
- upload?: boolean;
28
- strict?: StrictPolicy;
29
- translation?:
30
- | false
31
- | {
32
- enabled: true;
33
- maxChargeMicros: number;
34
- waitTimeoutMs?: number;
35
- publish: "development";
36
- };
37
- };
38
-
39
- const VERSION = "0.1.0";
40
- const OFFICIAL_PLUGINS: Record<SourceAdapter["id"], string[]> = {
41
- react: [
42
- "vite:react-babel",
43
- "vite:react-refresh",
44
- "react-refresh/babel",
45
- "tanstack-start",
46
- ],
47
- solid: ["solid"],
48
- vue: ["vite:vue"],
49
- svelte: ["vite-plugin-svelte"],
50
- };
51
-
52
- export function linguana(options: LinguanaViteOptions): Plugin {
53
- if (!options.adapter)
54
- throw new Error("Linguana requires exactly one framework adapter.");
55
- const environment = options.environment ?? "development";
56
- const sourceLocale = options.sourceLocale ?? "en";
57
- if (options.translation && (!options.token || environment !== "development"))
58
- throw new Error(
59
- "Build translation requires a token and the development environment.",
60
- );
61
- if (
62
- options.translation &&
63
- (!Number.isSafeInteger(options.translation.maxChargeMicros) ||
64
- options.translation.maxChargeMicros <= 0)
65
- )
66
- throw new Error(
67
- "translation.maxChargeMicros must be a positive safe integer.",
68
- );
69
- let root = process.cwd();
70
- let session: BuildSession;
71
- let filter: ReturnType<typeof createFilter>;
72
- let sawSsr = false;
73
- let processSource: (
74
- code: string,
75
- filename: string,
76
- ssr?: boolean,
77
- ) => Promise<TransformResult | null>;
78
-
79
- const plugin: Plugin & { api?: Record<string, unknown> } = {
80
- name: "linguana:vite",
81
- enforce: "pre",
82
- configResolved(config) {
83
- root = config.root;
84
- filter = createFilter(
85
- options.include ??
86
- options.adapter.extensions.map((extension) => `**/*${extension}`),
87
- options.exclude ?? ["**/node_modules/**", "**/*.test.*", "**/*.spec.*"],
88
- );
89
- session = new BuildSession({
90
- projectId: options.projectId,
91
- environment,
92
- sourceLocale,
93
- compilerVersion: VERSION,
94
- strict: options.strict,
95
- integration: {
96
- tool: "vite",
97
- toolVersion: viteVersion,
98
- framework: options.adapter.id,
99
- adapterVersion: options.adapter.version,
100
- ssr: false,
101
- },
102
- });
103
- const ownIndex = config.plugins.findIndex(
104
- (item) => item.name === "linguana:vite",
105
- );
106
- const frameworkIndex = config.plugins.findIndex((item) =>
107
- OFFICIAL_PLUGINS[options.adapter.id].some((name) =>
108
- item.name.includes(name),
109
- ),
110
- );
111
- if (frameworkIndex < 0)
112
- throw new Error(
113
- `Linguana ${options.adapter.id} adapter requires the official ${options.adapter.id} Vite plugin.`,
114
- );
115
- if (ownIndex > frameworkIndex)
116
- throw new Error(
117
- `Place linguana() before the official ${options.adapter.id} plugin in vite.config.ts.`,
118
- );
119
- processSource = async (code, filename, ssr = false) => {
120
- const cleanId = normalizePath(filename.split("?", 1)[0] ?? filename);
121
- const projectRelativeId = relative(root, cleanId);
122
- if (
123
- options.include === undefined &&
124
- (projectRelativeId === ".." ||
125
- projectRelativeId.startsWith("../") ||
126
- projectRelativeId.startsWith("..\\") ||
127
- isAbsolute(projectRelativeId))
128
- )
129
- return null;
130
- if (!filter(cleanId)) return null;
131
- if (ssr) {
132
- sawSsr = true;
133
- session.options.integration.ssr = true;
134
- }
135
- const result = await options.adapter.transform({
136
- code,
137
- filename: cleanId,
138
- root,
139
- sourceLocale,
140
- });
141
- if (!result) return null;
142
- session.collect(result);
143
- return {
144
- code: result.code,
145
- map: result.map as TransformResult["map"],
146
- };
147
- };
148
- },
149
- async transform(code, id, transformOptions) {
150
- return processSource(code, id, Boolean(transformOptions?.ssr));
151
- },
152
- async writeBundle() {
153
- const manifest = await session.write(
154
- resolve(root, options.output ?? ".linguana/manifest.json"),
155
- );
156
- for (const item of session.diagnostics)
157
- this[item.severity === "error" ? "error" : "warn"](
158
- `${item.code}: ${item.message}`,
159
- );
160
- if ((options.upload ?? Boolean(options.token)) && options.token)
161
- await session.upload(manifest, {
162
- apiUrl: options.apiUrl ?? "https://api.linguana.dev",
163
- token: options.token,
164
- translation: options.translation,
165
- onProgress: (message) => this.info(`[linguana] ${message}`),
166
- });
167
- void sawSsr;
168
- },
169
- };
170
- return plugin;
171
- }
172
-
173
- export default linguana;
package/src/react.ts DELETED
@@ -1,19 +0,0 @@
1
- import type { SourceAdapter } from "@linguanahq/build-core";
2
- import { transformSource } from "@linguanahq/compiler";
3
-
4
- export function react(): SourceAdapter {
5
- return {
6
- id: "react",
7
- version: "0.1.0",
8
- extensions: [".jsx", ".tsx"],
9
- runtimeModule: "@linguanahq/react/compiler-runtime",
10
- async transform(input) {
11
- return transformSource(input.code, input.filename, {
12
- sourceLocale: input.sourceLocale,
13
- root: input.root,
14
- }) as ReturnType<SourceAdapter["transform"]> extends Promise<infer T>
15
- ? T
16
- : never;
17
- },
18
- };
19
- }
package/src/shared.ts DELETED
@@ -1,145 +0,0 @@
1
- import { relative } from "node:path";
2
-
3
- import {
4
- contentHash,
5
- type Diagnostic,
6
- type ManifestMessage,
7
- normalizeSource,
8
- parseMessagePlaceholders,
9
- stableMessageId,
10
- } from "@linguanahq/catalog";
11
-
12
- export const EXCLUDED_ELEMENTS = new Set(["script", "style", "code", "pre"]);
13
- export const TRANSLATABLE_ATTRIBUTES = new Set([
14
- "title",
15
- "placeholder",
16
- "aria-label",
17
- "alt",
18
- "label",
19
- ]);
20
-
21
- export function renderedText(value: string) {
22
- return value.replace(/\s+/g, " ").trim();
23
- }
24
-
25
- export function escapeAttribute(value: string) {
26
- return value
27
- .replaceAll("&", "&amp;")
28
- .replaceAll('"', "&quot;")
29
- .replaceAll("<", "&lt;");
30
- }
31
-
32
- export function message(input: {
33
- source: string;
34
- filename: string;
35
- root: string;
36
- line: number;
37
- column: number;
38
- sourceLocale: string;
39
- element: string;
40
- }): ManifestMessage {
41
- const context = { kind: "text" as const, element: input.element };
42
- return {
43
- id: stableMessageId({
44
- sourceLocale: input.sourceLocale,
45
- source: input.source,
46
- context,
47
- }),
48
- source: input.source,
49
- normalized: normalizeSource(input.source),
50
- contentHash: contentHash(input.source),
51
- context,
52
- placeholders: parseMessagePlaceholders(input.source),
53
- confidence: "high",
54
- locations: [
55
- {
56
- file: relative(input.root, input.filename).replaceAll("\\", "/"),
57
- line: input.line,
58
- column: input.column,
59
- },
60
- ],
61
- };
62
- }
63
-
64
- export function attributeMessage(input: {
65
- source: string;
66
- filename: string;
67
- root: string;
68
- line: number;
69
- column: number;
70
- sourceLocale: string;
71
- element: string;
72
- attribute: string;
73
- }): ManifestMessage {
74
- const context = {
75
- kind: "attribute" as const,
76
- element: input.element,
77
- attribute: input.attribute,
78
- };
79
- return {
80
- id: stableMessageId({
81
- sourceLocale: input.sourceLocale,
82
- source: input.source,
83
- context,
84
- }),
85
- source: input.source,
86
- normalized: normalizeSource(input.source),
87
- contentHash: contentHash(input.source),
88
- context,
89
- placeholders: parseMessagePlaceholders(input.source),
90
- confidence: "high",
91
- locations: [
92
- {
93
- file: relative(input.root, input.filename).replaceAll("\\", "/"),
94
- line: input.line,
95
- column: input.column,
96
- },
97
- ],
98
- };
99
- }
100
-
101
- export function explicitMessage(input: {
102
- source: string;
103
- explicitId?: string;
104
- filename: string;
105
- root: string;
106
- line: number;
107
- column: number;
108
- sourceLocale: string;
109
- }): ManifestMessage {
110
- const context = { kind: "explicit" as const };
111
- return {
112
- id: stableMessageId({
113
- sourceLocale: input.sourceLocale,
114
- source: input.source,
115
- context,
116
- explicitId: input.explicitId,
117
- }),
118
- source: input.source,
119
- normalized: normalizeSource(input.source),
120
- contentHash: contentHash(input.source),
121
- context,
122
- placeholders: parseMessagePlaceholders(input.source),
123
- confidence: "explicit",
124
- locations: [
125
- {
126
- file: relative(input.root, input.filename).replaceAll("\\", "/"),
127
- line: input.line,
128
- column: input.column,
129
- },
130
- ],
131
- };
132
- }
133
-
134
- export function unsafeDiagnostic(
135
- item: ManifestMessage,
136
- ): Diagnostic | undefined {
137
- if (/^(?:https?:\/\/|mailto:|tel:|www\.)/i.test(item.normalized))
138
- return {
139
- code: "unsafe-static-copy",
140
- severity: "info",
141
- message:
142
- "URL-like or machine-readable text was excluded from extraction.",
143
- location: item.locations[0],
144
- };
145
- }
package/src/solid.ts DELETED
@@ -1,21 +0,0 @@
1
- import type { SourceAdapter } from "@linguanahq/build-core";
2
- import { transformSource } from "@linguanahq/compiler";
3
-
4
- export function solid(): SourceAdapter {
5
- return {
6
- id: "solid",
7
- version: "0.1.0",
8
- extensions: [".jsx", ".tsx"],
9
- runtimeModule: "@linguanahq/solid/compiler-runtime",
10
- async transform(input) {
11
- return transformSource(input.code, input.filename, {
12
- sourceLocale: input.sourceLocale,
13
- root: input.root,
14
- runtimePackage: "@linguanahq/solid",
15
- compilerRuntime: "@linguanahq/solid/compiler-runtime",
16
- }) as ReturnType<SourceAdapter["transform"]> extends Promise<infer T>
17
- ? T
18
- : never;
19
- },
20
- };
21
- }
package/src/svelte.ts DELETED
@@ -1,226 +0,0 @@
1
- import type { SourceAdapter } from "@linguanahq/build-core";
2
- import type { Diagnostic, ManifestMessage } from "@linguanahq/catalog";
3
- import MagicString from "magic-string";
4
- import { parse } from "svelte/compiler";
5
-
6
- import {
7
- attributeMessage,
8
- EXCLUDED_ELEMENTS,
9
- escapeAttribute,
10
- explicitMessage,
11
- message,
12
- renderedText,
13
- TRANSLATABLE_ATTRIBUTES,
14
- unsafeDiagnostic,
15
- } from "#shared";
16
-
17
- type SvelteAttribute = {
18
- type: string;
19
- name: string;
20
- start: number;
21
- end: number;
22
- value?: Array<{ type: string; data?: string }>;
23
- };
24
-
25
- type SvelteNode = {
26
- type: string;
27
- name?: string;
28
- start: number;
29
- end: number;
30
- data?: string;
31
- attributes?: SvelteAttribute[];
32
- fragment?: { nodes?: SvelteNode[] };
33
- [key: string]: unknown;
34
- };
35
-
36
- type SvelteRoot = {
37
- fragment: SvelteNode;
38
- instance?: { content?: { start?: number } };
39
- };
40
-
41
- function position(code: string, offset: number) {
42
- const before = code.slice(0, offset).split("\n");
43
- return { line: before.length, column: (before.at(-1) ?? "").length };
44
- }
45
-
46
- export function svelte(): SourceAdapter {
47
- return {
48
- id: "svelte",
49
- version: "0.1.0",
50
- extensions: [".svelte"],
51
- runtimeModule: "@linguanahq/svelte/compiler-runtime",
52
- async transform(input) {
53
- const ast = parse(input.code, {
54
- filename: input.filename,
55
- modern: true,
56
- }) as unknown as SvelteRoot;
57
- const output = new MagicString(input.code);
58
- const messages: ManifestMessage[] = [];
59
- const diagnostics: Diagnostic[] = [];
60
- const seen = new Set<SvelteNode>();
61
- const visit = (
62
- node: SvelteNode,
63
- excluded = false,
64
- parentTag = "svelte:fragment",
65
- ) => {
66
- if (!node || typeof node !== "object" || seen.has(node)) return;
67
- seen.add(node);
68
- const tag = ["RegularElement", "Component"].includes(node.type)
69
- ? String(node.name)
70
- : parentTag;
71
- const nextExcluded =
72
- excluded ||
73
- EXCLUDED_ELEMENTS.has(tag.toLowerCase()) ||
74
- (node.attributes ?? []).some((attribute) =>
75
- ["data-no-translate", "hidden"].includes(attribute.name),
76
- );
77
- if (
78
- node.type === "Component" &&
79
- ["T", "LinguanaMessage"].includes(tag)
80
- ) {
81
- const literal = (name: string) => {
82
- const attribute = (node.attributes ?? []).find(
83
- (item) => item.type === "Attribute" && item.name === name,
84
- );
85
- return attribute?.value?.length === 1 &&
86
- attribute.value[0]?.type === "Text"
87
- ? attribute.value[0].data
88
- : undefined;
89
- };
90
- const source = literal("defaultMessage");
91
- if (source) {
92
- const loc = position(input.code, node.start);
93
- messages.push(
94
- explicitMessage({
95
- source,
96
- explicitId: literal("id"),
97
- filename: input.filename,
98
- root: input.root,
99
- line: loc.line,
100
- column: loc.column,
101
- sourceLocale: input.sourceLocale,
102
- }),
103
- );
104
- }
105
- return;
106
- }
107
- const fragmentChildren = node.fragment?.nodes ?? [];
108
- if (
109
- node.type === "RegularElement" &&
110
- fragmentChildren.some(
111
- (child: { type: string; data?: string }) =>
112
- child.type === "Text" && Boolean(renderedText(child.data ?? "")),
113
- ) &&
114
- fragmentChildren.some(
115
- (child: { type: string }) => child.type !== "Text",
116
- )
117
- ) {
118
- const loc = position(input.code, node.start);
119
- diagnostics.push({
120
- code: "ambiguous-rich-text",
121
- severity: "warning",
122
- message:
123
- "Mixed text and Svelte template nodes require an explicit <T> message.",
124
- location: {
125
- file: input.filename.slice(input.root.length + 1),
126
- line: loc.line,
127
- column: loc.column,
128
- },
129
- remediation: "Use <T defaultMessage> or data-no-translate.",
130
- });
131
- return;
132
- }
133
- if (node.type === "RegularElement" && !nextExcluded) {
134
- for (const attribute of node.attributes ?? []) {
135
- const text =
136
- attribute.type === "Attribute" &&
137
- attribute.value?.length === 1 &&
138
- attribute.value[0]?.type === "Text"
139
- ? attribute.value[0]
140
- : undefined;
141
- if (
142
- !text ||
143
- typeof text.data !== "string" ||
144
- !TRANSLATABLE_ATTRIBUTES.has(attribute.name)
145
- )
146
- continue;
147
- const loc = position(input.code, attribute.start);
148
- const item = attributeMessage({
149
- source: text.data,
150
- filename: input.filename,
151
- root: input.root,
152
- line: loc.line,
153
- column: loc.column,
154
- sourceLocale: input.sourceLocale,
155
- element: tag,
156
- attribute: attribute.name,
157
- });
158
- messages.push(item);
159
- output.overwrite(
160
- attribute.start,
161
- attribute.end,
162
- `${attribute.name}={String(__linguana.translate(${JSON.stringify(item.id)}, ${JSON.stringify(text.data)}))}`,
163
- );
164
- }
165
- }
166
- if (node.type === "Text" && !nextExcluded) {
167
- const source = renderedText(
168
- node.data ?? input.code.slice(node.start, node.end),
169
- );
170
- if (source) {
171
- const loc = position(input.code, node.start);
172
- const item = message({
173
- source,
174
- filename: input.filename,
175
- root: input.root,
176
- line: loc.line,
177
- column: loc.column,
178
- sourceLocale: input.sourceLocale,
179
- element: parentTag,
180
- });
181
- const unsafe = unsafeDiagnostic(item);
182
- if (unsafe) diagnostics.push(unsafe);
183
- else {
184
- messages.push(item);
185
- output.overwrite(
186
- node.start,
187
- node.end,
188
- `<LinguanaMessage id="${item.id}" defaultMessage="${escapeAttribute(source)}" />`,
189
- );
190
- }
191
- }
192
- }
193
- for (const [key, value] of Object.entries(node)) {
194
- if (["parent", "metadata", "attributes"].includes(key)) continue;
195
- if (Array.isArray(value))
196
- for (const child of value)
197
- visit(child as SvelteNode, nextExcluded, tag);
198
- else if (value && typeof value === "object" && "type" in value)
199
- visit(value as SvelteNode, nextExcluded, tag);
200
- }
201
- };
202
- visit(ast.fragment);
203
- if (!messages.length && !diagnostics.length) return null;
204
- if (messages.length) {
205
- const importStatement = `\n<script>\nimport LinguanaMessage from "@linguanahq/svelte/compiler-runtime";\nimport { getLinguana } from "@linguanahq/svelte";\nconst __linguana = getLinguana();\n</script>\n`;
206
- const instance = ast.instance;
207
- if (instance?.content?.start !== undefined)
208
- output.appendLeft(
209
- instance.content.start,
210
- `\nimport LinguanaMessage from "@linguanahq/svelte/compiler-runtime";\nimport { getLinguana as __getLinguana } from "@linguanahq/svelte";\nconst __linguana = __getLinguana();`,
211
- );
212
- else output.prepend(importStatement);
213
- }
214
- return {
215
- code: output.toString(),
216
- map: output.generateMap({
217
- hires: true,
218
- source: input.filename,
219
- includeContent: true,
220
- }) as unknown as Record<string, unknown>,
221
- messages,
222
- diagnostics,
223
- };
224
- },
225
- };
226
- }