PWA - patched deps

This commit is contained in:
Giancarmine Salucci
2025-11-29 17:35:20 +01:00
parent dfa2eb1c4e
commit 0477964009
11 changed files with 10435 additions and 4656 deletions

7
Dockerfile Normal file
View File

@@ -0,0 +1,7 @@
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
EXPOSE 5173
CMD ["npm", "run", "dev", "--", "--host"]

34
docker-compose.yml Normal file
View File

@@ -0,0 +1,34 @@
services:
app:
build: .
ports:
- "5173:5173"
environment:
- PLAYWRIGHT_WS_ENDPOINT=ws://playwright-service:3000
- OPENAI_BASE_URL=http://ollama:11434/v1
- OPENAI_API_KEY=ollama
- LLM_MODEL=llama3.2
volumes:
- ./src:/app/src
- ./secrets:/app/secrets:ro
depends_on:
- playwright-service
- ollama
playwright-service:
build: ./playwright-service
ipc: host
ports: ["3000:3000"]
environment:
- DISPLAY=:99
security_opt:
- seccomp=unconfined
ollama:
image: ollama/ollama:latest
ports: ["11434:11434"]
volumes:
- ollama_data:/root/.ollama
volumes:
ollama_data:

14708
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,44 +1,49 @@
{
"name": "insta-recipe",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint .",
"test:unit": "vitest",
"test": "npm run test:unit -- --run"
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
"@sveltejs/adapter-node": "^5.4.0",
"@sveltejs/kit": "^2.48.5",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17",
"@types/node": "^22",
"@vitest/browser-playwright": "^4.0.10",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.13.0",
"globals": "^16.5.0",
"playwright": "^1.56.1",
"prettier": "^3.6.2",
"prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.7.1",
"svelte": "^5.43.8",
"svelte-check": "^4.3.4",
"tailwindcss": "^4.1.17",
"typescript": "^5.9.3",
"typescript-eslint": "^8.47.0",
"vite": "^7.2.2",
"vitest": "^4.0.10",
"vitest-browser-svelte": "^2.0.1"
}
"name": "insta-recipe",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint .",
"test:unit": "vitest",
"test": "npm run test:unit -- --run"
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
"@sveltejs/adapter-node": "^5.4.0",
"@sveltejs/kit": "^2.48.5",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17",
"@types/node": "^22",
"@vitest/browser-playwright": "^4.0.10",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.13.0",
"globals": "^16.5.0",
"playwright": "^1.56.1",
"prettier": "^3.6.2",
"prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.7.1",
"svelte": "^5.43.8",
"svelte-check": "^4.3.4",
"tailwindcss": "^4.1.17",
"typescript": "^5.9.3",
"typescript-eslint": "^8.47.0",
"vite": "^6.0.0",
"vitest": "^4.0.10",
"vitest-browser-svelte": "^2.0.1",
"@vite-pwa/sveltekit": "^0.3.0"
},
"dependencies": {
"zod": "^3.23.0",
"openai": "^4.20.0"
}
}

View File

@@ -0,0 +1,6 @@
FROM mcr.microsoft.com/playwright:v1.49.0-jammy
WORKDIR /app
RUN npm init -y && npm install playwright
COPY server.js .
EXPOSE 3000
CMD ["node", "server.js"]

View File

@@ -0,0 +1,10 @@
const { chromium } = require('playwright');
(async () => {
const server = await chromium.launchServer({
port: 3000,
headless: true,
args: ['--disable-gpu', '--no-sandbox', '--disable-dev-shm-usage']
});
console.log('Browser Server running on port 3000...');
await new Promise(() => {});
})();

25
scripts/gen-auth.js Normal file
View File

@@ -0,0 +1,25 @@
import { chromium } from 'playwright';
import fs from 'fs';
import path from 'path';
(async () => {
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
console.log('🔹 Navigating to Instagram...');
await page.goto('https://www.instagram.com/');
console.log('⏳ Please log in manually. Waiting for "Home" icon...');
try {
await page.waitForSelector('svg[aria-label="Home"]', { timeout: 120000 });
const secretsDir = path.resolve('secrets');
if (!fs.existsSync(secretsDir)) fs.mkdirSync(secretsDir);
await context.storageState({ path: path.join(secretsDir, 'auth.json') });
console.log('🎉 Session saved to secrets/auth.json');
} catch (e) {
console.error('❌ Timeout or error:', e);
}
await browser.close();
})();

12
src/lib/server/llm.ts Normal file
View File

@@ -0,0 +1,12 @@
import OpenAI from 'openai';
import { env } from '$env/dynamic/private';
export const createLLM = () => {
// Detect if we are using Ollama or OpenAI based on URL
const baseURL = env.OPENAI_BASE_URL;
const client = new OpenAI({
apiKey: env.OPENAI_API_KEY,
baseURL: baseURL
});
return { client, model: env.LLM_MODEL || 'gpt-4o' };
};

View File

@@ -0,0 +1,76 @@
import { json } from '@sveltejs/kit';
import { createLLM } from '$lib/server/llm';
import { z } from 'zod';
import { zodResponseFormat } from 'openai/helpers/zod';
import { chromium } from 'playwright';
import fs from 'fs';
import { env } from '$env/dynamic/private';
const RecipeSchema = z.object({
name: z.string(),
description: z.string(),
steps: z.array(z.string()),
ingredients: z.array(z.object({
item: z.string(),
amount: z.string(),
unit: z.string()
}))
});
export async function POST({ request }) {
const { url } = await request.json();
// 1. Browser Connection
// Fallback to localhost if env var not set (e.g. running outside docker)
const wsEndpoint = env.PLAYWRIGHT_WS_ENDPOINT || 'ws://127.0.0.1:3000';
console.log('Connecting to browser at:', wsEndpoint);
const browser = await chromium.connect(wsEndpoint);
// 2. Load Auth if available
const authPath = '/app/secrets/auth.json';
let context;
// We check absolute path (Docker) or relative (Local)
if (fs.existsSync(authPath)) {
context = await browser.newContext({ storageState: authPath });
} else if (fs.existsSync('./secrets/auth.json')) {
context = await browser.newContext({ storageState: './secrets/auth.json' });
} else {
console.warn('No auth.json found. Running as guest.');
context = await browser.newContext();
}
const page = await context.newPage();
let bodyText = '';
try {
await page.goto(url, { waitUntil: 'domcontentloaded' });
// Naive scraper attempt
bodyText = await page.evaluate(() => document.body.innerText);
} catch (e) {
console.error('Scraping error:', e);
return json({ error: 'Failed to scrape URL' }, { status: 500 });
} finally {
await page.close();
await context.close();
await browser.close();
}
// 3. LLM Processing
try {
const { client, model } = createLLM();
const completion = await client.beta.chat.completions.parse({
model,
messages: [
{ role: "system", content: "Extract a recipe structure from this text. If it is not a recipe, return empty arrays." },
{ role: "user", content: bodyText.substring(0, 8000) } // Limit context window
],
response_format: zodResponseFormat(RecipeSchema, "recipe")
});
return json({ recipe: completion.choices[0].message.parsed });
} catch (e) {
console.error('LLM error:', e);
return json({ error: 'Failed to parse recipe' }, { status: 500 });
}
}

View File

@@ -0,0 +1,84 @@
<script lang="ts">
import { page } from '$app/stores';
let status = $state('idle');
let logs = $state<string[]>([]);
let recipe = $state<any>(null);
// URL param parsing for Share Target
// Instagram typically shares text that contains the URL, so we might need to parse it out
let sharedText = $derived($page.url.searchParams.get('text') || '');
let sharedUrl = $derived($page.url.searchParams.get('url') || '');
function extractUrl(text: string) {
const match = text.match(/(https?:\/\/[^\s]+)/);
return match ? match[0] : null;
}
let targetUrl = $derived(sharedUrl || extractUrl(sharedText));
async function process() {
if(!targetUrl) return;
status = 'extracting';
logs = [...logs, 'Sending to server... ' + targetUrl];
try {
const res = await fetch('/api/extract', {
method: 'POST',
body: JSON.stringify({ url: targetUrl }),
headers: { 'Content-Type': 'application/json' }
});
const data = await res.json();
if (data.recipe) {
recipe = data.recipe;
status = 'done';
} else {
logs = [...logs, 'Error: ' + JSON.stringify(data)];
status = 'error';
}
} catch(e) {
logs = [...logs, 'Network Error'];
status = 'error';
}
}
</script>
<div class="p-8 max-w-lg mx-auto space-y-4">
<h1 class="text-2xl font-bold">InstaChef PWA</h1>
{#if targetUrl}
<div class="bg-gray-100 p-2 rounded break-all text-sm border">{targetUrl}</div>
{#if status === 'idle'}
<button onclick={process} class="bg-blue-600 text-white px-4 py-2 rounded shadow hover:bg-blue-700 w-full">
Extract Recipe
</button>
{/if}
{:else}
<p class="text-gray-500">No URL detected. Open this app via Instagram Share Menu.</p>
<div class="text-xs text-gray-400">Debug: Text={sharedText} URL={sharedUrl}</div>
{/if}
{#if status === 'extracting'}
<div class="animate-pulse text-blue-600">Extracting data...</div>
{/if}
{#if recipe}
<div class="border rounded p-4 bg-green-50 space-y-2">
<h2 class="font-bold text-xl">{recipe.name}</h2>
<p class="text-sm">{recipe.description}</p>
<h3 class="font-bold mt-2">Ingredients</h3>
<ul class="list-disc pl-5 text-sm">
{#each recipe.ingredients as ing}
<li>{ing.amount} {ing.unit} {ing.item}</li>
{/each}
</ul>
</div>
{/if}
<div class="font-mono text-xs bg-slate-900 text-green-400 p-4 rounded min-h-[100px] mt-8">
<div class="opacity-50 border-b border-slate-700 mb-2">System Logs</div>
{#each logs as l}<div>> {l}</div>{/each}
</div>
</div>

View File

@@ -2,9 +2,45 @@ import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vitest/config';
import { playwright } from '@vitest/browser-playwright';
import { sveltekit } from '@sveltejs/kit/vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit';
export default defineConfig({
plugins: [tailwindcss(), sveltekit()],
plugins: [
SvelteKitPWA({
srcDir: './src',
mode: 'development',
strategies: 'generateSW',
scope: '/',
base: '/',
selfDestroying: process.env.SELF_DESTROYING_SW === 'true',
manifest: {
short_name: 'InstaChef',
name: 'InstaChef Recipe Saver',
start_url: '/',
scope: '/',
display: 'standalone',
theme_color: "#ffffff",
background_color: "#ffffff",
icons: [
{ src: '/favicon.png', sizes: '192x192', type: 'image/png' },
{ src: '/favicon.png', sizes: '512x512', type: 'image/png' }
],
share_target: {
action: '/share',
method: 'GET',
enctype: 'application/x-www-form-urlencoded',
params: { title: 'title', text: 'text', url: 'url' }
}
},
workbox: {
globPatterns: ['client/**/*.{js,css,ico,png,svg,webp,woff,woff2}']
},
devOptions: {
enabled: true,
suppressWarnings: true,
navigateFallback: '/',
},
}),tailwindcss(), sveltekit()],
test: {
expect: { requireAssertions: true },
projects: [