diff --git a/CoCreate.config.js b/CoCreate.config.js index aafa9c8..5a59015 100644 --- a/CoCreate.config.js +++ b/CoCreate.config.js @@ -22,15 +22,15 @@ module.exports = { ], "projects": { "client": { - "path": "../../CoCreate-client", - "repo": "github.com/CoCreateJS/CoCreate-client.git", + "path": "../../client", + "repo": "github.com/CoCreateJS/client.git", "exclude": [ "fs/webpack" ] }, "server": { - "path": "../../CoCreate-server", - "repo": "github.com/CoCreateJS/CoCreate-server.git", + "path": "../server", + "repo": "github.com/CoCreateJS/server.git", "exclude": [ "fs/webpack" ] @@ -126,6 +126,10 @@ module.exports = { "fs/webpack" ] }, + "db": { + "path": "../db", + "repo": "github.com/CoCreateJS/db.git" + }, "css-parser": { "path": "../css-parser", "repo": "github.com/CoCreateJS/css-parser.git" @@ -134,9 +138,9 @@ module.exports = { "path": "../cursors", "repo": "github.com/CoCreateJS/cursors.git" }, - "device": { - "path": "../device", - "repo": "github.com/CoCreateJS/device.git" + "apps": { + "path": "../apps", + "repo": "github.com/CoCreateJS/apps.git" }, "docs": { "path": "../docs", @@ -248,10 +252,6 @@ module.exports = { "fs/webpack" ] }, - "socket-client": { - "path": "../socket-client", - "repo": "github.com/CoCreateJS/socket-client.git" - }, "socket": { "path": "../socket", "repo": "github.com/CoCreateJS/socket.git", @@ -329,158 +329,158 @@ module.exports = { }, "storages": { "amazon-redshift": { - "path": "../../CoCreate-storages/amazon-redshift", + "path": "../../storages/amazon-redshift", "repo": "github.com/CoCreateJS/amazon-redshift.git", "exclude": [ "fs/webpack" ] }, "auroradb": { - "path": "../../CoCreate-storages/auroradb", + "path": "../../storages/auroradb", "repo": "github.com/CoCreateJS/auroradb.git", "exclude": [ "fs/webpack" ] }, "cockroachdb": { - "path": "../../CoCreate-storages/cockroachdb", + "path": "../../storages/cockroachdb", "repo": "github.com/CoCreateJS/cockroachdb.git", "exclude": [ "fs/webpack" ] }, "cosmosdb": { - "path": "../../CoCreate-storages/cosmosdb", + "path": "../../storages/cosmosdb", "repo": "github.com/CoCreateJS/cosmosdb.git", "exclude": [ "fs/webpack" ] }, "documentdb": { - "path": "../../CoCreate-storages/documentdb", + "path": "../../storages/documentdb", "repo": "github.com/CoCreateJS/documentdb.git", "exclude": [ "fs/webpack" ] }, "dqlite": { - "path": "../../CoCreate-storages/dqlite", + "path": "../../storages/dqlite", "repo": "github.com/CoCreateJS/dqlite.git", "exclude": [ "fs/webpack" ] }, "dynamodb": { - "path": "../../CoCreate-storages/dynamodb", + "path": "../../storages/dynamodb", "repo": "github.com/CoCreateJS/dynamodb.git", "exclude": [ "fs/webpack" ] }, "ferretdb": { - "path": "../../CoCreate-storages/ferretdb", + "path": "../../storages/ferretdb", "repo": "github.com/CoCreateJS/ferretdb.git", "exclude": [ "fs/webpack" ] }, "firestore": { - "path": "../../CoCreate-storages/firestore", + "path": "../../storages/firestore", "repo": "github.com/CoCreateJS/firestore.git", "exclude": [ "fs/webpack" ] }, "indexeddb": { - "path": "../../CoCreate-storages/indexeddb", + "path": "../../storages/indexeddb", "repo": "github.com/CoCreateJS/indexeddb.git" }, "mariadb": { - "path": "../../CoCreate-storages/mariadb", + "path": "../../storages/mariadb", "repo": "github.com/CoCreateJS/mariadb.git", "exclude": [ "fs/webpack" ] }, "mongodb": { - "path": "../../CoCreate-storages/mongodb", + "path": "../../storages/mongodb", "repo": "github.com/CoCreateJS/mongodb.git", "exclude": [ "fs/webpack" ] }, "mysql": { - "path": "../../CoCreate-storages/mysql", + "path": "../../storages/mysql", "repo": "github.com/CoCreateJS/mysql.git", "exclude": [ "fs/webpack" ] }, "oracledb": { - "path": "../../CoCreate-storages/oracledb", + "path": "../../storages/oracledb", "repo": "github.com/CoCreateJS/oracledb.git", "exclude": [ "fs/webpack" ] }, "planetscale": { - "path": "../../CoCreate-storages/planetscale", + "path": "../../storages/planetscale", "repo": "github.com/CoCreateJS/planetscale.git", "exclude": [ "fs/webpack" ] }, "postgresql": { - "path": "../../CoCreate-storages/postgresql", + "path": "../../storages/postgresql", "repo": "github.com/CoCreateJS/postgresql.git", "exclude": [ "fs/webpack" ] }, "qdrant": { - "path": "../../CoCreate-storages/qdrant", + "path": "../../storages/qdrant", "repo": "github.com/CoCreateJS/qdrant.git", "exclude": [ "fs/webpack" ] }, "rqlite": { - "path": "../../CoCreate-storages/rqlite", + "path": "../../storages/rqlite", "repo": "github.com/CoCreateJS/rqlite.git", "exclude": [ "fs/webpack" ] }, "sqlite": { - "path": "../../CoCreate-storages/sqlite", + "path": "../../storages/sqlite", "repo": "github.com/CoCreateJS/sqlite.git", "exclude": [ "fs/webpack" ] }, "tidb": { - "path": "../../CoCreate-storages/tidb", + "path": "../../storages/tidb", "repo": "github.com/CoCreateJS/tidb.git", "exclude": [ "fs/webpack" ] }, "timescaledb": { - "path": "../../CoCreate-storages/timescaledb", + "path": "../../storages/timescaledb", "repo": "github.com/CoCreateJS/timescaledb.git", "exclude": [ "fs/webpack" ] }, "turso": { - "path": "../../CoCreate-storages/turso", + "path": "../../storages/turso", "repo": "github.com/CoCreateJS/turso.git", "exclude": [ "fs/webpack" ] }, "yugabytedb": { - "path": "../../CoCreate-storages/yugabytedb", + "path": "../../storages/yugabytedb", "repo": "github.com/CoCreateJS/yugabytedb.git", "exclude": [ "fs/webpack" @@ -490,7 +490,7 @@ module.exports = { "plugins": { "rollup": { "import": "@cocreate/rollup", - "path": "../../CoCreate-plugins/rollup", + "path": "../../plugins/rollup", "repo": "github.com/CoCreateJS/Rollup.git", "exclude": [ "fs/webpack" @@ -498,8 +498,8 @@ module.exports = { }, "webpack": { "import": "@cocreate/webpack", - "path": "../../CoCreate-plugins/webpack", - "repo": "github.com/CoCreateJS/Webpack.git", + "path": "../../plugins/webpack", + "repo": "github.com/CoCreateJS/webpack.git", "exclude": [ "fs/webpack" ] diff --git a/README.md b/README.md index afa9863..7136441 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,22 @@ are declarative; the rest are API records. Source comments use filter modules and doclets by their `@environment` tags. Without environment flags, both environments are included. +## Local CRUD + +`coc crud` accepts the same JSON envelope as `coc send` and calls CRUD server +directly. CRUD server handles storage initialization and routing; the command does +not open a Socket connection or require an API key or a database directory argument. + +```bash +coc crud '{"method":"object.read","organization_id":"5ff747727005da1c272740ab","database":"dev","array":"keys","filter":{"query":{"admin":true},"limit":1}}' +``` + +JSON files and stdin are optional ways to supply that same envelope. Create, +update, and delete use normal CRUD envelopes too. Results retain CRUD metadata, +credentials are redacted, and failures exit nonzero. The project configuration can +supply `organization_id` when the envelope omits it. `coc send` retains its Socket +behavior and name. Use `coc crud --help` for usage. + # Table of Contents - [Table of Contents](#table-of-contents) diff --git a/package.json b/package.json index 7c44fa8..47ad60d 100644 --- a/package.json +++ b/package.json @@ -51,9 +51,12 @@ "@cocreate/certificates": "^1.11.0", "@cocreate/config": "^2.0.1", "@cocreate/docs": "^2.0.0", + "@cocreate/ast": "^1.0.0", "@cocreate/file": "^2.0.1", "@cocreate/utils": "^2.0.2", "@google/genai": "2.15.0", - "@cocreate/socket": "^3.0.0" + "@cocreate/socket": "^3.0.0", + "@cocreate/crud": "^2.0.4", + "@cocreate/db": "^0.0.0-development" } } diff --git a/src/coc.js b/src/coc.js index 0422a88..c1dd201 100755 --- a/src/coc.js +++ b/src/coc.js @@ -28,6 +28,7 @@ const availableOptions = { const options = {}; const commandParts = []; +const commandArguments = []; for (let i = 0; i < argv.length; i++) { let option = availableOptions[argv[i]]; if (option) { @@ -38,6 +39,7 @@ for (let i = 0; i < argv.length; i++) { argv.splice(i + 1, 1); } } else { + commandArguments.push(argv[i]); if (argv[i].match(/[\s'"]/)) { commandParts.push(`'${argv[i].replace(/'/g, "\\'")}'`); } else { @@ -193,7 +195,7 @@ async function main(config = {}, options, sourceConfigSnapshot) { } // Execute the command across targeted repositories/modules/projects - const failed = await execute(command, config, sourceConfig); + const failed = await execute(command, config, sourceConfig, commandArguments); // Handle any failed command executions if (failed && failed.length > 0) { diff --git a/src/commands/crud.js b/src/commands/crud.js new file mode 100644 index 0000000..2584c42 --- /dev/null +++ b/src/commands/crud.js @@ -0,0 +1,64 @@ +const fs = require('node:fs/promises'); +const path = require('node:path'); + +const usage = `Usage: coc crud [JSON | request.json] +With no argument, reads the same JSON envelope as coc send from stdin. +Calls CRUD with CoCreateDB's local directory and persistence config, without Socket authorization.`; + +async function readStdin() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + return input; +} + +function stringifyResponse(response) { + const secrets = new Set(['key', 'apikey', 'api_key', 'password', 'token', 'authorization', + 'connectionstring', 'privatekey', 'clientsecret', 'secret', 'secretaccesskey']); + return JSON.stringify(response, (key, value) => secrets.has(key.toLowerCase()) ? '[redacted]' : value, 2); +} + +/** + * Execute a local CRUD envelope through CRUD server without a Socket connection. + * @name crud + * @kind function + * @environment server + */ +module.exports = async function crud(repositories, args = [], projectConfig = {}) { + if (args.includes('--help') || args.includes('-h')) { + process.stdout.write(`${usage}\n`); + return []; + } + try { + let input = args.length ? args.join(' ') : await readStdin(); + if (!input.trim()) throw new Error('Provide a JSON envelope, a JSON file, or stdin.'); + try { input = await fs.readFile(path.resolve(input.trim()), 'utf8'); } + catch (error) { if (!['ENOENT', 'ENAMETOOLONG', 'ENOTDIR', 'EINVAL'].includes(error.code)) throw error; } + const payload = JSON.parse(input); + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('The envelope must be a JSON object.'); + if (!/^(storage|database|array|index|object)\.(create|read|update|delete)$/.test(payload.method)) { + throw new Error('The envelope requires a supported CRUD method, such as object.read.'); + } + const organization_id = payload.organization_id || projectConfig.organization_id; + if (typeof organization_id !== 'string' || !organization_id.trim()) throw new Error('An organization_id is required.'); + const [{ default: Crud }, { CoCreateDB }] = await Promise.all([ + import('@cocreate/crud/server'), import('@cocreate/db') + ]); + const host = typeof payload.host === 'string' ? payload.host : + typeof projectConfig.host === 'string' ? projectConfig.host : undefined; + const db = await CoCreateDB.initLocal({ config: projectConfig, prompt: false }); + const instance = await Crud.init(undefined, { config: { + ...projectConfig, organization_id, host + }, db }); + const response = await instance.send({ ...payload, organization_id }); + process.stdout.write(`${stringifyResponse(response)}\n`); + if (!response || response.success === false || + (Array.isArray(response.error) ? response.error.length : response.error)) process.exitCode = 1; + return []; + } catch (error) { + // JSON parser errors can contain fragments of a credential-bearing input. + const message = error instanceof SyntaxError ? 'The envelope must contain valid JSON.' : error.message; + console.error(`CRUD failed: ${message}`); + process.exitCode = 1; + return []; + } +}; diff --git a/src/commands/docs.js b/src/commands/docs.js index 2dedde8..3099769 100644 --- a/src/commands/docs.js +++ b/src/commands/docs.js @@ -214,12 +214,28 @@ module.exports = async function docs(repositories = [], args = [], config = {}) logProgress( `[docs] Rendering ${documentationConfig.targets.length} configured target(s) with ${documentationConfig.template}.` ); - const { renderValue } = await import("@cocreate/utils"); + const [{ renderValue }, { astAsync }] = await Promise.all([ + import("@cocreate/utils"), + import("@cocreate/ast/server") + ]); + const renderValueWithAST = ( + node, + scope, + placeholder, + renderAs, + renderedNode, + index, + resolveValue, + options = {} + ) => renderValue(node, scope, placeholder, renderAs, renderedNode, index, resolveValue, { + ...options, + astAsync + }); files = await CoCreateDocs.renderDocumentation(data, { template: templatePath, output: outputPath, targets: documentationConfig.targets, - renderValue + renderValue: renderValueWithAST }); } diff --git a/src/commands/other/lazyload-modules.js b/src/commands/other/lazyload-modules.js index 62b0bed..143b005 100644 --- a/src/commands/other/lazyload-modules.js +++ b/src/commands/other/lazyload-modules.js @@ -34,7 +34,6 @@ import { getValueFromObject, objectToSearchParams } from '@cocreate/utils'; const require = createRequire(import.meta.url); let server = null; -let wsManager = null; let crud = null; const exclusion = { ...require.cache }; const scriptsDirectory = "./scripts"; @@ -48,7 +47,6 @@ let modulesList = {}; */ export async function init(Server) { server = Server; - wsManager = server.wsManager; crud = server.crud; try { @@ -58,7 +56,7 @@ export async function init(Server) { throw error; } - wsManager.on("endpoint", (data) => { + server.on("endpoint", (data) => { executeEndpoint(data); }); @@ -114,7 +112,7 @@ export async function request(req, res) { /** * Executes external dynamic API Gateway endpoints. - * Now cleanly decoupled to be invoked by the central Socket Manager (wsManager) routing matrix. + * Now cleanly decoupled to be invoked by the central socket routing matrix. */ export async function executeEndpoint(data) { try { diff --git a/src/commands/other/symlinkPwa.js b/src/commands/other/symlinkPwa.js index 1949704..edec392 100644 --- a/src/commands/other/symlinkPwa.js +++ b/src/commands/other/symlinkPwa.js @@ -1,47 +1,47 @@ -const fs = require('fs') -const path = require('path') - -function symlink(dir, dest, option) { - if (!fs.existsSync(dir)) { - return console.log(dir, 'does not exist') - } else - dir = path.resolve(dir) - - if (fs.existsSync(dest)) - fs.rm(dest, { recursive: true, force: true }, function (err) { - if (err) { - console.log('failed'); - } - createSymlink(dir, dest, option) - }); - else - createSymlink(dir, dest, option) -} - -function createSymlink(dir, dest, option) { - dest = path.resolve(dest) - - fs.symlink(dir, dest, option, (err) => { - console.log(dir, dest, option) - if (err) - console.log(err); - else { - console.log("symlink added"); - } - - }) - -} - - -symlink('./dist/service-worker.js', '../../service-worker.js', 'file') -// symlink('./dist/service-worker.js', '../../CoCreate-app/src/service-worker.js', 'file') - -symlink('./demo/offline.html', '../../offline.html', 'file') -// symlink('./demo/offline.html', '../../CoCreate-app/src/offline.html', 'file') - -symlink('./demo/manifest.webmanifest', '../../manifest.webmanifest', 'file') -// symlink('./demo/manifest.webmanifest', '../../CoCreate-app/src/manifest.webmanifest', 'file') - -// symlink('./demo/manifest-assets', '../../manifest-assets', 'dir') -// symlink('./demo/manifest-assets', '../../CoCreate-app/manifest-assets', 'dir') +const fs = require('fs') +const path = require('path') + +function symlink(dir, dest, option) { + if (!fs.existsSync(dir)) { + return console.log(dir, 'does not exist') + } else + dir = path.resolve(dir) + + if (fs.existsSync(dest)) + fs.rm(dest, { recursive: true, force: true }, function (err) { + if (err) { + console.log('failed'); + } + createSymlink(dir, dest, option) + }); + else + createSymlink(dir, dest, option) +} + +function createSymlink(dir, dest, option) { + dest = path.resolve(dest) + + fs.symlink(dir, dest, option, (err) => { + console.log(dir, dest, option) + if (err) + console.log(err); + else { + console.log("symlink added"); + } + + }) + +} + + +symlink('./dist/service-worker.js', '../../service-worker.js', 'file') +// symlink('./dist/service-worker.js', '../../app/src/service-worker.js', 'file') + +symlink('./demo/offline.html', '../../offline.html', 'file') +// symlink('./demo/offline.html', '../../app/src/offline.html', 'file') + +symlink('./demo/manifest.webmanifest', '../../manifest.webmanifest', 'file') +// symlink('./demo/manifest.webmanifest', '../../app/src/manifest.webmanifest', 'file') + +// symlink('./demo/manifest-assets', '../../manifest-assets', 'dir') +// symlink('./demo/manifest-assets', '../../app/manifest-assets', 'dir') diff --git a/src/commands/storage.js b/src/commands/storage.js index 460e0e7..496ad50 100644 --- a/src/commands/storage.js +++ b/src/commands/storage.js @@ -32,7 +32,7 @@ module.exports = async function storage(directory, args) { : Object.entries(config.modules || {}).filter(([, module]) => { if (!module?.path) return false; return path.normalize(module.path).includes( - `${path.sep}CoCreate-storages${path.sep}` + `${path.sep}storages${path.sep}` ); }); diff --git a/src/config.template.js b/src/config.template.js index acc5345..b9a234c 100644 --- a/src/config.template.js +++ b/src/config.template.js @@ -18,12 +18,12 @@ module.exports = { template: [ // { // entry: "./", - // output: "../CoCreate-app-template", + // output: "../app-template", // exclude: ["./src/admin/", "./src/account/", "./src/apps/", "./src/config/", "./node_modules/", "./.git/"] // }, // { // entry: "./", - // output: "../CoCreate-app-template", + // output: "../app-template", // include: ["./src/admin/", "./src/account/", "./src/apps/"] // } ], @@ -56,7 +56,7 @@ module.exports = { // Keep adapters separate from general-purpose modules for workspace organization. storages: { // "storage-name": { - // path: "../CoCreate-storages/storage-name", + // path: "../storages/storage-name", // repo: "github.com/CoCreateJS/storage-name.git" // } }, @@ -80,10 +80,10 @@ module.exports = { repositories: [ { // Relative path to the repository - path: "./CoCreate-client", + path: "./client", // Git repository URL - repo: "github.com/CoCreateJS/CoCreate-client.git", + repo: "github.com/CoCreateJS/client.git", // Optional: exclude command types from running on this repository // These are COMMAND TYPES to exclude, not file patterns @@ -94,7 +94,7 @@ module.exports = { } // Add more repositories as needed for polyrepo management // { - // path: "./CoCreate-modules/cli", + // path: "./modules/cli", // repo: "github.com/CoCreateJS/CoCreate-cli.git", // exclude: ["link"] // Don't link this package during "coc install" // } diff --git a/src/execute.js b/src/execute.js index 31ada29..8247c48 100644 --- a/src/execute.js +++ b/src/execute.js @@ -7,7 +7,7 @@ const { getConfig } = require("./getConfig"); const { color } = require("./fonts"); -module.exports = async function execute(command, config, sourceConfig = config) { +module.exports = async function execute(command, config, sourceConfig = config, commandArguments) { let failed = []; let [filename, ...args] = command.replaceAll("'", '"').trim().split(" "); @@ -22,6 +22,7 @@ module.exports = async function execute(command, config, sourceConfig = config) let predefined = path.resolve(__dirname, "commands", filename); let isPredefined = fs.existsSync(predefined); + if (isPredefined && commandArguments) args = commandArguments.slice(1); let repositories = []; // --- CONSOLIDATE REPOSITORIES --- diff --git a/test/crud.test.js b/test/crud.test.js new file mode 100644 index 0000000..4ddf28d --- /dev/null +++ b/test/crud.test.js @@ -0,0 +1,158 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const { spawn } = require('node:child_process'); +const test = require('node:test'); +const cli = path.resolve(__dirname, '../src/coc.js'); +const organization_id = '5ff747727005da1c272740ab'; + +async function fixture(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'coc-crud-')); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const directory = path.join(root, 'CoCreateDB'); + await fs.mkdir(directory); + await fs.writeFile(path.join(root, 'CoCreate.config.js'), `module.exports = ${JSON.stringify({ organization_id, repositories: [], db: { directory } })}`); + return { root, directory }; +} + +async function invoke(root, args, input, extraEnv = {}) { + const env = { ...process.env, ...extraEnv }; + // The command must use the explicit test storage, never a user's active data. + if (!Object.hasOwn(extraEnv, 'COCREATE_DB_DIRECTORY')) delete env.COCREATE_DB_DIRECTORY; + const child = spawn(process.execPath, [cli, 'crud', ...args], { cwd: root, env, stdio: ['pipe', 'pipe', 'pipe'] }); + let stdout = '', stderr = ''; + child.stdout.on('data', data => stdout += data); + child.stderr.on('data', data => stderr += data); + child.stdin.end(input === undefined ? '' : typeof input === 'string' ? input : JSON.stringify(input)); + const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); }); + const clean = stdout.replace(/\x1b\[[0-9;]*m/g, ''); + const start = clean.indexOf('{'); + return { code, stdout, stderr, data: start === -1 ? undefined : JSON.parse(clean.slice(start)) }; +} +const payload = (method, extra = {}) => ({ method, organization_id, database: 'dev', array: 'records', ...extra }); + +test('actual CLI uses CRUD server for create, indexed read, update, and delete with no API key', async t => { + const { root, directory } = await fixture(t); + const options = []; + const id = '6c0000000000000000000002'; + const created = await invoke(root, options, payload('object.create', { object: { _id: id, score: 1, name: "User's record" } })); + assert.equal(created.code, 0, created.stderr); + assert.equal(created.data.success, true); + assert.equal(created.data.storage, 'production', 'The result must pass through CRUD dispatch'); + const updated = await invoke(root, options, payload('object.update', { object: { _id: id, $inc: { score: 2 } } })); + assert.equal(updated.code, 0, updated.stderr); + const read = await invoke(root, options, payload('object.read', { apikey: 'deliberately-invalid-key', filter: { query: { score: 3 } } })); + assert.equal(read.code, 0, read.stderr); + assert.equal(read.data.object[0].score, 3); + assert.equal(read.data.object[0].name, "User's record"); + assert.equal(read.data.apikey, '[redacted]'); + assert.equal(read.stdout.includes('deliberately-invalid-key'), false); + const deleted = await invoke(root, options, payload('object.delete', { object: { _id: id } })); + assert.equal(deleted.code, 0, deleted.stderr); + const empty = await invoke(root, options, payload('object.read')); + assert.equal(empty.data.object.length, 0); +}); + +test('file and inline JSON inputs preserve paths, apostrophes, and credential redaction', async t => { + const { root, directory } = await fixture(t); + const request = payload('object.create', { array: 'keys', object: { key: 'test-secret-value', admin: true, name: "Key's name" } }); + const file = path.join(root, 'request with spaces.json'); + await fs.writeFile(file, JSON.stringify(request)); + const created = await invoke(root, [file]); + assert.equal(created.code, 0, created.stderr); + assert.equal(created.stdout.includes('test-secret-value'), false); + assert.equal(created.data.object[0].key, '[redacted]'); + const read = await invoke(root, [JSON.stringify(payload('object.read', { array: 'keys' }))]); + assert.equal(read.code, 0, read.stderr); + assert.equal(read.data.object[0].name, "Key's name"); +}); + +for (const [name, input, args, expected] of [ + ['malformed JSON', '{"key":"secret-that-must-not-be-echoed",', [], /valid JSON/], + ['non-object envelope', [], [], /JSON object/], + ['non-CRUD method', { method: 'workflow.example' }, [], /supported CRUD method/], + ['driver failure', payload('object.read', { database: ['dev', 'other'] }), [], undefined] +]) { + test(`failure returns nonzero: ${name}`, async t => { + const { root } = await fixture(t); + const result = await invoke(root, args, input); + assert.equal(result.code, 1); + if (expected) assert.match(result.stderr, expected); + else assert.equal(result.data.success, false); + assert.equal(result.stdout.includes('secret-that-must-not-be-echoed'), false); + assert.equal(result.stderr.includes('secret-that-must-not-be-echoed'), false); + }); +} + +test('environment directory and help work without Socket credentials', async t => { + const { root, directory } = await fixture(t); + const read = await invoke(root, [], payload('object.read'), { COCREATE_DB_DIRECTORY: directory }); + assert.equal(read.code, 0, read.stderr); + const help = await invoke(root, ['--help']); + assert.equal(help.code, 0); + assert.match(help.stdout, /Usage: coc crud/); +}); + + +test('configured DB directory resolves relative to the process directory and config stays unchanged', async t => { + const { root } = await fixture(t); + const config = `module.exports = ${JSON.stringify({ organization_id, repositories: [], db: { directory: 'local-db' } })}`; + await fs.writeFile(path.join(root, 'CoCreate.config.js'), config); + const created = await invoke(root, [], payload('object.create', { object: { name: 'local' } })); + assert.equal(created.code, 0, created.stderr); + const read = await invoke(root, [], payload('object.read')); + await fs.access(path.join(root, 'local-db')); + assert.equal(read.data.object[0].name, 'local'); + assert.equal(await fs.readFile(path.join(root, 'CoCreate.config.js'), 'utf8'), config); +}); + + +test('an inline envelope defaults to the nested process working directory', async t => { + const { root } = await fixture(t); + const nested = path.join(root, 'project', 'src'); + await fs.writeFile(path.join(root, 'CoCreate.config.js'), `module.exports = ${JSON.stringify({ organization_id, repositories: [] })}`); + await fs.mkdir(nested, { recursive: true }); + const request = payload('object.create', { object: { name: 'shared workspace' } }); + const created = await invoke(nested, [JSON.stringify(request)]); + assert.equal(created.code, 0, created.stderr); + const read = await invoke(nested, [], payload('object.read')); + assert.equal(read.code, 0, read.stderr); + assert.equal(read.data.object[0].name, 'shared workspace'); +}); + +test('the project supplies organization identity for an ordinary CRUD envelope', async t => { + const { root } = await fixture(t); + const result = await invoke(root, [JSON.stringify({ method: 'object.read', database: 'dev', array: 'records' })]); + assert.equal(result.code, 0, result.stderr); + assert.equal(result.data.organization_id, organization_id); + assert.equal(result.data.success, true); +}); + +test('standalone DB defaults to the process working directory', async t => { + const { root, directory } = await fixture(t); + await fs.rename(directory, path.join(root, 'unused')); + await fs.writeFile(path.join(root, 'CoCreate.config.js'), `module.exports = ${JSON.stringify({ organization_id, repositories: [] })}`); + const result = await invoke(root, [], payload('object.create', { object: { name: 'standalone' } })); + assert.equal(result.code, 0, result.stderr); + await fs.access(path.join(root, organization_id)); +}); + +test('an empty hierarchy bootstraps a key through CRUD with production/app defaults and no Socket credentials', async t => { + const { root, directory } = await fixture(t); + const id = '6c0000000000000000000008'; + const key = 'temporary-bootstrap-fixture'; + const created = await invoke(root, [], { method: 'object.create', array: 'keys', object: { _id: id, key, admin: true, status: 'active' } }); + assert.equal(created.code, 0, created.stderr); + assert.equal(created.data.storage, 'production'); + assert.equal(created.data.database, 'app'); + assert.equal(created.data.organization_id, organization_id); + assert.equal(created.data.object[0].admin, true); + assert.equal(created.stdout.includes(key), false); + const read = await invoke(root, [], { method: 'object.read', array: 'keys', filter: { query: { key } } }); + assert.equal(read.code, 0, read.stderr); + assert.equal(read.data.object[0]._id, id); + const files = await fs.readdir(path.join(directory, organization_id, 'storages'), { recursive: true }); + assert.ok(files.some(file => file.endsWith(`objects/${id}.json`))); + assert.equal(files.includes('production'), false, 'Storage names resolve to ID directories'); +});