Skip to content

Commit

Permalink
Merge pull request #3372 from opral/flat-list-for-compiler-ootions
Browse files Browse the repository at this point in the history
paraglide js beta 13 clean up
  • Loading branch information
samuelstroschein authored Jan 24, 2025
2 parents dd7d176 + 1d17bad commit 6c55c15
Show file tree
Hide file tree
Showing 46 changed files with 593 additions and 857 deletions.
2 changes: 1 addition & 1 deletion inlang/packages/paraglide/paraglide-astro/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@inlang/paraglide-astro",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"author": "inlang <[email protected]> (https://inlang.com/)",
"description": "A fully type-safe i18n library specifically designed for partial hydration patterns like Astro's islands.",
"homepage": "https://inlang.com/m/iljlwzfs/paraglide-astro-i18n",
Expand Down
13 changes: 8 additions & 5 deletions inlang/packages/paraglide/paraglide-astro/src/integration.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import type { AstroIntegration } from "astro";
import { paraglideVitePlugin, type CompilerArgs } from "@inlang/paraglide-js";
import {
paraglideVitePlugin,
type CompilerOptions,
} from "@inlang/paraglide-js";
import path from "node:path";
import { alias } from "./alias.js";
import { fileURLToPath } from "node:url";
import { alias } from "./alias.js";
import { nodeNormalizePath } from "./utilts.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const middlewarePath = path.join(__dirname, "middleware.js");

export function integration(args: CompilerArgs): AstroIntegration {
export function integration(options: CompilerOptions): AstroIntegration {
return {
name: "paraglide",
hooks: {
Expand All @@ -27,15 +30,15 @@ export function integration(args: CompilerArgs): AstroIntegration {

const runtimePath = path.resolve(
process.cwd(),
args.outdir,
options.outdir,
"runtime.js",
);

//Register the vite plugin
updateConfig({
vite: {
plugins: [
paraglideVitePlugin(args),
paraglideVitePlugin(options),
alias({
//normalizing the path is very important!
//otherwise you get duplicate modules on windows
Expand Down
47 changes: 2 additions & 45 deletions inlang/packages/paraglide/paraglide-astro/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,52 +20,9 @@ defineSetLocale(() => {
export const onRequest: MiddlewareHandler = async (context, next) => {
// const normalizedBase = normalizeBase(import.meta.env!.BASE_URL);

const locale =
context.currentLocale ??
// getLocaleFromPath(context.url.pathname, normalizedBase) ??
baseLocale;
// using astro's i18n routing locale
const locale = context.currentLocale ?? baseLocale;

return await asyncStorage.run(locale, next);
};

// function normalizeBase(rawBase: string): NormalizedBase {
// if (rawBase === "/") return "";
// // if there is a trailing slash, remove it
// return (
// rawBase.endsWith("/") ? rawBase.slice(0, -1) : rawBase
// ) as NormalizedBase;
// }

// function getLocaleFromPath(
// path: string,
// base: NormalizedBase,
// ): string | undefined {
// if (!path.startsWith(base)) return undefined;

// const withoutBasePath = path.replace(base, "");
// const maybeLocale = withoutBasePath.split("/").find(Boolean); // get the first segment
// return isAvailableLocale(maybeLocale) ? maybeLocale : undefined;
// }

// function guessTextDirection(lang: string): "ltr" | "rtl" {
// try {
// const locale = new Intl.Locale(lang);

// // Node
// if ("textInfo" in locale) {
// // @ts-ignore
// return locale.textInfo.direction;
// }

// // Spec compliant (future proofing)
// if ("getTextInfo" in locale) {
// // @ts-ignore
// return locale.getTextInfo().direction;
// }

// // Fallback
// return "ltr";
// } catch (e) {
// return "ltr";
// }
// }
21 changes: 21 additions & 0 deletions inlang/packages/paraglide/paraglide-js/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
# @inlang/paraglide-js

## 2.0.0-beta.13

- flat compiler options

```diff
await compile({
- compilerOptions: {
- emitPrettierIgnore: false,
- },
+ emitPrettierIgnore: false,
})
```

- removed `experimentalEmitTs`. the overhead of maintaing two syntaxes is too large https://github.com/opral/inlang-paraglide-js/issues/329

```diff
await compile({
- experimentalEmitTs: true,
})
```

## 2.0.0-beta.11

- improve: compiler awaits ongoing compilations before starting a new one
Expand Down
74 changes: 40 additions & 34 deletions inlang/packages/paraglide/paraglide-js/docs/compiler-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,22 @@ imports:

# Compiler options

## `project`

The `project` option is the path to the inlang project.

```json
"./project.inlang"
```

## `outdir`

The `outdir` option is the path to the output directory.

```json
"./src/paraglide"
```

## `emitGitIgnore`

If `emitGitIgnore` is set to `true` a `.gitignore` file will be emitted in the output directory. Defaults to `true`.
Expand All @@ -29,6 +45,30 @@ If `emitPrettierIgnore` is set to `true` a `.prettierignore` file will be emitte
- runtime.js
```

## `additionalFiles`

The `additionalFiles` option is an array of paths to additional files that should be copied to the output directory.

The option is often used by adapters to include additional files that are specific for a framework.

```diff
await compile({
project: "./project.inlang",
outdir: "./src/paraglide",
additionalFiles: [
+ "my-file.js": "console.log('hello')"
]
})
```

```diff
- outdir/
- messages/
+ - my-file.js
- messages.js
- runtime.js
```

## `outputStructure`

The `outputStructure` defines how modules are structured in the output.
Expand Down Expand Up @@ -70,37 +110,3 @@ Messages are bundled in a per locale module. Bundlers sometimes struggle tree-sh
- messages.js
- runtime.js
```

## `experimentalEmitTs`

Emits TypeScript files instead of JSDoc annotated JavaScript files. Defaults to `false`.

<doc-callout type="warning">
This feature is experimental and may change or be removed in the future.
</doc-callout>

```diff
- outdir/
- - messages.js
+ - messages.ts
- - runtime.js
+ - runtime.ts
...
```

## `experimentalUseTsImports`

Imports emitted files with `.ts` extension instead of `.js`. Defaults to `false`.

Only works in combination with `experimentalEmitTs`. The feature is useful in some
codebases which need to resolve TypeScript files with a `.ts` ending. Node's
strip-types flag is an example.

<doc-callout type="warning">
This feature is experimental and may change or be removed in the future.
</doc-callout>

```diff
-import { getLocale } from "./runtime.js";
+import { getLocale } from "./runtime.ts";
```
12 changes: 4 additions & 8 deletions inlang/packages/paraglide/paraglide-js/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@inlang/paraglide-js",
"type": "module",
"version": "2.0.0-beta.12",
"version": "2.0.0-beta.13",
"license": "MIT",
"publishConfig": {
"access": "public",
Expand All @@ -18,8 +18,7 @@
},
"files": [
"./dist",
"./bin",
"./default"
"./bin"
],
"scripts": {
"dev": "tsc --watch",
Expand All @@ -30,8 +29,7 @@
"env-variables": "node ./src/services/env-variables/create-index-file.js",
"lint": "eslint ./src --fix",
"format": "prettier ./src --write",
"clean": "rm -rf ./dist ./node_modules",
"check": "tsc --noEmit --emitDeclarationOnly false"
"clean": "rm -rf ./dist ./node_modules"
},
"dependencies": {
"@inlang/recommend-sherlock": "workspace:*",
Expand All @@ -58,9 +56,7 @@
"vitest": "2.1.8"
},
"exports": {
".": "./dist/index.js",
"./cli": "./dist/cli/index.js",
"./compiler": "./dist/compiler/index.js"
".": "./dist/index.js"
},
"keywords": [
"inlang",
Expand Down
16 changes: 0 additions & 16 deletions inlang/packages/paraglide/paraglide-js/project.inlang.json

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { UnpluginFactory } from "unplugin";
import { compile, type CompilerArgs } from "../compiler/compile.js";
import { compile, type CompilerOptions } from "../compiler/compile.js";
import fs from "node:fs";
import { resolve } from "node:path";

const PLUGIN_NAME = "unplugin-paraglide-js";

export const unpluginFactory: UnpluginFactory<CompilerArgs> = (args) => ({
export const unpluginFactory: UnpluginFactory<CompilerOptions> = (args) => ({
name: PLUGIN_NAME,
enforce: "pre",
async buildStart() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { test, expect } from "vitest";
import { compileBundle } from "./compile-bundle.js";
import type { BundleNested } from "@inlang/sdk";

test("compiles as ts", async () => {
test("compiles to jsdoc", async () => {
const result = compileBundle({
emitTs: true,
fallbackMap: {
en: "en",
"en-US": "en",
Expand All @@ -22,9 +21,12 @@ test("compiles as ts", async () => {
* - If you want to change the translations, you can either edit the source files e.g. \`en.json\`, or
* use another inlang app like [Fink](https://inlang.com/m/tdozzpar) or the [VSCode extension Sherlock](https://inlang.com/m/r7kp499g).
*
* @param {{ age: NonNullable<unknown> }} inputs
* @param {{ locale?: "en" | "en-US" }} options
* @returns {string}
*/
/* @__NO_SIDE_EFFECTS__ */
const blue_moon_bottle = (inputs: { age: NonNullable<unknown> } , options: { locale?: "en" | "en-US" } = {}) : string => {
const blue_moon_bottle = (inputs, options = {}) => {
const locale = options.locale ?? getLocale()
if (locale === "en") return en.blue_moon_bottle(inputs)
if (locale === "en-US") return en_US.blue_moon_bottle(inputs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export const compileBundle = (args: {
bundle: BundleNested;
fallbackMap: Record<string, string | undefined>;
registry: Registry;
emitTs: boolean;
}): CompiledBundleWithMessages => {
const compiledMessages: Record<string, Compiled<Message>> = {};

Expand All @@ -45,11 +44,8 @@ export const compileBundle = (args: {
const inputs = args.bundle.declarations.filter(
(decl) => decl.type === "input-variable"
);
if (args.emitTs) {
//
} else {
compiledMessage.code = `${jsDocMessageFunctionTypes({ inputs })}\n${compiledMessage.code}`;
}

compiledMessage.code = `${jsDocMessageFunctionTypes({ inputs })}\n${compiledMessage.code}`;

// set the pattern for the language tag
compiledMessages[message.locale] = compiledMessage;
Expand All @@ -59,7 +55,6 @@ export const compileBundle = (args: {
bundle: compileBundleFunction({
bundle: args.bundle,
availableLocales: Object.keys(args.fallbackMap),
emitTs: args.emitTs,
}),
messages: compiledMessages,
};
Expand All @@ -74,26 +69,23 @@ const compileBundleFunction = (args: {
* The language tags which are available
*/
availableLocales: string[];
emitTs: boolean;
}): Compiled<Bundle> => {
const inputs = args.bundle.declarations.filter(
(decl) => decl.type === "input-variable"
);
const hasInputs = inputs.length > 0;

const emitTs = args.emitTs;

let code = `/**
* This function has been compiled by [Paraglide JS](https://inlang.com/m/gerre34r).
*
* - Changing this function will be over-written by the next build.
*
* - If you want to change the translations, you can either edit the source files e.g. \`en.json\`, or
* use another inlang app like [Fink](https://inlang.com/m/tdozzpar) or the [VSCode extension Sherlock](https://inlang.com/m/r7kp499g).
* ${emitTs ? "" : jsDocBundleFunctionTypes({ inputs, locales: args.availableLocales })}
* ${jsDocBundleFunctionTypes({ inputs, locales: args.availableLocales })}
*/
/* @__NO_SIDE_EFFECTS__ */
const ${jsIdentifier(args.bundle.id)} = (inputs${emitTs ? tsInputType(inputs) : ""} ${hasInputs ? "" : "= {}"}, options${emitTs ? tsOptionsType(args.availableLocales) : ""} = {}) ${emitTs ? ": string" : ""} => {
const ${jsIdentifier(args.bundle.id)} = (inputs${hasInputs ? "" : "= {}"}, options = {}) => {
const locale = options.locale ?? getLocale()
${args.availableLocales
.map(
Expand All @@ -117,17 +109,3 @@ const ${jsIdentifier(args.bundle.id)} = (inputs${emitTs ? tsInputType(inputs) :
node: args.bundle,
};
};

function tsOptionsType(locales: string[]): string {
const localesUnion = locales.map((locale) => `"${locale}"`).join(" | ");
return `: { locale?: ${localesUnion} }`;
}

function tsInputType(inputs: { name: string }[]): string {
const inputParams = inputs
.map((input) => {
return `${input.name}: NonNullable<unknown>`;
})
.join(", ");
return `: { ${inputParams} }`;
}
Loading

0 comments on commit 6c55c15

Please sign in to comment.