@ossy/app 0.15.0 → 0.15.3

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/README.md CHANGED
@@ -41,17 +41,32 @@ Run `npx @ossy/cli dev` or `npx @ossy/cli build`.
41
41
 
42
42
  ## API routes
43
43
 
44
- Create `src/api.js` to define custom API endpoints. Each route must have `id`, `path`, and a `handle(req, res)` function:
44
+ Define HTTP handlers as an array of `{ id, path, handle(req, res) }` objects (same shape the server passes to `@ossy/router`).
45
+
46
+ **Split files (recommended):** add any number of `*.api.js` (or `.api.mjs` / `.api.cjs`) files under `src/` (nested dirs allowed). Each file’s **default export** is either one route object or an array of routes. They are merged: `src/api.js` first (if present), then each `*.api.js` in lexicographic file path order.
47
+
48
+ **Legacy single file:** `src/api.js` default export is still supported. If it exists, its routes are merged **first**, then every `*.api.js`.
49
+
50
+ At build/dev time this becomes `.ossy-api.generated.js` (gitignored) whenever you have `src/api.js` and/or any `*.api.js`, so the Rollup entry stays stable when you add or remove split files.
51
+
52
+ **Override:** pass `--api-source ./path/to/file.js` to use a single file and skip discovery.
53
+
54
+ Example `src/health.api.js`:
45
55
 
46
56
  ```js
47
- export default [
48
- {
49
- id: 'health',
50
- path: '/api/health',
51
- handle(req, res) {
52
- res.json({ status: 'ok' })
53
- },
57
+ export default {
58
+ id: 'health',
59
+ path: '/api/health',
60
+ handle(req, res) {
61
+ res.json({ status: 'ok' })
54
62
  },
63
+ }
64
+ ```
65
+
66
+ Example `src/api.js` (optional aggregate or empty `[]`):
67
+
68
+ ```js
69
+ export default [
55
70
  {
56
71
  id: 'users',
57
72
  path: '/api/users',
@@ -64,6 +79,18 @@ export default [
64
79
 
65
80
  API routes are matched before the app is rendered. The router supports dynamic segments (e.g. `path: '/api/users/:id'`); extract params from `req.originalUrl` if needed. Use paths that don't conflict with `/@ossy/*` (reserved for the internal proxy).
66
81
 
82
+ ## Background worker tasks (`*.task.js`)
83
+
84
+ For long-running job processors (separate from the SSR server), use **`npx @ossy/cli build --worker`** in a package that only needs the worker. It uses the same Rollup + Babel pipeline as `ossy build`, discovers **`*.task.js`** (and `.task.mjs` / `.task.cjs`) under `src/` (or `--pages <dir>`), and writes **`.ossy-tasks.generated.js`** (gitignored) when needed—same idea as `*.api.js` + `.ossy-api.generated.js`.
85
+
86
+ Optional legacy aggregate: **`src/tasks.js`** default export is merged **first**, then each `*.task.js` in path order.
87
+
88
+ Each task file’s **default export** is `{ type, handler }` where `type` matches the platform job type string, and `handler` is `async ({ sdk, job }) => { ... }` (see `@ossy/worker` for examples).
89
+
90
+ **Override:** `--task-source ./path/to/tasks.js` skips discovery and uses a single file.
91
+
92
+ Output: **`build/worker.js`**. Run with `node build/worker.js` (after `import 'dotenv/config'` via the entry). Set `OSSY_WORKSPACE_ID`, `OSSY_API_URL`, and `OSSY_API_TOKEN` as before.
93
+
67
94
  ## Port configuration
68
95
 
69
96
  By default, the server listens on port **3000**.
package/cli/build.js CHANGED
@@ -15,9 +15,206 @@ import replace from '@rollup/plugin-replace';
15
15
  import remove from 'rollup-plugin-delete';
16
16
  import arg from 'arg'
17
17
  import { ensureBuildStubs } from '../scripts/ensure-build-stubs.mjs'
18
+ import { builtinModules, createRequire } from 'node:module'
18
19
  // import inject from '@rollup/plugin-inject'
19
20
 
20
21
  const PAGE_FILE_PATTERN = /\.page\.(jsx?|tsx?)$/
22
+ const API_FILE_PATTERN = /\.api\.(mjs|cjs|js)$/
23
+ const TASK_FILE_PATTERN = /\.task\.(mjs|cjs|js)$/
24
+
25
+ export function discoverApiFiles(srcDir) {
26
+ const dir = path.resolve(srcDir)
27
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
28
+ return []
29
+ }
30
+ const files = []
31
+ const walk = (d) => {
32
+ const entries = fs.readdirSync(d, { withFileTypes: true })
33
+ for (const e of entries) {
34
+ const full = path.join(d, e.name)
35
+ if (e.isDirectory()) walk(full)
36
+ else if (API_FILE_PATTERN.test(e.name)) files.push(full)
37
+ }
38
+ }
39
+ walk(dir)
40
+ return files.sort()
41
+ }
42
+
43
+ export function discoverTaskFiles(srcDir) {
44
+ const dir = path.resolve(srcDir)
45
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
46
+ return []
47
+ }
48
+ const files = []
49
+ const walk = (d) => {
50
+ const entries = fs.readdirSync(d, { withFileTypes: true })
51
+ for (const e of entries) {
52
+ const full = path.join(d, e.name)
53
+ if (e.isDirectory()) walk(full)
54
+ else if (TASK_FILE_PATTERN.test(e.name)) files.push(full)
55
+ }
56
+ }
57
+ walk(dir)
58
+ return files.sort()
59
+ }
60
+
61
+ /**
62
+ * Merges `src/api.js` (optional) and every `*.api.js` under the pages tree into one default export array
63
+ * for the Ossy API router ({ id, path, handle }).
64
+ */
65
+ export function generateApiModule({ cwd, apiFiles, legacyPath }) {
66
+ const lines = [
67
+ '// Generated by @ossy/app — do not edit',
68
+ '',
69
+ ]
70
+ const hasLegacy = legacyPath && fs.existsSync(legacyPath)
71
+ if (hasLegacy) {
72
+ const rel = path.relative(cwd, legacyPath).replace(/\\/g, '/')
73
+ lines.push(`import _legacyApi from './${rel}'`)
74
+ }
75
+ apiFiles.forEach((f, i) => {
76
+ const rel = path.relative(cwd, f).replace(/\\/g, '/')
77
+ lines.push(`import * as _api${i} from './${rel}'`)
78
+ })
79
+ lines.push(
80
+ '',
81
+ 'function _normalizeApiExport(mod) {',
82
+ ' const d = mod?.default',
83
+ ' if (d == null) return []',
84
+ ' return Array.isArray(d) ? d : [d]',
85
+ '}',
86
+ '',
87
+ 'export default [',
88
+ )
89
+ const parts = []
90
+ if (hasLegacy) {
91
+ parts.push(' ..._normalizeApiExport({ default: _legacyApi }),')
92
+ }
93
+ apiFiles.forEach((_, i) => {
94
+ parts.push(` ..._normalizeApiExport(_api${i}),`)
95
+ })
96
+ lines.push(parts.join('\n'))
97
+ lines.push(']')
98
+ lines.push('')
99
+ return lines.join('\n')
100
+ }
101
+
102
+ /**
103
+ * Resolves the Rollup entry for @ossy/api/source-file and which files to scan for the build overview.
104
+ */
105
+ export function resolveApiSource({ cwd, pagesOpt, scriptDir, explicitApiSource }) {
106
+ const srcDir = path.resolve(cwd, pagesOpt)
107
+ const legacyPath = path.resolve(cwd, 'src/api.js')
108
+ const defaultStub = path.resolve(scriptDir, 'api.js')
109
+ const generatedPath = path.join(cwd, '.ossy-api.generated.js')
110
+
111
+ if (explicitApiSource) {
112
+ const p = path.isAbsolute(explicitApiSource)
113
+ ? explicitApiSource
114
+ : path.resolve(cwd, explicitApiSource)
115
+ if (fs.existsSync(p)) {
116
+ return { apiSourcePath: p, apiOverviewFiles: [p], usedGenerated: false }
117
+ }
118
+ return { apiSourcePath: defaultStub, apiOverviewFiles: [], usedGenerated: false }
119
+ }
120
+
121
+ const apiFiles = discoverApiFiles(srcDir)
122
+ const hasLegacy = fs.existsSync(legacyPath)
123
+ // Always feed Rollup the same entry (`.ossy-api.generated.js`) when there is any API surface,
124
+ // so adding/removing `*.api.js` does not require changing the replace target mid-dev.
125
+ if (apiFiles.length > 0 || hasLegacy) {
126
+ fs.writeFileSync(
127
+ generatedPath,
128
+ generateApiModule({
129
+ cwd,
130
+ apiFiles,
131
+ legacyPath: hasLegacy ? legacyPath : null,
132
+ })
133
+ )
134
+ const overview = [...(hasLegacy ? [legacyPath] : []), ...apiFiles]
135
+ return { apiSourcePath: generatedPath, apiOverviewFiles: overview, usedGenerated: true }
136
+ }
137
+
138
+ return { apiSourcePath: defaultStub, apiOverviewFiles: [], usedGenerated: false }
139
+ }
140
+
141
+ /**
142
+ * Merges `src/tasks.js` (optional) and every `*.task.js` under `src/` into one default export array
143
+ * of job handlers `{ type, handler }` for the Ossy worker.
144
+ */
145
+ export function generateTaskModule({ cwd, taskFiles, legacyPath }) {
146
+ const lines = [
147
+ '// Generated by @ossy/app — do not edit',
148
+ '',
149
+ ]
150
+ const hasLegacy = legacyPath && fs.existsSync(legacyPath)
151
+ if (hasLegacy) {
152
+ const rel = path.relative(cwd, legacyPath).replace(/\\/g, '/')
153
+ lines.push(`import _legacyTasks from './${rel}'`)
154
+ }
155
+ taskFiles.forEach((f, i) => {
156
+ const rel = path.relative(cwd, f).replace(/\\/g, '/')
157
+ lines.push(`import * as _task${i} from './${rel}'`)
158
+ })
159
+ lines.push(
160
+ '',
161
+ 'function _normalizeTaskExport(mod) {',
162
+ ' const d = mod?.default',
163
+ ' if (d == null) return []',
164
+ ' return Array.isArray(d) ? d : [d]',
165
+ '}',
166
+ '',
167
+ 'export default [',
168
+ )
169
+ const parts = []
170
+ if (hasLegacy) {
171
+ parts.push(' ..._normalizeTaskExport({ default: _legacyTasks }),')
172
+ }
173
+ taskFiles.forEach((_, i) => {
174
+ parts.push(` ..._normalizeTaskExport(_task${i}),`)
175
+ })
176
+ lines.push(parts.join('\n'))
177
+ lines.push(']')
178
+ lines.push('')
179
+ return lines.join('\n')
180
+ }
181
+
182
+ /**
183
+ * Resolves the Rollup entry for @ossy/tasks/source-file and which files to list in the worker build overview.
184
+ */
185
+ export function resolveTaskSource({ cwd, pagesOpt, scriptDir, explicitTaskSource }) {
186
+ const srcDir = path.resolve(cwd, pagesOpt)
187
+ const legacyPath = path.resolve(cwd, 'src/tasks.js')
188
+ const defaultStub = path.resolve(scriptDir, 'tasks.js')
189
+ const generatedPath = path.join(cwd, '.ossy-tasks.generated.js')
190
+
191
+ if (explicitTaskSource) {
192
+ const p = path.isAbsolute(explicitTaskSource)
193
+ ? explicitTaskSource
194
+ : path.resolve(cwd, explicitTaskSource)
195
+ if (fs.existsSync(p)) {
196
+ return { taskSourcePath: p, taskOverviewFiles: [p], usedGenerated: false }
197
+ }
198
+ return { taskSourcePath: defaultStub, taskOverviewFiles: [], usedGenerated: false }
199
+ }
200
+
201
+ const taskFiles = discoverTaskFiles(srcDir)
202
+ const hasLegacy = fs.existsSync(legacyPath)
203
+ if (taskFiles.length > 0 || hasLegacy) {
204
+ fs.writeFileSync(
205
+ generatedPath,
206
+ generateTaskModule({
207
+ cwd,
208
+ taskFiles,
209
+ legacyPath: hasLegacy ? legacyPath : null,
210
+ })
211
+ )
212
+ const overview = [...(hasLegacy ? [legacyPath] : []), ...taskFiles]
213
+ return { taskSourcePath: generatedPath, taskOverviewFiles: overview, usedGenerated: true }
214
+ }
215
+
216
+ return { taskSourcePath: defaultStub, taskOverviewFiles: [], usedGenerated: false }
217
+ }
21
218
 
22
219
  export function discoverPageFiles(srcDir) {
23
220
  const dir = path.resolve(srcDir)
@@ -75,6 +272,65 @@ export function generatePagesModule(pageFiles, cwd, srcDir = 'src') {
75
272
  return lines.join('\n')
76
273
  }
77
274
 
275
+ export async function discoverModulePageFiles({ cwd, configPath }) {
276
+ if (!configPath || !fs.existsSync(configPath)) return []
277
+ try {
278
+ // Try a cheap static parse first so we don't depend on the config file being
279
+ // importable (configs often import theme/template modules that may not be
280
+ // resolvable in the build-time node context).
281
+ const cfgSource = fs.readFileSync(configPath, 'utf8')
282
+ const modules = []
283
+
284
+ // pagesModules: ['a', "b"]
285
+ const arrMatch = cfgSource.match(/pagesModules\s*:\s*\[([^\]]*)\]/m)
286
+ if (arrMatch?.[1]) {
287
+ const body = arrMatch[1]
288
+ const re = /['"]([^'"]+)['"]/g
289
+ let m
290
+ while ((m = re.exec(body)) !== null) modules.push(m[1])
291
+ }
292
+
293
+ // pagesModule: 'a'
294
+ if (modules.length === 0) {
295
+ const singleMatch = cfgSource.match(/pagesModule\s*:\s*['"]([^'"]+)['"]/m)
296
+ if (singleMatch?.[1]) modules.push(singleMatch[1])
297
+ }
298
+
299
+ if (modules.length) {
300
+ const req = createRequire(path.resolve(cwd, 'package.json'))
301
+ const files = []
302
+ for (const name of modules) {
303
+ const pkgJsonPath = req.resolve(`${name}/package.json`)
304
+ const pkgDir = path.dirname(pkgJsonPath)
305
+ const modulePagesDir = path.join(pkgDir, 'src', 'pages')
306
+ files.push(...discoverPageFiles(modulePagesDir))
307
+ }
308
+ return files
309
+ }
310
+
311
+ const mod = await import(url.pathToFileURL(configPath))
312
+ const cfg = mod?.default ?? mod ?? {}
313
+ const modules2 = Array.isArray(cfg.pagesModules)
314
+ ? cfg.pagesModules
315
+ : (typeof cfg.pagesModule === 'string' ? [cfg.pagesModule] : [])
316
+
317
+ if (!modules2.length) return []
318
+
319
+ const req = createRequire(path.resolve(cwd, 'package.json'))
320
+ const files = []
321
+ for (const name of modules2) {
322
+ const pkgJsonPath = req.resolve(`${name}/package.json`)
323
+ const pkgDir = path.dirname(pkgJsonPath)
324
+ const modulePagesDir = path.join(pkgDir, 'src', 'pages')
325
+ files.push(...discoverPageFiles(modulePagesDir))
326
+ }
327
+ return files
328
+ } catch (e) {
329
+ console.warn('[@ossy/app][build] pagesModules config could not be loaded; continuing without modules')
330
+ return []
331
+ }
332
+ }
333
+
78
334
  export function parsePagesFromSource(filePath) {
79
335
  try {
80
336
  const content = fs.readFileSync(filePath, 'utf8')
@@ -108,7 +364,14 @@ export function parsePagesFromSource(filePath) {
108
364
  }
109
365
  }
110
366
 
111
- export function printBuildOverview({ pagesSourcePath, apiSourcePath, configPath, isPageFiles, pageFiles }) {
367
+ export function printBuildOverview({
368
+ pagesSourcePath,
369
+ apiSourcePath,
370
+ apiOverviewFiles = [],
371
+ configPath,
372
+ isPageFiles,
373
+ pageFiles,
374
+ }) {
112
375
  const rel = (p) => path.relative(process.cwd(), p)
113
376
  const cwd = process.cwd()
114
377
  const srcDir = path.resolve(cwd, 'src')
@@ -118,6 +381,7 @@ export function printBuildOverview({ pagesSourcePath, apiSourcePath, configPath,
118
381
  if (fs.existsSync(configPath)) {
119
382
  console.log(` \x1b[36mConfig:\x1b[0m ${rel(configPath)}`)
120
383
  }
384
+ console.log(` \x1b[36mAPI:\x1b[0m ${rel(apiSourcePath)}`)
121
385
  console.log(' ' + '─'.repeat(50))
122
386
 
123
387
  const pages = isPageFiles && pageFiles?.length
@@ -136,21 +400,127 @@ export function printBuildOverview({ pagesSourcePath, apiSourcePath, configPath,
136
400
  console.log(' \x1b[33mRoutes:\x1b[0m (could not parse or empty)')
137
401
  }
138
402
 
139
- if (fs.existsSync(apiSourcePath)) {
140
- const apiRoutes = parsePagesFromSource(apiSourcePath)
141
- if (apiRoutes.length > 0) {
142
- console.log(' \x1b[36mAPI routes:\x1b[0m')
143
- apiRoutes.forEach((r) => {
144
- console.log(` ${r.id} ${r.path}`)
145
- })
146
- }
403
+ const apiFilesToScan =
404
+ apiOverviewFiles?.length > 0
405
+ ? apiOverviewFiles
406
+ : fs.existsSync(apiSourcePath)
407
+ ? [apiSourcePath]
408
+ : []
409
+ const apiRoutes = []
410
+ for (const f of apiFilesToScan) {
411
+ if (fs.existsSync(f)) apiRoutes.push(...parsePagesFromSource(f))
412
+ }
413
+ if (apiRoutes.length > 0) {
414
+ console.log(' \x1b[36mAPI routes:\x1b[0m')
415
+ apiRoutes.forEach((r) => {
416
+ console.log(` ${r.id} ${r.path}`)
417
+ })
147
418
  }
148
419
  console.log(' ' + '─'.repeat(50) + '\n')
149
420
  }
150
421
 
151
- export const build = async (cliArgs) => {
152
- console.log('[@ossy/app][build] Starting...')
422
+ const WORKER_EXTERNAL_IDS = new Set([
423
+ ...builtinModules,
424
+ ...builtinModules.map((m) => `node:${m}`),
425
+ 'dotenv',
426
+ 'dotenv/config',
427
+ '@ossy/sdk',
428
+ 'openai',
429
+ 'sharp',
430
+ ])
431
+
432
+ function isWorkerExternal(id) {
433
+ if (id.startsWith('.') || path.isAbsolute(id)) return false
434
+ if (WORKER_EXTERNAL_IDS.has(id)) return true
435
+ if (id.startsWith('node:')) return true
436
+ if (id === '@ossy/sdk' || id.startsWith('@ossy/sdk/')) return true
437
+ if (id === 'openai' || id.startsWith('openai/')) return true
438
+ if (id === 'sharp' || id.startsWith('sharp/')) return true
439
+ if (id === 'dotenv' || id.startsWith('dotenv/')) return true
440
+ return false
441
+ }
442
+
443
+ /**
444
+ * Worker-only bundle: discovers `*.task.js` (and optional `src/tasks.js`), writes `.ossy-tasks.generated.js`
445
+ * when needed, and emits `build/worker.js`. Invoke via `npx @ossy/cli build --worker`.
446
+ */
447
+ export async function buildWorker(cliArgs) {
448
+ console.log('[@ossy/app][build][worker] Starting...')
449
+
450
+ const workerArgv = cliArgs.filter((a) => a !== '--worker')
451
+ const options = arg(
452
+ {
453
+ '--pages': String,
454
+ '--p': '--pages',
455
+ '--destination': String,
456
+ '--d': '--destination',
457
+ '--task-source': String,
458
+ },
459
+ { argv: workerArgv }
460
+ )
461
+
462
+ const scriptDir = path.dirname(url.fileURLToPath(import.meta.url))
463
+ const cwd = process.cwd()
464
+ const pagesOpt = options['--pages'] || 'src'
465
+ const buildPath = path.resolve(options['--destination'] || 'build')
466
+ const { taskSourcePath, taskOverviewFiles, usedGenerated } = resolveTaskSource({
467
+ cwd,
468
+ pagesOpt,
469
+ scriptDir,
470
+ explicitTaskSource: options['--task-source'],
471
+ })
472
+
473
+ const workerEntryPath = path.resolve(scriptDir, 'worker-entry.js')
474
+ if (!fs.existsSync(workerEntryPath)) {
475
+ throw new Error(`[@ossy/app][build][worker] Missing worker entry: ${workerEntryPath}`)
476
+ }
477
+
478
+ console.log('\n \x1b[1mWorker build\x1b[0m')
479
+ console.log(' ' + '─'.repeat(50))
480
+ console.log(` \x1b[36mTasks module:\x1b[0m ${path.relative(cwd, taskSourcePath)}`)
481
+ if (taskOverviewFiles.length > 0) {
482
+ console.log(' \x1b[36mTask files:\x1b[0m')
483
+ taskOverviewFiles.forEach((f) => console.log(` ${path.relative(cwd, f)}`))
484
+ } else if (!usedGenerated) {
485
+ console.log(' \x1b[33m(no *.task.js; using empty task list stub)\x1b[0m')
486
+ }
487
+ console.log(' ' + '─'.repeat(50) + '\n')
488
+
489
+ const bundle = await rollup({
490
+ input: workerEntryPath,
491
+ external: isWorkerExternal,
492
+ plugins: [
493
+ remove({ targets: buildPath }),
494
+ replace({
495
+ preventAssignment: true,
496
+ delimiters: ['%%', '%%'],
497
+ '@ossy/tasks/source-file': taskSourcePath,
498
+ }),
499
+ replace({
500
+ preventAssignment: true,
501
+ 'process.env.NODE_ENV': JSON.stringify('production'),
502
+ }),
503
+ json(),
504
+ resolveCommonJsDependencies(),
505
+ resolveDependencies({ preferBuiltins: true }),
506
+ babel({
507
+ babelHelpers: 'bundled',
508
+ presets: ['@babel/preset-env', '@babel/preset-react'],
509
+ }),
510
+ ],
511
+ })
512
+
513
+ await bundle.write({
514
+ dir: buildPath,
515
+ entryFileNames: 'worker.js',
516
+ chunkFileNames: '[name]-[hash].js',
517
+ format: 'esm',
518
+ })
153
519
 
520
+ console.log('[@ossy/app][build][worker] Finished')
521
+ }
522
+
523
+ export const build = async (cliArgs) => {
154
524
  const options = arg({
155
525
  '--pages': String,
156
526
  '--p': '--pages',
@@ -160,22 +530,34 @@ export const build = async (cliArgs) => {
160
530
 
161
531
  '--config': String,
162
532
  '-c': '--config',
533
+
534
+ '--api-source': String,
535
+ '--worker': Boolean,
536
+ '--task-source': String,
163
537
  }, { argv: cliArgs })
164
538
 
539
+ if (options['--worker']) {
540
+ return buildWorker(cliArgs)
541
+ }
542
+
543
+ console.log('[@ossy/app][build] Starting...')
544
+
165
545
 
166
546
  const scriptDir = path.dirname(url.fileURLToPath(import.meta.url))
167
547
  const cwd = process.cwd()
168
548
  const pagesOpt = options['--pages'] || 'src'
169
549
  const srcDir = path.resolve(pagesOpt)
550
+ const configPath = path.resolve(options['--config'] || 'src/config.js');
170
551
  const pageFiles = discoverPageFiles(srcDir)
552
+ const modulePageFiles = await discoverModulePageFiles({ cwd, configPath })
171
553
  const pagesJsxPath = path.resolve('src/pages.jsx')
172
554
  const hasPagesJsx = fs.existsSync(pagesJsxPath)
173
555
 
174
556
  let effectivePagesSource
175
557
  let isPageFiles = false
176
- if (pageFiles.length > 0) {
558
+ if (pageFiles.length > 0 || modulePageFiles.length > 0) {
177
559
  const generatedPath = path.join(cwd, '.ossy-pages.generated.jsx')
178
- fs.writeFileSync(generatedPath, generatePagesModule(pageFiles, cwd, pagesOpt))
560
+ fs.writeFileSync(generatedPath, generatePagesModule([...pageFiles, ...modulePageFiles], cwd, pagesOpt))
179
561
  effectivePagesSource = generatedPath
180
562
  isPageFiles = true
181
563
  } else if (hasPagesJsx) {
@@ -184,9 +566,17 @@ export const build = async (cliArgs) => {
184
566
  throw new Error(`[@ossy/app][build] No pages found. Create *.page.jsx files in src/, or src/pages.jsx`);
185
567
  }
186
568
 
187
- let apiSourcePath = path.resolve(options['--api-source'] || 'src/api.js');
569
+ const {
570
+ apiSourcePath: resolvedApi,
571
+ apiOverviewFiles,
572
+ } = resolveApiSource({
573
+ cwd,
574
+ pagesOpt,
575
+ scriptDir,
576
+ explicitApiSource: options['--api-source'],
577
+ })
578
+ let apiSourcePath = resolvedApi
188
579
  let middlewareSourcePath = path.resolve(options['--middleware-source'] || 'src/middleware.js');
189
- const configPath = path.resolve(options['--config'] || 'src/config.js');
190
580
  const buildPath = path.resolve(options['--destination'] || 'build');
191
581
  const publicDir = path.resolve('public')
192
582
 
@@ -196,7 +586,14 @@ export const build = async (cliArgs) => {
196
586
  const inputFiles = [inputClient, inputServer]
197
587
 
198
588
  const appEntryPath = path.resolve(scriptDir, 'default-app.jsx')
199
- printBuildOverview({ pagesSourcePath: effectivePagesSource, apiSourcePath, configPath, isPageFiles, pageFiles: isPageFiles ? pageFiles : [] });
589
+ printBuildOverview({
590
+ pagesSourcePath: effectivePagesSource,
591
+ apiSourcePath,
592
+ apiOverviewFiles,
593
+ configPath,
594
+ isPageFiles,
595
+ pageFiles: isPageFiles ? pageFiles : [],
596
+ });
200
597
 
201
598
  if (!fs.existsSync(apiSourcePath)) {
202
599
  apiSourcePath = path.resolve(scriptDir, 'api.js')
package/cli/dev.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import path from 'path';
2
2
  import url from 'url';
3
3
  import fs from 'fs';
4
- import { printBuildOverview, discoverPageFiles, generatePagesModule } from './build.js';
4
+ import {
5
+ printBuildOverview,
6
+ discoverPageFiles,
7
+ generatePagesModule,
8
+ discoverModulePageFiles,
9
+ resolveApiSource,
10
+ } from './build.js';
5
11
  import { watch } from 'rollup';
6
12
  import babel from '@rollup/plugin-babel';
7
13
  import { nodeResolve as resolveDependencies } from '@rollup/plugin-node-resolve'
8
14
  import resolveCommonJsDependencies from '@rollup/plugin-commonjs'
9
- import removeOwnPeerDependencies from 'rollup-plugin-peer-deps-external'
10
- import minifyJS from '@rollup/plugin-terser'
11
- // import typescript from '@rollup/plugin-typescript'
12
- import preserveDirectives from "rollup-plugin-preserve-directives"
13
15
  import json from "@rollup/plugin-json"
14
16
  import copy from 'rollup-plugin-copy';
15
17
  import replace from '@rollup/plugin-replace';
@@ -30,6 +32,8 @@ export const dev = async (cliArgs) => {
30
32
 
31
33
  '--config': String,
32
34
  '-c': '--config',
35
+
36
+ '--api-source': String,
33
37
  }, { argv: cliArgs, permissive: true })
34
38
 
35
39
 
@@ -37,15 +41,17 @@ export const dev = async (cliArgs) => {
37
41
  const cwd = process.cwd()
38
42
  const pagesOpt = options['--pages'] || 'src'
39
43
  const srcDir = path.resolve(pagesOpt)
44
+ const configPath = path.resolve(options['--config'] || 'src/config.js');
40
45
  const pageFiles = discoverPageFiles(srcDir)
46
+ const modulePageFiles = await discoverModulePageFiles({ cwd, configPath })
41
47
  const pagesJsxPath = path.resolve('src/pages.jsx')
42
48
  const hasPagesJsx = fs.existsSync(pagesJsxPath)
43
49
 
44
50
  let effectivePagesSource
45
51
  let isPageFiles = false
46
- if (pageFiles.length > 0) {
52
+ if (pageFiles.length > 0 || modulePageFiles.length > 0) {
47
53
  const generatedPath = path.join(cwd, '.ossy-pages.generated.jsx')
48
- fs.writeFileSync(generatedPath, generatePagesModule(pageFiles, cwd, pagesOpt))
54
+ fs.writeFileSync(generatedPath, generatePagesModule([...pageFiles, ...modulePageFiles], cwd, pagesOpt))
49
55
  effectivePagesSource = generatedPath
50
56
  isPageFiles = true
51
57
  } else if (hasPagesJsx) {
@@ -54,9 +60,17 @@ export const dev = async (cliArgs) => {
54
60
  throw new Error(`[@ossy/app][dev] No pages found. Create *.page.jsx files in src/, or src/pages.jsx`);
55
61
  }
56
62
 
57
- let apiSourcePath = path.resolve(options['--api-source'] || 'src/api.js');
63
+ const {
64
+ apiSourcePath: resolvedApi,
65
+ apiOverviewFiles,
66
+ } = resolveApiSource({
67
+ cwd,
68
+ pagesOpt,
69
+ scriptDir,
70
+ explicitApiSource: options['--api-source'],
71
+ })
72
+ let apiSourcePath = resolvedApi
58
73
  let middlewareSourcePath = path.resolve(options['--middleware-source'] || 'src/middleware.js');
59
- const configPath = path.resolve(options['--config'] || 'src/config.js');
60
74
  const buildPath = path.resolve(options['--destination'] || 'build');
61
75
  const publicDir = path.resolve('public')
62
76
 
@@ -65,7 +79,14 @@ export const dev = async (cliArgs) => {
65
79
 
66
80
  const inputFiles = [inputClient, inputServer]
67
81
 
68
- printBuildOverview({ pagesSourcePath: effectivePagesSource, apiSourcePath, configPath, isPageFiles, pageFiles: isPageFiles ? pageFiles : [] });
82
+ printBuildOverview({
83
+ pagesSourcePath: effectivePagesSource,
84
+ apiSourcePath,
85
+ apiOverviewFiles,
86
+ configPath,
87
+ isPageFiles,
88
+ pageFiles: isPageFiles ? pageFiles : [],
89
+ });
69
90
 
70
91
  if (!fs.existsSync(apiSourcePath)) {
71
92
  apiSourcePath = path.resolve(scriptDir, 'api.js')
@@ -202,15 +223,32 @@ export const dev = async (cliArgs) => {
202
223
  }
203
224
  })
204
225
 
205
- if (isPageFiles) {
206
- fs.watch(srcDir, { recursive: true }, (eventType, filename) => {
207
- if (filename && /\.page\.(jsx?|tsx?)$/.test(filename)) {
208
- const files = discoverPageFiles(srcDir)
209
- if (files.length > 0) {
210
- const generatedPath = path.join(cwd, '.ossy-pages.generated.jsx')
211
- fs.writeFileSync(generatedPath, generatePagesModule(files, cwd, pagesOpt))
212
- }
213
- }
226
+ const regenApiBundle = () => {
227
+ if (options['--api-source']) return
228
+ resolveApiSource({
229
+ cwd,
230
+ pagesOpt,
231
+ scriptDir,
232
+ explicitApiSource: undefined,
214
233
  })
234
+ const gen = path.resolve(cwd, '.ossy-api.generated.js')
235
+ if (fs.existsSync(gen) && typeof watcher?.invalidate === 'function') {
236
+ watcher.invalidate(gen)
237
+ }
215
238
  }
216
- };
239
+
240
+ fs.watch(srcDir, { recursive: true }, (eventType, filename) => {
241
+ if (!filename) return
242
+ if (/\.page\.(jsx?|tsx?)$/.test(filename)) {
243
+ if (!isPageFiles) return
244
+ const files = discoverPageFiles(srcDir)
245
+ if (files.length > 0) {
246
+ const generatedPath = path.join(cwd, '.ossy-pages.generated.jsx')
247
+ fs.writeFileSync(generatedPath, generatePagesModule(files, cwd, pagesOpt))
248
+ }
249
+ }
250
+ if (/\.api\.(mjs|cjs|js)$/.test(filename) || /(^|\/)api\.js$/.test(filename.replace(/\\/g, '/'))) {
251
+ regenApiBundle()
252
+ }
253
+ })
254
+ };
@@ -105,9 +105,10 @@ export function ProxyInternal() {
105
105
  })
106
106
  }
107
107
 
108
- res.clearCookie('auth')
109
- res.status(response.status);
110
- res.json("");
108
+ return response.arrayBuffer().then((buffer) => {
109
+ res.status(response.status)
110
+ res.send(Buffer.from(buffer))
111
+ })
111
112
  })
112
113
  .catch((error) => {
113
114
  console.log(`[@ossy/app][proxy][error]`, error)
package/cli/tasks.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Stub when no `*.task.js` / `src/tasks.js` — replaced at build time when tasks exist. */
2
+ export default []
@@ -0,0 +1,5 @@
1
+ import 'dotenv/config'
2
+ import taskHandlers from '%%@ossy/tasks/source-file%%'
3
+ import { runWorkerScheduler } from './worker-runtime.js'
4
+
5
+ runWorkerScheduler(taskHandlers)
@@ -0,0 +1,120 @@
1
+ import { SDK } from '@ossy/sdk'
2
+
3
+ /**
4
+ * @param {Array<{ type: string, handler: (ctx: { sdk: import('@ossy/sdk').SDK, job: Record<string, unknown> }) => Promise<void> }>} handlers
5
+ */
6
+ export function runWorkerScheduler(handlers) {
7
+ const sdk = SDK.of({
8
+ workspaceId: process.env.OSSY_WORKSPACE_ID,
9
+ apiUrl: process.env.OSSY_API_URL,
10
+ authorization: process.env.OSSY_API_TOKEN,
11
+ })
12
+
13
+ const jobsClient = /** @type {{ getUnprocessed: () => Promise<unknown[]> }} */ (sdk.jobs)
14
+
15
+ let status = 'running'
16
+
17
+ console.log('Starting scheduler')
18
+
19
+ main()
20
+
21
+ setInterval(() => {
22
+ if (status === 'running') return
23
+ status = 'running'
24
+ try {
25
+ main()
26
+ } catch (error) {
27
+ console.log('Error running main')
28
+ console.error(error)
29
+ status = 'idle'
30
+ }
31
+ }, 3000)
32
+
33
+ function main() {
34
+ console.log('Looking for jobs')
35
+ jobsClient
36
+ .getUnprocessed()
37
+ .then(async (jobs) => {
38
+ if (!jobs || !jobs.length) {
39
+ console.log('No jobs found, going idle')
40
+ status = 'idle'
41
+ return
42
+ }
43
+
44
+ const jobsGroupedByResourceId = groupJobsByResourceId(jobs)
45
+
46
+ console.log(`Found ${jobs.length} jobs between ${jobsGroupedByResourceId.length} resources`)
47
+
48
+ const processedGroups = jobsGroupedByResourceId.map(([resourceId, groupJobs]) => {
49
+ console.log(`Processing group for resourceId ${resourceId}`)
50
+ return processJobsSequentially(groupJobs)
51
+ .then(() => console.log(`Completed group for resourceId ${resourceId}`))
52
+ .catch((err) => {
53
+ console.log(`Failed to process group for resourceId ${resourceId}`)
54
+ console.error(err)
55
+ })
56
+ })
57
+
58
+ try {
59
+ await Promise.allSettled(processedGroups)
60
+
61
+ console.log(`Finished processing of groups...`)
62
+ console.log('Going idle')
63
+ status = 'idle'
64
+ console.log('----------------------------------')
65
+ console.groupEnd()
66
+ } catch (error) {
67
+ console.log('Error processing groups')
68
+ console.error(error)
69
+ status = 'idle'
70
+ }
71
+ })
72
+ .catch((error) => {
73
+ console.log('Error getting jobs')
74
+ console.error(error)
75
+ status = 'idle'
76
+ })
77
+ }
78
+
79
+ function groupJobsByResourceId(jobList) {
80
+ return Object.entries(
81
+ jobList.reduce((acc, job) => {
82
+ const content = /** @type {{ resourceId?: string }} */ (job.content || {})
83
+ const rid = content.resourceId
84
+ return {
85
+ ...acc,
86
+ [rid]: [...(acc[rid] || []), job],
87
+ }
88
+ }, /** @type {Record<string, unknown[]>} */ ({}))
89
+ )
90
+ }
91
+
92
+ async function processJobsSequentially(jobList) {
93
+ console.log(`Processing ${jobList.length} jobs`)
94
+ for (const job of jobList) {
95
+ console.log(`Processing job ${job.id}`)
96
+ const handler = handlers.find((h) => h.type === job.type)
97
+
98
+ if (!handler) {
99
+ console.log('No handler found for job', job.id)
100
+ continue
101
+ }
102
+
103
+ console.log(`Handler found for ${handler.type}`)
104
+
105
+ try {
106
+ console.log('create sdk')
107
+ const jobSdk = SDK.of({
108
+ workspaceId: job.belongsTo,
109
+ authorization: process.env.OSSY_API_TOKEN,
110
+ })
111
+ console.log('created sdk')
112
+
113
+ await handler.handler({ sdk: jobSdk, job }).catch(() => {})
114
+ } catch (error) {
115
+ console.error(error)
116
+ console.log('Failed to processing job')
117
+ }
118
+ }
119
+ }
120
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ossy/app",
3
- "version": "0.15.0",
3
+ "version": "0.15.3",
4
4
  "description": "",
5
5
  "source": "./src/index.js",
6
6
  "main": "./src/index.js",
@@ -66,5 +66,5 @@
66
66
  "README.md",
67
67
  "tsconfig.json"
68
68
  ],
69
- "gitHead": "a575c008d0b4ebba15186143db5fc837bd6ac2d7"
69
+ "gitHead": "2f021c5267eda824587a8670dc51507ce48720e0"
70
70
  }
package/src/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { build } from '../cli/build.js'
1
+ export { build, buildWorker } from '../cli/build.js'
2
2
  export { dev } from '../cli/dev.js'
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Ossy
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.