diff --git a/composer.json b/composer.json index 3d8f3b4bf1..0e45b48ffe 100644 --- a/composer.json +++ b/composer.json @@ -108,7 +108,7 @@ ], "require-dev": { "ext-fileinfo": "*", - "appwrite/sdk-generator": "*", + "appwrite/sdk-generator": "^2.0", "brianium/paratest": "7.*", "phpunit/phpunit": "12.*", "swoole/ide-helper": "6.*", diff --git a/composer.lock b/composer.lock index 80ff9265c9..5fb89d8d4c 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1cc46b6b8e657c29ee41fd975a2033f8", + "content-hash": "9f9908fb48b239cd403e78fb9e1cdbb8", "packages": [ { "name": "adhocore/jwt", @@ -5398,16 +5398,16 @@ "packages-dev": [ { "name": "appwrite/sdk-generator", - "version": "1.32.0", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/appwrite/sdk-generator.git", - "reference": "7ec48fd30746e9fbc3a9bd7d3af8052acf400ff8" + "reference": "60a2e804c1464494d763e5ff6bfff9b188502253" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/appwrite/sdk-generator/zipball/7ec48fd30746e9fbc3a9bd7d3af8052acf400ff8", - "reference": "7ec48fd30746e9fbc3a9bd7d3af8052acf400ff8", + "url": "https://api.github.com/repos/appwrite/sdk-generator/zipball/60a2e804c1464494d763e5ff6bfff9b188502253", + "reference": "60a2e804c1464494d763e5ff6bfff9b188502253", "shasum": "" }, "require": { @@ -5415,19 +5415,20 @@ "ext-json": "*", "ext-mbstring": "*", "matthiasmullie/minify": "1.3.*", - "php": ">=8.3", + "php": ">=8.5", "twig/twig": "3.27.*" }, "require-dev": { "brianium/paratest": "7.*", "phpunit/phpunit": "11.*", + "rector/rector": "^2.4", "squizlabs/php_codesniffer": "3.*" }, "type": "library", "autoload": { "psr-4": { - "Appwrite\\SDK\\": "src/SDK", - "Appwrite\\Spec\\": "src/Spec" + "Appwrite\\SDK\\": "src/SDK/", + "Appwrite\\Spec\\": "src/Spec/" } }, "notification-url": "https://packagist.org/downloads/", @@ -5440,12 +5441,12 @@ "email": "eldad@appwrite.io" } ], - "description": "Appwrite PHP library for generating API SDKs for multiple programming languages and platforms", + "description": "SDK generator for Appwrite APIs across multiple programming languages and platforms", "support": { "issues": "https://github.com/appwrite/sdk-generator/issues", - "source": "https://github.com/appwrite/sdk-generator/tree/1.32.0" + "source": "https://github.com/appwrite/sdk-generator/tree/2.0.0" }, - "time": "2026-06-03T08:49:57+00:00" + "time": "2026-06-11T05:54:24+00:00" }, { "name": "brianium/paratest", diff --git a/src/Appwrite/Platform/Tasks/SDKs.php b/src/Appwrite/Platform/Tasks/SDKs.php index 69e1828a66..b3802b8eac 100644 --- a/src/Appwrite/Platform/Tasks/SDKs.php +++ b/src/Appwrite/Platform/Tasks/SDKs.php @@ -27,8 +27,8 @@ use Appwrite\SDK\Language\Swift; use Appwrite\SDK\Language\Unity; use Appwrite\SDK\Language\Web; use Appwrite\SDK\SDK; +use Appwrite\Spec\OpenAPI3; use Appwrite\Spec\StaticSpec; -use Appwrite\Spec\Swagger2; use CzProject\GitPhp\Git; use Utopia\Agents\Adapters\OpenAI; use Utopia\Agents\DiffCheck\DiffCheck; @@ -302,14 +302,14 @@ class SDKs extends Action } Console::info("━━━ {$language['name']} SDK ({$platform['name']}, {$version}) ━━━"); - $specFormat = $language['spec'] ?? 'swagger2'; + $specFormat = $language['spec'] ?? 'openapi3'; $spec = null; if ($specFormat === 'static') { Console::log(' Using static SDK spec...'); } else { Console::log(' Fetching API spec...'); - $specPath = __DIR__ . '/../../../../app/config/specs/swagger2-' . $version . '-' . $language['family'] . '.json'; + $specPath = __DIR__ . '/../../../../app/config/specs/open-api3-' . $version . '-' . $language['family'] . '.json'; if (!file_exists($specPath)) { throw new \Exception('Spec file not found: ' . $specPath . '. Please run "docker compose exec appwrite specs --version=' . $version . '" first to generate the specs.'); @@ -483,7 +483,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND licenseName: 'BSD-3-Clause', licenseURL: 'https://raw.githubusercontent.com/appwrite/appwrite/master/LICENSE', ) - : new Swagger2($spec) + : new OpenAPI3($spec) ); $sdk diff --git a/src/Appwrite/Platform/Tasks/Specs.php b/src/Appwrite/Platform/Tasks/Specs.php index 4db9e99e58..bd2a03ecf0 100644 --- a/src/Appwrite/Platform/Tasks/Specs.php +++ b/src/Appwrite/Platform/Tasks/Specs.php @@ -6,7 +6,6 @@ use Appwrite\Network\Validator\Redirect; use Appwrite\SDK\AuthType; use Appwrite\SDK\Method; use Appwrite\SDK\Specification\Format\OpenAPI3; -use Appwrite\SDK\Specification\Format\Swagger2; use Appwrite\SDK\Specification\Specification; use Appwrite\Utopia\Request as AppwriteRequest; use Appwrite\Utopia\Response as AppwriteResponse; @@ -62,7 +61,6 @@ class Specs extends Action protected function getFormatInstance(string $format, array $arguments) { return match ($format) { - 'swagger2' => new Swagger2(...$arguments), 'open-api3' => new OpenAPI3(...$arguments), default => throw new Exception('Format not found: ' . $format) }; @@ -660,7 +658,7 @@ class Specs extends Action $platform ]; - foreach (['swagger2', 'open-api3'] as $format) { + foreach (['open-api3'] as $format) { $formatInstance = $this->getFormatInstance($format, $arguments); $specs = new Specification($formatInstance); diff --git a/src/Appwrite/SDK/Specification/Format/Swagger2.php b/src/Appwrite/SDK/Specification/Format/Swagger2.php deleted file mode 100644 index 8b5bac9d5b..0000000000 --- a/src/Appwrite/SDK/Specification/Format/Swagger2.php +++ /dev/null @@ -1,1050 +0,0 @@ - '2.0', - 'info' => [ - 'version' => $this->getParam('version'), - 'title' => $this->getParam('name'), - 'description' => $this->getParam('description'), - 'termsOfService' => $this->getParam('terms'), - 'contact' => [ - 'name' => $this->getParam('contact.name'), - 'url' => $this->getParam('contact.url'), - 'email' => $this->getParam('contact.email'), - ], - 'license' => [ - 'name' => 'BSD-3-Clause', - 'url' => 'https://raw.githubusercontent.com/appwrite/appwrite/master/LICENSE', - ], - ], - 'host' => \parse_url($this->getParam('endpoint', ''), PHP_URL_HOST), - 'x-host-docs' => \parse_url($this->getParam('endpoint.docs', ''), PHP_URL_HOST), - 'basePath' => \parse_url($this->getParam('endpoint', ''), PHP_URL_PATH), - 'schemes' => [\parse_url($this->getParam('endpoint', ''), PHP_URL_SCHEME)], - 'consumes' => ['application/json', 'multipart/form-data'], - 'produces' => ['application/json'], - 'securityDefinitions' => $this->keys, - 'paths' => [], - 'tags' => $this->services, - 'definitions' => [], - 'externalDocs' => [ - 'description' => $this->getParam('docs.description'), - 'url' => $this->getParam('docs.url'), - ], - ]; - - foreach ([ - 'Project' => '', - 'ProjectPath' => '', - 'Key' => '', - 'JWT' => '', - 'Locale' => 'en', - 'Mode' => '', - ] as $key => $demo) { - if (isset($output['securityDefinitions'][$key])) { - $output['securityDefinitions'][$key]['x-appwrite'] = \array_merge( - $output['securityDefinitions'][$key]['x-appwrite'] ?? [], - ['demo' => $demo] - ); - } - } - - $usedModels = []; - - foreach ($this->routes as $route) { - /** @var Route $route */ - $url = \str_replace('/v1', '', $route->getPath()); - - $scope = $route->getLabel('scope', ''); - - $sdk = $route->getLabel('sdk', false); - - if ($sdk === false) { - continue; - } - - $additionalMethods = null; - if (\is_array($sdk)) { - $additionalMethods = $sdk; - $sdkValues = \array_values($sdk); - /** @var Method $sdk */ - $sdk = $sdkValues[0]; - } - - $consumes = []; - if (strtoupper($route->getMethod()) !== 'GET' && strtoupper($route->getMethod()) !== 'HEAD') { - $consumes = [$sdk->getRequestType()->value]; - } - - $methodName = $sdk->getMethodName(); - - $desc = $sdk->getDescriptionFilePath() ?: $sdk->getDescription(); - $produces = ($sdk->getContentType())->value; - $routeSecurity = $sdk->getAuth(); - - $specs = new Specs(); - $sdkPlatforms = $specs->getSDKPlatformsForRouteSecurity($routeSecurity); - - $sdkPlatforms = array_values(array_unique($sdkPlatforms)); - $namespace = $sdk->getNamespace(); - - $descContents = $this->getDescriptionContents($desc); - - $temp = [ - 'summary' => $route->getDesc(), - 'operationId' => $namespace . ucfirst($methodName), - 'consumes' => [], - 'produces' => [], - 'tags' => [$namespace], - 'description' => $descContents, - 'responses' => [], - 'deprecated' => $sdk->isDeprecated(), - 'x-appwrite' => [ // Appwrite related metadata - 'method' => $methodName, - 'group' => $sdk->getGroup(), - 'cookies' => $route->getLabel('sdk.cookies', false), - 'type' => $sdk->getType()->value ?? '', - 'demo' => \strtolower($namespace) . '/' . Template::fromCamelCaseToDash($methodName) . '.md', - 'rate-limit' => $route->getLabel('abuse-limit', 0), - 'rate-time' => $route->getLabel('abuse-time', 3600), - 'rate-key' => $route->getLabel('abuse-key', 'url:{url},ip:{ip}'), - 'scope' => $route->getLabel('scope', ''), - 'platforms' => $sdkPlatforms, - 'packaging' => $sdk->isPackaging(), - 'public' => $sdk->isPublic(), - ], - ]; - - if ($sdk->getDescriptionFilePath() !== null) { - $temp['x-appwrite']['edit'] = 'https://github.com/appwrite/appwrite/edit/master' . $sdk->getDescription(); - } - - if ($sdk->getDeprecated()) { - $temp['x-appwrite']['deprecated'] = [ - 'since' => $sdk->getDeprecated()->getSince(), - 'replaceWith' => $sdk->getDeprecated()->getReplaceWith(), - ]; - } - - if ($produces) { - $temp['produces'][] = $produces; - } - - if (\is_array($additionalMethods) && \count($additionalMethods) > 0) { - $temp['x-appwrite']['methods'] = []; - foreach ($additionalMethods as $methodObj) { - /** @var Method $methodObj */ - $desc = $methodObj->getDescriptionFilePath(); - - $methodSecurities = $methodObj->getAuth(); - $methodSdkPlatforms = $specs->getSDKPlatformsForRouteSecurity($methodSecurities); - - if (!\in_array($this->platform, $methodSdkPlatforms)) { - continue; - } - - $methodSecurities = [($methodObj->getLocationAuth()[0] ?? 'Project') => []]; - foreach ($methodObj->getAuth() as $security) { - /** @var AuthType $security */ - if (\array_key_exists($security->value, $this->keys)) { - $methodSecurities[$security->value] = []; - } - } - - $additionalMethod = [ - 'name' => $methodObj->getMethodName(), - 'namespace' => $methodObj->getNamespace(), - 'desc' => $methodObj->getDesc(), - 'auth' => \array_slice($methodSecurities, 0, $this->authCount), - 'parameters' => [], - 'required' => [], - 'responses' => [], - 'description' => $this->getDescriptionContents($desc), - 'demo' => \strtolower($namespace) . '/' . Template::fromCamelCaseToDash($methodObj->getMethodName()) . '.md', - 'public' => $methodObj->isPublic(), - ]; - - // add deprecation only if method has it! - if ($methodObj->getDeprecated()) { - $additionalMethod['deprecated'] = [ - 'since' => $methodObj->getDeprecated()->getSince(), - 'replaceWith' => $methodObj->getDeprecated()->getReplaceWith(), - ]; - } - - // If additional method has no parameters, inherit from route - if (empty($methodObj->getParameters())) { - foreach ($route->getParams() as $name => $param) { - $additionalMethod['parameters'][] = $name; - if (!$param['optional']) { - $additionalMethod['required'][] = $name; - } - } - } else { - // Use method's own parameters - foreach ($methodObj->getParameters() as $parameter) { - $additionalMethod['parameters'][] = $parameter->getName(); - if (!$parameter->getOptional()) { - $additionalMethod['required'][] = $parameter->getName(); - } - } - } - - foreach ($methodObj->getResponses() as $response) { - /** @var Response|array $response */ - $responseModel = $response->getModel(); - if (\is_array($responseModel)) { - foreach ($responseModel as $modelName) { - foreach ($this->models as $value) { - if ($value->getType() === $modelName) { - $usedModels[] = $modelName; - break; - } - } - } - $additionalMethod['responses'][] = [ - 'code' => $response->getCode(), - 'model' => \array_map(fn ($m) => '#/definitions/' . $m, $responseModel) - ]; - } else { - $responseData = [ - 'code' => $response->getCode(), - ]; - - // lets not assume stuff here! - if ($response->getCode() !== 204) { - $responseData['model'] = '#/definitions/' . $responseModel; - foreach ($this->models as $value) { - if ($value->getType() === $responseModel) { - $usedModels[] = $responseModel; - break; - } - } - } - - $additionalMethod['responses'][] = $responseData; - } - } - - $temp['x-appwrite']['methods'][] = $additionalMethod; - } - } - - // Handle Responses - foreach ($sdk->getResponses() as $response) { - /** @var Response $response */ - $model = $response->getModel(); - - foreach ($this->models as $value) { - if (\is_array($model)) { - $model = \array_map(fn ($m) => $m === $value->getType() ? $value : $m, $model); - } else { - if ($value->getType() === $model) { - $model = $value; - break; - } - } - } - - if (\is_string($model)) { - throw new \RuntimeException("Unresolved response model '{$model}' for method '{$sdk->getNamespace()}.{$sdk->getMethodName()}'. Ensure the model is registered."); - } - - if (\is_array($model)) { - foreach ($model as $m) { - if (\is_string($m)) { - throw new \RuntimeException("Unresolved response model '{$m}' for method '{$sdk->getNamespace()}.{$sdk->getMethodName()}'. Ensure the model is registered."); - } - } - } - - if (!(\is_array($model)) && $model->isNone()) { - if ($produces === ContentType::TEXT->value && !\in_array($response->getCode(), [204, 301, 302, 308], true)) { - $temp['responses'][(string)$response->getCode()] = [ - 'description' => 'Text', - 'schema' => [ - 'type' => 'string', - ], - ]; - - continue; - } - - $temp['responses'][(string)$response->getCode()] = [ - 'description' => in_array($produces, [ - 'image/*', - 'image/jpeg', - 'image/gif', - 'image/png', - 'image/webp', - 'image/svg-x', - 'image/x-icon', - 'image/bmp', - ]) ? 'Image' : 'File', - 'schema' => [ - 'type' => 'file' - ], - ]; - } else { - if (\is_array($model)) { - $modelDescription = \join(', or ', \array_map(fn ($m) => $m->getName(), $model)); - // model has multiple possible responses, we will use oneOf - foreach ($model as $m) { - $usedModels[] = $m->getType(); - } - $temp['responses'][(string)$response->getCode()] = [ - 'description' => $modelDescription, - 'schema' => \array_filter([ - 'x-oneOf' => \array_map(function ($m) { - return ['$ref' => '#/definitions/' . $m->getType()]; - }, $model), - 'x-discriminator' => $this->getDiscriminator($model, '#/definitions/'), - ]), - ]; - } else { - // Response definition using one type - $usedModels[] = $model->getType(); - $temp['responses'][(string)$response->getCode()] = [ - 'description' => $model->getName(), - 'schema' => [ - '$ref' => '#/definitions/' . $model->getType(), - ], - ]; - } - } - - if (in_array($response->getCode(), [204, 301, 302, 308], true)) { - $temp['responses'][(string)$response->getCode()]['description'] = 'No content'; - unset($temp['responses'][(string)$response->getCode()]['schema']); - } - } - - if (!empty($scope)) { - $securities = [($sdk->getLocationAuth()[0] ?? 'Project') => []]; - - foreach ($sdk->getAuth() as $security) { - if (\array_key_exists($security->value, $this->keys)) { - $securities[$security->value] = []; - } - } - - $temp['x-appwrite']['auth'] = \array_slice($securities, 0, $this->authCount); - - if ($sdk->getType() === MethodType::LOCATION) { - foreach ($sdk->getLocationAuth() as $key) { - if (\array_key_exists($key, $this->keys)) { - $securities[$key] = []; - $temp['x-appwrite']['auth'][$key] = []; - } - } - } - - $temp['security'][] = $securities; - } - - $body = [ - 'name' => 'payload', - 'in' => 'body', - 'schema' => [ - 'type' => 'object', - 'properties' => [], - ], - ]; - - $bodyRequired = []; - - $parameters = \array_merge( - $route->getParams(), - $sdk->getAdditionalParameters() ?? [], - ); - - foreach ($parameters as $name => $param) { // Set params - if (($param['deprecated'] ?? false) === true) { - continue; - } - - /** @var Validator $validator */ - $validator = $this->getValidator($param); - - $isNullable = $validator instanceof Nullable; - - $parameter = $this->getRequestParameterConfig( - $param['optional'], - $isNullable, - $param['default'], - $sdk->getNamespace() . '.' . $sdk->getMethodName(), - $name, - ); - - $node = [ - 'name' => $name, - 'description' => $param['description'], - 'required' => $parameter['required'], - ]; - - if ($isNullable) { - /** @var Nullable $validator */ - $validator = $validator->getValidator(); - } - - $class = \get_class($validator); - - $base = \get_parent_class($class); - - switch ($base) { - case \Appwrite\Utopia\Database\Validator\Queries\Base::class: - $class = $base; - break; - } - - if ($class === \Utopia\Validator\AnyOf::class) { - $validator = $param['validator']->getValidators()[0]; - $class = \get_class($validator); - } - - $array = false; - if ($class === \Utopia\Validator\ArrayList::class) { - $array = true; - $subclass = \get_class($validator->getValidator()); - switch ($subclass) { - case \Appwrite\Utopia\Database\Validator\Operation::class: - case \Utopia\Validator\WhiteList::class: - $class = $subclass; - break; - } - } - - switch ($class) { - case \Utopia\Validator\Text::class: - case \Utopia\Database\Validator\UID::class: - $node['type'] = $validator->getType(); - $node['x-example'] = ($param['example'] ?? '') ?: '<' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . '>'; - break; - case \Utopia\Validator\Boolean::class: - $node['type'] = $validator->getType(); - $node['x-example'] = ($param['example'] ?? '') ?: false; - break; - case \Appwrite\Utopia\Database\Validator\CustomId::class: - if ($sdk->getType() === MethodType::UPLOAD) { - $node['x-upload-id'] = true; - } - $node['type'] = $validator->getType(); - $node['x-appwrite'] = [ - 'idGenerator' => 'ID.unique', - ]; - $node['x-example'] = ($param['example'] ?? '') ?: '<' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . '>'; - break; - case \Utopia\Database\Validator\Datetime::class: - $node['type'] = $validator->getType(); - $node['format'] = 'datetime'; - $node['x-example'] = ($param['example'] ?? '') ?: Model::TYPE_DATETIME_EXAMPLE; - break; - case \Utopia\Database\Validator\Spatial::class: - /** @var Spatial $validator */ - $node['type'] = 'array'; - $node['items'] = match ($validator->getSpatialType()) { - Database::VAR_POINT => [ - 'type' => 'number', - 'format' => 'double', - ], - Database::VAR_LINESTRING => [ - 'type' => 'array', - 'items' => [ - 'type' => 'number', - 'format' => 'double', - ], - ], - Database::VAR_POLYGON => [ - 'type' => 'array', - 'items' => [ - 'type' => 'array', - 'items' => [ - 'type' => 'number', - 'format' => 'double', - ], - ], - ], - default => [ - 'type' => 'array', - 'items' => [ - 'type' => 'number', - 'format' => 'double', - ], - ], - }; - $node['x-example'] = ($param['example'] ?? '') ?: match ($validator->getSpatialType()) { - Database::VAR_POINT => '[1, 2]', - Database::VAR_LINESTRING => '[[1, 2], [3, 4], [5, 6]]', - Database::VAR_POLYGON => '[[[1, 2], [3, 4], [5, 6], [1, 2]]]', - default => '', - }; - break; - case \Utopia\Emails\Validator\Email::class: - $node['type'] = $validator->getType(); - $node['format'] = 'email'; - $node['x-example'] = ($param['example'] ?? '') ?: 'email@example.com'; - break; - case \Utopia\Validator\Host::class: - case \Utopia\Validator\URL::class: - case \Appwrite\Network\Validator\Redirect::class: - $node['type'] = $validator->getType(); - $node['format'] = 'url'; - $node['x-example'] = ($param['example'] ?? '') ?: 'https://example.com'; - break; - case \Utopia\Validator\ArrayList::class: - /** @var ArrayList $validator */ - $node['type'] = 'array'; - $node['collectionFormat'] = 'multi'; - $node['items'] = [ - 'type' => $validator->getValidator()->getType(), - ]; - if (!empty($param['example'])) { - $node['x-example'] = $param['example']; - } - break; - case \Utopia\Validator\JSON::class: - case \Utopia\Validator\Assoc::class: - $node['type'] = 'object'; - $node['default'] = (empty($param['default'])) ? new \stdClass() : $param['default']; - $node['x-example'] = ($param['example'] ?? '') ?: '{}'; - break; - case \Utopia\Storage\Validator\File::class: - $consumes = ['multipart/form-data']; - $node['type'] = 'file'; - break; - case \Appwrite\Functions\Validator\Payload::class: - $consumes = ['multipart/form-data']; - $node['type'] = 'payload'; - break; - case \Appwrite\Utopia\Database\Validator\Queries\Base::class: - case \Utopia\Database\Validator\Queries::class: - case \Utopia\Database\Validator\Queries\Document::class: - case \Utopia\Database\Validator\Queries\Documents::class: - case \Appwrite\Utopia\Database\Validator\Queries\Branches::class: - case \Appwrite\Utopia\Database\Validator\Queries\Columns::class: - case \Appwrite\Utopia\Database\Validator\Queries\Tables::class: - $node['type'] = 'array'; - $node['collectionFormat'] = 'multi'; - $node['items'] = [ - 'type' => 'string', - ]; - break; - case \Utopia\Database\Validator\Permissions::class: - $node['type'] = $validator->getType(); - $node['collectionFormat'] = 'multi'; - $node['items'] = [ - 'type' => 'string', - ]; - $node['x-example'] = ($param['example'] ?? '') ?: '["' . Permission::read(Role::any()) . '"]'; - break; - case \Utopia\Database\Validator\Roles::class: - $node['type'] = $validator->getType(); - $node['collectionFormat'] = 'multi'; - $node['items'] = [ - 'type' => 'string', - ]; - $node['x-example'] = ($param['example'] ?? '') ?: '["' . Role::any()->toString() . '"]'; - break; - case \Appwrite\Auth\Validator\Password::class: - case \Appwrite\SDK\Specification\Validator\PasswordFormat::class: - $node['type'] = $validator->getType(); - $node['format'] = 'password'; - $node['x-example'] = ($param['example'] ?? '') ?: 'password'; - break; - case \Appwrite\Auth\Validator\Phone::class: - $node['type'] = $validator->getType(); - $node['format'] = 'phone'; - $node['x-example'] = ($param['example'] ?? '') ?: '+12065550100'; - break; - case \Utopia\Validator\Range::class: - /** @var Range $validator */ - $node['type'] = $validator->getType() === Validator::TYPE_FLOAT ? 'number' : $validator->getType(); - $node['format'] = $validator->getType() == Validator::TYPE_INTEGER ? 'int32' : 'float'; - $node['x-example'] = ($param['example'] ?? '') ?: $validator->getMin(); - break; - case \Utopia\Validator\Integer::class: - $node['type'] = $validator->getType(); - $node['format'] = $validator->getFormat(); - if (!empty($param['example'])) { - $node['x-example'] = $param['example']; - } - break; - case \Utopia\Validator\Numeric::class: - case \Utopia\Validator\FloatValidator::class: - $node['type'] = 'number'; - $node['format'] = 'float'; - if (!empty($param['example'])) { - $node['x-example'] = $param['example']; - } - break; - case \Utopia\Validator\WhiteList::class: - if ($array) { - $validator = $validator->getValidator(); - - $node['type'] = 'array'; - $node['collectionFormat'] = 'multi'; - $node['items'] = [ - 'type' => $validator->getType(), - ]; - if (!empty($param['example'])) { - $node['x-example'] = $param['example']; - } - - if ($validator->getType() === 'string') { - $enum = $param['enum'] ?? null; - - if ($enum instanceof Enum) { - $enumValues = \array_values($validator->getList()); - - if (!empty($enum->exclude)) { - $keepIndices = []; - foreach ($enumValues as $index => $value) { - if (!\in_array($value, $enum->exclude, true)) { - $keepIndices[] = $index; - } - } - - $enumValues = \array_values(\array_intersect_key($enumValues, \array_flip($keepIndices))); - $node['description'] = $this->parseDescription($node['description'], $enum->exclude); - } - - $enumKeys = []; - foreach ($enumValues as $enumValue) { - $enumKeys[] = $enum->map[$enumValue] ?? $enumValue; - } - - $node['items']['enum'] = $enumValues; - if (!empty($enum->name)) { - $node['items']['x-enum-name'] = $enum->name; - } - $node['items']['x-enum-keys'] = $enumKeys; - } - } - if ($validator->getType() === 'integer') { - $node['items']['format'] = $validator->getFormat(); - } - } else { - $node['type'] = $validator->getType(); - $node['x-example'] = ($param['example'] ?? '') ?: $validator->getList()[0]; - - if ($validator->getType() === 'string') { - $enum = $param['enum'] ?? null; - - if ($enum instanceof Enum) { - $enumValues = \array_values($validator->getList()); - - if (!empty($enum->exclude)) { - $keepIndices = []; - foreach ($enumValues as $index => $value) { - if (!\in_array($value, $enum->exclude, true)) { - $keepIndices[] = $index; - } - } - - $enumValues = \array_values(\array_intersect_key($enumValues, \array_flip($keepIndices))); - $node['description'] = $this->parseDescription($node['description'], $enum->exclude); - } - - $enumKeys = []; - foreach ($enumValues as $enumValue) { - $enumKeys[] = $enum->map[$enumValue] ?? $enumValue; - } - - $node['enum'] = $enumValues; - if (!empty($enum->name)) { - $node['x-enum-name'] = $enum->name; - } - $node['x-enum-keys'] = $enumKeys; - } - } - if ($validator->getType() === 'integer') { - $node['format'] = $validator->getFormat(); - } - } - break; - case \Appwrite\Utopia\Database\Validator\CompoundUID::class: - $node['type'] = $validator->getType(); - $node['x-example'] = ($param['example'] ?? '') ?: ''; - break; - case \Appwrite\Utopia\Database\Validator\Operation::class: - if ($array) { - $validator = $validator->getValidator(); - } - - /** @var Operation $validator */ - $collectionIdKey = $validator->getCollectionIdKey(); - $documentIdKey = $validator->getDocumentIdKey(); - if ($array) { - $node['type'] = 'array'; - $node['collectionFormat'] = 'multi'; - $node['items'] = ['type' => 'object']; - } else { - $node['type'] = 'object'; - } - if (empty($param['example'])) { - $example = [ - 'action' => 'create', - 'databaseId' => '', - $collectionIdKey => '<'.\strtoupper(Template::fromCamelCaseToSnake($collectionIdKey)).'>', - $documentIdKey => '<'.\strtoupper(Template::fromCamelCaseToSnake($documentIdKey)).'>', - 'data' => [ - 'name' => 'Walter O\'Brien', - ], - ]; - if ($array) { - $example = [$example]; - } - $node['x-example'] = \str_replace("\n", "\n\t", \json_encode($example, JSON_PRETTY_PRINT)); - } else { - $node['x-example'] = $param['example']; - } - break; - default: - $node['type'] = 'string'; - if (!empty($param['example'])) { - $node['x-example'] = $param['example']; - } - break; - } - - if ($parameter['emitDefault'] && $this->shouldEmitDefaultForSchema($param['default'], $node)) { // Param has default value - $node['default'] = $param['default']; - } - - $pathAliases = [$name, ...($param['aliases'] ?? [])]; - $pathAliasMap = \array_flip($pathAliases); - $isPathParam = false; - - foreach (\explode('/', $url) as $segment) { - if ($segment !== '' && $segment[0] === ':' && isset($pathAliasMap[\substr($segment, 1)])) { - $isPathParam = true; - break; - } - } - - if ($isPathParam) { // Param is in URL path (directly or through alias) - $node['in'] = 'path'; - $temp['parameters'][] = $node; - } elseif (\in_array($route->getMethod(), ['GET', 'DELETE'], true)) { // Param is in query - $node['in'] = 'query'; - $temp['parameters'][] = $node; - } else { // Param is in payload - if (\in_array('multipart/form-data', $consumes)) { - $node['in'] = 'formData'; - $temp['parameters'][] = $node; - - continue; - } - - if ($node['required']) { - $bodyRequired[] = $name; - } - - $body['schema']['properties'][$name] = [ - 'type' => $node['type'], - 'description' => $node['description'], - ]; - - if (\array_key_exists('default', $node)) { - $body['schema']['properties'][$name]['default'] = $node['default']; - } - - $body['schema']['properties'][$name]['x-example'] = $node['x-example'] ?? null; - - if (isset($node['format'])) { - $body['schema']['properties'][$name]['format'] = $node['format']; - } - - if (isset($node['enum'])) { - /// If the enum flag is Set, add the enum values to the body - $body['schema']['properties'][$name]['enum'] = $node['enum']; - $body['schema']['properties'][$name]['x-enum-name'] = $node['x-enum-name'] ?? null; - $body['schema']['properties'][$name]['x-enum-keys'] = $node['x-enum-keys']; - } - - if (isset($node['x-appwrite'])) { - $body['schema']['properties'][$name]['x-appwrite'] = $node['x-appwrite']; - } - - if ($parameter['nullable']) { - $body['schema']['properties'][$name]['x-nullable'] = true; - } - - if (\array_key_exists('items', $node)) { - $body['schema']['properties'][$name]['items'] = $node['items']; - } - } - - $segments = \explode('/', $url); - foreach ($segments as &$segment) { - if ($segment !== '' && $segment[0] === ':' && isset($pathAliasMap[\substr($segment, 1)])) { - $segment = '{' . $name . '}'; - } - } - unset($segment); - $url = \implode('/', $segments); - } - - if (!empty($bodyRequired)) { - $body['schema']['required'] = $bodyRequired; - } - - if (!empty($body['schema']['properties'])) { - $temp['parameters'][] = $body; - } - - $temp['consumes'] = $consumes; - - $output['paths'][$url][\strtolower($route->getMethod())] = $temp; - } - - foreach ($this->models as $model) { - $this->getNestedModels($model, $usedModels); - } - - foreach ($this->models as $model) { - if (!in_array($model->getType(), $usedModels)) { - continue; - } - - $required = $model->getRequired(); - $rules = $model->getRules(); - $examples = []; - - $output['definitions'][$model->getType()] = [ - 'description' => $model->getName(), - 'type' => 'object', - ]; - - if (!empty($rules)) { - $output['definitions'][$model->getType()]['properties'] = []; - } - - if ($model->isAny()) { - $output['definitions'][$model->getType()]['additionalProperties'] = true; - } - - if (!empty($required)) { - $output['definitions'][$model->getType()]['required'] = $required; - } - - foreach ($model->getRules() as $name => $rule) { - if (($rule['hidden'] ?? false) === true) { - continue; - } - - $type = ''; - $format = $rule['format'] ?? null; - $items = null; - - $examples[$name] = $rule['example'] ?? null; - - switch ($rule['type']) { - case 'string': - case 'datetime': - $type = 'string'; - break; - - case 'id': - $type = 'string'; - break; - - case 'enum': - $type = 'string'; - break; - - case 'json': - $type = 'object'; - break; - - case 'array': - $type = 'array'; - $items = $this->getArrayItemsSchema($rule['example'] ?? []); - break; - - case 'integer': - $type = 'integer'; - $format = $rule['format'] ?? 'int32'; - break; - - case 'float': - $type = 'number'; - $format = 'float'; - break; - - case 'double': - $type = 'number'; - $format = 'double'; - break; - - case 'boolean': - $type = 'boolean'; - break; - - case 'payload': - $type = 'payload'; - break; - - default: - $type = 'object'; - $rule['type'] = ($rule['type']) ?: 'none'; - - if (\is_array($rule['type'])) { - $resolvedModels = \array_map(function (string $type) { - foreach ($this->models as $model) { - if ($model->getType() === $type) { - return $model; - } - } - - throw new \RuntimeException("Unresolved model '{$type}'. Ensure the model is registered."); - }, $rule['type']); - $xDiscriminator = $this->getDiscriminator($resolvedModels, '#/definitions/'); - - if ($rule['array']) { - $items = \array_filter([ - 'x-anyOf' => \array_map(fn ($type) => ['$ref' => '#/definitions/' . $type], $rule['type']), - 'x-discriminator' => $xDiscriminator, - ]); - } else { - $items = \array_filter([ - 'x-oneOf' => \array_map(fn ($type) => ['$ref' => '#/definitions/' . $type], $rule['type']), - 'x-discriminator' => $xDiscriminator, - ]); - } - } else { - $items = [ - '$ref' => '#/definitions/' . $rule['type'], - ]; - } - break; - } - - $readOnly = $rule['readOnly'] ?? false; - if ($rule['type'] == 'json') { - $output['definitions'][$model->getType()]['properties'][$name] = [ - 'type' => $type, - 'additionalProperties' => true, - 'description' => $rule['description'] ?? '', - 'x-example' => $rule['example'] ?? null, - ]; - - if ($readOnly) { - $output['definitions'][$model->getType()]['properties'][$name]['readOnly'] = true; - } - continue; - } - - if ($rule['array']) { - $output['definitions'][$model->getType()]['properties'][$name] = [ - 'type' => 'array', - 'description' => $rule['description'] ?? '', - 'items' => [ - 'type' => $type, - ], - 'x-example' => $rule['example'] ?? null, - ]; - - if ($format) { - $output['definitions'][$model->getType()]['properties'][$name]['items']['format'] = $format; - } - if ($readOnly) { - $output['definitions'][$model->getType()]['properties'][$name]['readOnly'] = true; - } - } else { - $output['definitions'][$model->getType()]['properties'][$name] = [ - 'type' => $type, - 'description' => $rule['description'] ?? '', - 'x-example' => $rule['example'] ?? null, - ]; - - if ($format) { - $output['definitions'][$model->getType()]['properties'][$name]['format'] = $format; - } - if ($readOnly) { - $output['definitions'][$model->getType()]['properties'][$name]['readOnly'] = true; - } - } - if ($items) { - if ($rule['array'] || $rule['type'] === 'array') { - $output['definitions'][$model->getType()]['properties'][$name]['items'] = $items; - } else { - if (isset($items['$ref'])) { - $items = ['allOf' => [$items]]; - } - /** @var array $property */ - $property = $output['definitions'][$model->getType()]['properties'][$name]; - $output['definitions'][$model->getType()]['properties'][$name] = [ - ...$property, - ...$items, - ]; - } - } - if ($rule['type'] === 'enum' && !empty($rule['enum'])) { - if ($rule['array']) { - $output['definitions'][$model->getType()]['properties'][$name]['items']['enum'] = \array_values($rule['enum']); - if (!empty($rule['enumSDKName'])) { - $output['definitions'][$model->getType()]['properties'][$name]['items']['x-enum-name'] = $rule['enumSDKName']; - } - } else { - $output['definitions'][$model->getType()]['properties'][$name]['enum'] = \array_values($rule['enum']); - if (!empty($rule['enumSDKName'])) { - $output['definitions'][$model->getType()]['properties'][$name]['x-enum-name'] = $rule['enumSDKName']; - } - } - } - if (!in_array($name, $required)) { - $output['definitions'][$model->getType()]['properties'][$name]['x-nullable'] = true; - } - } - - /** @var Any $model */ - if ($model->isAny() && !empty($model->getSampleData())) { - $examples = array_merge($examples, $model->getSampleData()); - } - - $output['definitions'][$model->getType()]['example'] = $examples; - } - - \ksort($output['paths']); - - return $output; - } -} diff --git a/tests/unit/SDK/Specification/FormatTest.php b/tests/unit/SDK/Specification/FormatTest.php index c70674cec6..0b9a472be3 100644 --- a/tests/unit/SDK/Specification/FormatTest.php +++ b/tests/unit/SDK/Specification/FormatTest.php @@ -7,7 +7,6 @@ use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; use Appwrite\SDK\Specification\Format; use Appwrite\SDK\Specification\Format\OpenAPI3; -use Appwrite\SDK\Specification\Format\Swagger2; use Appwrite\SDK\Specification\Validator\PasswordFormat; use Appwrite\Utopia\Database\Validator\CustomId; use Appwrite\Utopia\Response; @@ -155,7 +154,6 @@ final class FormatTest extends TestCase ->param('transactionId', null, new Nullable(new Text(256)), 'Transaction ID.', true); $openApi = (new OpenAPI3(new Container(), [], [$route], [], [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], [], [], 0, 'console'))->parse(); $this->assertArrayNotHasKey('requestBody', $openApi['paths']['/tests/{testId}']['delete']); $this->assertCount(2, $openApi['paths']['/tests/{testId}']['delete']['parameters']); @@ -163,10 +161,6 @@ final class FormatTest extends TestCase $this->assertSame('transactionId', $openApi['paths']['/tests/{testId}']['delete']['parameters'][1]['name']); $this->assertSame('query', $openApi['paths']['/tests/{testId}']['delete']['parameters'][1]['in']); - $this->assertCount(2, $swagger['paths']['/tests/{testId}']['delete']['parameters']); - $this->assertSame('path', $swagger['paths']['/tests/{testId}']['delete']['parameters'][0]['in']); - $this->assertSame('transactionId', $swagger['paths']['/tests/{testId}']['delete']['parameters'][1]['name']); - $this->assertSame('query', $swagger['paths']['/tests/{testId}']['delete']['parameters'][1]['in']); } public function testModelReferencesDoNotEmitItemsOnObjectProperties(): void @@ -197,20 +191,14 @@ final class FormatTest extends TestCase ]; $openApi = (new OpenAPI3(new Container(), [], [$route], $models, [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], $models, [], 0, 'console'))->parse(); $openApiPrefs = $openApi['components']['schemas']['team']['properties']['prefs']; - $swaggerPrefs = $swagger['definitions']['team']['properties']['prefs']; $this->assertArrayNotHasKey('items', $openApiPrefs); $this->assertArrayNotHasKey('error', $openApi['components']['schemas']); $this->assertSame('object', $openApiPrefs['type']); $this->assertSame([['$ref' => '#/components/schemas/preferences']], $openApiPrefs['allOf']); - $this->assertArrayNotHasKey('items', $swaggerPrefs); - $this->assertArrayNotHasKey('error', $swagger['definitions']); - $this->assertSame('object', $swaggerPrefs['type']); - $this->assertSame([['$ref' => '#/definitions/preferences']], $swaggerPrefs['allOf']); } public function testArrayItemsSchemaInfersTypesFromJsonStringExamples(): void @@ -278,10 +266,8 @@ final class FormatTest extends TestCase ]; $openApi = (new OpenAPI3(new Container(), [], [$route], $models, [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], $models, [], 0, 'console'))->parse(); $openApiHashOptions = $openApi['components']['schemas']['user']['properties']['hashOptions']; - $swaggerHashOptions = $swagger['definitions']['user']['properties']['hashOptions']; $this->assertSame('object', $openApiHashOptions['type']); $this->assertArrayNotHasKey('items', $openApiHashOptions); @@ -290,10 +276,6 @@ final class FormatTest extends TestCase $this->assertCount(7, $openApiHashOptions['allOf'][0]['oneOf']); $this->assertSame(['$ref' => '#/components/schemas/algoArgon2'], $openApiHashOptions['allOf'][0]['oneOf'][0]); - $this->assertSame('object', $swaggerHashOptions['type']); - $this->assertArrayNotHasKey('items', $swaggerHashOptions); - $this->assertCount(7, $swaggerHashOptions['x-oneOf']); - $this->assertSame(['$ref' => '#/definitions/algoArgon2'], $swaggerHashOptions['x-oneOf'][0]); } public function testArraySchemasEmitItems(): void @@ -330,14 +312,11 @@ final class FormatTest extends TestCase )); $openApi = (new OpenAPI3(new Container(), [], [$requestRoute, $modelRoute], [new AttributeLine()], [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$requestRoute, $modelRoute], [new AttributeLine()], [], 0, 'console'))->parse(); $openApiRequestDefault = $openApi['paths']['/tests/spatial']['post']['requestBody']['content']['application/json']['schema']['properties']['default']; - $swaggerRequestDefault = $swagger['paths']['/tests/spatial']['post']['parameters'][0]['schema']['properties']['default']; $openApiModelDefault = $openApi['components']['schemas']['attributeLine']['properties']['default']; - $swaggerModelDefault = $swagger['definitions']['attributeLine']['properties']['default']; - foreach ([$openApiRequestDefault, $swaggerRequestDefault, $openApiModelDefault, $swaggerModelDefault] as $default) { + foreach ([$openApiRequestDefault, $openApiModelDefault] as $default) { $this->assertSame('array', $default['type']); $this->assertSame('array', $default['items']['type']); $this->assertSame('number', $default['items']['items']['type']); @@ -370,10 +349,8 @@ final class FormatTest extends TestCase ->param('name', '', new Text(256), 'Name.'); $openApi = (new OpenAPI3(new Container(), [], [$route], [new Webhook()], [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], [new Webhook()], [], 0, 'console'))->parse(); $openApiProperties = $openApi['paths']['/tests']['post']['requestBody']['content']['application/json']['schema']['properties']; - $swaggerProperties = $swagger['paths']['/tests']['post']['parameters'][0]['schema']['properties']; $this->assertSame('password', $openApiProperties['password']['format']); $this->assertSame('password', $openApiProperties['nullablePassword']['format']); @@ -381,11 +358,6 @@ final class FormatTest extends TestCase $this->assertArrayNotHasKey('format', $openApiProperties['name']); $this->assertSame('password', $openApi['components']['schemas']['webhook']['properties']['authPassword']['format']); - $this->assertSame('password', $swaggerProperties['password']['format']); - $this->assertSame('password', $swaggerProperties['nullablePassword']['format']); - $this->assertTrue($swaggerProperties['nullablePassword']['x-nullable']); - $this->assertArrayNotHasKey('format', $swaggerProperties['name']); - $this->assertSame('password', $swagger['definitions']['webhook']['properties']['authPassword']['format']); } public function testNoContentMethodsKeepProducesMetadata(): void @@ -412,13 +384,11 @@ final class FormatTest extends TestCase ->param('testId', '', new Text(256), 'Test ID.'); $openApi = (new OpenAPI3(new Container(), [], [$route], [new NoneModel()], [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], [new NoneModel()], [], 0, 'console'))->parse(); $openApiMethod = $openApi['paths']['/tests/{testId}']['delete']; $this->assertArrayNotHasKey('content', $openApiMethod['responses']['204']); $this->assertSame(['application/json'], $openApiMethod['x-appwrite']['produces']); - $this->assertSame(['application/json'], $swagger['paths']['/tests/{testId}']['delete']['produces']); } public function testBinaryResponsesEmitResponseContent(): void @@ -444,7 +414,6 @@ final class FormatTest extends TestCase )); $openApi = (new OpenAPI3(new Container(), [], [$route], [new NoneModel()], [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], [new NoneModel()], [], 0, 'console'))->parse(); $openApiMethod = $openApi['paths']['/tests/icon']['get']; @@ -453,7 +422,6 @@ final class FormatTest extends TestCase $openApiMethod['responses']['200']['content']['image/png']['schema'] ); $this->assertArrayNotHasKey('produces', $openApiMethod['x-appwrite']); - $this->assertSame(['image/png'], $swagger['paths']['/tests/icon']['get']['produces']); } public function testAdditionalParametersAreIncludedInRequestBody(): void @@ -481,13 +449,10 @@ final class FormatTest extends TestCase )); $openApi = (new OpenAPI3(new Container(), [], [$route], [], [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], [], [], 0, 'console'))->parse(); $openApiQuery = $openApi['paths']['/tests/graphql']['post']['requestBody']['content']['application/json']['schema']['properties']['query']; - $swaggerQuery = $swagger['paths']['/tests/graphql']['post']['parameters'][0]['schema']['properties']['query']; $this->assertSame('object', $openApiQuery['type']); - $this->assertEquals($swaggerQuery, $openApiQuery); } public function testJsonModelRulesKeepAdditionalPropertiesAndSkipNullable(): void @@ -517,13 +482,10 @@ final class FormatTest extends TestCase ]; $openApi = (new OpenAPI3(new Container(), [], [$route], $models, [], 0, 'console'))->parse(); - $swagger = (new Swagger2(new Container(), [], [$route], $models, [], 0, 'console'))->parse(); $openApiOptions = $openApi['components']['schemas']['provider']['properties']['options']; - $swaggerOptions = $swagger['definitions']['provider']['properties']['options']; $this->assertTrue($openApiOptions['additionalProperties']); $this->assertArrayNotHasKey('nullable', $openApiOptions); - $this->assertEquals($swaggerOptions, $openApiOptions); } }