Explorar el Código

Update package definitions

Split modules to each package.
refactor/new-arch
TheoryOfNekomata hace 5 meses
padre
commit
2865bb7d3a
Se han modificado 53 ficheros con 2659 adiciones y 62 borrados
  1. +43
    -1
      packages/core/package.json
  2. +6
    -1
      packages/core/pridepack.json
  3. +2
    -2
      packages/core/src/backend/server.ts
  4. +1
    -0
      packages/core/src/common/index.ts
  5. +0
    -0
      packages/core/src/index.ts
  6. +107
    -0
      packages/data-sources/duckdb/.gitignore
  7. +7
    -0
      packages/data-sources/duckdb/LICENSE
  8. +67
    -0
      packages/data-sources/duckdb/package.json
  9. +3
    -0
      packages/data-sources/duckdb/pridepack.json
  10. +268
    -0
      packages/data-sources/duckdb/src/index.ts
  11. +8
    -0
      packages/data-sources/duckdb/test/index.test.ts
  12. +23
    -0
      packages/data-sources/duckdb/tsconfig.json
  13. +107
    -0
      packages/data-sources/file-jsonl/.gitignore
  14. +7
    -0
      packages/data-sources/file-jsonl/LICENSE
  15. +66
    -0
      packages/data-sources/file-jsonl/package.json
  16. +3
    -0
      packages/data-sources/file-jsonl/pridepack.json
  17. +255
    -0
      packages/data-sources/file-jsonl/src/index.ts
  18. +236
    -0
      packages/data-sources/file-jsonl/test/index.test.ts
  19. +23
    -0
      packages/data-sources/file-jsonl/tsconfig.json
  20. +107
    -0
      packages/examples/http-resource-server/.gitignore
  21. +45
    -0
      packages/examples/http-resource-server/package.json
  22. +3
    -0
      packages/examples/http-resource-server/pridepack.json
  23. +6
    -0
      packages/examples/http-resource-server/src/index.ts
  24. +8
    -0
      packages/examples/http-resource-server/test/index.test.ts
  25. +23
    -0
      packages/examples/http-resource-server/tsconfig.json
  26. +107
    -0
      packages/extenders/http/.gitignore
  27. +7
    -0
      packages/extenders/http/LICENSE
  28. +49
    -0
      packages/extenders/http/package.json
  29. +7
    -0
      packages/extenders/http/pridepack.json
  30. +4
    -5
      packages/extenders/http/src/backend/core.ts
  31. +0
    -0
      packages/extenders/http/src/backend/index.ts
  32. +3
    -3
      packages/extenders/http/src/client/core.ts
  33. +1
    -0
      packages/extenders/http/src/client/index.ts
  34. +7
    -7
      packages/extenders/http/test/default.test.ts
  35. +5
    -5
      packages/extenders/http/test/error-handling.test.ts
  36. +23
    -0
      packages/extenders/http/tsconfig.json
  37. +107
    -0
      packages/recipes/resource/.gitignore
  38. +7
    -0
      packages/recipes/resource/LICENSE
  39. +49
    -0
      packages/recipes/resource/package.json
  40. +3
    -0
      packages/recipes/resource/pridepack.json
  41. +2
    -3
      packages/recipes/resource/src/core.ts
  42. +2
    -2
      packages/recipes/resource/src/implementation/create.ts
  43. +2
    -2
      packages/recipes/resource/src/implementation/delete.ts
  44. +2
    -2
      packages/recipes/resource/src/implementation/emplace.ts
  45. +2
    -2
      packages/recipes/resource/src/implementation/fetch.ts
  46. +2
    -2
      packages/recipes/resource/src/implementation/patch-delta.ts
  47. +2
    -2
      packages/recipes/resource/src/implementation/patch-merge.ts
  48. +2
    -2
      packages/recipes/resource/src/implementation/query.ts
  49. +0
    -0
      packages/recipes/resource/src/index.ts
  50. +1
    -1
      packages/recipes/resource/src/response.ts
  51. +8
    -0
      packages/recipes/resource/test/index.test.ts
  52. +23
    -0
      packages/recipes/resource/tsconfig.json
  53. +808
    -20
      pnpm-lock.yaml

+ 43
- 1
packages/core/package.json Ver fichero

@@ -1,5 +1,5 @@
{
"name": "core",
"name": "@modal-sh/yasumi",
"version": "0.0.0",
"files": [
"dist",
@@ -45,5 +45,47 @@
},
"dependencies": {
"valibot": "^0.30.0"
},
"types": "./dist/types/common/index.d.ts",
"main": "./dist/cjs/production/index.js",
"module": "./dist/esm/production/index.js",
"exports": {
".": {
"development": {
"require": "./dist/cjs/development/index.js",
"import": "./dist/esm/development/index.js"
},
"require": "./dist/cjs/production/index.js",
"import": "./dist/esm/production/index.js",
"types": "./dist/types/common/index.d.ts"
},
"./backend": {
"development": {
"require": "./dist/cjs/development/backend.js",
"import": "./dist/esm/development/backend.js"
},
"require": "./dist/cjs/production/backend.js",
"import": "./dist/esm/production/backend.js",
"types": "./dist/types/backend/index.d.ts"
},
"./client": {
"development": {
"require": "./dist/cjs/development/client.js",
"import": "./dist/esm/development/client.js"
},
"require": "./dist/cjs/production/client.js",
"import": "./dist/esm/production/client.js",
"types": "./dist/types/client/index.d.ts"
}
},
"typesVersions": {
"*": {
"backend": [
"./dist/types/backend/index.d.ts"
],
"client": [
"./dist/types/client/index.d.ts"
]
}
}
}

+ 6
- 1
packages/core/pridepack.json Ver fichero

@@ -1,3 +1,8 @@
{
"target": "es2018"
"target": "es2018",
"entrypoints": {
".": "src/common/index.ts",
"./backend": "src/backend/index.ts",
"./client": "src/client/index.ts"
}
}

+ 2
- 2
packages/core/src/backend/server.ts Ver fichero

@@ -1,9 +1,9 @@
import {ServiceParams} from '../common';
import {Backend as BaseBackend} from './common';

export interface ServerRequest {}
export interface ServerRequestContext {}

export interface ServerResponse {}
export interface ServerResponseContext {}

export interface ServerParams<Backend extends BaseBackend = BaseBackend> {
backend: Backend;


+ 1
- 0
packages/core/src/common/index.ts Ver fichero

@@ -5,6 +5,7 @@ export * from './language';
export * from './media-type';
export * from './operation';
export * from './queries';
export * from './recipe';
export * from './response';
export * from './service';
export * as statusCodes from './status-codes';


+ 0
- 0
packages/core/src/index.ts Ver fichero


+ 107
- 0
packages/data-sources/duckdb/.gitignore Ver fichero

@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

+ 7
- 0
packages/data-sources/duckdb/LICENSE Ver fichero

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2024 TheoryOfNekomata <allan.crisostomo@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 67
- 0
packages/data-sources/duckdb/package.json Ver fichero

@@ -0,0 +1,67 @@
{
"name": "@modal-sh/yasumi-data-source-duckdb",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=16"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^20.11.0",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
},
"dependencies": {
"@modal-sh/yasumi": "workspace:*",
"duckdb-async": "^0.10.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": false,
"description": "DuckDB adapter for Yasumi.",
"repository": {
"url": "",
"type": "git"
},
"homepage": "",
"bugs": {
"url": ""
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
},
"types": "./dist/types/index.d.ts",
"main": "./dist/cjs/production/index.js",
"module": "./dist/esm/production/index.js",
"exports": {
".": {
"development": {
"require": "./dist/cjs/development/index.js",
"import": "./dist/esm/development/index.js"
},
"require": "./dist/cjs/production/index.js",
"import": "./dist/esm/production/index.js",
"types": "./dist/types/index.d.ts"
}
},
"typesVersions": {
"*": {}
}
}

+ 3
- 0
packages/data-sources/duckdb/pridepack.json Ver fichero

@@ -0,0 +1,3 @@
{
"target": "es2018"
}

+ 268
- 0
packages/data-sources/duckdb/src/index.ts Ver fichero

@@ -0,0 +1,268 @@
import { Resource, validation as v, BaseResourceType } from '@modal-sh/yasumi';
import { DataSource, ResourceIdConfig } from '@modal-sh/yasumi/backend';
import { Database } from 'duckdb-async';
import assert from 'assert';

type ID = number;

interface DuckDbDataSourceBase<
ID,
Schema extends v.BaseSchema = v.BaseSchema,
CurrentName extends string = string,
CurrentRouteName extends string = string,
Data extends object = v.Output<Schema>,
> extends DataSource<Data, ID> {
resource?: Resource<BaseResourceType & {
schema: Schema,
name: CurrentName,
routeName: CurrentRouteName,
}>;

db?: Database;
}

export const AutoincrementIdConfig = {
// TODO add options: https://duckdb.org/docs/sql/statements/create_sequence
generationStrategy: async (dataSourceRaw: DataSource) => {
const dataSource = dataSourceRaw as DuckDbDataSourceBase<ID>;
assert(typeof dataSource.db !== 'undefined');
assert(typeof dataSource.resource !== 'undefined');
const idAttr = dataSource.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

const con = await dataSource.db.connect();
const stmt = await con.prepare(`
SELECT nextval('${dataSource.resource.state.routeName}_sequence') as ${idAttr};
`);
const [v] = await stmt.all();
return v[idAttr];
},
schema: v.number(),
serialize: (v: unknown) => v?.toString() ?? '',
deserialize: (v: string) => Number(v),
}

export class DuckDbDataSource<
Schema extends v.BaseSchema = v.BaseSchema,
CurrentName extends string = string,
CurrentRouteName extends string = string,
Data extends object = v.Output<Schema>,
> implements DuckDbDataSourceBase<ID, Schema, CurrentName, CurrentRouteName, Data> {
resource?: Resource<BaseResourceType & {
schema: Schema,
name: CurrentName,
routeName: CurrentRouteName,
}>;

db?: Database;

constructor(private readonly path: string) {
// noop
}

async initialize() {
assert(typeof this.path !== 'undefined');
assert(typeof this.resource !== 'undefined');

const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined;
assert(typeof idConfig !== 'undefined');

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

const idSchema = idConfig.schema as v.BaseSchema;

this.db = await Database.create(this.path);
const clause = `CREATE TABLE IF NOT EXISTS ${this.resource.state.routeName}`;
const resourceSchema = this.resource.schema as unknown as v.ObjectSchema<any>;
const tableSchema = Object.entries(resourceSchema.entries)
.map(([columnName, columnDefRaw]) => {
const columnDef = columnDefRaw as unknown as v.BaseSchema;
return [columnName, columnDef.type].join(' ');
})
.join(',');
let sequenceSql = '';
let defaultValue = '';
let idType = 'STRING';
if (idSchema.type === 'number') {
// TODO support more sequence statements: https://duckdb.org/docs/sql/statements/create_sequence
sequenceSql = `CREATE SEQUENCE IF NOT EXISTS ${this.resource.state.routeName}_sequence START 1;`;
defaultValue = `DEFAULT nextval('${this.resource.state.routeName}_sequence')`;
idType = 'INTEGER';
}
const sql = `${sequenceSql}${clause} (${idAttr} ${idType} ${defaultValue},${tableSchema});`;
const con = await this.db.connect();
const stmt = await con.prepare(sql);
await stmt.run();
}

prepareResource<Schema extends v.BaseSchema>(resource: Resource<BaseResourceType & {
schema: Schema,
name: CurrentName,
routeName: CurrentRouteName,
}>) {
resource.dataSource = resource.dataSource ?? this;
const originalResourceId = resource.id;
resource.id = <NewIdAttr extends BaseResourceType['idAttr'], NewIdSchema extends BaseResourceType['idSchema']>(newIdAttr: NewIdAttr, params: ResourceIdConfig<NewIdSchema>) => {
originalResourceId(newIdAttr, params);
return resource as Resource<BaseResourceType & {
name: CurrentName,
routeName: CurrentRouteName,
schema: Schema,
idAttr: NewIdAttr,
idSchema: NewIdSchema,
}>;
};
this.resource = resource as any;
}

async getMultiple(query) {
// TODO translate query to SQL statements
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const con = await this.db.connect();
const stmt = await con.prepare(`
SELECT * FROM ${this.resource.state.routeName};
`);
const data = await stmt.all();
return data as Data[];
}

async newId() {
assert(typeof this.resource !== 'undefined');
const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any>;
assert(typeof idConfig !== 'undefined');

const theNewId = await idConfig.generationStrategy(this);
return theNewId as ID;
}

async create(data: Data) {
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined;
assert(typeof idConfig !== 'undefined');

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

let theId: any;
const { [idAttr]: dataId } = data as Record<string, unknown>;
if (typeof dataId !== 'undefined') {
theId = idConfig.deserialize((data as Record<string, string>)[idAttr]);
} else {
const newId = await this.newId();
theId = idConfig.deserialize(newId.toString());
}
const effectiveData = {
...data,
} as Record<string, unknown>;
effectiveData[idAttr] = theId;

const clause = `INSERT INTO ${this.resource.state.routeName}`;
const keys = Object.keys(effectiveData).join(',');
const values = Object.values(effectiveData).map((d) => JSON.stringify(d).replace(/"/g, "'")).join(',');
const sql = `${clause} (${keys}) VALUES (${values});`;
const con = await this.db.connect();
const stmt = await con.prepare(sql);
await stmt.run();
const newData = {
...effectiveData
};
return newData as Data;
}

async getTotalCount(query) {
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

const con = await this.db.connect();
const stmt = await con.prepare(`
SELECT COUNT(*) as c FROM ${this.resource.state.routeName};
`);
const [data] = await stmt.all();
return data['c'] as unknown as number;
}

async getById(id: ID) {
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

const con = await this.db.connect();
const stmt = await con.prepare(`
SELECT * FROM ${this.resource.state.routeName} WHERE ${idAttr} = ${JSON.stringify(id).replace(/"/g, "'")};
`);
const [data = null] = await stmt.all();
return data as Data | null;
}

async getSingle(query) {
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const con = await this.db.connect();
const stmt = await con.prepare(`
SELECT * FROM ${this.resource.state.routeName} LIMIT 1;
`);
const [data = null] = await stmt.all();
return data as Data | null;
}

async delete(id: ID) {
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

const con = await this.db.connect();
const stmt = await con.prepare(`
DELETE FROM ${this.resource.state.routeName} WHERE ${idAttr} = ${JSON.stringify(id).replace(/"/g, "'")};
`);
await stmt.run();
}

async emplace(id: ID, data: Data) {
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

const clause = `INSERT OR REPLACE INTO ${this.resource.state.routeName}`;
const keys = Object.keys(data).join(',');
const values = Object.values(data).map((d) => JSON.stringify(d).replace(/"/g, "'")).join(',');
const sql = `${clause} (${idAttr},${keys}) VALUES (${id},${values});`;
const con = await this.db.connect();
const stmt = await con.prepare(sql);
const [newData] = await stmt.all();
// TODO check if created flag
return [newData, false] as [Data, boolean];
}

async patch(id: ID, data: Partial<Data>) {
assert(typeof this.db !== 'undefined');
assert(typeof this.resource !== 'undefined');

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string');

const clause = `UPDATE ${this.resource.state.routeName}`;
const setParams = Object.entries(data).map(([key, value]) => (
`${key} = ${JSON.stringify(value).replace(/"/g, "'")}`
)).join(',');
const sql = `${clause} SET ${setParams} WHERE ${idAttr} = ${JSON.stringify(id).replace(/"/g, "'")}`
const con = await this.db.connect();
const stmt = await con.prepare(sql);
const [newData] = await stmt.all();
return newData as Data;
}
}

+ 8
- 0
packages/data-sources/duckdb/test/index.test.ts Ver fichero

@@ -0,0 +1,8 @@
import { describe, it, expect } from 'vitest';
import add from '../src';

describe('blah', () => {
it('works', () => {
expect(add(1, 1)).toEqual(2);
});
});

+ 23
- 0
packages/data-sources/duckdb/tsconfig.json Ver fichero

@@ -0,0 +1,23 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "bundler",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018",
"useDefineForClassFields": false,
"declarationMap": true
}
}

+ 107
- 0
packages/data-sources/file-jsonl/.gitignore Ver fichero

@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

+ 7
- 0
packages/data-sources/file-jsonl/LICENSE Ver fichero

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2024 TheoryOfNekomata <allan.crisostomo@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 66
- 0
packages/data-sources/file-jsonl/package.json Ver fichero

@@ -0,0 +1,66 @@
{
"name": "@modal-sh/yasumi-data-source-file-jsonl",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=16"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^20.11.0",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"dependencies": {
"@modal-sh/yasumi": "workspace:*"
},
"private": false,
"description": "JSON lines file data source for Yasumi.",
"repository": {
"url": "",
"type": "git"
},
"homepage": "",
"bugs": {
"url": ""
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
},
"types": "./dist/types/index.d.ts",
"main": "./dist/cjs/production/index.js",
"module": "./dist/esm/production/index.js",
"exports": {
".": {
"development": {
"require": "./dist/cjs/development/index.js",
"import": "./dist/esm/development/index.js"
},
"require": "./dist/cjs/production/index.js",
"import": "./dist/esm/production/index.js",
"types": "./dist/types/index.d.ts"
}
},
"typesVersions": {
"*": {}
}
}

+ 3
- 0
packages/data-sources/file-jsonl/pridepack.json Ver fichero

@@ -0,0 +1,3 @@
{
"target": "es2018"
}

+ 255
- 0
packages/data-sources/file-jsonl/src/index.ts Ver fichero

@@ -0,0 +1,255 @@
import { readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { Resource, validation as v, BaseResourceType } from '@modal-sh/yasumi';
import { DataSource, ResourceIdConfig } from '@modal-sh/yasumi/backend';
import assert from 'assert';

export class ResourceNotPreparedError extends Error {}

export class ResourceIdNotDesignatedError extends Error {}

export class JsonLinesDataSource<
Schema extends v.BaseSchema = v.BaseSchema,
CurrentName extends string = string,
CurrentRouteName extends string = string,
Data extends object = v.Output<Schema>,
> implements DataSource<Data> {
private path?: string;

private resource?: Resource<BaseResourceType & {
schema: Schema,
name: CurrentName,
routeName: CurrentRouteName,
}>;

data: Data[] = [];

constructor(private readonly baseDir = '') {
// noop
}

prepareResource<Schema extends v.BaseSchema>(resource: Resource<BaseResourceType & {
schema: Schema,
name: CurrentName,
routeName: CurrentRouteName,
}>) {
this.path = join(this.baseDir, `${resource.state.routeName}.jsonl`);
resource.dataSource = resource.dataSource ?? this;
const originalResourceId = resource.id;
resource.id = <NewIdAttr extends BaseResourceType['idAttr'], NewIdSchema extends BaseResourceType['idSchema']>(newIdAttr: NewIdAttr, params: ResourceIdConfig<NewIdSchema>) => {
originalResourceId(newIdAttr, params);
return resource as Resource<BaseResourceType & {
name: CurrentName,
routeName: CurrentRouteName,
schema: Schema,
idAttr: NewIdAttr,
idSchema: NewIdSchema,
}>;
};
this.resource = resource as any;
}

async initialize() {
assert(typeof this.path === 'string', new ResourceNotPreparedError());

try {
const fileContents = await readFile(this.path, 'utf-8');
const lines = fileContents.split('\n');
this.data = lines.filter((l) => l.trim().length > 0).map((l) => JSON.parse(l));
} catch (err) {
await writeFile(this.path, '');
}
}

async getTotalCount() {
return this.data.length;
}

async getMultiple() {
return [...this.data];
}

async newId() {
const idConfig = this.resource?.state.shared.get('idConfig') as ResourceIdConfig<any>;
assert(typeof idConfig !== 'undefined', new ResourceNotPreparedError());
const theNewId = await idConfig.generationStrategy(this);
return theNewId as string;
}

async getById(idSerialized: string) {
assert(typeof this.resource !== 'undefined', new ResourceNotPreparedError());
assert(typeof this.path === 'string', new ResourceNotPreparedError());

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string', new ResourceIdNotDesignatedError());

const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined;
assert(typeof idConfig !== 'undefined', new ResourceIdNotDesignatedError());

const id = idConfig.deserialize(idSerialized);
const foundData = this.data.find((s) => (s as any)[idAttr] === id);

if (foundData) {
return {
...foundData
};
}

return null;
}

async create(data: Data) {
assert(typeof this.resource !== 'undefined', new ResourceNotPreparedError());
assert(typeof this.path === 'string', new ResourceNotPreparedError());

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string', new ResourceIdNotDesignatedError());

const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined;
assert(typeof idConfig !== 'undefined', new ResourceIdNotDesignatedError());

let theId: any;
const { [idAttr]: dataId, ...etcData } = data as Record<string, unknown>;
if (typeof dataId !== 'undefined') {
theId = idConfig.deserialize((data as Record<string, string>)[idAttr]);
} else {
const newId = await this.newId();
theId = idConfig.deserialize(newId);
}
const newData = {
[idAttr]: theId,
...etcData
} as Record<string, unknown>;

const now = Date.now(); // TODO how to serialize dates
const createdAt = this.resource.state.shared.get('createdAtAttr');
if (typeof createdAt === 'string') {
newData[createdAt] = now;
}

const updatedAt = this.resource.state.shared.get('updatedAtAttr');
if (typeof updatedAt === 'string') {
newData[updatedAt] = now;
}

const newCollection = [
...this.data,
newData
];

await writeFile(this.path, newCollection.map((d) => JSON.stringify(d)).join('\n'));

return newData as Data;
}

async delete(idSerialized: string) {
assert(typeof this.resource !== 'undefined', new ResourceNotPreparedError());
assert(typeof this.path === 'string', new ResourceNotPreparedError());

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string', new ResourceIdNotDesignatedError());

const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined;
assert(typeof idConfig !== 'undefined', new ResourceIdNotDesignatedError());

const oldDataLength = this.data.length;

const id = idConfig.deserialize(idSerialized);
const newData = this.data.filter((s) => !((s as any)[idAttr] === id));

await writeFile(this.path, newData.map((d) => JSON.stringify(d)).join('\n'));

return oldDataLength !== newData.length;
}

async emplace(idSerialized: string, dataWithId: Data) {
assert(typeof this.resource !== 'undefined', new ResourceNotPreparedError());
assert(typeof this.path === 'string', new ResourceNotPreparedError());

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string', new ResourceIdNotDesignatedError());

const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined;
assert(typeof idConfig !== 'undefined', new ResourceIdNotDesignatedError());

const existing = await this.getById(idSerialized);
const id = idConfig.deserialize(idSerialized);
const { [idAttr]: idFromResource, ...data } = (dataWithId as any);
const dataToEmplace = {
[idAttr]: id,
...data,
} as Record<string, unknown>;

if (existing) {
const createdAt = this.resource.state.shared.get('createdAtAttr');
if (typeof createdAt === 'string') {
dataToEmplace[createdAt] = (existing as Record<string, unknown>)[createdAt];
}

const now = Date.now(); // TODO how to serialize dates
const updatedAt = this.resource.state.shared.get('updatedAtAttr');
if (typeof updatedAt === 'string') {
dataToEmplace[updatedAt] = now;
}

const newData = this.data.map((d) => {
if ((d as any)[idAttr] === id) {
return dataToEmplace;
}

return d;
});

await writeFile(this.path, newData.map((d) => JSON.stringify(d)).join('\n'));

return [dataToEmplace, false] as [Data, boolean];
}

const newData = await this.create(dataToEmplace as Data);
return [newData, true] as [Data, boolean];
}

async patch(idSerialized: string, data: Partial<Data>) {
assert(typeof this.resource !== 'undefined', new ResourceNotPreparedError());
assert(typeof this.path === 'string', new ResourceNotPreparedError());

const idAttr = this.resource.state.shared.get('idAttr');
assert(typeof idAttr === 'string', new ResourceIdNotDesignatedError());

const idConfig = this.resource.state.shared.get('idConfig') as ResourceIdConfig<any> | undefined;
assert(typeof idConfig !== 'undefined', new ResourceIdNotDesignatedError());

const existing = await this.getById(idSerialized);
if (!existing) {
return null;
}

const newItem = {
...existing,
...data,
} as Record<string, unknown>;

const createdAt = this.resource.state.shared.get('createdAtAttr');
if (typeof createdAt === 'string') {
newItem[createdAt] = (existing as Record<string, unknown>)[createdAt];
}

const now = Date.now(); // TODO how to serialize dates
const updatedAt = this.resource.state.shared.get('updatedAtAttr');
if (typeof updatedAt === 'string') {
newItem[updatedAt] = now;
}

const id = idConfig.deserialize(idSerialized);
const newData = this.data.map((d) => {
if ((d as any)[idAttr] === id) {
return newItem;
}

return d;
});

await writeFile(this.path, newData.map((d) => JSON.stringify(d)).join('\n'));
return newItem as Data;
}
}

+ 236
- 0
packages/data-sources/file-jsonl/test/index.test.ts Ver fichero

@@ -0,0 +1,236 @@
import {describe, it, expect, vi, Mock, beforeAll, beforeEach} from 'vitest';
import { readFile, writeFile } from 'fs/promises';
import { JsonLinesDataSource } from '../src';
import { resource, validation as v, BaseResourceType } from '@modal-sh/yasumi';
import {DataSource} from '@modal-sh/yasumi/dist/types/backend';

vi.mock('fs/promises');

const toJsonl = (dummyItems: unknown[]) => dummyItems.map((i) => JSON.stringify(i)).join('\n');

const ID_ATTR = 'id' as const;

describe('prepareResource', () => {
beforeAll(() => {
const mockWriteFile = writeFile as Mock;
mockWriteFile.mockImplementation(() => { /* noop */ })
});

it('works', () => {
const schema = v.object({});
const r = resource(schema);
const ds = new JsonLinesDataSource<typeof schema>();
expect(() => ds.prepareResource(r)).not.toThrow();
});
});

describe('methods', () => {
const dummyItems = [
{
id: 1,
name: 'foo',
},
{
id: 2,
name: 'bar',
},
{
id: 3,
name: 'baz',
},
];
const schema = v.object({
name: v.string(),
});
let ds: DataSource<v.Output<typeof schema>>;
let mockGenerationStrategy: Mock;
beforeEach(() => {
mockGenerationStrategy = vi.fn();
const r = resource(schema)
.id(ID_ATTR, {
generationStrategy: mockGenerationStrategy,
schema: v.any(),
serialize: (id) => id.toString(),
deserialize: (id) => Number(id?.toString() ?? 0),
});
ds = new JsonLinesDataSource<typeof schema>();
ds.prepareResource(r);
});

beforeEach(() => {
const mockReadFile = readFile as Mock;
mockReadFile.mockReturnValueOnce(toJsonl(dummyItems));
});

let mockWriteFile: Mock;
beforeEach(() => {
mockWriteFile = writeFile as Mock;
mockWriteFile.mockImplementationOnce(() => { /* noop */ });
});

describe('initialize', () => {
it('works', async () => {
try {
await ds.initialize();
} catch {
expect.fail('Could not initialize data source.');
}
});
});

describe('operations', () => {
beforeEach(async () => {
await ds.initialize();
});

describe('getTotalCount', () => {
it('works', async () => {
if (typeof ds.getTotalCount !== 'function') {
return;
}
const totalCount = await ds.getTotalCount();
expect(totalCount).toBe(dummyItems.length);
});
});

describe('getMultiple', () => {
it('works', async () => {
const items = await ds.getMultiple();
expect(items).toEqual(dummyItems);
});
});

describe('getById', () => {
it('works', async () => {
const id = 2;
const item = await ds.getById(id.toString()); // ID is always a string because it originates from URLs
const expected = dummyItems.find((i) => i[ID_ATTR] === id);
expect(item).toEqual(expected);
});
});

describe('getSingle', () => {
it('works', async () => {
if (typeof ds.getSingle !== 'function') {
// skip if data source doesn't offer this
return;
}
const item = await ds.getSingle();
const expected = dummyItems[0];
expect(item).toEqual(expected);
});
});

describe('create', () => {
it('works', async () => {
const data = {
// notice we don't have IDs here, as it is expected to be generated by newId()
name: 'foo'
};
const newItem = await ds.create(data);

expect(mockWriteFile).toBeCalledWith(
expect.any(String),
toJsonl([
...dummyItems,
{
id: 0,
...data,
}
])
);
expect(newItem).toEqual({ id: 0, ...data});
});
});

describe('delete', () => {
it('works', async () => {
await ds.delete('1');
expect(mockWriteFile).toBeCalledWith(
expect.any(String),
toJsonl(dummyItems.filter((d) => d[ID_ATTR] !== 1)),
);
});
});

describe('emplace', () => {
it('replaces existing data', async () => {
const data = {
[ID_ATTR]: 2,
name: 'foo',
};
const { id, ...etcData } = data;
const newItem = await ds.emplace(
id.toString(),
etcData,
);

expect(mockWriteFile).toBeCalledWith(
expect.any(String),
toJsonl(dummyItems.map((d) =>
d[ID_ATTR] === data[ID_ATTR]
// ID will be defined first, since we are just writing to file, we need strict ordering
? { [ID_ATTR]: id, ...etcData }
: d
)),
);
expect(newItem).toEqual([data, false]);
});

it('creates new data', async () => {
const data = {
[ID_ATTR]: 4,
name: 'quux',
};
const { [ID_ATTR]: id, ...etcData } = data;
const newItem = await ds.emplace(
id.toString(),
etcData,
);

expect(mockWriteFile).toBeCalledWith(
expect.any(String),
toJsonl([
...dummyItems,
data
]),
);
expect(newItem).toEqual([data, true]);
});
});

describe('patch', () => {
it('works', async () => {
const data = {
[ID_ATTR]: 2,
name: 'foo',
};
const { id, ...etcData } = data;
const newItem = await ds.emplace(
id.toString(),
etcData,
);

expect(mockWriteFile).toBeCalledWith(
expect.any(String),
toJsonl(dummyItems.map((d) =>
d[ID_ATTR] === data[ID_ATTR]
// ID will be defined first, since we are just writing to file, we need strict ordering
? { [ID_ATTR]: id, ...etcData }
: d
)),
);
expect(newItem).toBeDefined();
});
});

describe('newId', () => {
it('works', async () => {
const v = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
mockGenerationStrategy.mockResolvedValueOnce(v);
const id = await ds.newId();
expect(id).toBe(v);
});
});
});
});

+ 23
- 0
packages/data-sources/file-jsonl/tsconfig.json Ver fichero

@@ -0,0 +1,23 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "bundler",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018",
"useDefineForClassFields": false,
"declarationMap": true
}
}

+ 107
- 0
packages/examples/http-resource-server/.gitignore Ver fichero

@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

+ 45
- 0
packages/examples/http-resource-server/package.json Ver fichero

@@ -0,0 +1,45 @@
{
"name": "http-resource-server",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=16"
},
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^20.11.0",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": true,
"description": "Basic HTTP resource server example for Yasumi.",
"repository": {
"url": "",
"type": "git"
},
"homepage": "",
"bugs": {
"url": ""
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "restricted"
}
}

+ 3
- 0
packages/examples/http-resource-server/pridepack.json Ver fichero

@@ -0,0 +1,3 @@
{
"target": "es2018"
}

+ 6
- 0
packages/examples/http-resource-server/src/index.ts Ver fichero

@@ -0,0 +1,6 @@
export default function add(a: number, b: number): number {
if (process.env.NODE_ENV !== 'production') {
console.log('This code would not appear on production builds');
}
return a + b;
}

+ 8
- 0
packages/examples/http-resource-server/test/index.test.ts Ver fichero

@@ -0,0 +1,8 @@
import { describe, it, expect } from 'vitest';
import add from '../src';

describe('blah', () => {
it('works', () => {
expect(add(1, 1)).toEqual(2);
});
});

+ 23
- 0
packages/examples/http-resource-server/tsconfig.json Ver fichero

@@ -0,0 +1,23 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "bundler",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018",
"useDefineForClassFields": false,
"declarationMap": true
}
}

+ 107
- 0
packages/extenders/http/.gitignore Ver fichero

@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

+ 7
- 0
packages/extenders/http/LICENSE Ver fichero

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2024 TheoryOfNekomata <allan.crisostomo@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 49
- 0
packages/extenders/http/package.json Ver fichero

@@ -0,0 +1,49 @@
{
"name": "@modal-sh/yasumi-extender-http",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=16"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^20.11.0",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": false,
"description": "HTTP extender for Yasumi.",
"repository": {
"url": "",
"type": "git"
},
"homepage": "",
"bugs": {
"url": ""
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
},
"dependencies": {
"@modal-sh/yasumi": "workspace:*"
}
}

+ 7
- 0
packages/extenders/http/pridepack.json Ver fichero

@@ -0,0 +1,7 @@
{
"target": "es2018",
"entrypoints": {
"./backend": "src/backend/index.ts",
"./client": "src/client/index.ts"
}
}

packages/core/src/extenders/http/backend/core.ts → packages/extenders/http/src/backend/core.ts Ver fichero

@@ -1,15 +1,14 @@
import {ErrorResponse, parseToEndpointQueue, ServiceParams} from '../../../common';
import http from 'http';
import {ErrorResponse, parseToEndpointQueue, ServiceParams, statusCodes} from '@modal-sh/yasumi';
import {
Backend as BaseBackend,
Server,
ServerRequestContext,
ServerResponseContext,
ServerParams,
} from '../../../backend';
import http from 'http';
import { statusCodes } from '../../../common';
} from '@modal-sh/yasumi/backend';

declare module '../../../backend' {
declare module '@modal-sh/yasumi/backend' {
interface ServerRequestContext extends http.IncomingMessage {}

interface ServerResponseContext extends http.ServerResponse {}

packages/core/src/extenders/http/backend/index.ts → packages/extenders/http/src/backend/index.ts Ver fichero


packages/core/src/extenders/http/client.ts → packages/extenders/http/src/client/core.ts Ver fichero

@@ -5,10 +5,10 @@ import {
GetEndpointParams,
Operation, serializeEndpointQueue,
ServiceParams,
} from '../../common';
import {Client, ClientParams, ClientConnection} from '../../client';
} from '@modal-sh/yasumi';
import {Client, ClientParams, ClientConnection} from '@modal-sh/yasumi/client';

declare module '../../client' {
declare module '@modal-sh/yasumi/client' {
interface ClientConnection {
host: string;
port: number;

+ 1
- 0
packages/extenders/http/src/client/index.ts Ver fichero

@@ -0,0 +1 @@
export * from './core';

packages/core/test/http/default.test.ts → packages/extenders/http/test/default.test.ts Ver fichero

@@ -11,13 +11,13 @@ import {
app,
Endpoint,
Operation,
} from '../../src/common';
import {DataSource, DataSourceQuery, EmplaceDetails, Server} from '../../src/backend';
import {Client} from '../../src/client';
import {server} from '../../src/extenders/http/backend';
import {client} from '../../src/extenders/http/client';
import {composeRecipes} from '../../src/common/recipe';
import {addResourceRecipe, ResourceItemFetchedResponse} from '../../src/recipes/resource';
composeRecipes,
} from '@modal-sh/yasumi';
import {DataSource, DataSourceQuery, EmplaceDetails, Server} from '@modal-sh/yasumi/backend';
import {Client} from '@modal-sh/yasumi/client';
import {server} from '@modal-sh/yasumi-extender-http/backend';
import {client} from '@modal-sh/yasumi-extender-http/client';
import {addResourceRecipe, ResourceItemFetchedResponse} from '@modal-sh/yasumi-recipe-resource';

describe('default', () => {
let theClient: Client;

packages/core/test/index.test.ts → packages/extenders/http/test/error-handling.test.ts Ver fichero

@@ -8,11 +8,11 @@ import {
operation,
statusCodes,
validation as v,
} from '../src/common';
import {Backend, backend, DataSource, Server} from '../src/backend';
import {Client} from '../src/client';
import {server} from '../src/extenders/http/backend';
import {client} from '../src/extenders/http/client';
} from '../../../core/src/common';
import {Backend, backend, DataSource, Server} from '../../../core/src/backend';
import {Client} from '../../../core/src/client';
import {server} from '../../../core/src/extenders/http/backend';
import {client} from '../../../core/src/extenders/http/client';

const op = operation({
name: 'create' as const,

+ 23
- 0
packages/extenders/http/tsconfig.json Ver fichero

@@ -0,0 +1,23 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "bundler",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018",
"useDefineForClassFields": false,
"declarationMap": true
}
}

+ 107
- 0
packages/recipes/resource/.gitignore Ver fichero

@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

+ 7
- 0
packages/recipes/resource/LICENSE Ver fichero

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2024 TheoryOfNekomata <allan.crisostomo@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 49
- 0
packages/recipes/resource/package.json Ver fichero

@@ -0,0 +1,49 @@
{
"name": "@modal-sh/yasumi-recipe-resource",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=16"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^20.11.0",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": false,
"description": "Resource recipe for Yasumi.",
"repository": {
"url": "",
"type": "git"
},
"homepage": "",
"bugs": {
"url": ""
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
},
"dependencies": {
"@modal-sh/yasumi": "workspace:*"
}
}

+ 3
- 0
packages/recipes/resource/pridepack.json Ver fichero

@@ -0,0 +1,3 @@
{
"target": "es2018"
}

packages/core/src/recipes/resource/core.ts → packages/recipes/resource/src/core.ts Ver fichero

@@ -1,6 +1,5 @@
import {Recipe} from '../../common/recipe';
import {endpoint, validation as v} from '../../common';
import {backend, DataSource} from '../../backend';
import {Recipe, endpoint, validation as v} from '@modal-sh/yasumi';
import {backend, DataSource} from '@modal-sh/yasumi/backend';
import * as fetchOperation from './implementation/fetch';
import * as createOperation from './implementation/create';
import * as emplaceOperation from './implementation/emplace';

packages/core/src/recipes/resource/implementation/create.ts → packages/recipes/resource/src/implementation/create.ts Ver fichero

@@ -1,5 +1,5 @@
import {ImplementationFunction} from '../../../backend';
import {operation as defineOperation} from '../../../common';
import {ImplementationFunction} from '@modal-sh/yasumi/backend';
import {operation as defineOperation} from '@modal-sh/yasumi';

export const name = 'create' as const;


packages/core/src/recipes/resource/implementation/delete.ts → packages/recipes/resource/src/implementation/delete.ts Ver fichero

@@ -1,5 +1,5 @@
import {ImplementationFunction} from '../../../backend';
import {operation as defineOperation} from '../../../common';
import {ImplementationFunction} from '@modal-sh/yasumi/backend';
import {operation as defineOperation} from '@modal-sh/yasumi';

export const name = 'delete' as const;


packages/core/src/recipes/resource/implementation/emplace.ts → packages/recipes/resource/src/implementation/emplace.ts Ver fichero

@@ -1,5 +1,5 @@
import {ImplementationFunction} from '../../../backend';
import {operation as defineOperation} from '../../../common';
import {ImplementationFunction} from '@modal-sh/yasumi/backend';
import {operation as defineOperation} from '@modal-sh/yasumi';

export const name = 'emplace' as const;


packages/core/src/recipes/resource/implementation/fetch.ts → packages/recipes/resource/src/implementation/fetch.ts Ver fichero

@@ -1,11 +1,11 @@
import {DataSource, ImplementationFunction} from '../../../backend';
import {ImplementationFunction, DataSource} from '@modal-sh/yasumi/backend';
import {operation as defineOperation} from '@modal-sh/yasumi';
import {
DataSourceNotFoundResponseError,
ItemNotFoundReponseError,
ResourceCollectionFetchedResponse,
ResourceItemFetchedResponse,
} from '../response';
import {operation as defineOperation} from '../../../common';

export const name = 'fetch' as const;


packages/core/src/recipes/resource/implementation/patch-delta.ts → packages/recipes/resource/src/implementation/patch-delta.ts Ver fichero

@@ -1,5 +1,5 @@
import {ImplementationFunction} from '../../../backend';
import {operation as defineOperation} from '../../../common';
import {ImplementationFunction} from '@modal-sh/yasumi/backend';
import {operation as defineOperation} from '@modal-sh/yasumi';

export const name = 'patchDelta' as const;


packages/core/src/recipes/resource/implementation/patch-merge.ts → packages/recipes/resource/src/implementation/patch-merge.ts Ver fichero

@@ -1,5 +1,5 @@
import {ImplementationFunction} from '../../../backend';
import {operation as defineOperation} from '../../../common';
import {ImplementationFunction} from '@modal-sh/yasumi/backend';
import {operation as defineOperation} from '@modal-sh/yasumi';

export const name = 'patchMerge' as const;


packages/core/src/recipes/resource/implementation/query.ts → packages/recipes/resource/src/implementation/query.ts Ver fichero

@@ -1,5 +1,5 @@
import {ImplementationFunction} from '../../../backend';
import {operation as defineOperation} from '../../../common';
import {ImplementationFunction} from '@modal-sh/yasumi/backend';
import {operation as defineOperation} from '@modal-sh/yasumi';

export const name = 'query' as const;


packages/core/src/recipes/resource/index.ts → packages/recipes/resource/src/index.ts Ver fichero


packages/core/src/recipes/resource/response.ts → packages/recipes/resource/src/response.ts Ver fichero

@@ -1,4 +1,4 @@
import {HttpResponse, statusCodes} from '../../common';
import {HttpResponse, statusCodes} from '@modal-sh/yasumi';

export class ResourceItemFetchedResponse extends HttpResponse(statusCodes.HTTP_STATUS_OK) {}


+ 8
- 0
packages/recipes/resource/test/index.test.ts Ver fichero

@@ -0,0 +1,8 @@
import { describe, it, expect } from 'vitest';
import add from '../src';

describe('blah', () => {
it('works', () => {
expect(add(1, 1)).toEqual(2);
});
});

+ 23
- 0
packages/recipes/resource/tsconfig.json Ver fichero

@@ -0,0 +1,23 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "bundler",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018",
"useDefineForClassFields": false,
"declarationMap": true
}
}

+ 808
- 20
pnpm-lock.yaml
La diferencia del archivo ha sido suprimido porque es demasiado grande
Ver fichero


Cargando…
Cancelar
Guardar