@snowcone-app/mockup-resolver 1.0.0

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.
@@ -0,0 +1,228 @@
1
+ // Worker-runtime integration tests. Imports `../src/index` which uses
2
+ // `cloudflare:workers` — only resolvable inside the Cloudflare Workers
3
+ // runtime (or with `@cloudflare/vitest-pool-workers` configured). Excluded
4
+ // from the default `pnpm test` glob via `--exclude '**/integration/**'`.
5
+ // Run with `pnpm test:integration` once the worker pool is wired up.
6
+
7
+ import { describe, expect, it } from 'vitest'
8
+
9
+ describe('Mockup Resolver Worker', () => {
10
+ // Mock account data for testing
11
+ const ACCOUNT_ID = 'account123'
12
+ const TEST_CLIENT_ID = 'client_1'
13
+ const TEST_API_KEY = 'api_key_1'
14
+
15
+ // Sample account data with API keys and clientIds
16
+ const mockAccountData = {
17
+ apiKeys: {
18
+ [TEST_API_KEY]: { rateLimit: 1000 },
19
+ },
20
+ clientIds: {
21
+ [TEST_CLIENT_ID]: {
22
+ rateLimit: 100,
23
+ },
24
+ },
25
+ }
26
+
27
+ // Mock environment object for the worker
28
+ const mockEnv = {
29
+ URL_SIGNING_SECRET: 'test-secret',
30
+ ACCOUNTS: {
31
+ get: async (key: string) => {
32
+ if (key === ACCOUNT_ID) {
33
+ return JSON.stringify(mockAccountData)
34
+ }
35
+ return null
36
+ },
37
+ put: async () => {},
38
+ delete: async () => {},
39
+ list: async () => ({ keys: [], list_complete: true, cursor: '' }),
40
+ getWithMetadata: async () => ({ value: null, metadata: null }),
41
+ },
42
+ } as any // Use type assertion to avoid TypeScript errors
43
+
44
+ // Helper function to get the worker module using dynamic import
45
+ const getWorker = async () => {
46
+ // Using dynamic import instead of require
47
+ const module = await import('../../src')
48
+ return module.default
49
+ }
50
+
51
+ it('should support clientId parameter authentication', async () => {
52
+ const worker = await getWorker()
53
+ const request = new Request(
54
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}&clientId=${TEST_CLIENT_ID}`,
55
+ {
56
+ headers: {
57
+ Origin: 'http://localhost:3000',
58
+ },
59
+ },
60
+ )
61
+
62
+ const response = await worker.fetch(request, mockEnv, {})
63
+ expect(response.status).toBe(200)
64
+ })
65
+
66
+ it('should support X-Client-ID header authentication', async () => {
67
+ const worker = await getWorker()
68
+ const request = new Request(
69
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}`,
70
+ {
71
+ headers: {
72
+ Origin: 'http://localhost:3000',
73
+ 'X-Client-ID': TEST_CLIENT_ID,
74
+ },
75
+ },
76
+ )
77
+
78
+ const response = await worker.fetch(request, mockEnv, {})
79
+ expect(response.status).toBe(200)
80
+ })
81
+
82
+ it('should support API key authentication', async () => {
83
+ const worker = await getWorker()
84
+ const request = new Request(
85
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}`,
86
+ {
87
+ headers: {
88
+ 'X-API-Key': TEST_API_KEY,
89
+ },
90
+ },
91
+ )
92
+
93
+ const response = await worker.fetch(request, mockEnv, {})
94
+ expect(response.status).toBe(200)
95
+ })
96
+
97
+ it('should reject requests with invalid API keys', async () => {
98
+ const worker = await getWorker()
99
+ const request = new Request(
100
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}`,
101
+ {
102
+ headers: {
103
+ 'X-API-Key': 'invalid-api-key',
104
+ },
105
+ },
106
+ )
107
+
108
+ const response = await worker.fetch(request, mockEnv, {})
109
+ expect(response.status).toBe(401)
110
+ })
111
+
112
+ it('should reject requests with invalid clientIds', async () => {
113
+ const worker = await getWorker()
114
+ const request = new Request(
115
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}&clientId=invalid-client-id`,
116
+ {
117
+ headers: {
118
+ Origin: 'http://localhost:3000',
119
+ },
120
+ },
121
+ )
122
+
123
+ const response = await worker.fetch(request, mockEnv, {})
124
+ expect(response.status).toBe(401)
125
+ })
126
+
127
+ it('should reject requests with invalid origins', async () => {
128
+ const worker = await getWorker()
129
+ const request = new Request(
130
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}&clientId=${TEST_CLIENT_ID}`,
131
+ {
132
+ headers: {
133
+ Origin: 'http://evil-site.com',
134
+ },
135
+ },
136
+ )
137
+
138
+ const response = await worker.fetch(request, mockEnv, {})
139
+ expect(response.status).toBe(401)
140
+ })
141
+
142
+ it('should handle CORS preflight requests', async () => {
143
+ const worker = await getWorker()
144
+ const request = new Request(
145
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}`,
146
+ {
147
+ method: 'OPTIONS',
148
+ headers: {
149
+ Origin: 'http://localhost:3000',
150
+ 'Access-Control-Request-Method': 'GET',
151
+ 'Access-Control-Request-Headers': 'x-client-id, x-api-key',
152
+ },
153
+ },
154
+ )
155
+
156
+ const response = await worker.fetch(request, mockEnv, {})
157
+ expect(response.status).toBe(200)
158
+ expect(response.headers.get('Access-Control-Allow-Headers')).toContain('X-Client-ID')
159
+ expect(response.headers.get('Access-Control-Allow-Headers')).toContain('X-API-Key')
160
+ })
161
+
162
+ it('should reject requests without required accountId parameter', async () => {
163
+ const worker = await getWorker()
164
+ const request = new Request('http://localhost/sign?url=https://example.com/test', {
165
+ headers: {
166
+ 'X-API-Key': TEST_API_KEY,
167
+ },
168
+ })
169
+
170
+ const response = await worker.fetch(request, mockEnv, {})
171
+ expect(response.status).toBe(401)
172
+ const responseData = (await response.json()) as { error: string }
173
+ expect(responseData.error).toContain('accountId in the URL')
174
+ })
175
+
176
+ it('should reject requests for unknown accounts', async () => {
177
+ const worker = await getWorker()
178
+ const request = new Request(
179
+ 'http://localhost/sign?url=https://example.com/test?accountId=unknown-account',
180
+ {
181
+ headers: {
182
+ 'X-API-Key': TEST_API_KEY,
183
+ },
184
+ },
185
+ )
186
+
187
+ const response = await worker.fetch(request, mockEnv, {})
188
+ expect(response.status).toBe(401)
189
+ const responseData = (await response.json()) as { error: string }
190
+ expect(responseData.error).toContain('Unknown account')
191
+ })
192
+
193
+ it('should provide sign and verify endpoints', async () => {
194
+ const worker = await getWorker()
195
+
196
+ // Test sign endpoint
197
+ const signRequest = new Request(
198
+ `http://localhost/sign?url=https://example.com/test?accountId=${ACCOUNT_ID}`,
199
+ {
200
+ headers: {
201
+ 'X-API-Key': TEST_API_KEY,
202
+ },
203
+ },
204
+ )
205
+
206
+ const signResponse = await worker.fetch(signRequest, mockEnv, {})
207
+
208
+ expect(signResponse.status).toBe(200)
209
+ const signResult = (await signResponse.json()) as { signature: string }
210
+ expect(signResult).toHaveProperty('signature')
211
+
212
+ // Test verify endpoint with the signature we just got
213
+ const verifyRequest = new Request(
214
+ `http://localhost/verify?url=https://example.com/test?accountId=${ACCOUNT_ID}&signature=${signResult.signature}`,
215
+ {
216
+ headers: {
217
+ 'X-API-Key': TEST_API_KEY,
218
+ },
219
+ },
220
+ )
221
+
222
+ const verifyResponse = await worker.fetch(verifyRequest, mockEnv, {})
223
+
224
+ expect(verifyResponse.status).toBe(200)
225
+ const verifyResult = (await verifyResponse.json()) as { valid: boolean }
226
+ expect(verifyResult).toHaveProperty('valid', true)
227
+ })
228
+ })
@@ -0,0 +1,76 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { resolveVariant, slugify, type ResolvedProduct } from "../src/resolve";
3
+
4
+ // A size×color-style product WITH combinations (picks select the SKU).
5
+ const tee: ResolvedProduct = {
6
+ id: "KMYKUK",
7
+ variants: [{ gvid: "qS" }, { gvid: "qM" }],
8
+ mockups: [],
9
+ placements: [],
10
+ defaultGvid: "qS",
11
+ attributes: { Size: { affectsCombinations: true, choices: ["S", "M", "L"] } },
12
+ combinations: [
13
+ { variantId: "qS", options: { Size: "S" } },
14
+ { variantId: "qM", options: { Size: "M" } },
15
+ ],
16
+ };
17
+
18
+ // The cap: NO combinations; render-only attributes (resolve via defaultGvid).
19
+ const cap: ResolvedProduct = {
20
+ id: "RQNU68",
21
+ variants: [{ gvid: "nJwPrq" }],
22
+ mockups: [],
23
+ placements: [],
24
+ defaultGvid: "nJwPrq",
25
+ attributes: {
26
+ Crown: { affectsCombinations: false, choices: [] },
27
+ Pocket: { affectsCombinations: false, choices: ["None", "Left chest"] },
28
+ },
29
+ combinations: [],
30
+ };
31
+
32
+ describe("resolveVariant", () => {
33
+ it("matches a combination row by case-insensitive picks", () => {
34
+ expect(resolveVariant(tee, { size: "m" })).toEqual({
35
+ variantId: "qM",
36
+ optionSelections: {},
37
+ });
38
+ expect(resolveVariant(tee, { Size: "M" })?.variantId).toBe("qM");
39
+ });
40
+
41
+ it("falls back to defaultGvid when no combination picks are given", () => {
42
+ expect(resolveVariant(tee, {})?.variantId).toBe("qS");
43
+ });
44
+
45
+ it("uses defaultGvid + render-only optionSelections when there are no combinations", () => {
46
+ const r = resolveVariant(cap, { pocket: "left chest" });
47
+ expect(r?.variantId).toBe("nJwPrq");
48
+ // canonicalized to the catalog label casing (rendercenter matches case-sensitively)
49
+ expect(r?.optionSelections).toEqual({ Pocket: "Left chest" });
50
+ });
51
+
52
+ it("honors a variant override", () => {
53
+ expect(resolveVariant(tee, { size: "m" }, "FORCED")?.variantId).toBe("FORCED");
54
+ });
55
+
56
+ it("returns null when no variant can be determined", () => {
57
+ const empty: ResolvedProduct = {
58
+ id: "X",
59
+ variants: [],
60
+ mockups: [],
61
+ placements: [],
62
+ defaultGvid: null,
63
+ attributes: {},
64
+ combinations: [],
65
+ };
66
+ expect(resolveVariant(empty, {})).toBeNull();
67
+ });
68
+ });
69
+
70
+ describe("slugify", () => {
71
+ it("derives URL-safe placement keys from labels", () => {
72
+ expect(slugify("Front")).toBe("front");
73
+ expect(slugify("Left sleeve")).toBe("left_sleeve");
74
+ expect(slugify("Front Left")).toBe("front_left");
75
+ });
76
+ });
package/test/setup.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { beforeAll } from 'vitest'
2
+ import { exec } from 'child_process'
3
+ import { promisify } from 'util'
4
+
5
+ const execAsync = promisify(exec)
6
+
7
+ // Only run integration tests if the service is running and KV store is initialized
8
+ beforeAll(async () => {
9
+ const BASE_URL = process.env.MOCKUP_RESOLVER_URL || 'http://localhost:8102'
10
+
11
+ try {
12
+ // First, try to seed the KV store
13
+ console.log('🌱 Seeding KV store...')
14
+ await execAsync('node seed-local-kv.js')
15
+ console.log('✅ KV store seeded successfully')
16
+
17
+ // Then check if service is running
18
+ console.log('🔍 Checking if service is running...')
19
+ const response = await fetch(BASE_URL)
20
+ if (!response.ok && response.status !== 401) {
21
+ // 401 is expected when no auth
22
+ throw new Error(`Service returned status ${response.status}`)
23
+ }
24
+ console.log('✅ Service is running')
25
+
26
+ // Finally, verify KV store is working by trying to authenticate
27
+ console.log('🔐 Verifying KV store...')
28
+ const testUrl = 'https://example.com/image.jpg?accountId=account123'
29
+ const authResponse = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(testUrl)}`, {
30
+ headers: {
31
+ 'x-api-key': 'test-api-key-1',
32
+ },
33
+ })
34
+
35
+ if (!authResponse.ok) {
36
+ const error = await authResponse.text()
37
+ throw new Error(`KV store verification failed: ${error}`)
38
+ }
39
+ console.log('✅ KV store verified')
40
+ } catch (error) {
41
+ // Don't process.exit(1) — that nukes pure unit-test runs too. The
42
+ // integration tests themselves will skip/fail individually if the
43
+ // service isn't reachable. To run them locally: `pnpm run dev` in this
44
+ // workspace, then `pnpm test:integration`.
45
+ console.warn('⚠ Integration setup skipped:', error instanceof Error ? error.message : error)
46
+ }
47
+ })
package/test-kv.js ADDED
@@ -0,0 +1,89 @@
1
+ // Test script to verify KV store data
2
+ const fs = require('fs')
3
+ const path = require('path')
4
+
5
+ console.log('Testing KV store data...')
6
+ console.log('Checking KV files directly...')
7
+
8
+ // Path to the KV store files
9
+ const kvDir = path.join(__dirname, '.wrangler/state/kv/ACCOUNTS')
10
+
11
+ try {
12
+ // Check if directory exists
13
+ if (!fs.existsSync(kvDir)) {
14
+ console.error(`KV directory does not exist: ${kvDir}`)
15
+ process.exit(1)
16
+ }
17
+
18
+ console.log(`Found KV directory: ${kvDir}`)
19
+
20
+ // List all files in the directory
21
+ const files = fs.readdirSync(kvDir)
22
+ console.log('Files in KV directory:')
23
+ console.log(files)
24
+
25
+ // Try to find the account123 data
26
+ const account123File = files.find((file) => {
27
+ // We need to check file content since the KV store uses hash-based filenames
28
+ const filePath = path.join(kvDir, file)
29
+ const content = fs.readFileSync(filePath, 'utf8')
30
+ try {
31
+ // Try to parse the content as JSON
32
+ const json = JSON.parse(content)
33
+ // If this is key-value metadata, check the key
34
+ if (json.key === 'account123') {
35
+ return true
36
+ }
37
+ } catch (e) {
38
+ // Not JSON or not matching, continue
39
+ }
40
+ return false
41
+ })
42
+
43
+ if (account123File) {
44
+ console.log(`\nFound account123 in file: ${account123File}`)
45
+ const filePath = path.join(kvDir, account123File)
46
+ const content = fs.readFileSync(filePath, 'utf8')
47
+ console.log('File content:')
48
+ console.log(content)
49
+
50
+ // Try to find the value file
51
+ const metadata = JSON.parse(content)
52
+ if (metadata.value) {
53
+ const valuePath = path.join(kvDir, metadata.value)
54
+ if (fs.existsSync(valuePath)) {
55
+ const valueContent = fs.readFileSync(valuePath, 'utf8')
56
+ console.log('\nValue content:')
57
+ console.log(valueContent)
58
+ } else {
59
+ console.log(`\nValue file not found: ${metadata.value}`)
60
+ }
61
+ }
62
+ } else {
63
+ console.log('\naccount123 not found in KV store!')
64
+
65
+ // List all keys
66
+ console.log('\nAll keys in KV store:')
67
+ files.forEach((file) => {
68
+ const filePath = path.join(kvDir, file)
69
+ try {
70
+ const content = fs.readFileSync(filePath, 'utf8')
71
+ try {
72
+ const json = JSON.parse(content)
73
+ if (json.key) {
74
+ console.log(`Key: ${json.key}`)
75
+ }
76
+ } catch (e) {
77
+ // Not JSON or doesn't have key property
78
+ }
79
+ } catch (e) {
80
+ console.log(`Error reading file ${file}: ${e.message}`)
81
+ }
82
+ })
83
+ }
84
+
85
+ console.log('\nVerification complete!')
86
+ } catch (error) {
87
+ console.error('Error occurred during verification:')
88
+ console.error(error.message)
89
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ES2022",
5
+ "lib": ["ES2022"],
6
+ "moduleResolution": "node",
7
+ "types": ["@cloudflare/workers-types"],
8
+ "noEmit": false,
9
+ "isolatedModules": true,
10
+ "allowSyntheticDefaultImports": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "strict": true,
13
+ "skipLibCheck": true,
14
+ "outDir": "dist",
15
+ "rootDir": "src"
16
+ },
17
+ "include": ["src/**/*"],
18
+ "exclude": ["node_modules", "dist", "test"]
19
+ }
@@ -0,0 +1,15 @@
1
+ /// <reference types="vitest" />
2
+ import { defineConfig } from 'vitest/config'
3
+
4
+ export default defineConfig({
5
+ test: {
6
+ include: [
7
+ 'src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}',
8
+ 'test/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}',
9
+ ],
10
+ exclude: ['**/node_modules/**', '**/dist/**', '**/.{idea,git,cache}/**'],
11
+ environment: 'node',
12
+ testTimeout: 10000,
13
+ setupFiles: ['./test/setup.ts'],
14
+ },
15
+ })
package/wrangler.jsonc ADDED
@@ -0,0 +1,84 @@
1
+ {
2
+ "$schema": "node_modules/wrangler/config-schema.json",
3
+ "name": "mockup-resolver",
4
+ "main": "src/index.ts",
5
+ "compatibility_date": "2024-04-03",
6
+ "durable_objects": {
7
+ "bindings": [
8
+ {
9
+ "name": "API_RATE_LIMITER",
10
+ "class_name": "RateLimiter"
11
+ }
12
+ ]
13
+ },
14
+ "migrations": [
15
+ {
16
+ "tag": "v1",
17
+ "new_sqlite_classes": ["RateLimiter"]
18
+ }
19
+ ],
20
+ // The top-level config IS production. `pnpm deploy` deploys this one worker
21
+ // (`mockup-resolver`) — there is no separate `mockup-resolver-production`.
22
+ //
23
+ // img.snowcone.app (public image-CDN resolver, ADR-0076) and s.snowcone.app
24
+ // (server endpoints) are custom domains bound to THIS worker in the Cloudflare
25
+ // dashboard. They are intentionally NOT in `routes`: the CI deploy token lacks
26
+ // DNS write, so `wrangler deploy` would try (and fail) to provision them.
27
+ //
28
+ // Local dev runs via process-compose, which passes
29
+ // --var MEILISEARCH_INDEX:snowcone-dev --var KV_CACHE_BASE_URL:http://localhost:4000
30
+ // to override these prod defaults. For standalone `pnpm dev`, copy
31
+ // .dev.vars.example -> .dev.vars.
32
+ "vars": {
33
+ "TTL_DEFAULT": "86400",
34
+ "LOG_LEVEL": "info",
35
+ // MEILISEARCH_API_KEY is the public read-only search key (same as apps/www);
36
+ // URL_SIGNING_SECRET + KV_CACHE_SERVICE_TOKEN stay secrets (wrangler secret put).
37
+ "MEILISEARCH_HOST": "https://search.snowcone.app",
38
+ "MEILISEARCH_API_KEY": "eee819b849798ad9091228c486ec05d0931e5292",
39
+ "MEILISEARCH_INDEX": "snowcone",
40
+ "MOCKUP_BASE_URL": "https://cdn.snowcone.app",
41
+ "KV_CACHE_BASE_URL": "https://api.snowcone.app"
42
+ },
43
+ "kv_namespaces": [
44
+ {
45
+ "binding": "ACCOUNTS",
46
+ "id": "de3d0db77ca34aeaa95e808e574d2f04",
47
+ "preview_id": "de3d0db77ca34aeaa95e808e574d2f04"
48
+ }
49
+ ],
50
+ "dev": {
51
+ "port": 8102,
52
+ "local_protocol": "http"
53
+ },
54
+ "env": {
55
+ // Optional staging worker (`mockup-resolver-development`), deployed with
56
+ // `pnpm deploy:worker`. Independent of prod; resolves the dev catalog.
57
+ "development": {
58
+ "name": "mockup-resolver-development",
59
+ "vars": {
60
+ "TTL_DEFAULT": "3600",
61
+ "LOG_LEVEL": "debug",
62
+ "MEILISEARCH_HOST": "https://search.snowcone.app",
63
+ "MEILISEARCH_API_KEY": "eee819b849798ad9091228c486ec05d0931e5292",
64
+ "MEILISEARCH_INDEX": "snowcone-dev",
65
+ "MOCKUP_BASE_URL": "https://cdn.snowcone.app",
66
+ "KV_CACHE_BASE_URL": "http://localhost:4000"
67
+ },
68
+ "kv_namespaces": [
69
+ {
70
+ "binding": "ACCOUNTS",
71
+ "id": "de3d0db77ca34aeaa95e808e574d2f04"
72
+ }
73
+ ],
74
+ "durable_objects": {
75
+ "bindings": [
76
+ {
77
+ "name": "API_RATE_LIMITER",
78
+ "class_name": "RateLimiter"
79
+ }
80
+ ]
81
+ }
82
+ }
83
+ }
84
+ }