1 Commits

Author SHA1 Message Date
Sebastian 66e96432a8 chore(deps): update vue-language-tools monorepo to v3.3.4 2026-06-09 03:04:50 +00:00
51 changed files with 1773 additions and 7037 deletions
-42
View File
@@ -1,42 +0,0 @@
name: Build Test
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install Server
uses: ./action-server-install
with:
install-php: 'false'
install-node: 'true'
php-version: '8.5'
node-version: '24'
server-path: './server'
- name: Checkout Pull Request
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha }}
path: server/modules/people_manager
github-server-url: https://git.ktrix.dev
- name: Install dependencies
run: npm ci
working-directory: server/modules/people_manager
- name: Build
run: npm run build
working-directory: server/modules/people_manager
-42
View File
@@ -1,42 +0,0 @@
name: JS Unit Tests
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install Server
uses: ./action-server-install
with:
install-php: 'false'
install-node: 'true'
php-version: '8.5'
node-version: '24'
server-path: './server'
- name: Checkout Pull Request
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha }}
path: server/modules/people_manager
github-server-url: https://git.ktrix.dev
- name: Install dependencies
run: npm ci
working-directory: server/modules/people_manager
- name: Run tests
run: npm run test:unit
working-directory: server/modules/people_manager
@@ -1,59 +0,0 @@
name: PHP Integration Tests
on:
pull_request:
workflow_dispatch:
jobs:
test:
name: Integration Tests
runs-on: ubuntu-latest
services:
mongo:
image: mongo:8
options: >-
--health-cmd "mongosh --quiet --eval \"db.adminCommand('ping')\""
--health-interval 5s
--health-timeout 5s
--health-retries 12
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install server
uses: ./action-server-install
with:
install-php: 'true'
php-version: '8.5'
server-path: './server'
database-uri: 'mongodb://mongo:27017/?tls=false'
database-name: 'ktrix_ci'
app-environment: 'test'
- name: Checkout module under test
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha || github.sha }}
path: server/modules/people_manager
github-server-url: https://git.ktrix.dev
- name: Install module dependencies
run: composer install --prefer-dist --no-progress
working-directory: server/modules/people_manager
- name: Install and enable module
working-directory: server
run: |
php bin/console module:install people_manager
php bin/console module:enable people_manager
- name: Run integration tests
working-directory: server/modules/people_manager
run: composer test:integration
-42
View File
@@ -1,42 +0,0 @@
name: PHP Unit Tests
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install Server
uses: ./action-server-install
with:
install-php: 'true'
install-node: 'false'
php-version: '8.5'
node-version: '24'
server-path: './server'
- name: Checkout Pull Request
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha }}
path: server/modules/people_manager
github-server-url: https://git.ktrix.dev
- name: Install dependencies
run: composer install --prefer-dist --no-progress
working-directory: server/modules/people_manager
- name: Run tests
run: composer test:unit
working-directory: server/modules/people_manager
+2 -8
View File
@@ -25,17 +25,11 @@ jobs:
tools: composer:v2 tools: composer:v2
- name: Install Renovate - name: Install Renovate
run: | run: npm install -g renovate
npm install --global --no-audit --fund=false \
--prefix "${{ runner.temp }}/renovate-npm" \
--cache "${{ runner.temp }}/renovate-npm-cache" \
renovate
"${{ runner.temp }}/renovate-npm/bin/renovate" --version
- name: Run Renovate - name: Run Renovate
env: env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_PLATFORM: gitea RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1 RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1
run: | run: renovate ${{ gitea.repository }}
"${{ runner.temp }}/renovate-npm/bin/renovate" ${{ gitea.repository }}
+4 -1
View File
@@ -14,7 +14,10 @@ node_modules/
# Backend development # Backend development
/lib/vendor/ /lib/vendor/
coverage/ coverage/
*.cache phpunit.xml.cache
.phpunit.result.cache
.php-cs-fixer.cache
.phpstan.cache
.phpactor/ .phpactor/
# Editors # Editors
+2 -15
View File
@@ -10,30 +10,17 @@
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,
"platform": { "platform": {
"php": "8.3" "php": "8.2"
}, },
"autoloader-suffix": "PeopleManager", "autoloader-suffix": "PeopleManager",
"vendor-dir": "lib/vendor" "vendor-dir": "lib/vendor"
}, },
"require": { "require": {
"php": ">=8.3 <=8.5", "php": ">=8.2 <=8.5"
"sabre/vobject": "^5.0"
},
"require-dev": {
"phpunit/phpunit": "^12.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"KTXM\\PeopleManager\\": "lib/" "KTXM\\PeopleManager\\": "lib/"
} }
},
"autoload-dev": {
"psr-4": {
"KTXT\\PeopleManager\\Tests\\": "tests/php/"
}
},
"scripts": {
"test:unit": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Unit Tests\" --colors=always --testdox",
"test:integration": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Integration Tests\" --colors=always --testdox"
} }
} }
Generated
+7 -1938
View File
File diff suppressed because it is too large Load Diff
+271 -476
View File
@@ -11,48 +11,37 @@ namespace KTXM\PeopleManager\Controllers;
use InvalidArgumentException; use InvalidArgumentException;
use KTXC\Http\Response\JsonResponse; use KTXC\Http\Response\JsonResponse;
use KTXC\Http\Response\Response; use KTXC\SessionIdentity;
use KTXC\Http\Response\StreamedNdJsonResponse; use KTXC\SessionTenant;
use KTXC\Context\IdentityContextInterface;
use KTXC\Context\TenantContextInterface;
use KTXF\Controller\ControllerAbstract; use KTXF\Controller\ControllerAbstract;
use KTXF\Json\JsonSerializable; use KTXF\Resource\Selector\SourceSelector;
use KTXF\Resource\Identifier\CollectionIdentifier;
use KTXF\Resource\Identifier\EntityIdentifier;
use KTXF\Resource\Identifier\ResourceIdentifier;
use KTXF\Resource\Identifier\ResourceIdentifiers;
use KTXF\Resource\Identifier\ServiceIdentifier;
use KTXF\Routing\Attributes\AuthenticatedRoute; use KTXF\Routing\Attributes\AuthenticatedRoute;
use KTXM\PeopleManager\Import\ImportOptions;
use KTXM\PeopleManager\Import\ImportService;
use KTXM\PeopleManager\Manager; use KTXM\PeopleManager\Manager;
use KTXM\PeopleManager\Stream\ExpectedTotal;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Throwable; use Throwable;
class DefaultController extends ControllerAbstract { class DefaultController extends ControllerAbstract {
private const ERR_MISSING_PROVIDER = 'Missing parameter: provider'; private const ERR_MISSING_PROVIDER = 'Missing parameter: provider';
private const ERR_MISSING_IDENTIFIER = 'Missing parameter: identifier'; private const ERR_MISSING_IDENTIFIER = 'Missing parameter: identifier';
private const ERR_MISSING_SERVICE = 'Missing parameter: service'; private const ERR_MISSING_SERVICE = 'Missing parameter: service';
private const ERR_MISSING_COLLECTION = 'Missing parameter: collection';
private const ERR_MISSING_DATA = 'Missing parameter: data'; private const ERR_MISSING_DATA = 'Missing parameter: data';
private const ERR_MISSING_SOURCES = 'Missing parameter: sources'; private const ERR_MISSING_SOURCES = 'Missing parameter: sources';
private const ERR_MISSING_TARGET = 'Missing parameter: target'; private const ERR_MISSING_IDENTIFIERS = 'Missing parameter: identifiers';
private const ERR_MISSING_TARGETS = 'Missing parameter: targets';
private const ERR_INVALID_OPERATION = 'Invalid operation: '; private const ERR_INVALID_OPERATION = 'Invalid operation: ';
private const ERR_INVALID_PROVIDER = 'Invalid parameter: provider must be a string'; private const ERR_INVALID_PROVIDER = 'Invalid parameter: provider must be a string';
private const ERR_INVALID_SERVICE = 'Invalid parameter: service must be a string'; private const ERR_INVALID_SERVICE = 'Invalid parameter: service must be a string';
private const ERR_INVALID_IDENTIFIER = 'Invalid parameter: identifier must be a string'; private const ERR_INVALID_IDENTIFIER = 'Invalid parameter: identifier must be a string';
private const ERR_INVALID_COLLECTION = 'Invalid parameter: collection must be a string or integer';
private const ERR_INVALID_SOURCES = 'Invalid parameter: sources must be an array'; private const ERR_INVALID_SOURCES = 'Invalid parameter: sources must be an array';
private const ERR_INVALID_TARGET = 'Invalid parameter: target must be an array'; private const ERR_INVALID_IDENTIFIERS = 'Invalid parameter: identifiers must be an array';
private const ERR_INVALID_TARGETS = 'Invalid parameter: targets must be an array';
private const ERR_INVALID_DATA = 'Invalid parameter: data must be an array'; private const ERR_INVALID_DATA = 'Invalid parameter: data must be an array';
public function __construct( public function __construct(
private readonly TenantContextInterface $tenantContext, private readonly SessionTenant $tenantIdentity,
private readonly IdentityContextInterface $identityContext, private readonly SessionIdentity $userIdentity,
private readonly Manager $manager, private readonly Manager $manager,
private readonly ImportService $importService,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
) {} ) {}
@@ -76,21 +65,16 @@ class DefaultController extends ControllerAbstract {
string|null $operation = null, string|null $operation = null,
array|null $data = null, array|null $data = null,
string|null $user = null string|null $user = null
): Response { ): JsonResponse {
// authorize request // authorize request
$tenantId = $this->tenantContext->identifier(); $tenantId = $this->tenantIdentity->identifier();
$userId = $this->identityContext->identifier(); $userId = $this->userIdentity->identifier();
try { try {
if ($operation !== null) { if ($operation !== null) {
$result = $this->processOperation($tenantId, $userId, $operation, $data ?? [], $version, $transaction); $result = $this->processOperation($tenantId, $userId, $operation, $data ?? [], []);
if ($result instanceof Response) {
return $result;
}
return new JsonResponse([ return new JsonResponse([
'version' => $version, 'version' => $version,
'transaction' => $transaction, 'transaction' => $transaction,
@@ -117,11 +101,10 @@ class DefaultController extends ControllerAbstract {
} }
} }
/** /**
* Process a single operation * Process a single operation
*/ */
private function processOperation(string $tenantId, string $userId, string $operation, array $data, int $version = 1, string $transaction = ''): mixed { private function processOperation(string $tenantId, string $userId, string $operation, array $data): mixed {
return match ($operation) { return match ($operation) {
// Provider operations // Provider operations
'provider.list' => $this->providerList($tenantId, $userId, $data), 'provider.list' => $this->providerList($tenantId, $userId, $data),
@@ -135,7 +118,7 @@ class DefaultController extends ControllerAbstract {
'service.create' => $this->serviceCreate($tenantId, $userId, $data), 'service.create' => $this->serviceCreate($tenantId, $userId, $data),
'service.update' => $this->serviceUpdate($tenantId, $userId, $data), 'service.update' => $this->serviceUpdate($tenantId, $userId, $data),
'service.delete' => $this->serviceDelete($tenantId, $userId, $data), 'service.delete' => $this->serviceDelete($tenantId, $userId, $data),
'service.test' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'service.test' => $this->serviceTest($tenantId, $userId, $data),
// Collection operations // Collection operations
'collection.list' => $this->collectionList($tenantId, $userId, $data), 'collection.list' => $this->collectionList($tenantId, $userId, $data),
@@ -146,18 +129,16 @@ class DefaultController extends ControllerAbstract {
'collection.delete' => $this->collectionDelete($tenantId, $userId, $data), 'collection.delete' => $this->collectionDelete($tenantId, $userId, $data),
// Entity operations // Entity operations
'entity.listBulk' => $this->entityListBulk($tenantId, $userId, $data), 'entity.list' => $this->entityList($tenantId, $userId, $data),
'entity.listStream' => $this->entityListStream($tenantId, $userId, $data, $version, $transaction),
'entity.fetch' => $this->entityFetch($tenantId, $userId, $data), 'entity.fetch' => $this->entityFetch($tenantId, $userId, $data),
'entity.extant' => $this->entityExtant($tenantId, $userId, $data), 'entity.extant' => $this->entityExtant($tenantId, $userId, $data),
'entity.delta' => $this->entityDelta($tenantId, $userId, $data),
'entity.create' => $this->entityCreate($tenantId, $userId, $data), 'entity.create' => $this->entityCreate($tenantId, $userId, $data),
'entity.update' => $this->entityUpdate($tenantId, $userId, $data), 'entity.update' => $this->entityUpdate($tenantId, $userId, $data),
'entity.delete' => $this->entityDelete($tenantId, $userId, $data), 'entity.delete' => $this->entityDelete($tenantId, $userId, $data),
'entity.move' => $this->entityMove($tenantId, $userId, $data), 'entity.delta' => $this->entityDelta($tenantId, $userId, $data),
'entity.copy' => $this->entityCopy($tenantId, $userId, $data), 'entity.move' => throw new InvalidArgumentException('Operation not implemented: ' . $operation),
'entity.import' => $this->entityImport($tenantId, $userId, $data, $version, $transaction), 'entity.copy' => throw new InvalidArgumentException('Operation not implemented: ' . $operation),
default => throw new InvalidArgumentException(self::ERR_INVALID_OPERATION . $operation) default => throw new InvalidArgumentException(self::ERR_INVALID_OPERATION . $operation)
}; };
} }
@@ -166,66 +147,55 @@ class DefaultController extends ControllerAbstract {
private function providerList(string $tenantId, string $userId, array $data): mixed { private function providerList(string $tenantId, string $userId, array $data): mixed {
if (isset($data['targets'])) { $sources = null;
if (!is_array($data['targets'])) { if (isset($data['sources']) && is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS); $sources = new SourceSelector();
} $sources->jsonDeserialize($data['sources']);
}
foreach ($data['targets'] as $target) {
if (!is_string($target)) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
}
}
}
return $this->manager->providerList($tenantId, $userId, $data['targets'] ?? []); return $this->manager->providerList($tenantId, $userId, $sources);
} }
private function providerFetch(string $tenantId, string $userId, array $data): mixed { private function providerFetch(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['target'])) { if (!isset($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET); throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
} }
if (!is_string($data['target'])) { if (!is_string($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET); throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
} }
return $this->manager->providerFetch($tenantId, $userId, $data['target']); return $this->manager->providerFetch($tenantId, $userId, $data['identifier']);
} }
private function providerExtant(string $tenantId, string $userId, array $data): mixed { private function providerExtant(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) { if (!isset($data['sources'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS); throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
} }
if (!is_array($data['sources'])) {
foreach ($data['targets'] as $target) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
if (!is_string($target)) { }
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS); $sources = new SourceSelector();
} $sources->jsonDeserialize($data['sources']);
}
return $this->manager->providerExtant($tenantId, $userId, $data['targets']); return $this->manager->providerExtant($tenantId, $userId, $sources);
} }
// ==================== Service Operations ===================== // ==================== Service Operations =====================
private function serviceList(string $tenantId, string $userId, array $data): mixed { private function serviceList(string $tenantId, string $userId, array $data): mixed {
$targets = null; $sources = null;
if (isset($data['targets']) && is_array($data['targets'])) { if (isset($data['sources']) && is_array($data['sources'])) {
$targets = ResourceIdentifiers::fromArray($data['targets']); $sources = new SourceSelector();
foreach ($targets as $target) { $sources->jsonDeserialize($data['sources']);
if (!$target instanceof CollectionIdentifier && !$target instanceof ServiceIdentifier) {
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service, provider:service:collection, or provider:service:collection:entity identifiers');
}
}
} }
return $this->manager->serviceList($tenantId, $userId, $targets); return $this->manager->serviceList($tenantId, $userId, $sources);
} }
@@ -249,20 +219,16 @@ class DefaultController extends ControllerAbstract {
private function serviceExtant(string $tenantId, string $userId, array $data): mixed { private function serviceExtant(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) { if (!isset($data['sources'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS); throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
} }
if (!is_array($data['targets'])) { if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS); throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
} }
$targets = ResourceIdentifiers::fromArray($data['targets']); $sources = new SourceSelector();
foreach ($targets as $target) { $sources->jsonDeserialize($data['sources']);
if (!$target instanceof ServiceIdentifier) {
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service identifiers'); return $this->manager->serviceExtant($tenantId, $userId, $sources);
}
}
return $this->manager->serviceExtant($tenantId, $userId, $targets);
} }
private function serviceCreate(string $tenantId, string $userId, array $data): mixed { private function serviceCreate(string $tenantId, string $userId, array $data): mixed {
@@ -306,17 +272,13 @@ class DefaultController extends ControllerAbstract {
if (!is_array($data['data'])) { if (!is_array($data['data'])) {
throw new InvalidArgumentException(self::ERR_INVALID_DATA); throw new InvalidArgumentException(self::ERR_INVALID_DATA);
} }
if (isset($data['delta']) && !is_bool($data['delta'])) {
throw new InvalidArgumentException('Invalid parameter: delta must be a boolean');
}
return $this->manager->serviceUpdate( return $this->manager->serviceUpdate(
$tenantId, $tenantId,
$userId, $userId,
$data['provider'], $data['provider'],
$data['identifier'], $data['identifier'],
$data['data'], $data['data']
$data['delta'] ?? false,
); );
} }
@@ -342,17 +304,36 @@ class DefaultController extends ControllerAbstract {
); );
} }
private function serviceTest(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['provider'])) {
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
}
if (!is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
}
if (!isset($data['identifier']) && !isset($data['location']) && !isset($data['identity'])) {
throw new InvalidArgumentException('Either a service identifier or location and identity must be provided for service test');
}
return $this->manager->serviceTest(
$tenantId,
$userId,
$data['provider'],
$data['identifier'] ?? null,
$data['location'] ?? null,
$data['identity'] ?? null,
);
}
// ==================== Collection Operations ==================== // ==================== Collection Operations ====================
private function collectionList(string $tenantId, string $userId, array $data): mixed { private function collectionList(string $tenantId, string $userId, array $data): mixed {
$sources = null; $sources = null;
if (isset($data['sources']) && is_array($data['sources'])) { if (isset($data['sources']) && is_array($data['sources'])) {
$sources = ResourceIdentifiers::fromArray($data['sources']); $sources = new SourceSelector();
foreach ($sources as $source) { $sources->jsonDeserialize($data['sources']);
if (!$source instanceof CollectionIdentifier && !$source instanceof ServiceIdentifier) {
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service, provider:service:collection, or provider:service:collection:entity identifiers');
}
}
} }
$filter = $data['filter'] ?? null; $filter = $data['filter'] ?? null;
@@ -361,47 +342,49 @@ class DefaultController extends ControllerAbstract {
return $this->manager->collectionList($tenantId, $userId, $sources, $filter, $sort); return $this->manager->collectionList($tenantId, $userId, $sources, $filter, $sort);
} }
private function collectionFetch(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
}
if (!is_array($data['targets'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
}
$targetIdentifiers = ResourceIdentifiers::fromArray($data['targets']);
foreach ($targetIdentifiers as $targetIdentifier) {
if (!$targetIdentifier instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
}
}
$list = $this->manager->collectionFetch(
$tenantId,
$userId,
$targetIdentifier
);
return $list;
}
private function collectionExtant(string $tenantId, string $userId, array $data): mixed { private function collectionExtant(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) { if (!isset($data['sources'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS); throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
} }
if (!is_array($data['targets'])) { if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS); throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
} }
$sources = ResourceIdentifiers::fromArray($data['targets']); $sources = new SourceSelector();
foreach ($sources as $source) { $sources->jsonDeserialize($data['sources']);
if (!$source instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service, provider:service:collection, or provider:service:collection:entity identifiers');
}
}
return $this->manager->collectionExtant($tenantId, $userId, $sources); return $this->manager->collectionExtant($tenantId, $userId, $sources);
} }
private function collectionFetch(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['provider'])) {
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
}
if (!is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
}
if (!isset($data['service'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
}
if (!is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
}
if (!isset($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
}
if (!is_string($data['identifier']) && !is_int($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
}
return $this->manager->collectionFetch(
$tenantId,
$userId,
$data['provider'],
$data['service'],
$data['identifier']
);
}
private function collectionCreate(string $tenantId, string $userId, array $data): mixed { private function collectionCreate(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['provider'])) { if (!isset($data['provider'])) {
throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
@@ -415,8 +398,8 @@ class DefaultController extends ControllerAbstract {
if (!is_string($data['service'])) { if (!is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
} }
if (isset($data['target']) && !is_string($data['target']) && !is_int($data['target'])) { if (isset($data['collection']) && !is_string($data['collection']) && !is_int($data['collection'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET); throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
} }
if (!isset($data['properties'])) { if (!isset($data['properties'])) {
throw new InvalidArgumentException(self::ERR_MISSING_DATA); throw new InvalidArgumentException(self::ERR_MISSING_DATA);
@@ -424,30 +407,35 @@ class DefaultController extends ControllerAbstract {
if (!is_array($data['properties'])) { if (!is_array($data['properties'])) {
throw new InvalidArgumentException(self::ERR_INVALID_DATA); throw new InvalidArgumentException(self::ERR_INVALID_DATA);
} }
if (isset($data['target'])) {
$targetIdentifier = ResourceIdentifier::fromString($data['target']);
if (!$targetIdentifier instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
}
}
return $this->manager->collectionCreate( return $this->manager->collectionCreate(
$tenantId, $tenantId,
$userId, $userId,
$data['provider'], $data['provider'],
$data['service'], $data['service'],
$targetIdentifier ?? null, $data['collection'] ?? null,
$data['properties'] $data['properties']
); );
} }
private function collectionUpdate(string $tenantId, string $userId, array $data): mixed { private function collectionUpdate(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['target'])) { if (!isset($data['provider'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET); throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
} }
if (!is_string($data['target'])) { if (!is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET); throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
}
if (!isset($data['service'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
}
if (!is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
}
if (!isset($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
}
if (!is_string($data['identifier']) && !is_int($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
} }
if (!isset($data['properties'])) { if (!isset($data['properties'])) {
throw new InvalidArgumentException(self::ERR_MISSING_DATA); throw new InvalidArgumentException(self::ERR_MISSING_DATA);
@@ -455,337 +443,182 @@ class DefaultController extends ControllerAbstract {
if (!is_array($data['properties'])) { if (!is_array($data['properties'])) {
throw new InvalidArgumentException(self::ERR_INVALID_DATA); throw new InvalidArgumentException(self::ERR_INVALID_DATA);
} }
$targetIdentifier = ResourceIdentifier::fromString($data['target']);
if (!$targetIdentifier instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
}
return $this->manager->collectionUpdate( return $this->manager->collectionUpdate(
$tenantId, $tenantId,
$userId, $userId,
$targetIdentifier, $data['provider'],
$data['service'],
$data['identifier'],
$data['properties'] $data['properties']
); );
} }
private function collectionDelete(string $tenantId, string $userId, array $data): mixed { private function collectionDelete(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['target'])) { if (!isset($data['provider'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET); throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
} }
if (!is_string($data['target'])) { if (!is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET); throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
} }
if (!isset($data['service'])) {
$targetIdentifier = ResourceIdentifier::fromString($data['target']); throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
if (!$targetIdentifier instanceof CollectionIdentifier) { }
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection'); if (!is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
}
if (!isset($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER);
}
if (!is_string($data['identifier']) && !is_int($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
} }
$result = $this->manager->collectionDelete($tenantId, $userId, $targetIdentifier, $data['options'] ?? [] ); return $this->manager->collectionDelete(
$tenantId,
if (is_bool($result)) { $userId,
return [ $data['provider'],
'disposition' => 'deleted' $data['service'],
]; $data['identifier'],
} $data['options'] ?? []
);
if ($result instanceof JsonSerializable) {
return [
'disposition' => 'moved',
'mutation' => $result
];
}
return $result;
} }
// ==================== Entity Operations ==================== // ==================== Entity Operations ====================
private function entityListBulk(string $tenantId, string $userId, array $data): mixed { private function entityList(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['sources'])) {
if (isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
}
$sources = ResourceIdentifiers::fromArray($data['sources']);
foreach ($sources as $source) {
if (!$source instanceof ServiceIdentifier && !$source instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service or provider:service:collection identifiers');
}
}
} else {
$sources = null;
} }
if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
}
$sources = new SourceSelector();
$sources->jsonDeserialize($data['sources']);
$filter = $data['filter'] ?? null; $filter = $data['filter'] ?? null;
$sort = $data['sort'] ?? null; $sort = $data['sort'] ?? null;
$range = $data['range'] ?? null; $range = $data['range'] ?? null;
return $this->manager->entityListBulk($tenantId, $userId, $sources, $filter, $sort, $range); return $this->manager->entityList($tenantId, $userId, $sources, $filter, $sort, $range);
} }
private function entityListStream(string $tenantId, string $userId, array $data, int $version, string $transaction): StreamedNdJsonResponse {
if (isset($data['sources'])) {
if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
}
$sources = ResourceIdentifiers::fromArray($data['sources']);
foreach ($sources as $source) {
if (!$source instanceof ServiceIdentifier && !$source instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service or provider:service:collection identifiers');
}
}
} else {
$sources = null;
}
$filter = $data['filter'] ?? null;
$sort = $data['sort'] ?? null;
$range = $data['range'] ?? null;
$entities = $this->manager->entityListStream($tenantId, $userId, $sources, $filter, $sort, $range);
return new StreamedNdJsonResponse(
$this->streamEnvelope($entities, $version, $transaction),
1,
200,
['Content-Type' => 'application/json'],
);
}
/**
* Import vCards into a collection, streaming one NDJSON event per contact.
*
* Request data: { target: "provider:service:collection", data: "<raw vCard string>", options?: {...} }
*/
private function entityImport(string $tenantId, string $userId, array $data, int $version, string $transaction): StreamedNdJsonResponse {
if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
}
if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
}
if (!isset($data['data']) || !is_string($data['data']) || trim($data['data']) === '') {
throw new InvalidArgumentException('Invalid parameter: data must be a non-empty string');
}
$target = ResourceIdentifier::fromString($data['target']);
if (!$target instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
}
$options = ImportOptions::fromArray($data['options'] ?? []);
// Spill the payload to a temp file and release the in-memory copy before the
// (potentially long) streaming parse, so peak memory stays at one contact object.
$tempFile = tmpfile();
if ($tempFile === false) {
throw new \RuntimeException('Unable to allocate temporary file for import');
}
fwrite($tempFile, $data['data']);
unset($data);
rewind($tempFile);
$events = $this->importService->import($tempFile, $target, $options, $tenantId, $userId);
$frames = $this->streamEnvelope($events, $version, $transaction);
// Stream the envelope, releasing the spilled temp file once it is fully
// drained (or the client disconnects) so it never outlives its stream.
$response = (function () use ($frames, $tempFile): \Generator {
try {
yield from $frames;
} finally {
fclose($tempFile);
}
})();
return new StreamedNdJsonResponse($response, 1, 200);
}
/**
* Wrap a generator of JsonSerializable domain objects in the canonical NDJSON
* stream envelope shared by every streaming operation:
*
* control:start {version, transaction, total?} — total? = expected count
* data {data} — one per domain object
* error {message} — on failure, then stop
* control:end {total} — total = objects emitted
*
* If the generator leads with an {@see ExpectedTotal} event, its value is
* folded into the start frame's `total` (the progress denominator) rather
* than emitted as a data frame.
*
* @param \Generator<\JsonSerializable> $items
*/
private function streamEnvelope(\Generator $items, int $version, string $transaction): \Generator {
// Peek the first event: an expected-total marker rides on the start frame.
$expected = null;
$items->rewind();
if ($items->valid() && $items->current() instanceof ExpectedTotal) {
$expected = $items->current()->expectedTotal();
$items->next();
}
$start = ['type' => 'control', 'status' => 'start', 'version' => $version, 'transaction' => $transaction];
if ($expected !== null) {
$start['total'] = $expected;
}
yield $start;
$total = 0;
try {
for (; $items->valid(); $items->next()) {
$item = $items->current();
if (!$item instanceof \JsonSerializable) {
continue;
}
yield ['type' => 'data', 'data' => $item->jsonSerialize()];
$total++;
}
} catch (\Throwable $t) {
$this->logger->error('Error streaming response', ['exception' => $t]);
yield ['type' => 'error', 'message' => $t->getMessage()];
return;
}
yield ['type' => 'control', 'status' => 'end', 'total' => $total];
}
private function entityFetch(string $tenantId, string $userId, array $data): mixed { private function entityFetch(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) { if (!isset($data['provider'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS); throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER);
} }
if (!is_array($data['targets'])) { if (!is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS); throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
} }
if (!isset($data['service'])) {
$targets = ResourceIdentifiers::fromArray($data['targets']); throw new InvalidArgumentException(self::ERR_MISSING_SERVICE);
foreach ($targets as $target) { }
if (!$target instanceof EntityIdentifier) { if (!is_string($data['service'])) {
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection:entity identifiers'); throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
} }
if (!isset($data['collection'])) {
throw new InvalidArgumentException(self::ERR_MISSING_COLLECTION);
}
if (!is_string($data['collection']) && !is_int($data['collection'])) {
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
}
if (!isset($data['identifiers'])) {
throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIERS);
}
if (!is_array($data['identifiers'])) {
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIERS);
} }
return $this->manager->entityFetchBulk( return $this->manager->entityFetch(
$tenantId, $tenantId,
$userId, $userId,
...$targets->all() $data['provider'],
$data['service'],
$data['collection'],
$data['identifiers']
); );
} }
private function entityExtant(string $tenantId, string $userId, array $data): mixed { private function entityExtant(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) { if (!isset($data['sources'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS); throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
} }
if (!is_array($data['targets'])) { if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS); throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
} }
$targets = ResourceIdentifiers::fromArray($data['targets']); $sources = new SourceSelector();
foreach ($targets as $target) { $sources->jsonDeserialize($data['sources']);
if (!$target instanceof CollectionIdentifier && !$target instanceof EntityIdentifier) {
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection or provider:service:collection:entity identifiers'); return $this->manager->entityExtant($tenantId, $userId, $sources);
} }
private function entityCreate(string $tenantId, string $userId, array $data = []): mixed {
if (!isset($data['provider']) || !is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
}
if (!isset($data['service']) || !is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
}
if (!isset($data['collection'])) {
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
}
$properties = $data['properties'] ?? $data['data'] ?? null;
if (!is_array($properties)) {
throw new InvalidArgumentException('Invalid parameter: properties must be an array');
}
$options = $data['options'] ?? [];
return $this->manager->entityCreate($tenantId, $userId, $data['provider'], $data['service'], $data['collection'], $properties, $options);
}
private function entityUpdate(string $tenantId, string $userId, array $data = []): mixed {
if (!isset($data['provider']) || !is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
}
if (!isset($data['service']) || !is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
}
if (!isset($data['collection'])) {
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
}
if (!isset($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
}
$properties = $data['properties'] ?? $data['data'] ?? null;
if (!is_array($properties)) {
throw new InvalidArgumentException('Invalid parameter: properties must be an array');
} }
return $this->manager->entityExtant($tenantId, $userId, $targets); return $this->manager->entityUpdate($tenantId, $userId, $data['provider'], $data['service'], $data['collection'], $data['identifier'], $properties);
}
}
private function entityDelete(string $tenantId, string $userId, array $data = []): mixed {
if (!isset($data['provider']) || !is_string($data['provider'])) {
throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER);
}
if (!isset($data['service']) || !is_string($data['service'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SERVICE);
}
if (!isset($data['collection'])) {
throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION);
}
if (!isset($data['identifier'])) {
throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER);
}
return $this->manager->entityDelete($tenantId, $userId, $data['provider'], $data['service'], $data['collection'], $data['identifier']);
}
private function entityDelta(string $tenantId, string $userId, array $data): mixed { private function entityDelta(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
}
if (!is_array($data['targets'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
}
$targets = ResourceIdentifiers::fromArray($data['targets']);
foreach ($targets as $target) {
if (!$target instanceof CollectionIdentifier && !$target instanceof EntityIdentifier) {
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection or provider:service:collection:signature identifiers');
}
}
return $this->manager->entityDelta($tenantId, $userId, $targets);
}
private function entityCreate(string $tenantId, string $userId, array $data = []): mixed {
if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
}
if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
}
if (!isset($data['properties'])) {
throw new InvalidArgumentException(self::ERR_MISSING_DATA);
}
if (!is_array($data['properties'])) {
throw new InvalidArgumentException(self::ERR_INVALID_DATA);
}
$target = ResourceIdentifier::fromString($data['target']);
if (!$target instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
}
$options = $data['options'] ?? [];
return $this->manager->entityCreate($tenantId, $userId, $target, $data['properties'], $options);
}
private function entityUpdate(string $tenantId, string $userId, array $data = []): mixed {
if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
}
if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
}
if (!isset($data['properties'])) {
throw new InvalidArgumentException(self::ERR_MISSING_DATA);
}
if (!is_array($data['properties'])) {
throw new InvalidArgumentException(self::ERR_INVALID_DATA);
}
$target = ResourceIdentifier::fromString($data['target']);
if (!$target instanceof EntityIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection:entity');
}
return $this->manager->entityModify($tenantId, $userId, $target, $data['properties']);
}
private function entityDelete(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['targets'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGETS);
}
if (!is_array($data['targets'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGETS);
}
$targets = ResourceIdentifiers::fromArray($data['targets']);
foreach ($targets as $target) {
if (!$target instanceof EntityIdentifier) {
throw new InvalidArgumentException('Invalid parameter: targets must contain provider:service:collection:entity identifiers');
}
}
return $this->manager->entityDelete($tenantId, $userId, ...$targets->all());
}
private function entityMove(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
}
if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
}
if (!isset($data['sources'])) { if (!isset($data['sources'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
} }
@@ -793,48 +626,10 @@ class DefaultController extends ControllerAbstract {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
} }
$target = ResourceIdentifier::fromString($data['target']); $sources = new SourceSelector();
if (!$target instanceof CollectionIdentifier) { $sources->jsonDeserialize($data['sources']);
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
} return $this->manager->entityDelta($tenantId, $userId, $sources);
$sources = ResourceIdentifiers::fromArray($data['sources']);
foreach ($sources as $source) {
if (!$source instanceof EntityIdentifier) {
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service:collection:entity identifiers');
}
}
return $this->manager->entityMove($tenantId, $userId, $target, ...$sources->all());
}
private function entityCopy(string $tenantId, string $userId, array $data): mixed {
if (!isset($data['target'])) {
throw new InvalidArgumentException(self::ERR_MISSING_TARGET);
}
if (!is_string($data['target'])) {
throw new InvalidArgumentException(self::ERR_INVALID_TARGET);
}
if (!isset($data['sources'])) {
throw new InvalidArgumentException(self::ERR_MISSING_SOURCES);
}
if (!is_array($data['sources'])) {
throw new InvalidArgumentException(self::ERR_INVALID_SOURCES);
}
$target = ResourceIdentifier::fromString($data['target']);
if (!$target instanceof CollectionIdentifier) {
throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection');
}
$sources = ResourceIdentifiers::fromArray($data['sources']);
foreach ($sources as $source) {
if (!$source instanceof EntityIdentifier) {
throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service:collection:entity identifiers');
}
}
return $this->manager->entityCopy($tenantId, $userId, $target, ...$sources->all());
} }
} }
-30
View File
@@ -1,30 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\PeopleManager\Import;
use KTXM\PeopleManager\Stream\ExpectedTotal;
final readonly class ImportCountEvent implements ImportEvent, ExpectedTotal {
public function __construct(
public int $total,
) {}
public function expectedTotal(): int {
return $this->total;
}
/**
* @return array{total: int}
*/
public function jsonSerialize(): array {
return ['total' => $this->total];
}
}
-17
View File
@@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\PeopleManager\Import;
enum ImportDisposition: string {
case Created = 'created';
case Updated = 'updated';
case Exists = 'exists';
case Error = 'error';
}
-15
View File
@@ -1,15 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\PeopleManager\Import;
use JsonSerializable;
interface ImportEvent extends JsonSerializable {
}
-37
View File
@@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\PeopleManager\Import;
final readonly class ImportObjectEvent implements ImportEvent {
/**
* @param list<string> $errors
*/
public function __construct(
public ?string $identifier,
public ImportDisposition $disposition,
public array $errors = [],
) {}
public function isError(): bool {
return $this->disposition === ImportDisposition::Error;
}
/**
* @return array{identifier: ?string, disposition: string, errors: list<string>}
*/
public function jsonSerialize(): array {
return [
'identifier' => $this->identifier,
'disposition' => $this->disposition->value,
'errors' => $this->errors,
];
}
}
-71
View File
@@ -1,71 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\PeopleManager\Import;
use InvalidArgumentException;
final class ImportOptions {
public const ERROR_CONTINUE = 0;
public const ERROR_FAIL = 1;
public const ERROR_OPTIONS = [self::ERROR_CONTINUE, self::ERROR_FAIL];
/** Overwrite an existing entity when the same UID is already present. */
private bool $supersede = false;
/** Emit an ImportCountEvent (discovered total) before the object stream. */
private bool $counts = true;
/** How to handle per-object errors. */
private int $errors = self::ERROR_CONTINUE;
public function getSupersede(): bool {
return $this->supersede;
}
public function setSupersede(bool $value): void {
$this->supersede = $value;
}
public function getCounts(): bool {
return $this->counts;
}
public function setCounts(bool $value): void {
$this->counts = $value;
}
public function getErrors(): int {
return $this->errors;
}
public function setErrors(int $value): void {
if (!in_array($value, self::ERROR_OPTIONS, true)) {
throw new InvalidArgumentException('Invalid errors option specified');
}
$this->errors = $value;
}
/**
* Build options from the raw `options` array carried in the request.
*
* @param array<string,mixed> $data
*/
public static function fromArray(array $data): self {
$options = new self();
$options->supersede = (bool)($data['supersede'] ?? false);
$options->counts = (bool)($data['counts'] ?? true);
$options->errors = (int)($data['errors'] ?? self::ERROR_CONTINUE);
if (!in_array($options->errors, [self::ERROR_CONTINUE, self::ERROR_FAIL], true)) {
throw new InvalidArgumentException('Invalid errors option specified');
}
return $options;
}
}
-358
View File
@@ -1,358 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\PeopleManager\Import;
use Generator;
use InvalidArgumentException;
use KTXF\People\Entity as E;
use KTXF\People\Entity\Property as P;
use KTXF\Resource\Identifier\CollectionIdentifier;
use KTXM\PeopleManager\Manager;
use Sabre\VObject\Component\VCard as VCardComponent;
use Sabre\VObject\ParseException;
use Sabre\VObject\Parser\MimeDir;
use Sabre\VObject\Property;
use Sabre\VObject\Splitter\VCard as VCardSplitter;
use Throwable;
class ImportService {
public function __construct(
private readonly Manager $manager,
) {}
/**
* @param resource $source readable, seekable file resource containing one or more objects
*
* @return Generator<int, ImportEvent>
*/
public function import($source, CollectionIdentifier $target, ImportOptions $options, string $tenantId, string $userId): Generator {
if (!is_resource($source)) {
throw new InvalidArgumentException('Invalid import source: must be a file resource');
}
// Discovered count — cheap O(1)-memory byte scan, no second parse.
if ($options->getCounts()) {
yield new ImportCountEvent($this->countCards($source));
}
rewind($source);
$splitter = new VCardSplitter($source, MimeDir::OPTION_FORGIVING | MimeDir::OPTION_IGNORE_INVALID_LINES);
while (true) {
try {
$vCard = $splitter->getNext();
} catch (ParseException $e) {
// The parser position is unreliable after a parse error, so stop here.
yield new ImportObjectEvent(null, ImportDisposition::Error, ['Malformed vCard: ' . $e->getMessage()]);
return;
}
if ($vCard === null) {
break;
}
$uid = isset($vCard->UID) ? (string)$vCard->UID : null;
try {
$properties = $this->mapVCard($vCard);
$this->manager->entityCreate($tenantId, $userId, $target, $properties);
yield new ImportObjectEvent($uid, ImportDisposition::Created);
} catch (Throwable $e) {
yield new ImportObjectEvent($uid, ImportDisposition::Error, [$e->getMessage()]);
if ($options->getErrors() === ImportOptions::ERROR_FAIL) {
return;
}
}
unset($vCard);
}
}
/**
* Count vCards by scanning for BEGIN:VCARD lines — no parsing, O(1) memory.
*
* @param resource $source
*/
private function countCards($source): int {
rewind($source);
$count = 0;
while (($line = fgets($source)) !== false) {
if (stripos($line, 'BEGIN:VCARD') === 0) {
$count++;
}
}
rewind($source);
return $count;
}
/**
* Map a sabre vCard to an entity property array (the shape entity.create consumes).
*
* @return array<string,mixed>
*/
private function mapVCard(VCardComponent $vCard): array {
$kind = isset($vCard->KIND) ? strtolower((string)$vCard->KIND) : 'individual';
return match ($kind) {
'org', 'organization' => $this->mapOrganization($vCard)->jsonSerialize(),
'group' => $this->mapGroup($vCard)->jsonSerialize(),
default => $this->mapIndividual($vCard)->jsonSerialize(),
};
}
private function mapIndividual(VCardComponent $vCard): E\IndividualObject {
$object = new E\IndividualObject();
$object->urid = $this->uid($vCard);
$object->label = $this->text($vCard, 'FN');
// Structured name: N = family;given;additional;prefix;suffix
if (isset($vCard->N)) {
$parts = $vCard->N->getParts();
$object->names->family = $this->part($parts, 0);
$object->names->given = $this->part($parts, 1);
$object->names->additional = $this->part($parts, 2);
$object->names->prefix = $this->part($parts, 3);
$object->names->suffix = $this->part($parts, 4);
}
foreach ($vCard->select('EMAIL') as $prop) {
$email = new P\EmailObject();
$email->address = (string)$prop;
$email->context = $this->firstType($prop);
$object->emails->add($email, $this->key());
}
foreach ($vCard->select('TEL') as $prop) {
$phone = new P\PhoneObject();
$phone->number = (string)$prop;
$phone->context = $this->firstType($prop);
$object->phones->add($phone, $this->key());
}
foreach ($vCard->select('ADR') as $prop) {
$object->physicalLocations->add($this->address(new P\PhysicalLocationObject(), $prop), $this->key());
}
foreach ($vCard->select('URL') as $prop) {
$location = new P\VirtualLocationObject();
$location->location = (string)$prop;
$location->context = $this->firstType($prop);
$object->virtualLocations->add($location, $this->key());
}
foreach ($vCard->select('NOTE') as $prop) {
$note = new P\NoteObject();
$note->content = (string)$prop;
$object->notes->add($note, $this->key());
}
foreach ($vCard->select('TITLE') as $prop) {
$title = new P\TitleObject();
$title->kind = P\TitleTypes::Title;
$title->label = (string)$prop;
$object->titles->add($title, $this->key());
}
foreach ($vCard->select('ROLE') as $prop) {
$title = new P\TitleObject();
$title->kind = P\TitleTypes::Role;
$title->label = (string)$prop;
$object->titles->add($title, $this->key());
}
if (isset($vCard->BDAY)) {
$this->anniversary($object, P\AnniversaryTypes::Birth, (string)$vCard->BDAY);
}
if (isset($vCard->ANNIVERSARY)) {
$this->anniversary($object, P\AnniversaryTypes::Nuptial, (string)$vCard->ANNIVERSARY);
}
foreach ($this->categories($vCard) as $tag) {
$object->tags->add($tag);
}
return $object;
}
private function mapOrganization(VCardComponent $vCard): E\OrganizationObject {
$object = new E\OrganizationObject();
$object->urid = $this->uid($vCard);
$object->label = $this->text($vCard, 'FN') ?? $this->text($vCard, 'ORG');
$object->names->full = $object->label;
$object->names->sort = $this->text($vCard, 'SORT-STRING');
foreach ($vCard->select('EMAIL') as $prop) {
$email = new P\EmailObject();
$email->address = (string)$prop;
$email->context = $this->firstType($prop);
$object->emails->add($email, $this->key());
}
foreach ($vCard->select('TEL') as $prop) {
$phone = new P\PhoneObject();
$phone->number = (string)$prop;
$phone->context = $this->firstType($prop);
$object->phones->add($phone, $this->key());
}
foreach ($vCard->select('ADR') as $prop) {
$object->physicalLocations->add($this->address(new P\PhysicalLocationObject(), $prop), $this->key());
}
foreach ($vCard->select('URL') as $prop) {
$location = new P\VirtualLocationObject();
$location->location = (string)$prop;
$location->context = $this->firstType($prop);
$object->virtualLocations->add($location, $this->key());
}
foreach ($vCard->select('NOTE') as $prop) {
$note = new P\NoteObject();
$note->content = (string)$prop;
$object->notes->add($note, $this->key());
}
return $object;
}
private function mapGroup(VCardComponent $vCard): E\GroupObject {
$object = new E\GroupObject();
$object->urid = $this->uid($vCard);
$object->label = $this->text($vCard, 'FN');
$object->names->full = $object->label;
foreach ($vCard->select('MEMBER') as $prop) {
$member = new P\MemberObject();
// MEMBER values are URIs, commonly urn:uuid:<id>.
$member->entityId = preg_replace('/^urn:uuid:/i', '', (string)$prop);
$object->members->add($member, $this->key());
}
foreach ($vCard->select('URL') as $prop) {
$location = new P\VirtualLocationObject();
$location->location = (string)$prop;
$location->context = $this->firstType($prop);
$object->virtualLocations->add($location, $this->key());
}
foreach ($vCard->select('NOTE') as $prop) {
$note = new P\NoteObject();
$note->content = (string)$prop;
$object->notes->add($note, $this->key());
}
return $object;
}
// ==================== Helpers ====================
/**
* Populate a physical-location object from an ADR property.
* ADR = pobox;ext(unit);street;locality;region;code;country
*/
private function address(P\PhysicalLocationObject $location, Property $prop): P\PhysicalLocationObject {
$parts = $prop->getParts();
$location->box = $this->part($parts, 0);
$location->unit = $this->part($parts, 1);
$location->street = $this->part($parts, 2);
$location->locality = $this->part($parts, 3);
$location->region = $this->part($parts, 4);
$location->code = $this->part($parts, 5);
$location->country = $this->part($parts, 6);
$location->context = $this->firstType($prop);
return $location;
}
private function anniversary(E\IndividualObject $object, P\AnniversaryTypes $type, string $value): void {
$date = $this->date($value);
if ($date === null) {
return;
}
$anniversary = new P\AnniversaryObject();
$anniversary->type = $type;
$anniversary->when = $date;
$object->anniversaries->add($anniversary);
}
private function uid(VCardComponent $vCard): ?string {
return isset($vCard->UID) ? (string)$vCard->UID : null;
}
private function text(VCardComponent $vCard, string $name): ?string {
if (!isset($vCard->$name)) {
return null;
}
$value = trim((string)$vCard->$name);
return $value === '' ? null : $value;
}
/**
* First TYPE parameter value, lowercased (used as `context`).
*/
private function firstType(Property $prop): ?string {
$type = $prop['TYPE'] ?? null;
if ($type === null) {
return null;
}
$parts = $type->getParts();
return isset($parts[0]) && $parts[0] !== '' ? strtolower((string)$parts[0]) : null;
}
/**
* @param array<int,string> $parts
*/
private function part(array $parts, int $index): ?string {
if (!isset($parts[$index])) {
return null;
}
$value = trim((string)$parts[$index]);
return $value === '' ? null : $value;
}
/**
* @return list<string>
*/
private function categories(VCardComponent $vCard): array {
$tags = [];
foreach ($vCard->select('CATEGORIES') as $prop) {
foreach ($prop->getParts() as $part) {
$part = trim((string)$part);
if ($part !== '') {
$tags[] = $part;
}
}
}
return $tags;
}
/**
* Best-effort parse of a vCard date value; null if unparseable.
*/
private function date(string $value): ?\DateTimeImmutable {
$value = trim($value);
if ($value === '') {
return null;
}
// Common compact form YYYYMMDD.
if (preg_match('/^\d{8}$/', $value)) {
$date = \DateTimeImmutable::createFromFormat('!Ymd', $value);
return $date ?: null;
}
try {
return new \DateTimeImmutable($value);
} catch (Throwable) {
return null;
}
}
private function key(): string {
return bin2hex(random_bytes(8));
}
}
+377 -632
View File
File diff suppressed because it is too large Load Diff
-9
View File
@@ -14,15 +14,6 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
public function __construct() public function __construct()
{ } { }
public function boot(): void
{
// Load module-local vendored dependencies (e.g. sabre/vobject for VCF import).
$vendorAutoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($vendorAutoload)) {
require_once $vendorAutoload;
}
}
public function handle(): string public function handle(): string
{ {
return 'people_manager'; return 'people_manager';
-20
View File
@@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\PeopleManager\Stream;
/**
* Implemented by a stream event that declares, up front, how many data frames
* are expected to follow. When such an event leads a stream generator, the
* envelope writer folds its value into the `control:start` frame's `total`
* (the progress denominator) instead of emitting it as a `data` frame.
*/
interface ExpectedTotal {
public function expectedTotal(): int;
}
+201 -1257
View File
File diff suppressed because it is too large Load Diff
+3 -10
View File
@@ -10,22 +10,15 @@
"build": "vite build --mode production --config vite.config.ts", "build": "vite build --mode production --config vite.config.ts",
"dev": "vite build --mode development --config vite.config.ts", "dev": "vite build --mode development --config vite.config.ts",
"watch": "vite build --mode development --watch --config vite.config.ts", "watch": "vite build --mode development --watch --config vite.config.ts",
"typecheck": "vue-tsc --noEmit", "typecheck": "vue-tsc --noEmit"
"test": "vitest run --config tests/js/vitest.config.ts",
"test:unit": "vitest run --config tests/js/vitest.config.ts",
"test:watch": "vitest watch --config tests/js/vitest.config.ts",
"test:coverage": "vitest run --coverage --config tests/js/vitest.config.ts"
}, },
"dependencies": { "dependencies": {
"pinia": "^4.0.0" "pinia": "^3.0.0"
}, },
"devDependencies": { "devDependencies": {
"@vue/tsconfig": "^0.9.0", "@vue/tsconfig": "^0.9.0",
"typescript": "~6.0.0", "typescript": "~6.0.0",
"vite": "^8.0.0", "vite": "^8.0.0",
"vue-tsc": "^3.0.5", "vue-tsc": "^3.0.5"
"@vitest/coverage-v8": "^4.1.6",
"jsdom": "^30.0.0",
"vitest": "^4.1.6"
} }
} }
-27
View File
@@ -1,27 +0,0 @@
import { isProxy, toRaw } from 'vue';
function normalizeCloneable<T>(value: T): T {
if (value === null || value === undefined) {
return value;
}
if (typeof value !== 'object') {
return value;
}
const rawValue = isProxy(value) ? toRaw(value) : value;
if (Array.isArray(rawValue)) {
return rawValue.map(item => normalizeCloneable(item)) as T;
}
const plainObject = Object.fromEntries(
Object.entries(rawValue).map(([key, nestedValue]) => [key, normalizeCloneable(nestedValue)])
);
return plainObject as T;
}
export function clonePlain<T>(value: T): T {
return structuredClone(normalizeCloneable(value));
}
+61 -52
View File
@@ -2,51 +2,46 @@
* Class model for Collection Interface * Class model for Collection Interface
*/ */
import type { import type { CollectionContentTypes, CollectionInterface, CollectionPropertiesInterface } from "@/types/collection";
CollectionContentTypes,
CollectionInterface,
CollectionModelInterface,
CollectionPropertiesInterface,
CollectionPropertiesModelInterface
} from "@/types/collection";
import type {
CollectionIdentifier,
ServiceIdentifier
} from "@/types/common";
import { clonePlain } from './clone-plain';
export class CollectionObject implements CollectionModelInterface { export class CollectionObject implements CollectionInterface {
_data!: CollectionInterface<CollectionPropertiesInterface>; _data!: CollectionInterface;
_properties: CollectionPropertiesObject | undefined = undefined;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'people:collection',
version: 1,
provider: '', provider: '',
service: '' as ServiceIdentifier, service: '',
collection: null as CollectionIdentifier | null, collection: null,
identifier: '' as CollectionIdentifier, identifier: '',
properties: new CollectionPropertiesObject().toJson(), signature: null,
created: null,
modified: null,
properties: new CollectionPropertiesObject(),
}; };
} }
fromJson(data: CollectionInterface): CollectionObject { fromJson(data: CollectionInterface): CollectionObject {
this._data = clonePlain(data); this._data = data;
this._properties = undefined; if (data.properties) {
this._data.properties = new CollectionPropertiesObject().fromJson(data.properties as CollectionPropertiesInterface);
}
return this; return this;
} }
toJson(): CollectionInterface { toJson(): CollectionInterface {
const json = this._properties const json = { ...this._data };
? { ...this._data, properties: this._properties.toJson() } if (this._data.properties instanceof CollectionPropertiesObject) {
: this._data; json.properties = this._data.properties.toJson();
return clonePlain(json); }
return json;
} }
clone(): CollectionObject { clone(): CollectionObject {
return new CollectionObject().fromJson(this.toJson()); const cloned = new CollectionObject();
cloned._data = { ...this._data };
cloned._data.properties = this.properties.clone();
return cloned;
} }
/** Immutable Properties */ /** Immutable Properties */
@@ -55,16 +50,16 @@ export class CollectionObject implements CollectionModelInterface {
return this._data.provider; return this._data.provider;
} }
get service(): ServiceIdentifier { get service(): string | number {
return this._data.service as ServiceIdentifier; return this._data.service;
} }
get collection(): CollectionIdentifier | null { get collection(): string | number | null {
return this._data.collection as CollectionIdentifier | null; return this._data.collection;
} }
get identifier(): CollectionIdentifier { get identifier(): string | number {
return this._data.identifier as CollectionIdentifier; return this._data.identifier;
} }
get signature(): string | null | undefined { get signature(): string | null | undefined {
@@ -79,33 +74,37 @@ export class CollectionObject implements CollectionModelInterface {
return this._data.modified; return this._data.modified;
} }
/** Mutable Properties */
get properties(): CollectionPropertiesObject { get properties(): CollectionPropertiesObject {
if (this._properties) { if (this._data.properties instanceof CollectionPropertiesObject) {
return this._properties; return this._data.properties;
}
else if (this._data.properties) {
const properties = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface);
this._properties = properties;
return properties;
} }
if (this._data.properties) {
const hydrated = new CollectionPropertiesObject().fromJson(this._data.properties as CollectionPropertiesInterface);
this._data.properties = hydrated;
return hydrated;
}
return new CollectionPropertiesObject(); return new CollectionPropertiesObject();
} }
set properties(value: CollectionPropertiesObject) { set properties(value: CollectionPropertiesObject) {
this._properties = value; if (value instanceof CollectionPropertiesObject) {
this._data.properties = value as any;
} else {
this._data.properties = value;
}
} }
} }
export class CollectionPropertiesObject implements CollectionPropertiesModelInterface { export class CollectionPropertiesObject implements CollectionPropertiesInterface {
private _data!: CollectionPropertiesInterface; _data!: CollectionPropertiesInterface;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'people:addressbook', '@type': 'people:collection',
version: 1,
content: [], content: [],
label: '', label: '',
description: null, description: null,
@@ -116,22 +115,32 @@ export class CollectionPropertiesObject implements CollectionPropertiesModelInte
} }
fromJson(data: CollectionPropertiesInterface): CollectionPropertiesObject { fromJson(data: CollectionPropertiesInterface): CollectionPropertiesObject {
this._data = clonePlain(data); this._data = data;
return this; return this;
} }
toJson(): CollectionPropertiesInterface { toJson(): CollectionPropertiesInterface {
return clonePlain(this._data); return this._data;
} }
clone(): CollectionPropertiesObject { clone(): CollectionPropertiesObject {
return new CollectionPropertiesObject().fromJson(this.toJson()); const cloned = new CollectionPropertiesObject();
cloned._data = { ...this._data };
return cloned;
} }
/** Immutable Properties */ /** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get version(): number {
return this._data.version;
}
get content(): CollectionContentTypes[] { get content(): CollectionContentTypes[] {
return this._data.content ?? []; return this._data.content || [];
} }
/** Mutable Properties */ /** Mutable Properties */
@@ -176,4 +185,4 @@ export class CollectionPropertiesObject implements CollectionPropertiesModelInte
this._data.color = value; this._data.color = value;
} }
} }
+48 -45
View File
@@ -2,57 +2,64 @@
* Class model for Entity Interface * Class model for Entity Interface
*/ */
import type { EntityInterface, EntityModelInterface, EntityPropertiesInterface } from "@/types/entity"; import type { EntityInterface } from "@/types/entity";
import type { IndividualInterface } from "@/types/individual"; import type { IndividualInterface } from "@/types/individual";
import type { OrganizationInterface } from "@/types/organization"; import type { OrganizationInterface } from "@/types/organization";
import type { GroupInterface } from "@/types/group"; import type { GroupInterface } from "@/types/group";
import type { CollectionIdentifier, EntityIdentifier } from "@/types/common";
import { IndividualObject } from "./individual"; import { IndividualObject } from "./individual";
import { OrganizationObject } from "./organization"; import { OrganizationObject } from "./organization";
import { GroupObject } from "./group"; import { GroupObject } from "./group";
import { clonePlain } from './clone-plain';
export type EntityPropertiesObject = IndividualObject | OrganizationObject | GroupObject; export class EntityObject implements EntityInterface {
export class EntityObject implements EntityModelInterface {
private _data!: EntityInterface<EntityPropertiesInterface>;
private _properties: EntityPropertiesObject | undefined = undefined;
_data!: EntityInterface;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'people:entity',
version: 1,
provider: '', provider: '',
service: '', service: '',
collection: '' as CollectionIdentifier, collection: '',
identifier: '' as EntityIdentifier, identifier: '',
signature: null, signature: null,
created: null, created: null,
modified: null, modified: null,
properties: new IndividualObject().toJson(), properties: new IndividualObject(),
}; };
} }
fromJson(data: EntityInterface): EntityObject { fromJson(data: EntityInterface) : EntityObject {
this._data = clonePlain(data); this._data = data;
this._properties = undefined; if (data.properties) {
const type = data.properties.type;
if (type === 'organization') {
this._data.properties = new OrganizationObject().fromJson(data.properties as OrganizationInterface);
} else if (type === 'group') {
this._data.properties = new GroupObject().fromJson(data.properties as GroupInterface);
} else {
this._data.properties = new IndividualObject().fromJson(data.properties as IndividualInterface);
}
}
return this; return this;
} }
toJson(): EntityInterface { toJson(): EntityInterface {
const json = this._properties const json = { ...this._data };
? { ...this._data, properties: this._properties.toJson() } if (this._data.properties instanceof IndividualObject ||
: this._data; this._data.properties instanceof OrganizationObject ||
return clonePlain(json); this._data.properties instanceof GroupObject) {
json.properties = this._data.properties.toJson();
}
return json;
} }
clone(): EntityObject { clone(): EntityObject {
return new EntityObject().fromJson(this.toJson()); const cloned = new EntityObject();
cloned._data = { ...this._data };
return cloned;
} }
/** Metadata Properties */ /** Immutable Properties */
get provider(): string { get provider(): string {
return this._data.provider; return this._data.provider;
} }
@@ -61,11 +68,11 @@ export class EntityObject implements EntityModelInterface {
return this._data.service; return this._data.service;
} }
get collection(): CollectionIdentifier { get collection(): string | number {
return this._data.collection; return this._data.collection;
} }
get identifier(): EntityIdentifier { get identifier(): string | number {
return this._data.identifier; return this._data.identifier;
} }
@@ -81,24 +88,20 @@ export class EntityObject implements EntityModelInterface {
return this._data.modified; return this._data.modified;
} }
/** Entity Properties (individual | organization | group) */ get properties(): IndividualObject | OrganizationObject | GroupObject {
if (this._data.properties instanceof IndividualObject ||
get properties(): EntityPropertiesObject { this._data.properties instanceof OrganizationObject ||
if (this._properties) return this._properties; this._data.properties instanceof GroupObject) {
return this._data.properties;
const raw = this._data.properties;
if (raw.type === 'organization') {
this._properties = new OrganizationObject().fromJson(raw as OrganizationInterface);
} else if (raw.type === 'group') {
this._properties = new GroupObject().fromJson(raw as GroupInterface);
} else {
this._properties = new IndividualObject().fromJson(raw as IndividualInterface);
} }
return this._properties; const defaultProperties = new IndividualObject();
this._data.properties = defaultProperties;
return defaultProperties;
} }
set properties(value: EntityPropertiesObject) { set properties(value: IndividualObject | OrganizationObject | GroupObject) {
this._properties = value; this._data.properties = value;
} }
}
}
+85 -207
View File
@@ -1,5 +1,5 @@
/** /**
* Identity implementation classes for People Manager services * Identity implementation classes for Mail Manager services
*/ */
import type { import type {
@@ -10,55 +10,13 @@ import type {
ServiceIdentityOAuth, ServiceIdentityOAuth,
ServiceIdentityCertificate ServiceIdentityCertificate
} from '@/types/service'; } from '@/types/service';
import { MutationProxy } from './mutation-proxy';
import { clonePlain } from './clone-plain';
/** /**
* Base Identity class * Base Identity class
*/ */
export abstract class Identity<T extends ServiceIdentity = ServiceIdentity> { export abstract class Identity {
protected _original: T; abstract toJson(): ServiceIdentity;
protected _mutated: Partial<T>;
protected _mutationProxy: MutationProxy<T>;
protected _data: T;
protected constructor(initial: T) {
this._original = clonePlain(initial);
this._mutated = {};
this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated);
this._data = this._mutationProxy.create();
}
protected load(data: T): this {
this._original = clonePlain(data);
this._mutated = {};
this._data = this._mutationProxy.create();
return this;
}
toJSON(): ServiceIdentity {
return this.toJson();
}
toJson(): T;
toJson(delta: true): Partial<T>;
toJson(delta?: boolean): T | Partial<T> {
if (delta) {
return clonePlain(this._mutated);
}
return {
...clonePlain(this._original),
...clonePlain(this._mutated),
};
}
abstract clone(): Identity;
mutated(): boolean {
return Reflect.ownKeys(this._mutated).length > 0;
}
static fromJson(data: ServiceIdentity): Identity { static fromJson(data: ServiceIdentity): Identity {
switch (data.type) { switch (data.type) {
case 'NA': case 'NA':
@@ -80,109 +38,81 @@ export abstract class Identity<T extends ServiceIdentity = ServiceIdentity> {
/** /**
* No authentication * No authentication
*/ */
export class IdentityNone extends Identity<ServiceIdentityNone> { export class IdentityNone extends Identity {
readonly type = 'NA' as const;
constructor() {
super({
type: 'NA'
});
}
static fromJson(_data: ServiceIdentityNone): IdentityNone { static fromJson(_data: ServiceIdentityNone): IdentityNone {
return new IdentityNone(); return new IdentityNone();
} }
clone(): IdentityNone { toJson(): ServiceIdentityNone {
return IdentityNone.fromJson(this.toJson()); return {
type: this.type
};
} }
get type(): 'NA' {
return this._data.type;
}
} }
/** /**
* Basic authentication (username/password) * Basic authentication (username/password)
*/ */
export class IdentityBasic extends Identity<ServiceIdentityBasic> { export class IdentityBasic extends Identity {
readonly type = 'BA' as const;
identity: string;
secret: string;
constructor(identity: string = '', secret: string = '') { constructor(identity: string = '', secret: string = '') {
super({ super();
type: 'BA', this.identity = identity;
identity, this.secret = secret;
secret
});
} }
static fromJson(data: ServiceIdentityBasic): IdentityBasic { static fromJson(data: ServiceIdentityBasic): IdentityBasic {
return new IdentityBasic().load(data); return new IdentityBasic(data.identity, data.secret);
} }
clone(): IdentityBasic { toJson(): ServiceIdentityBasic {
return IdentityBasic.fromJson(this.toJson()); return {
type: this.type,
identity: this.identity,
secret: this.secret
};
} }
get type(): 'BA' {
return this._data.type;
}
get identity(): string {
return this._data.identity;
}
set identity(value: string) {
this._data.identity = value;
}
get secret(): string {
return this._data.secret;
}
set secret(value: string) {
this._data.secret = value;
}
} }
/** /**
* Token authentication (API key, static token) * Token authentication (API key, static token)
*/ */
export class IdentityToken extends Identity<ServiceIdentityToken> { export class IdentityToken extends Identity {
readonly type = 'TA' as const;
token: string;
constructor(token: string = '') { constructor(token: string = '') {
super({ super();
type: 'TA', this.token = token;
token
});
} }
static fromJson(data: ServiceIdentityToken): IdentityToken { static fromJson(data: ServiceIdentityToken): IdentityToken {
return new IdentityToken().load(data); return new IdentityToken(data.token);
} }
clone(): IdentityToken { toJson(): ServiceIdentityToken {
return IdentityToken.fromJson(this.toJson()); return {
type: this.type,
token: this.token
};
} }
get type(): 'TA' {
return this._data.type;
}
get token(): string {
return this._data.token;
}
set token(value: string) {
this._data.token = value;
}
} }
/** /**
* OAuth authentication * OAuth authentication
*/ */
export class IdentityOAuth extends Identity<ServiceIdentityOAuth> { export class IdentityOAuth extends Identity {
readonly type = 'OA' as const;
accessToken: string;
accessScope?: string[];
accessExpiry?: number;
refreshToken?: string;
refreshLocation?: string;
constructor( constructor(
accessToken: string = '', accessToken: string = '',
@@ -191,22 +121,33 @@ export class IdentityOAuth extends Identity<ServiceIdentityOAuth> {
refreshToken?: string, refreshToken?: string,
refreshLocation?: string refreshLocation?: string
) { ) {
super({ super();
type: 'OA', this.accessToken = accessToken;
accessToken, this.accessScope = accessScope;
accessScope, this.accessExpiry = accessExpiry;
accessExpiry, this.refreshToken = refreshToken;
refreshToken, this.refreshLocation = refreshLocation;
refreshLocation
});
} }
static fromJson(data: ServiceIdentityOAuth): IdentityOAuth { static fromJson(data: ServiceIdentityOAuth): IdentityOAuth {
return new IdentityOAuth().load(data); return new IdentityOAuth(
data.accessToken,
data.accessScope,
data.accessExpiry,
data.refreshToken,
data.refreshLocation
);
} }
clone(): IdentityOAuth { toJson(): ServiceIdentityOAuth {
return IdentityOAuth.fromJson(this.toJson()); return {
type: this.type,
accessToken: this.accessToken,
...(this.accessScope && { accessScope: this.accessScope }),
...(this.accessExpiry && { accessExpiry: this.accessExpiry }),
...(this.refreshToken && { refreshToken: this.refreshToken }),
...(this.refreshLocation && { refreshLocation: this.refreshLocation })
};
} }
isExpired(): boolean { isExpired(): boolean {
@@ -218,101 +159,38 @@ export class IdentityOAuth extends Identity<ServiceIdentityOAuth> {
if (!this.accessExpiry) return Infinity; if (!this.accessExpiry) return Infinity;
return Math.max(0, this.accessExpiry - Date.now() / 1000); return Math.max(0, this.accessExpiry - Date.now() / 1000);
} }
get type(): 'OA' {
return this._data.type;
}
get accessToken(): string {
return this._data.accessToken;
}
set accessToken(value: string) {
this._data.accessToken = value;
}
get accessScope(): string[] | undefined {
return this._data.accessScope ? [...this._data.accessScope] : undefined;
}
set accessScope(value: string[] | undefined) {
this._data.accessScope = value ? [...value] : undefined;
}
get accessExpiry(): number | undefined {
return this._data.accessExpiry;
}
set accessExpiry(value: number | undefined) {
this._data.accessExpiry = value;
}
get refreshToken(): string | undefined {
return this._data.refreshToken;
}
set refreshToken(value: string | undefined) {
this._data.refreshToken = value;
}
get refreshLocation(): string | undefined {
return this._data.refreshLocation;
}
set refreshLocation(value: string | undefined) {
this._data.refreshLocation = value;
}
} }
/** /**
* Client certificate authentication (mTLS) * Client certificate authentication (mTLS)
*/ */
export class IdentityCertificate extends Identity<ServiceIdentityCertificate> { export class IdentityCertificate extends Identity {
readonly type = 'CC' as const;
certificate: string;
privateKey: string;
passphrase?: string;
constructor(certificate: string = '', privateKey: string = '', passphrase?: string) { constructor(certificate: string = '', privateKey: string = '', passphrase?: string) {
super({ super();
type: 'CC', this.certificate = certificate;
certificate, this.privateKey = privateKey;
privateKey, this.passphrase = passphrase;
passphrase
});
} }
static fromJson(data: ServiceIdentityCertificate): IdentityCertificate { static fromJson(data: ServiceIdentityCertificate): IdentityCertificate {
return new IdentityCertificate().load(data); return new IdentityCertificate(
data.certificate,
data.privateKey,
data.passphrase
);
} }
clone(): IdentityCertificate { toJson(): ServiceIdentityCertificate {
return IdentityCertificate.fromJson(this.toJson()); return {
type: this.type,
certificate: this.certificate,
privateKey: this.privateKey,
...(this.passphrase && { passphrase: this.passphrase })
};
} }
get type(): 'CC' {
return this._data.type;
}
get certificate(): string {
return this._data.certificate;
}
set certificate(value: string) {
this._data.certificate = value;
}
get privateKey(): string {
return this._data.privateKey;
}
set privateKey(value: string) {
this._data.privateKey = value;
}
get passphrase(): string | undefined {
return this._data.passphrase;
}
set passphrase(value: string | undefined) {
this._data.passphrase = value;
}
} }
+1 -20
View File
@@ -1,26 +1,7 @@
export { ProviderObject } from './provider'; export { ProviderObject } from './provider';
export { ServiceObject } from './service'; export { ServiceObject } from './service';
export { export { CollectionObject } from './collection';
CollectionObject,
CollectionPropertiesObject
} from './collection';
export { EntityObject } from './entity'; export { EntityObject } from './entity';
export { GroupObject } from './group'; export { GroupObject } from './group';
export { IndividualObject } from './individual'; export { IndividualObject } from './individual';
export { OrganizationObject } from './organization'; export { OrganizationObject } from './organization';
export {
Identity,
IdentityNone,
IdentityBasic,
IdentityToken,
IdentityOAuth,
IdentityCertificate
} from './identity';
export {
Location,
LocationUri,
LocationFile
} from './location';
export {
MutationProxy
} from './mutation-proxy';
+170 -122
View File
@@ -1,61 +1,29 @@
/** /**
* Location implementation classes for People Manager services * Location implementation classes for Mail Manager services
*/ */
import type { import type {
ServiceLocation, ServiceLocation,
ServiceLocationUri, ServiceLocationUri,
ServiceLocationSocketSole,
ServiceLocationSocketSplit,
ServiceLocationFile ServiceLocationFile
} from '@/types/service'; } from '@/types/service';
import { MutationProxy } from './mutation-proxy';
import { clonePlain } from './clone-plain';
/** /**
* Base Location class * Base Location class
*/ */
export abstract class Location<T extends ServiceLocation = ServiceLocation> { export abstract class Location {
protected _original: T; abstract toJson(): ServiceLocation;
protected _mutated: Partial<T>;
protected _mutationProxy: MutationProxy<T>;
protected _data: T;
protected constructor(initial: T) {
this._original = clonePlain(initial);
this._mutated = {};
this._mutationProxy = new MutationProxy<T>(() => this._original, () => this._mutated);
this._data = this._mutationProxy.create();
}
protected load(data: T): this {
this._original = clonePlain(data);
this._mutated = {};
this._data = this._mutationProxy.create();
return this;
}
toJson(): T;
toJson(delta: true): Partial<T>;
toJson(delta?: boolean): T | Partial<T> {
if (delta) {
return clonePlain(this._mutated);
}
return {
...clonePlain(this._original),
...clonePlain(this._mutated),
};
}
abstract clone(): Location;
mutated(): boolean {
return Reflect.ownKeys(this._mutated).length > 0;
}
static fromJson(data: ServiceLocation): Location { static fromJson(data: ServiceLocation): Location {
switch (data.type) { switch (data.type) {
case 'URI': case 'URI':
return LocationUri.fromJson(data); return LocationUri.fromJson(data);
case 'SOCKET_SOLE':
return LocationSocketSole.fromJson(data);
case 'SOCKET_SPLIT':
return LocationSocketSplit.fromJson(data);
case 'FILE': case 'FILE':
return LocationFile.fromJson(data); return LocationFile.fromJson(data);
default: default:
@@ -66,9 +34,16 @@ export abstract class Location<T extends ServiceLocation = ServiceLocation> {
/** /**
* URI-based service location for API and web services * URI-based service location for API and web services
* Used by: CardDAV, Google People API, etc. * Used by: JMAP, Gmail API, etc.
*/ */
export class LocationUri extends Location<ServiceLocationUri> { export class LocationUri extends Location {
readonly type = 'URI' as const;
scheme: string;
host: string;
port: number;
path?: string;
verifyPeer: boolean;
verifyHost: boolean;
constructor( constructor(
scheme: string = 'https', scheme: string = 'https',
@@ -78,115 +53,188 @@ export class LocationUri extends Location<ServiceLocationUri> {
verifyPeer: boolean = true, verifyPeer: boolean = true,
verifyHost: boolean = true verifyHost: boolean = true
) { ) {
super({ super();
type: 'URI', this.scheme = scheme;
scheme, this.host = host;
host, this.port = port;
port, this.path = path;
...(path !== undefined && { path }), this.verifyPeer = verifyPeer;
verifyPeer, this.verifyHost = verifyHost;
verifyHost,
});
} }
static fromJson(data: ServiceLocationUri): LocationUri { static fromJson(data: ServiceLocationUri): LocationUri {
return new LocationUri().load(data); return new LocationUri(
data.scheme,
data.host,
data.port,
data.path,
data.verifyPeer ?? true,
data.verifyHost ?? true
);
}
toJson(): ServiceLocationUri {
return {
type: this.type,
scheme: this.scheme,
host: this.host,
port: this.port,
...(this.path && { path: this.path }),
...(this.verifyPeer !== undefined && { verifyPeer: this.verifyPeer }),
...(this.verifyHost !== undefined && { verifyHost: this.verifyHost })
};
} }
getUrl(): string { getUrl(): string {
const path = this.path || ''; const path = this.path || '';
return `${this.scheme}://${this.host}:${this.port}${path}`; return `${this.scheme}://${this.host}:${this.port}${path}`;
} }
}
clone(): LocationUri { /**
return LocationUri.fromJson(structuredClone(this.toJson())); * Single socket-based service location
* Used by: services using a single host/port combination
*/
export class LocationSocketSole extends Location {
readonly type = 'SOCKET_SOLE' as const;
host: string;
port: number;
encryption: 'none' | 'ssl' | 'tls' | 'starttls';
verifyPeer: boolean;
verifyHost: boolean;
constructor(
host: string = '',
port: number = 993,
encryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
verifyPeer: boolean = true,
verifyHost: boolean = true
) {
super();
this.host = host;
this.port = port;
this.encryption = encryption;
this.verifyPeer = verifyPeer;
this.verifyHost = verifyHost;
} }
get type(): 'URI' { static fromJson(data: ServiceLocationSocketSole): LocationSocketSole {
return this._data.type; return new LocationSocketSole(
data.host,
data.port,
data.encryption,
data.verifyPeer ?? true,
data.verifyHost ?? true
);
} }
get scheme(): string { toJson(): ServiceLocationSocketSole {
return this._data.scheme; return {
type: this.type,
host: this.host,
port: this.port,
encryption: this.encryption,
...(this.verifyPeer !== undefined && { verifyPeer: this.verifyPeer }),
...(this.verifyHost !== undefined && { verifyHost: this.verifyHost })
};
}
}
/**
* Split socket-based service location
* Used by: traditional IMAP/SMTP configurations
*/
export class LocationSocketSplit extends Location {
readonly type = 'SOCKET_SPLIT' as const;
inboundHost: string;
inboundPort: number;
inboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls';
outboundHost: string;
outboundPort: number;
outboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls';
inboundVerifyPeer: boolean;
inboundVerifyHost: boolean;
outboundVerifyPeer: boolean;
outboundVerifyHost: boolean;
constructor(
inboundHost: string = '',
inboundPort: number = 993,
inboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
outboundHost: string = '',
outboundPort: number = 465,
outboundEncryption: 'none' | 'ssl' | 'tls' | 'starttls' = 'ssl',
inboundVerifyPeer: boolean = true,
inboundVerifyHost: boolean = true,
outboundVerifyPeer: boolean = true,
outboundVerifyHost: boolean = true
) {
super();
this.inboundHost = inboundHost;
this.inboundPort = inboundPort;
this.inboundEncryption = inboundEncryption;
this.outboundHost = outboundHost;
this.outboundPort = outboundPort;
this.outboundEncryption = outboundEncryption;
this.inboundVerifyPeer = inboundVerifyPeer;
this.inboundVerifyHost = inboundVerifyHost;
this.outboundVerifyPeer = outboundVerifyPeer;
this.outboundVerifyHost = outboundVerifyHost;
} }
set scheme(value: string) { static fromJson(data: ServiceLocationSocketSplit): LocationSocketSplit {
this._data.scheme = value; return new LocationSocketSplit(
data.inboundHost,
data.inboundPort,
data.inboundEncryption,
data.outboundHost,
data.outboundPort,
data.outboundEncryption,
data.inboundVerifyPeer ?? true,
data.inboundVerifyHost ?? true,
data.outboundVerifyPeer ?? true,
data.outboundVerifyHost ?? true
);
} }
get host(): string { toJson(): ServiceLocationSocketSplit {
return this._data.host; return {
type: this.type,
inboundHost: this.inboundHost,
inboundPort: this.inboundPort,
inboundEncryption: this.inboundEncryption,
outboundHost: this.outboundHost,
outboundPort: this.outboundPort,
outboundEncryption: this.outboundEncryption,
...(this.inboundVerifyPeer !== undefined && { inboundVerifyPeer: this.inboundVerifyPeer }),
...(this.inboundVerifyHost !== undefined && { inboundVerifyHost: this.inboundVerifyHost }),
...(this.outboundVerifyPeer !== undefined && { outboundVerifyPeer: this.outboundVerifyPeer }),
...(this.outboundVerifyHost !== undefined && { outboundVerifyHost: this.outboundVerifyHost })
};
} }
set host(value: string) {
this._data.host = value;
}
get port(): number {
return this._data.port;
}
set port(value: number) {
this._data.port = value;
}
get path(): string | undefined {
return this._data.path;
}
set path(value: string | undefined) {
this._data.path = value;
}
get verifyPeer(): boolean {
return this._data.verifyPeer ?? true;
}
set verifyPeer(value: boolean) {
this._data.verifyPeer = value;
}
get verifyHost(): boolean {
return this._data.verifyHost ?? true;
}
set verifyHost(value: boolean) {
this._data.verifyHost = value;
}
} }
/** /**
* File-based service location * File-based service location
* Used by: local file system providers * Used by: local file system providers
*/ */
export class LocationFile extends Location<ServiceLocationFile> { export class LocationFile extends Location {
readonly type = 'FILE' as const;
path: string;
constructor(path: string = '') { constructor(path: string = '') {
super({ super();
type: 'FILE', this.path = path;
path,
});
} }
static fromJson(data: ServiceLocationFile): LocationFile { static fromJson(data: ServiceLocationFile): LocationFile {
return new LocationFile().load(data); return new LocationFile(data.path);
} }
clone(): LocationFile { toJson(): ServiceLocationFile {
return LocationFile.fromJson(structuredClone(this.toJson())); return {
type: this.type,
path: this.path
};
} }
get type(): 'FILE' {
return this._data.type;
}
get path(): string {
return this._data.path;
}
set path(value: string) {
this._data.path = value;
}
} }
-61
View File
@@ -1,61 +0,0 @@
import { clonePlain } from './clone-plain';
export class MutationProxy<T extends object> {
private readonly getOriginal: () => T;
private readonly getMutated: () => Partial<T>;
constructor(
getOriginal: () => T,
getMutated: () => Partial<T>,
) {
this.getOriginal = getOriginal;
this.getMutated = getMutated;
}
create(): T {
return new Proxy({} as T, {
get: (_target, prop: string | symbol) => {
if (typeof prop !== 'string') {
return undefined;
}
const key = prop as keyof T;
const mutated = this.getMutated();
const original = this.getOriginal();
return key in mutated ? mutated[key] : original[key];
},
set: (_target, prop: string | symbol, value: unknown) => {
if (typeof prop === 'string') {
const key = prop as keyof T;
(this.getMutated() as Record<keyof T, unknown>)[key] = clonePlain(value);
}
return true;
},
has: (_target, prop: string | symbol) => {
if (typeof prop !== 'string') {
return false;
}
const mutated = this.getMutated();
const original = this.getOriginal();
return prop in mutated || prop in original;
},
ownKeys: () => {
const mutated = this.getMutated();
const original = this.getOriginal();
return Array.from(new Set([
...Reflect.ownKeys(original),
...Reflect.ownKeys(mutated),
]));
},
getOwnPropertyDescriptor: () => ({
enumerable: true,
configurable: true,
}),
});
}
}
+10 -13
View File
@@ -2,21 +2,18 @@
* Class model for Provider Interface * Class model for Provider Interface
*/ */
import type { import type {
ProviderInterface, ProviderInterface,
ProviderCapabilitiesInterface, ProviderCapabilitiesInterface
ProviderModelInterface
} from "@/types/provider"; } from "@/types/provider";
import { clonePlain } from './clone-plain';
export class ProviderObject implements ProviderModelInterface { export class ProviderObject implements ProviderInterface {
_data!: ProviderInterface; _data!: ProviderInterface;
constructor() { constructor() {
this._data = { this._data = {
'@type': 'people:provider', '@type': 'people:provider',
version: 1,
identifier: '', identifier: '',
label: '', label: '',
capabilities: {}, capabilities: {},
@@ -24,16 +21,12 @@ export class ProviderObject implements ProviderModelInterface {
} }
fromJson(data: ProviderInterface): ProviderObject { fromJson(data: ProviderInterface): ProviderObject {
this._data = clonePlain(data); this._data = data;
return this; return this;
} }
toJson(): ProviderInterface { toJson(): ProviderInterface {
return clonePlain(this._data); return this._data;
}
clone(): ProviderObject {
return new ProviderObject().fromJson(this.toJson());
} }
capable(capability: keyof ProviderCapabilitiesInterface): boolean { capable(capability: keyof ProviderCapabilitiesInterface): boolean {
@@ -50,6 +43,10 @@ export class ProviderObject implements ProviderModelInterface {
/** Immutable Properties */ /** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get identifier(): string { get identifier(): string {
return this._data.identifier; return this._data.identifier;
} }
@@ -59,7 +56,7 @@ export class ProviderObject implements ProviderModelInterface {
} }
get capabilities(): ProviderCapabilitiesInterface { get capabilities(): ProviderCapabilitiesInterface {
return clonePlain(this._data.capabilities); return this._data.capabilities;
} }
} }
+40 -89
View File
@@ -5,85 +5,34 @@
import type { import type {
ServiceInterface, ServiceInterface,
ServiceCapabilitiesInterface, ServiceCapabilitiesInterface,
ServiceLocation, ServiceIdentity,
ServiceModelInterface ServiceLocation
} from "@/types/service"; } from "@/types/service";
import { Identity } from './identity'; import { Identity } from './identity';
import { Location } from './location'; import { Location } from './location';
import { MutationProxy } from './mutation-proxy';
import { clonePlain } from './clone-plain';
export class ServiceObject implements ServiceModelInterface { export class ServiceObject implements ServiceInterface {
private _original: ServiceInterface;
private _mutated: Partial<ServiceInterface>;
private _mutationProxy = new MutationProxy<ServiceInterface>(() => this._original, () => this._mutated);
_data!: ServiceInterface; _data!: ServiceInterface;
_location: Location | null | undefined = undefined;
_identity: Identity | null | undefined = undefined;
constructor() { constructor() {
this._original = { this._data = {
'@type': 'people:service', '@type': 'people:service',
version: 1,
provider: '', provider: '',
identifier: null, identifier: null,
label: null, label: null,
enabled: false, enabled: false,
capabilities: {} capabilities: {}
}; };
this._mutated = {};
this._data = this._mutationProxy.create();
} }
fromJson(data: ServiceInterface): ServiceObject { fromJson(data: ServiceInterface): ServiceObject {
this._original = clonePlain(data); this._data = data;
this._mutated = {};
this._data = this._mutationProxy.create();
this._location = undefined;
this._identity = undefined;
return this; return this;
} }
toJson(): ServiceInterface; toJson(): ServiceInterface {
toJson(delta: true): Partial<ServiceInterface>; return this._data;
toJson(delta?: boolean): ServiceInterface | Partial<ServiceInterface> {
if (delta) {
const json: Partial<ServiceInterface> = clonePlain(this._mutated);
if (this._location?.mutated()) {
json.location = this._location.toJson(true) as ServiceInterface['location'];
}
if (this._identity?.mutated()) {
json.identity = this._identity.toJson(true) as ServiceInterface['identity'];
}
return json;
}
const json: ServiceInterface = {
...clonePlain(this._original),
...clonePlain(this._mutated),
};
if (this._location !== undefined) {
json.location = this._location ? this._location.toJson() : null;
}
if (this._identity !== undefined) {
json.identity = this._identity ? this._identity.toJson() : null;
}
return json;
}
clone(): ServiceObject {
return new ServiceObject().fromJson(this.toJson());
}
mutated(): boolean {
return Reflect.ownKeys(this._mutated).length > 0 || (this._location?.mutated() ?? false) || (this._identity?.mutated() ?? false);
} }
capable(capability: keyof ServiceCapabilitiesInterface): boolean { capable(capability: keyof ServiceCapabilitiesInterface): boolean {
@@ -100,6 +49,10 @@ export class ServiceObject implements ServiceModelInterface {
/** Immutable Properties */ /** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get provider(): string { get provider(): string {
return this._data.provider; return this._data.provider;
} }
@@ -108,8 +61,8 @@ export class ServiceObject implements ServiceModelInterface {
return this._data.identifier; return this._data.identifier;
} }
get capabilities(): ServiceCapabilitiesInterface { get capabilities(): ServiceCapabilitiesInterface | undefined {
return this._data.capabilities ?? {}; return this._data.capabilities;
} }
/** Mutable Properties */ /** Mutable Properties */
@@ -130,48 +83,46 @@ export class ServiceObject implements ServiceModelInterface {
this._data.enabled = value; this._data.enabled = value;
} }
get location(): Location | null { get location(): ServiceLocation | null {
if (this._location !== undefined) { return this._data.location ?? null;
return this._location;
}
if (this._data.location) {
this._location = Location.fromJson(this._data.location as ServiceLocation);
return this._location;
}
this._location = null;
return null;
} }
set location(value: Location | null) { set location(value: ServiceLocation | null) {
this._location = value; this._data.location = value;
} }
get identity(): Identity | null { get identity(): ServiceIdentity | null {
if (this._identity !== undefined) { return this._data.identity ?? null;
return this._identity;
}
if (this._data.identity) {
this._identity = Identity.fromJson(this._data.identity);
return this._identity;
}
this._identity = null;
return null;
} }
set identity(value: Identity | null) { set identity(value: ServiceIdentity | null) {
this._identity = value; this._data.identity = value;
} }
get auxiliary(): Record<string, any> { get auxiliary(): Record<string, any> {
return this._data.auxiliary ?? {}; return this._data.auxiliary ?? {};
} }
set auxiliary(value: Record<string, any>) { set auxiliary(value: Record<string, any>) {
this._data.auxiliary = value; this._data.auxiliary = value;
} }
/** Helper Methods */
/**
* Get identity as a class instance for easier manipulation
*/
getIdentity(): Identity | null {
if (!this._data.identity) return null;
return Identity.fromJson(this._data.identity);
}
/**
* Get location as a class instance for easier manipulation
*/
getLocation(): Location | null {
if (!this._data.location) return null;
return Location.fromJson(this._data.location);
}
} }
+4 -17
View File
@@ -70,16 +70,9 @@ export const collectionService = {
* *
* @returns Promise with collection object * @returns Promise with collection object
*/ */
async fetch(request: CollectionFetchRequest): Promise<Record<string, CollectionObject>> { async fetch(request: CollectionFetchRequest): Promise<CollectionObject> {
const response = await transceivePost<CollectionFetchRequest, CollectionFetchResponse>('collection.fetch', request); const response = await transceivePost<CollectionFetchRequest, CollectionFetchResponse>('collection.fetch', request);
return createCollectionObject(response);
// Convert response to CollectionObject instances
const list: Record<string, CollectionObject> = {};
Object.entries(response).forEach(([, collection]) => {
list[collection.identifier] = createCollectionObject(collection);
});
return list;
}, },
/** /**
@@ -130,14 +123,8 @@ export const collectionService = {
* *
* @returns Promise with deletion result * @returns Promise with deletion result
*/ */
async delete(request: CollectionDeleteRequest): Promise<boolean | CollectionObject> { async delete(request: CollectionDeleteRequest): Promise<CollectionDeleteResponse> {
const response = await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request); return await transceivePost<CollectionDeleteRequest, CollectionDeleteResponse>('collection.delete', request);
if (response.disposition === 'moved' && response.mutation) {
return createCollectionObject(response.mutation);
}
return true;
}, },
}; };
+31 -91
View File
@@ -2,12 +2,10 @@
* Entity management service * Entity management service
*/ */
import { transceivePost, transceiveStream } from './transceive'; import { transceivePost } from './transceive';
import type { import type {
EntityListBulkRequest, EntityListRequest,
EntityListBulkResponse, EntityListResponse,
EntityListStreamRequest,
EntityListStreamResponse,
EntityFetchRequest, EntityFetchRequest,
EntityFetchResponse, EntityFetchResponse,
EntityExtantRequest, EntityExtantRequest,
@@ -20,10 +18,6 @@ import type {
EntityDeleteResponse, EntityDeleteResponse,
EntityDeltaRequest, EntityDeltaRequest,
EntityDeltaResponse, EntityDeltaResponse,
EntityMoveRequest,
EntityMoveResponse,
EntityImportRequest,
EntityImportResponse,
EntityInterface, EntityInterface,
} from '../types/entity'; } from '../types/entity';
import { useIntegrationStore } from '@KTXC/stores/integrationStore'; import { useIntegrationStore } from '@KTXC/stores/integrationStore';
@@ -37,7 +31,7 @@ function createEntityObject(data: EntityInterface): EntityObject {
const integrationStore = useIntegrationStore(); const integrationStore = useIntegrationStore();
const factoryItem = integrationStore.getItemById('people_entity_factory', data.provider) as any; const factoryItem = integrationStore.getItemById('people_entity_factory', data.provider) as any;
const factory = factoryItem?.factory; const factory = factoryItem?.factory;
// Use provider factory if available, otherwise base class // Use provider factory if available, otherwise base class
return factory ? factory(data) : new EntityObject().fromJson(data); return factory ? factory(data) : new EntityObject().fromJson(data);
} }
@@ -45,15 +39,15 @@ function createEntityObject(data: EntityInterface): EntityObject {
export const entityService = { export const entityService = {
/** /**
* Retrieve list of entities, optionally filtered by source collection identifiers * Retrieve list of entities, optionally filtered by source selector
* *
* @param request - list request parameters * @param request - list request parameters
* *
* @returns Promise with entity object list grouped by provider, service, collection, and entity identifier * @returns Promise with entity object list grouped by provider, service, collection, and entity identifier
*/ */
async listBulk(request: EntityListBulkRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> { async list(request: EntityListRequest = {}): Promise<Record<string, Record<string, Record<string, Record<string, EntityObject>>>>> {
const response = await transceivePost<EntityListBulkRequest, EntityListBulkResponse>('entity.listBulk', request); const response = await transceivePost<EntityListRequest, EntityListResponse>('entity.list', request);
// Convert nested response to EntityObject instances // Convert nested response to EntityObject instances
const providerList: Record<string, Record<string, Record<string, Record<string, EntityObject>>>> = {}; const providerList: Record<string, Record<string, Record<string, Record<string, EntityObject>>>> = {};
Object.entries(response).forEach(([providerId, providerServices]) => { Object.entries(response).forEach(([providerId, providerServices]) => {
@@ -71,55 +65,34 @@ export const entityService = {
}); });
providerList[providerId] = serviceList; providerList[providerId] = serviceList;
}); });
return providerList; return providerList;
}, },
/**
* Stream entities as NDJSON, invoking onEntity for each entity as it arrives.
*
* The server emits one entity per line so the caller receives entities
* progressively rather than waiting for the full collection to load.
*
* @param request - stream request parameters (same shape as list)
* @param onEntity - called synchronously for each entity as it is received
*
* @returns Promise resolving to { total } when the stream completes
*/
async listStream(request: EntityListStreamRequest, onEntity: (entity: EntityObject) => void): Promise<{ total: number }> {
return await transceiveStream<EntityListStreamRequest, EntityListStreamResponse>(
'entity.listStream',
request,
(entity) => {
onEntity(createEntityObject(entity));
}
);
},
/** /**
* Retrieve a specific entity by provider and identifier * Retrieve a specific entity by provider and identifier
* *
* @param request - fetch request parameters * @param request - fetch request parameters
* *
* @returns Promise with entity objects keyed by identifier * @returns Promise with entity objects keyed by identifier
*/ */
async fetch(request: EntityFetchRequest): Promise<Record<string, EntityObject>> { async fetch(request: EntityFetchRequest): Promise<Record<string, EntityObject>> {
const response = await transceivePost<EntityFetchRequest, EntityFetchResponse>('entity.fetch', request); const response = await transceivePost<EntityFetchRequest, EntityFetchResponse>('entity.fetch', request);
// Convert response to EntityObject instances // Convert response to EntityObject instances
const list: Record<string, EntityObject> = {}; const list: Record<string, EntityObject> = {};
Object.entries(response).forEach(([, entity]) => { Object.entries(response).forEach(([identifier, entityData]) => {
list[entity.identifier] = createEntityObject(entity); list[identifier] = createEntityObject(entityData);
}); });
return list; return list;
}, },
/** /**
* Retrieve entity availability status for a given set of entity identifiers * Retrieve entity availability status for a given source selector
* *
* @param request - extant request parameters * @param request - extant request parameters
* *
* @returns Promise with entity availability status * @returns Promise with entity availability status
*/ */
async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> { async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> {
@@ -128,9 +101,9 @@ export const entityService = {
/** /**
* Create a new entity * Create a new entity
* *
* @param request - create request parameters * @param request - create request parameters
* *
* @returns Promise with created entity object * @returns Promise with created entity object
*/ */
async create(request: EntityCreateRequest): Promise<EntityObject> { async create(request: EntityCreateRequest): Promise<EntityObject> {
@@ -140,9 +113,9 @@ export const entityService = {
/** /**
* Update an existing entity * Update an existing entity
* *
* @param request - update request parameters * @param request - update request parameters
* *
* @returns Promise with updated entity object * @returns Promise with updated entity object
*/ */
async update(request: EntityUpdateRequest): Promise<EntityObject> { async update(request: EntityUpdateRequest): Promise<EntityObject> {
@@ -151,11 +124,11 @@ export const entityService = {
}, },
/** /**
* Delete entities by their identifiers * Delete an entity
* *
* @param request - delete request parameters * @param request - delete request parameters
* *
* @returns Promise with deletion results keyed by source entity identifier * @returns Promise with deletion result
*/ */
async delete(request: EntityDeleteRequest): Promise<EntityDeleteResponse> { async delete(request: EntityDeleteRequest): Promise<EntityDeleteResponse> {
return await transceivePost<EntityDeleteRequest, EntityDeleteResponse>('entity.delete', request); return await transceivePost<EntityDeleteRequest, EntityDeleteResponse>('entity.delete', request);
@@ -163,48 +136,15 @@ export const entityService = {
/** /**
* Retrieve delta changes for entities * Retrieve delta changes for entities
* *
* @param request - delta request parameters * @param request - delta request parameters
* *
* @returns Promise with delta changes (additions, modifications, deletions) * @returns Promise with delta changes (created, modified, deleted)
*/ */
async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> { async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> {
return await transceivePost<EntityDeltaRequest, EntityDeltaResponse>('entity.delta', request); return await transceivePost<EntityDeltaRequest, EntityDeltaResponse>('entity.delta', request);
}, },
/**
* Move entities to a target collection
*
* @param request - move request parameters
*
* @returns Promise with move results keyed by source entity identifier
*/
async move(request: EntityMoveRequest): Promise<EntityMoveResponse> {
return await transceivePost<EntityMoveRequest, EntityMoveResponse>('entity.move', request);
},
/**
* Import vCards into a collection, streaming progress as it arrives.
*
* @param request - import request (target collection, raw data, options)
* @param onObject - called synchronously for each per-contact result frame
* @param onDiscovered - called once with the discovered total (progress denominator)
*
* @returns Promise resolving to { total } (objects processed) when the stream completes
*/
async import(
request: EntityImportRequest,
onObject: (object: EntityImportResponse) => void,
onDiscovered: (expected: number) => void,
): Promise<{ total: number }> {
return await transceiveStream<EntityImportRequest, EntityImportResponse>(
'entity.import',
request,
onObject,
{ onStart: (expected) => { if (expected !== undefined) onDiscovered(expected); } },
);
},
}; };
export default entityService; export default entityService;
+2 -91
View File
@@ -4,7 +4,7 @@
*/ */
import { createFetchWrapper } from '@KTXC'; import { createFetchWrapper } from '@KTXC';
import type { ApiRequest, ApiResponse, ApiStreamResponse } from '../types/common'; import type { ApiRequest, ApiResponse } from '../types/common';
const fetchWrapper = createFetchWrapper(); const fetchWrapper = createFetchWrapper();
const API_URL = '/m/people_manager/v1'; const API_URL = '/m/people_manager/v1';
@@ -45,95 +45,6 @@ export async function transceivePost<TRequest, TResponse>(
const errorMessage = `[${operation}] ${response.data.message}${response.data.code ? ` (code: ${response.data.code})` : ''}`; const errorMessage = `[${operation}] ${response.data.message}${response.data.code ? ` (code: ${response.data.code})` : ''}`;
throw new Error(errorMessage); throw new Error(errorMessage);
} }
return response.data; return response.data;
} }
/**
* Stream an NDJSON API response, unwrapping data frames for the caller.
*
* The server emits one JSON object per line with a transport-level `type`
* discriminant. This consumes the chunked body, splits it into lines, forwards
* only unwrapped `data` payloads to the caller, and returns the final total.
*
* @param operation - Operation name, e.g. 'entity.listStream', 'entity.import'
* @param data - Operation-specific request data
* @param onData - Synchronous callback invoked for every unwrapped data payload.
* May throw to abort the stream.
* @param options - Optional `user` override and an `onStart` hook, invoked once
* with the expected total (the progress denominator) when the
* server declares one on the start frame.
* @returns Promise resolving to the final stream total from the control/end frame
*/
export async function transceiveStream<TRequest, TData>(
operation: string,
data: TRequest,
onData: (data: TData) => void,
options?: { user?: string; onStart?: (expected?: number) => void }
): Promise<{ total: number }> {
const request: ApiRequest<TRequest> = {
version: API_VERSION,
transaction: generateTransactionId(),
operation,
data,
user: options?.user,
};
let total = 0;
// Interpret one NDJSON line: control frames carry start/end metadata, error
// frames abort, data frames are unwrapped to the caller.
const dispatch = (line: string): void => {
const message = JSON.parse(line) as ApiStreamResponse<TData>;
if (message.type === 'control') {
if (message.status === 'start') {
options?.onStart?.(message.total);
} else if (message.status === 'end') {
total = message.total;
}
return;
}
if (message.type === 'error') {
throw new Error(`[${operation}] ${message.message}`);
}
onData(message.data);
};
await fetchWrapper.post(API_URL, request, {
headers: { 'Accept': 'application/json' },
onStream: async (response: Response) => {
if (!response.body) {
throw new Error(`[${operation}] Response body is not readable`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop()!; // retain any incomplete trailing chunk
for (const line of lines) {
if (line.trim()) dispatch(line);
}
}
// flush any remaining bytes still in the buffer
if (buffer.trim()) dispatch(buffer);
} finally {
reader.releaseLock();
}
},
});
return { total };
}
+125 -113
View File
@@ -4,17 +4,11 @@
import { ref, computed, readonly } from 'vue' import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import {
type ServiceIdentifier,
type CollectionIdentifier,
type ListFilter,
type ListSort,
} from '../types'
import { collectionService } from '../services' import { collectionService } from '../services'
import { CollectionObject, CollectionPropertiesObject } from '../models/collection' import { CollectionObject, CollectionPropertiesObject } from '../models/collection'
import type { SourceSelector, ListFilter, ListSort } from '../types'
export const useCollectionsStore = defineStore('peopleCollectionsStore', () => { export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
// State // State
const _collections = ref<Record<string, CollectionObject>>({}) const _collections = ref<Record<string, CollectionObject>>({})
const transceiving = ref(false) const transceiving = ref(false)
@@ -39,65 +33,85 @@ export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
*/ */
const collectionsByService = computed(() => { const collectionsByService = computed(() => {
const groups: Record<string, CollectionObject[]> = {} const groups: Record<string, CollectionObject[]> = {}
Object.values(_collections.value).forEach((collection) => { Object.values(_collections.value).forEach((collection) => {
const serviceKey = String(collection.service) const serviceKey = `${collection.provider}:${collection.service}`
const serviceCollections = (groups[serviceKey] ??= []) if (!groups[serviceKey]) {
serviceCollections.push(collection) groups[serviceKey] = []
}
groups[serviceKey].push(collection)
}) })
return groups return groups
}) })
/** /**
* Get a specific collection from store, with optional retrieval * Get a specific collection from store, with optional retrieval
* *
* @param target - collection identifier * @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only * @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
* *
* @returns Collection object or null * @returns Collection object or null
*/ */
function collection(target: CollectionIdentifier, retrieve: boolean = false): CollectionObject | null { function collection(provider: string, service: string | number, identifier: string | number, retrieve: boolean = false): CollectionObject | null {
if (retrieve === true && !_collections.value[target]) { const key = identifierKey(provider, service, identifier)
console.debug(`[People Manager][Store] - Force fetching collection "${target}"`) if (retrieve === true && !_collections.value[key]) {
fetch([target]) console.debug(`[People Manager][Store] - Force fetching collection "${key}"`)
fetch(provider, service, identifier)
} }
return _collections.value[target] || null return _collections.value[key] || null
} }
/** /**
* Get all collections for a specific service * Get all collections for a specific service
* *
* @param provider - provider identifier * @param provider - provider identifier
* @param service - service identifier * @param service - service identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only * @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
* *
* @returns Array of collection objects * @returns Array of collection objects
*/ */
function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] { function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] {
const serviceIdentifier = `${provider}:${service}` as ServiceIdentifier const serviceKeyPrefix = `${provider}:${service}:`
const serviceCollections = Object.values(_collections.value) const serviceCollections = Object.entries(_collections.value)
.filter(collection => String(collection.service) === serviceIdentifier) .filter(([key]) => key.startsWith(serviceKeyPrefix))
.map(([_, collection]) => collection)
if (retrieve === true && serviceCollections.length === 0) { if (retrieve === true && serviceCollections.length === 0) {
console.debug(`[People Manager][Store] - Force fetching collections for service "${serviceIdentifier}"`) console.debug(`[People Manager][Store] - Force fetching collections for service "${provider}:${service}"`)
list([serviceIdentifier]) const sources: SourceSelector = {
[provider]: {
[String(service)]: true
}
}
list(sources)
} }
return serviceCollections return serviceCollections
} }
/** /**
* Retrieve all or specific collections, optionally filtered by service/collection identifiers * Create unique key for a collection
* */
* @param sources - optional service/collection identifiers function identifierKey(provider: string, service: string | number | null, identifier: string | number | null): string {
return `${provider}:${service ?? ''}:${identifier ?? ''}`
}
// Actions
/**
* Retrieve all or specific collections, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter * @param filter - optional list filter
* @param sort - optional list sort * @param sort - optional list sort
* *
* @returns Promise with collection object list keyed by collection identifier * @returns Promise with collection object list keyed by provider, service, and collection identifier
*/ */
async function list(sources?: ServiceIdentifier[] | CollectionIdentifier[], filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> { async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.list({ sources, filter, sort }) const response = await collectionService.list({ sources, filter, sort })
@@ -107,7 +121,8 @@ export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
Object.entries(response).forEach(([_providerId, providerServices]) => { Object.entries(response).forEach(([_providerId, providerServices]) => {
Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => { Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => { Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => {
collections[collectionObj.identifier] = collectionObj const key = identifierKey(collectionObj.provider, collectionObj.service, collectionObj.identifier)
collections[key] = collectionObj
}) })
}) })
}) })
@@ -124,28 +139,29 @@ export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
transceiving.value = false transceiving.value = false
} }
} }
/** /**
* Retrieve specific collections by their identifiers * Retrieve a specific collection by provider, service, and identifier
* *
* @param targets - collection identifiers to fetch * @param provider - provider identifier
* * @param service - service identifier
* @returns Promise with collection objects keyed by identifier * @param identifier - collection identifier
*
* @returns Promise with collection object
*/ */
async function fetch(targets: CollectionIdentifier[]): Promise<Record<string, CollectionObject>> { async function fetch(provider: string, service: string | number, identifier: string | number): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.fetch({ targets }) const response = await collectionService.fetch({ provider, service, collection: identifier })
// Merge fetched collection into state
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response
// Merge fetched collections into state console.debug('[People Manager][Store] - Successfully fetched collection:', key)
Object.values(response).forEach(collectionObj => {
_collections.value[collectionObj.identifier] = collectionObj
})
console.debug('[People Manager][Store] - Successfully fetched collections:', Object.keys(response).join(', '))
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to fetch collections:', error) console.error('[People Manager][Store] - Failed to fetch collection:', error)
throw error throw error
} finally { } finally {
transceiving.value = false transceiving.value = false
@@ -153,18 +169,18 @@ export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
} }
/** /**
* Retrieve collection availability status for the given collection identifiers * Retrieve collection availability status for a given source selector
* *
* @param targets - collection identifiers to check availability for * @param sources - source selector to check availability for
* *
* @returns Promise with collection availability status * @returns Promise with collection availability status
*/ */
async function extant(targets: CollectionIdentifier[]): Promise<Record<string, Record<string, Record<string, boolean>>>> { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.extant({ targets }) const response = await collectionService.extant({ sources })
console.debug('[People Manager][Store] - Successfully checked', targets ? targets.length : 0, 'collections') console.debug('[People Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'collections')
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to check collections:', error) console.error('[People Manager][Store] - Failed to check collections:', error)
@@ -175,28 +191,30 @@ export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
} }
/** /**
* Create a new collection with given provider, service, and properties * Create a new collection with given provider, service, and data
* *
* @param provider - provider identifier for the new collection * @param provider - provider identifier for the new collection
* @param service - service identifier for the new collection * @param service - service identifier for the new collection
* @param properties - collection properties for creation * @param collection - optional parent collection identifier
* * @param data - collection properties for creation
*
* @returns Promise with created collection object * @returns Promise with created collection object
*/ */
async function create(provider: string, service: string | number, properties: CollectionPropertiesObject): Promise<CollectionObject> { async function create(provider: string, service: string | number, collection: string | number | null, data: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.create({ const response = await collectionService.create({
provider, provider,
service, service,
properties: properties.toJson(), collection,
properties: data
}) })
if (response instanceof CollectionObject) { // Merge created collection into state
_collections.value[response.identifier] = response const key = identifierKey(response.provider, response.service, response.identifier)
} _collections.value[key] = response
console.debug('[People Manager][Store] - Successfully created collection:', response.identifier) console.debug('[People Manager][Store] - Successfully created collection:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to create collection:', error) console.error('[People Manager][Store] - Failed to create collection:', error)
@@ -207,26 +225,30 @@ export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
} }
/** /**
* Update an existing collection with given target and properties * Update an existing collection with given provider, service, identifier, and data
* *
* @param target - collection identifier for the collection to update * @param provider - provider identifier for the collection to update
* @param properties - collection properties for update * @param service - service identifier for the collection to update
* * @param identifier - collection identifier for the collection to update
* @param data - collection properties for update
*
* @returns Promise with updated collection object * @returns Promise with updated collection object
*/ */
async function update(target: CollectionIdentifier, properties: CollectionPropertiesObject): Promise<CollectionObject> { async function update(provider: string, service: string | number, identifier: string | number, data: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.update({ const response = await collectionService.update({
target, provider,
properties: properties.toJson(), service,
identifier,
properties: data
}) })
if (response instanceof CollectionObject) { // Merge updated collection into state
_collections.value[response.identifier] = response const key = identifierKey(response.provider, response.service, response.identifier)
} _collections.value[key] = response
console.debug('[People Manager][Store] - Successfully updated collection:', response.identifier) console.debug('[People Manager][Store] - Successfully updated collection:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to update collection:', error) console.error('[People Manager][Store] - Failed to update collection:', error)
@@ -237,34 +259,24 @@ export const useCollectionsStore = defineStore('peopleCollectionsStore', () => {
} }
/** /**
* Delete a collection by identifier, with optional force delete if collection is not empty. * Delete a collection by provider, service, and identifier
* *
* @param target - collection identifier for the collection to delete * @param provider - provider identifier for the collection to delete
* @param force - optional flag to force delete if collection is not empty * @param service - service identifier for the collection to delete
* * @param identifier - collection identifier for the collection to delete
*
* @returns Promise with deletion result * @returns Promise with deletion result
*/ */
async function remove(target: CollectionIdentifier, force?: boolean): Promise<CollectionObject | boolean> { async function remove(provider: string, service: string | number, identifier: string | number): Promise<any> {
transceiving.value = true transceiving.value = true
try { try {
const response = await collectionService.delete({ target, options: { force } }) await collectionService.delete({ provider, service, identifier })
// Remove deleted collection from state
const key = identifierKey(provider, service, identifier)
delete _collections.value[key]
if (response !== true && !(response instanceof CollectionObject)) { console.debug('[People Manager][Store] - Successfully deleted collection:', key)
console.warn('[People Manager][Store] - Delete failed. Received unexpected response from delete operation:', response)
return false
}
delete _collections.value[target]
if (response instanceof CollectionObject) {
_collections.value[response.identifier] = response
console.debug('[People Manager][Store] - Successfully moved collection to trash', target, '->', response.identifier)
return response
}
console.debug('[People Manager][Store] - Successfully deleted collection:', target)
return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to delete collection:', error) console.error('[People Manager][Store] - Failed to delete collection:', error)
throw error throw error
+166 -230
View File
@@ -5,15 +5,8 @@
import { ref, computed, readonly } from 'vue' import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { entityService } from '../services' import { entityService } from '../services'
import { EntityObject, GroupObject, IndividualObject, OrganizationObject } from '../models' import { EntityObject } from '../models'
import type { import type { SourceSelector, ListFilter, ListSort, ListRange } from '../types/common'
CollectionIdentifier,
EntityIdentifier,
ListFilter,
ListRange,
ListSort,
} from '../types/common'
import type { EntityPropertiesInterface } from '@/types/entity'
export const useEntitiesStore = defineStore('peopleEntitiesStore', () => { export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
// State // State
@@ -37,64 +30,96 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
/** /**
* Get a specific entity from store, with optional retrieval * Get a specific entity from store, with optional retrieval
* *
* @param target - entity identifier * @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param identifier - entity identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only * @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
* *
* @returns Entity object or null * @returns Entity object or null
*/ */
function entity(target: EntityIdentifier, retrieve: boolean = false): EntityObject | null { function entity(provider: string, service: string | number, collection: string | number, identifier: string | number, retrieve: boolean = false): EntityObject | null {
if (retrieve === true && !_entities.value[target]) { const key = identifierKey(provider, service, collection, identifier)
console.debug(`[People Manager][Store] - Force fetching entity "${target}"`) if (retrieve === true && !_entities.value[key]) {
fetch([target]) console.debug(`[People Manager][Store] - Force fetching entity "${key}"`)
fetch(provider, service, collection, [identifier])
} }
return _entities.value[target] || null return _entities.value[key] || null
} }
/** /**
* Get all entities for a specific collection * Get all entities for a specific collection
* *
* @param target - collection identifier * @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only * @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
* *
* @returns Array of entity objects * @returns Array of entity objects
*/ */
function entitiesForCollection(target: CollectionIdentifier, retrieve: boolean = false): EntityObject[] { function entitiesForCollection(provider: string, service: string | number, collection: string | number, retrieve: boolean = false): EntityObject[] {
const collectionKeyPrefix = `${provider}:${service}:${collection}:`
const collectionEntities = Object.entries(_entities.value) const collectionEntities = Object.entries(_entities.value)
.filter(([key]) => key.startsWith(`${target}:`)) .filter(([key]) => key.startsWith(collectionKeyPrefix))
.map(([_, entity]) => entity) .map(([_, entity]) => entity)
if (retrieve === true && collectionEntities.length === 0) { if (retrieve === true && collectionEntities.length === 0) {
console.debug(`[People Manager][Store] - Force fetching entities for collection "${target}"`) console.debug(`[People Manager][Store] - Force fetching entities for collection "${provider}:${service}:${collection}"`)
list([target]) const sources: SourceSelector = {
[provider]: {
[String(service)]: {
[String(collection)]: true
}
}
}
list(sources)
} }
return collectionEntities return collectionEntities
} }
// Actions
/** /**
* Retrieve all or specific entities, optionally filtered by source collection identifiers * Create unique key for an entity
* */
* @param sources - collection identifiers to stream entities from function identifierKey(provider: string, service: string | number, collection: string | number, identifier: string | number): string {
return `${provider}:${service}:${collection}:${identifier}`
}
// Actions
/**
* Retrieve all or specific entities, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter * @param filter - optional list filter
* @param sort - optional list sort * @param sort - optional list sort
* @param range - optional list range * @param range - optional list range
* *
* @returns Promise with entity object list keyed by identifier * @returns Promise with entity object list keyed by identifier
*/ */
async function list(sources: CollectionIdentifier[], filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> { async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> {
transceiving.value = true transceiving.value = true
try { try {
const entities: Record<string, EntityObject> = {} const response = await entityService.list({ sources, filter, sort, range })
await entityService.listStream({ sources, filter, sort, range }, (entity: EntityObject) => { // Flatten nested structure: provider:service:collection:entity -> "provider:service:collection:entity": object
_entities.value[entity.identifier] = entity const entities: Record<string, EntityObject> = {}
entities[entity.identifier] = entity Object.entries(response).forEach(([providerId, providerServices]) => {
Object.entries(providerServices).forEach(([serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([collectionId, collectionEntities]) => {
Object.entries(collectionEntities).forEach(([entityId, entityData]) => {
const key = identifierKey(providerId, serviceId, collectionId, entityId)
entities[key] = entityData
})
})
})
}) })
// Merge retrieved entities into state
_entities.value = { ..._entities.value, ...entities }
console.debug('[People Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities') console.debug('[People Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities')
return entities return entities
} catch (error: any) { } catch (error: any) {
@@ -104,24 +129,28 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
transceiving.value = false transceiving.value = false
} }
} }
/** /**
* Retrieve specific entities by their identifiers * Retrieve specific entities by provider, service, collection, and identifiers
* *
* @param targets - array of entity identifiers to fetch * @param provider - provider identifier
* * @param service - service identifier
* @param collection - collection identifier
* @param identifiers - array of entity identifiers to fetch
*
* @returns Promise with entity objects keyed by identifier * @returns Promise with entity objects keyed by identifier
*/ */
async function fetch(targets: EntityIdentifier[]): Promise<Record<string, EntityObject>> { async function fetch(provider: string, service: string | number, collection: string | number, identifiers: (string | number)[]): Promise<Record<string, EntityObject>> {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.fetch({ targets }) const response = await entityService.fetch({ provider, service, collection, identifiers })
// Merge fetched entities into state // Merge fetched entities into state
const entities: Record<string, EntityObject> = {} const entities: Record<string, EntityObject> = {}
Object.entries(response).forEach(([identifier, entity]) => { Object.entries(response).forEach(([identifier, entityData]) => {
entities[identifier] = entity const key = identifierKey(provider, service, collection, identifier)
_entities.value[identifier] = entity entities[key] = entityData
_entities.value[key] = entityData
}) })
console.debug('[People Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities') console.debug('[People Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities')
@@ -135,16 +164,16 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
} }
/** /**
* Retrieve entity availability status for a given set of entity identifiers * Retrieve entity availability status for a given source selector
* *
* @param targets - array of entity identifiers to check availability for * @param sources - source selector to check availability for
* *
* @returns Promise with entity availability status * @returns Promise with entity availability status
*/ */
async function extant(targets: EntityIdentifier[]) { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.extant({ targets }) const response = await entityService.extant({ sources })
console.debug('[People Manager][Store] - Successfully checked entity availability') console.debug('[People Manager][Store] - Successfully checked entity availability')
return response return response
} catch (error: any) { } catch (error: any) {
@@ -156,87 +185,25 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
} }
/** /**
* Retrieve delta changes for entities * Create a new entity with given provider, service, collection, and data
* *
* @param targets - collection identifiers (provider:service:collection), optionally * @param provider - provider identifier for the new entity
* suffixed with a known signature (provider:service:collection:signature) * @param service - service identifier for the new entity
* to request a delta relative to that signature * @param collection - collection identifier for the new entity
* * @param data - entity properties for creation
* @returns Promise with delta changes (additions, modifications, deletions) *
*
* Note: Delta returns only identifiers, not full entities.
* Caller should fetch full entities for additions/modifications separately.
*/
async function delta(targets: (CollectionIdentifier | EntityIdentifier)[]) {
transceiving.value = true
try {
const response = await entityService.delta({ targets })
// Process delta and update store
Object.entries(response).forEach(([, providerData]) => {
// Skip if no changes for provider
if (providerData === false) return
Object.entries(providerData).forEach(([, serviceData]) => {
// Skip if no changes for service
if (serviceData === false) return
Object.entries(serviceData).forEach(([, collectionData]) => {
// Skip if no changes for collection
if (collectionData === false) return
// Process deletions (remove from store)
if (collectionData.deletions && collectionData.deletions.length > 0) {
collectionData.deletions.forEach((identifier) => {
delete _entities.value[identifier]
})
}
// Note: additions and modifications contain only identifiers
// The caller should fetch full entities using the fetch() method
})
})
})
console.debug('[People Manager][Store] - Successfully processed delta changes')
return response
} catch (error: any) {
console.error('[People Manager][Store] - Failed to process delta:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Create a new empty entity object
*
* @returns New entity object instance
*/
function fresh(): EntityObject {
return new EntityObject()
}
/**
* Create a new entity with given collection identifier and properties
*
* @param target - collection identifier for the new entity
* @param properties - entity properties for creation
*
* @returns Promise with created entity object * @returns Promise with created entity object
*/ */
async function create(target: CollectionIdentifier, properties: EntityPropertiesInterface | IndividualObject | OrganizationObject | GroupObject): Promise<EntityObject> { async function create(provider: string, service: string | number, collection: string | number, data: any): Promise<EntityObject> {
transceiving.value = true transceiving.value = true
try { try {
if (properties instanceof IndividualObject || properties instanceof OrganizationObject || properties instanceof GroupObject) { const response = await entityService.create({ provider, service, collection, properties: data })
properties = properties.toJson()
}
const response = await entityService.create({ target, properties })
// Add created entity to state // Add created entity to state
_entities.value[response.identifier] = response const key = identifierKey(response.provider, response.service, response.collection, response.identifier)
_entities.value[key] = response
console.debug('[People Manager][Store] - Successfully created entity:', response.identifier) console.debug('[People Manager][Store] - Successfully created entity:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to create entity:', error) console.error('[People Manager][Store] - Failed to create entity:', error)
@@ -247,25 +214,26 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
} }
/** /**
* Update an existing entity with given entity identifier and properties * Update an existing entity with given provider, service, collection, identifier, and data
* *
* @param target - entity identifier for the entity to update * @param provider - provider identifier for the entity to update
* @param properties - entity properties for update * @param service - service identifier for the entity to update
* * @param collection - collection identifier for the entity to update
* @param identifier - entity identifier for the entity to update
* @param data - entity properties for update
*
* @returns Promise with updated entity object * @returns Promise with updated entity object
*/ */
async function update(target: EntityIdentifier, properties: EntityPropertiesInterface | IndividualObject | OrganizationObject | GroupObject): Promise<EntityObject> { async function update(provider: string, service: string | number, collection: string | number, identifier: string | number, data: any): Promise<EntityObject> {
transceiving.value = true transceiving.value = true
try { try {
if (properties instanceof IndividualObject || properties instanceof OrganizationObject || properties instanceof GroupObject) { const response = await entityService.update({ provider, service, collection, identifier, properties: data })
properties = properties.toJson()
}
const response = await entityService.update({ target, properties })
// Update entity in state // Update entity in state
_entities.value[response.identifier] = response const key = identifierKey(response.provider, response.service, response.collection, response.identifier)
_entities.value[key] = response
console.debug('[People Manager][Store] - Successfully updated entity:', response.identifier) console.debug('[People Manager][Store] - Successfully updated entity:', key)
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to update entity:', error) console.error('[People Manager][Store] - Failed to update entity:', error)
@@ -276,54 +244,28 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
} }
/** /**
* Delete entities by their identifiers. * Delete an entity by provider, service, collection, and identifier
* *
* Removes successfully deleted entities from the local store. * @param provider - provider identifier for the entity to delete
* * @param service - service identifier for the entity to delete
* @param targets - entity identifiers to delete * @param collection - collection identifier for the entity to delete
* * @param identifier - entity identifier for the entity to delete
* @returns Promise with successes/failures keyed by target identifier *
* @returns Promise with deletion result
*/ */
async function remove(targets: EntityIdentifier[]): Promise<{ successes: EntityIdentifier[], failures: EntityIdentifier[] }> { async function remove(provider: string, service: string | number, collection: string | number, identifier: string | number): Promise<any> {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.delete({ targets }) const response = await entityService.delete({ provider, service, collection, identifier })
const successes: EntityIdentifier[] = []
const failures: EntityIdentifier[] = [] // Remove entity from state
const key = identifierKey(provider, service, collection, identifier)
delete _entities.value[key]
Object.entries(response).forEach(([targetIdentifier, result]) => { console.debug('[People Manager][Store] - Successfully deleted entity:', key)
const originalIdentifier = targetIdentifier as EntityIdentifier return response
if (!result.disposition || result.disposition === 'error') {
console.warn(`[People Manager][Store] - Entity delete on "${originalIdentifier}" returned an error: ${result.error})`)
failures.push(originalIdentifier)
return
}
if (result.disposition !== 'moved' && result.disposition !== 'deleted') {
console.warn(`[People Manager][Store] - Entity delete on "${originalIdentifier}" returned invalid disposition: ${result.disposition})`)
failures.push(originalIdentifier)
return
}
const cachedEntity = _entities.value[originalIdentifier]
if (result.disposition === 'moved' && cachedEntity && result.mutation) {
const movedEntity = cachedEntity.clone().fromJson({
...cachedEntity.toJson(),
collection: result.destination,
identifier: result.mutation,
})
_entities.value[result.mutation] = movedEntity
}
delete _entities.value[originalIdentifier]
successes.push(originalIdentifier)
})
console.debug('[People Manager][Store] - Successfully deleted', successes.length, 'entities')
return { successes, failures }
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to delete entities:', error) console.error('[People Manager][Store] - Failed to delete entity:', error)
throw error throw error
} finally { } finally {
transceiving.value = false transceiving.value = false
@@ -331,55 +273,51 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
} }
/** /**
* Move entities to another collection. * Retrieve delta changes for entities
* *
* Updates local store keys for successfully moved entities when they are * @param sources - source selector for delta check
* already present in cache. *
* * @returns Promise with delta changes (additions, modifications, deletions)
* @param target - target collection identifier *
* @param sources - source entity identifiers * Note: Delta returns only identifiers, not full entities.
* * Caller should fetch full entities for additions/modifications separately.
* @returns Promise with successes/failures keyed by source identifier
*/ */
async function move(target: CollectionIdentifier, sources: EntityIdentifier[]): Promise<{ successes: EntityIdentifier[], failures: EntityIdentifier[] }> { async function delta(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await entityService.move({ target, sources }) const response = await entityService.delta({ sources })
const successes: EntityIdentifier[] = []
const failures: EntityIdentifier[] = [] // Process delta and update store
Object.entries(response).forEach(([provider, providerData]) => {
Object.entries(response).forEach(([sourceIdentifier, result]) => { // Skip if no changes for provider
const originalIdentifier = sourceIdentifier as EntityIdentifier if (providerData === false) return
if (!result.disposition || result.disposition === 'error') {
console.warn(`[People Manager][Store] - Entity move on "${originalIdentifier}" returned an error: ${result.error})`) Object.entries(providerData).forEach(([service, serviceData]) => {
failures.push(originalIdentifier) // Skip if no changes for service
return if (serviceData === false) return
}
Object.entries(serviceData).forEach(([collection, collectionData]) => {
if (result.disposition !== 'moved') { // Skip if no changes for collection
console.warn(`[People Manager][Store] - Entity move on "${originalIdentifier}" returned invalid disposition: ${result.disposition})`) if (collectionData === false) return
failures.push(originalIdentifier)
return // Process deletions (remove from store)
} if (collectionData.deletions && collectionData.deletions.length > 0) {
collectionData.deletions.forEach((identifier) => {
const cachedEntity = _entities.value[originalIdentifier] const key = identifierKey(provider, service, collection, identifier)
if (cachedEntity && result.mutation) { delete _entities.value[key]
const movedEntity = cachedEntity.clone().fromJson({ })
...cachedEntity.toJson(), }
collection: result.destination,
identifier: result.mutation, // Note: additions and modifications contain only identifiers
// The caller should fetch full entities using the fetch() method
}) })
_entities.value[result.mutation] = movedEntity })
delete _entities.value[originalIdentifier]
}
successes.push(originalIdentifier)
}) })
console.debug('[People Manager][Store] - Successfully moved', successes.length, 'entities') console.debug('[People Manager][Store] - Successfully processed delta changes')
return { successes, failures } return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to move entities:', error) console.error('[People Manager][Store] - Failed to process delta:', error)
throw error throw error
} finally { } finally {
transceiving.value = false transceiving.value = false
@@ -400,11 +338,9 @@ export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
list, list,
fetch, fetch,
extant, extant,
fresh,
create, create,
update, update,
delete: remove, delete: remove,
delta, delta,
move,
} }
}) })
-219
View File
@@ -1,219 +0,0 @@
/**
* Contact Import Store
*/
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { entityService } from '../services/entityService'
import type { CollectionIdentifier } from '../types/common'
import type { EntityImportResponse } from '../types/entity'
import type {
ImportCounters,
ImportFileAdd,
ImportFileEntry,
ImportFileOptions,
ImportSession,
ImportSessionStage,
} from '../types/import'
/** Max object results retained per session for UI display. */
const RECENT_RESULTS_CAP = 25
function createEmptyCounters(): ImportCounters {
return { discovered: 0, processed: 0, created: 0, updated: 0, exists: 0, error: 0 }
}
function defaultOptions(): ImportFileOptions {
return { supersede: false }
}
export const useImportStore = defineStore('peopleImportStore', () => {
// State
const lastFileInsertId = ref(-1)
const files = ref<ImportFileEntry[]>([])
const stage = ref<ImportSessionStage>('idle')
const running = ref(false)
const activeFileId = ref<number | null>(null)
const lastError = ref<string | null>(null)
const sessions = ref<Record<number, ImportSession>>({})
const order = ref<number[]>([])
// Computed
/** Aggregate counters across every session. */
const totals = computed<ImportCounters>(() => {
const aggregate = createEmptyCounters()
for (const id of order.value) {
const session = sessions.value[id]
if (!session) continue
aggregate.discovered += session.counters.discovered
aggregate.processed += session.counters.processed
aggregate.created += session.counters.created
aggregate.updated += session.counters.updated
aggregate.exists += session.counters.exists
aggregate.error += session.counters.error
}
return aggregate
})
const activeSession = computed<ImportSession | null>(() =>
activeFileId.value !== null ? sessions.value[activeFileId.value] ?? null : null,
)
// Actions
function addFile(file: ImportFileAdd): number {
const id = ++lastFileInsertId.value
files.value.push({
file: { id, ...file },
collectionId: null,
options: defaultOptions(),
})
return id
}
/** Clear the queue, retaining the insert counter. */
function removeAllFiles(): void {
files.value = []
}
/** Reset run state, preserving queued files. */
function reset(): void {
stage.value = 'idle'
running.value = false
activeFileId.value = null
lastError.value = null
sessions.value = {}
order.value = []
}
function entryFor(fileId: number): ImportFileEntry | undefined {
return files.value.find((entry) => entry.file.id === fileId)
}
/** Set the destination collection for a queued file. */
function setCollectionForFile(fileId: number, collectionId: CollectionIdentifier | null): void {
const entry = entryFor(fileId)
if (entry) entry.collectionId = collectionId
}
/** Merge option changes for a queued file without dropping untouched keys. */
function setOptionsForFile(fileId: number, options: Partial<ImportFileOptions>): void {
const entry = entryFor(fileId)
if (entry) entry.options = { ...entry.options, ...options }
}
/** Record the discovered total (progress denominator) for a session. */
function setDiscovered(fileId: number, expected: number): void {
const session = sessions.value[fileId]
if (session) session.counters.discovered = expected
}
/** Fold one per-contact result into a session's counters and recent window. */
function recordObject(fileId: number, object: EntityImportResponse): void {
const session = sessions.value[fileId]
if (!session) return
session.recentResults = [object, ...session.recentResults].slice(0, RECENT_RESULTS_CAP)
session.counters.processed += 1
session.counters[object.disposition] += 1
}
/**
* Import every queued file sequentially, streaming live counters into each session.
*
* @returns aggregated counters across all files
* @throws if a queued file has no destination collection
*/
async function startImport(): Promise<ImportCounters> {
const entries = files.value.slice()
if (entries.length === 0) {
stage.value = 'completed'
return createEmptyCounters()
}
// Initialise sessions up front so the UI can render the full set.
sessions.value = {}
order.value = []
for (const entry of entries) {
sessions.value[entry.file.id] = {
fileId: entry.file.id,
fileName: entry.file.name,
targetDisplayName: entry.collectionId ?? '',
targetIdentifier: entry.collectionId,
status: 'pending',
counters: createEmptyCounters(),
recentResults: [],
lastError: null,
}
order.value.push(entry.file.id)
}
running.value = true
stage.value = 'importing'
lastError.value = null
try {
for (const entry of entries) {
const session = sessions.value[entry.file.id]
if (!entry.collectionId) {
session.status = 'error'
session.lastError = 'No destination collection selected'
throw new Error(`Selected collection not found for "${entry.file.name}"`)
}
activeFileId.value = entry.file.id
session.status = 'importing'
try {
await entityService.import(
{ target: entry.collectionId, data: entry.file.contents, options: entry.options },
(object) => recordObject(entry.file.id, object),
(expected) => setDiscovered(entry.file.id, expected),
)
session.status = session.counters.error > 0 ? 'error' : 'completed'
} catch (error) {
session.status = 'error'
session.lastError = error instanceof Error ? error.message : String(error)
throw error
}
}
stage.value = 'completed'
return totals.value
} catch (error) {
stage.value = 'error'
lastError.value = error instanceof Error ? error.message : String(error)
throw error
} finally {
running.value = false
activeFileId.value = null
}
}
return {
// state
lastFileInsertId,
files,
stage,
running,
activeFileId,
lastError,
sessions,
order,
// computed
totals,
activeSession,
// actions
addFile,
removeAllFiles,
reset,
setCollectionForFile,
setOptionsForFile,
startImport,
}
})
export default useImportStore
-1
View File
@@ -2,4 +2,3 @@ export { useProvidersStore } from './providersStore';
export { useServicesStore } from './servicesStore'; export { useServicesStore } from './servicesStore';
export { useCollectionsStore } from './collectionsStore'; export { useCollectionsStore } from './collectionsStore';
export { useEntitiesStore } from './entitiesStore'; export { useEntitiesStore } from './entitiesStore';
export { useImportStore } from './importStore';
+7 -7
View File
@@ -6,7 +6,7 @@ import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { providerService } from '../services' import { providerService } from '../services'
import { ProviderObject } from '../models/provider' import { ProviderObject } from '../models/provider'
import type { ProviderIdentifier } from '../types' import type { SourceSelector } from '../types'
export const useProvidersStore = defineStore('peopleProvidersStore', () => { export const useProvidersStore = defineStore('peopleProvidersStore', () => {
// State // State
@@ -54,10 +54,10 @@ export const useProvidersStore = defineStore('peopleProvidersStore', () => {
* *
* @returns Promise with provider object list keyed by provider identifier * @returns Promise with provider object list keyed by provider identifier
*/ */
async function list(targets?: ProviderIdentifier[]): Promise<Record<string, ProviderObject>> { async function list(sources?: SourceSelector): Promise<Record<string, ProviderObject>> {
transceiving.value = true transceiving.value = true
try { try {
const providers = await providerService.list({ targets }) const providers = await providerService.list({ sources })
// Merge retrieved providers into state // Merge retrieved providers into state
_providers.value = { ..._providers.value, ...providers } _providers.value = { ..._providers.value, ...providers }
@@ -82,7 +82,7 @@ export const useProvidersStore = defineStore('peopleProvidersStore', () => {
async function fetch(identifier: string): Promise<ProviderObject> { async function fetch(identifier: string): Promise<ProviderObject> {
transceiving.value = true transceiving.value = true
try { try {
const provider = await providerService.fetch({ target: identifier }) const provider = await providerService.fetch({ identifier })
// Merge fetched provider into state // Merge fetched provider into state
_providers.value[provider.identifier] = provider _providers.value[provider.identifier] = provider
@@ -104,10 +104,10 @@ export const useProvidersStore = defineStore('peopleProvidersStore', () => {
* *
* @returns Promise with provider availability status * @returns Promise with provider availability status
*/ */
async function extant(targets: ProviderIdentifier[]) { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await providerService.extant({ targets }) const response = await providerService.extant({ sources })
Object.entries(response).forEach(([providerId, providerStatus]) => { Object.entries(response).forEach(([providerId, providerStatus]) => {
if (providerStatus === false) { if (providerStatus === false) {
@@ -115,7 +115,7 @@ export const useProvidersStore = defineStore('peopleProvidersStore', () => {
} }
}) })
console.debug('[People Manager][Store] - Successfully checked', targets ? targets.length : 0, 'providers') console.debug('[People Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'providers')
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to check providers:', error) console.error('[People Manager][Store] - Failed to check providers:', error)
+47 -74
View File
@@ -7,8 +7,7 @@ import { defineStore } from 'pinia'
import { serviceService } from '../services' import { serviceService } from '../services'
import { ServiceObject } from '../models/service' import { ServiceObject } from '../models/service'
import type { import type {
CollectionIdentifier, SourceSelector,
ServiceIdentifier,
ServiceInterface, ServiceInterface,
} from '../types' } from '../types'
@@ -32,78 +31,59 @@ export const useServicesStore = defineStore('peopleServicesStore', () => {
*/ */
const services = computed(() => Object.values(_services.value)) const services = computed(() => Object.values(_services.value))
/**
* Get all enabled services present in store
*/
const servicesEnabled = computed(() => services.value.filter(service => service.enabled))
/** /**
* Get all services present in store grouped by provider * Get all services present in store grouped by provider
*/ */
const servicesByProvider = computed(() => { const servicesByProvider = computed(() => {
const groups: Record<string, ServiceObject[]> = {} const groups: Record<string, ServiceObject[]> = {}
Object.values(_services.value).forEach((service) => { Object.values(_services.value).forEach((service) => {
const providerServices = (groups[service.provider] ??= []) const providerServices = (groups[service.provider] ??= [])
providerServices.push(service) providerServices.push(service)
}) })
return groups return groups
}) })
/** /**
* Get a specific service from store, with optional retrieval * Get a specific service from store, with optional retrieval
* *
* @param provider - provider identifier * @param provider - provider identifier
* @param identifier - service identifier * @param identifier - service identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only * @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
* *
* @returns Service object or null * @returns Service object or null
*/ */
function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null { function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null {
return serviceByIdentifier(identifierKey(provider, identifier), retrieve) const key = identifierKey(provider, identifier)
} if (retrieve === true && !_services.value[key]) {
console.debug(`[People Manager][Store] - Force fetching service "${key}"`)
/** fetch(provider, identifier)
* Get a service from store by its unique identifier, with optional retrieval
*
* @param identifier - unique service identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
* @returns Service object or null
*/
function serviceByIdentifier(identifier: ServiceIdentifier, retrieve: boolean = false): ServiceObject | null {
if (retrieve === true && !_services.value[identifier]) {
console.debug(`[People Manager][Store] - Force fetching service "${identifier}"`)
const separatorIndex = identifier.indexOf(':')
const provider = identifier.slice(0, separatorIndex)
const serviceIdentifier = identifier.slice(separatorIndex + 1)
void fetch(provider, serviceIdentifier)
} }
return _services.value[identifier] ?? null return _services.value[key] || null
} }
/** /**
* Unique key for a service * Unique key for a service
*/ */
function identifierKey(provider: string, identifier: string | number | null): ServiceIdentifier { function identifierKey(provider: string, identifier: string | number | null): string {
return `${provider}:${identifier ?? ''}` as ServiceIdentifier return `${provider}:${identifier ?? ''}`
} }
// Actions // Actions
/** /**
* Retrieve all or specific services, optionally filtered by provider/service identifiers * Retrieve all or specific services, optionally filtered by source selector
* *
* @param targets - optional array of provider:service (or provider:service:collection) identifiers * @param sources - optional source selector
* *
* @returns Promise with service object list keyed by provider and service identifier * @returns Promise with service object list keyed by provider and service identifier
*/ */
async function list(targets?: ServiceIdentifier[] | CollectionIdentifier[]): Promise<Record<string, ServiceObject>> { async function list(sources?: SourceSelector): Promise<Record<string, ServiceObject>> {
transceiving.value = true transceiving.value = true
try { try {
const response = await serviceService.list({ targets }) const response = await serviceService.list({ sources })
// Flatten nested structure: provider-id: { service-id: object } -> "provider-id:service-id": object // Flatten nested structure: provider-id: { service-id: object } -> "provider-id:service-id": object
const services: Record<string, ServiceObject> = {} const services: Record<string, ServiceObject> = {}
@@ -126,20 +106,20 @@ export const useServicesStore = defineStore('peopleServicesStore', () => {
transceiving.value = false transceiving.value = false
} }
} }
/** /**
* Retrieve a specific service by provider and identifier * Retrieve a specific service by provider and identifier
* *
* @param provider - provider identifier * @param provider - provider identifier
* @param identifier - service identifier * @param identifier - service identifier
* *
* @returns Promise with service object * @returns Promise with service object
*/ */
async function fetch(provider: string, identifier: string | number): Promise<ServiceObject> { async function fetch(provider: string, identifier: string | number): Promise<ServiceObject> {
transceiving.value = true transceiving.value = true
try { try {
const service = await serviceService.fetch({ provider, identifier }) const service = await serviceService.fetch({ provider, identifier })
// Merge fetched service into state // Merge fetched service into state
const key = identifierKey(service.provider, service.identifier) const key = identifierKey(service.provider, service.identifier)
_services.value[key] = service _services.value[key] = service
@@ -155,18 +135,18 @@ export const useServicesStore = defineStore('peopleServicesStore', () => {
} }
/** /**
* Retrieve service availability status for the given service identifiers * Retrieve service availability status for a given source selector
* *
* @param targets - array of provider:service identifiers to check availability for * @param sources - source selector to check availability for
* *
* @returns Promise with service availability status * @returns Promise with service availability status
*/ */
async function extant(targets: ServiceIdentifier[]) { async function extant(sources: SourceSelector) {
transceiving.value = true transceiving.value = true
try { try {
const response = await serviceService.extant({ targets }) const response = await serviceService.extant({ sources })
console.debug('[People Manager][Store] - Successfully checked', targets?.length ?? 0, 'services') console.debug('[People Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'services')
return response return response
} catch (error: any) { } catch (error: any) {
console.error('[People Manager][Store] - Failed to check services:', error) console.error('[People Manager][Store] - Failed to check services:', error)
@@ -178,21 +158,21 @@ export const useServicesStore = defineStore('peopleServicesStore', () => {
/** /**
* Create a new service with given provider and data * Create a new service with given provider and data
* *
* @param provider - provider identifier for the new service * @param provider - provider identifier for the new service
* @param data - partial service data for creation * @param data - partial service data for creation
* *
* @returns Promise with created service object * @returns Promise with created service object
*/ */
async function create(provider: string, data: Partial<ServiceInterface>): Promise<ServiceObject> { async function create(provider: string, data: Partial<ServiceInterface>): Promise<ServiceObject> {
transceiving.value = true transceiving.value = true
try { try {
const service = await serviceService.create({ provider, data }) const service = await serviceService.create({ provider, data })
// Merge created service into state // Merge created service into state
const key = identifierKey(service.provider, service.identifier) const key = identifierKey(service.provider, service.identifier)
_services.value[key] = service _services.value[key] = service
console.debug('[People Manager][Store] - Successfully created service:', key) console.debug('[People Manager][Store] - Successfully created service:', key)
return service return service
} catch (error: any) { } catch (error: any) {
@@ -205,28 +185,22 @@ export const useServicesStore = defineStore('peopleServicesStore', () => {
/** /**
* Update an existing service with given provider, identifier, and data * Update an existing service with given provider, identifier, and data
* *
* @param provider - provider identifier for the service to update * @param provider - provider identifier for the service to update
* @param identifier - service identifier for the service to update * @param identifier - service identifier for the service to update
* @param delta - whether the update is a delta (partial) update or a full replacement * @param data - partial service data for update
* @param data - service data for update *
*
* @returns Promise with updated service object * @returns Promise with updated service object
*/ */
async function update(provider: string, identifier: string | number, delta: boolean, data: ServiceObject | Partial<ServiceInterface>): Promise<ServiceObject> { async function update(provider: string, identifier: string | number, data: Partial<ServiceInterface>): Promise<ServiceObject> {
transceiving.value = true transceiving.value = true
try { try {
// convert ServiceObject to JSON if needed const service = await serviceService.update({ provider, identifier, data })
const payload: Partial<ServiceInterface> = data instanceof ServiceObject
? (delta ? data.toJson(true) : data.toJson())
: data
const service = await serviceService.update({ provider, identifier, delta, data: payload })
// Merge updated service into state // Merge updated service into state
const key = identifierKey(service.provider, service.identifier) const key = identifierKey(service.provider, service.identifier)
_services.value[key] = service _services.value[key] = service
console.debug('[People Manager][Store] - Successfully updated service:', key) console.debug('[People Manager][Store] - Successfully updated service:', key)
return service return service
} catch (error: any) { } catch (error: any) {
@@ -239,17 +213,17 @@ export const useServicesStore = defineStore('peopleServicesStore', () => {
/** /**
* Delete a service by provider and identifier * Delete a service by provider and identifier
* *
* @param provider - provider identifier for the service to delete * @param provider - provider identifier for the service to delete
* @param identifier - service identifier for the service to delete * @param identifier - service identifier for the service to delete
* *
* @returns Promise with deletion result * @returns Promise with deletion result
*/ */
async function remove(provider: string, identifier: string | number): Promise<any> { async function remove(provider: string, identifier: string | number): Promise<any> {
transceiving.value = true transceiving.value = true
try { try {
await serviceService.delete({ provider, identifier }) await serviceService.delete({ provider, identifier })
// Remove deleted service from state // Remove deleted service from state
const key = identifierKey(provider, identifier) const key = identifierKey(provider, identifier)
delete _services.value[key] delete _services.value[key]
@@ -271,11 +245,10 @@ export const useServicesStore = defineStore('peopleServicesStore', () => {
count, count,
has, has,
services, services,
servicesEnabled,
servicesByProvider, servicesByProvider,
// Actions // Actions
service, service,
serviceByIdentifier,
list, list,
fetch, fetch,
extant, extant,
+20 -28
View File
@@ -1,37 +1,27 @@
/** /**
* Collection type definitions * Collection type definitions
*/ */
import type { import type { ListFilter, ListSort, SourceSelector } from './common';
ServiceIdentifier,
CollectionIdentifier,
ListFilter,
ListSort
} from './common';
/** /**
* Collection information * Collection information
*/ */
export interface CollectionInterface<T = CollectionPropertiesInterface> { export interface CollectionInterface {
'@type': string;
version: number;
provider: string; provider: string;
service: string | number; service: string | number;
collection: CollectionIdentifier | null; collection: string | number | null;
identifier: CollectionIdentifier; identifier: string | number;
signature?: string | null; signature?: string | null;
created?: string | null; created?: string | null;
modified?: string | null; modified?: string | null;
properties: T; properties: CollectionPropertiesInterface;
}
export interface CollectionModelInterface extends Omit<CollectionInterface<CollectionPropertiesInterface>, '@type' | 'version' | 'properties'> {
properties: CollectionPropertiesModelInterface;
} }
export type CollectionContentTypes = 'individual' | 'organization' | 'group'; export type CollectionContentTypes = 'individual' | 'organization' | 'group';
export interface CollectionBaseProperties { export interface CollectionBaseProperties {
'@type': string; '@type': string;
version: number;
} }
export interface CollectionImmutableProperties extends CollectionBaseProperties { export interface CollectionImmutableProperties extends CollectionBaseProperties {
@@ -48,13 +38,11 @@ export interface CollectionMutableProperties extends CollectionBaseProperties {
export interface CollectionPropertiesInterface extends CollectionMutableProperties, CollectionImmutableProperties {} export interface CollectionPropertiesInterface extends CollectionMutableProperties, CollectionImmutableProperties {}
export interface CollectionPropertiesModelInterface extends Omit<CollectionPropertiesInterface, '@type'> {}
/** /**
* Collection list * Collection list
*/ */
export interface CollectionListRequest { export interface CollectionListRequest {
sources?: ServiceIdentifier[] | CollectionIdentifier[]; sources?: SourceSelector;
filter?: ListFilter; filter?: ListFilter;
sort?: ListSort; sort?: ListSort;
} }
@@ -71,18 +59,18 @@ export interface CollectionListResponse {
* Collection fetch * Collection fetch
*/ */
export interface CollectionFetchRequest { export interface CollectionFetchRequest {
targets: CollectionIdentifier[]; provider: string;
service: string | number;
collection: string | number;
} }
export interface CollectionFetchResponse { export interface CollectionFetchResponse extends CollectionInterface {}
[identifier: CollectionIdentifier]: CollectionInterface;
}
/** /**
* Collection extant * Collection extant
*/ */
export interface CollectionExtantRequest { export interface CollectionExtantRequest {
targets: CollectionIdentifier[]; sources: SourceSelector;
} }
export interface CollectionExtantResponse { export interface CollectionExtantResponse {
@@ -99,6 +87,7 @@ export interface CollectionExtantResponse {
export interface CollectionCreateRequest { export interface CollectionCreateRequest {
provider: string; provider: string;
service: string | number; service: string | number;
collection?: string | number | null; // Parent Collection Identifier
properties: CollectionMutableProperties; properties: CollectionMutableProperties;
} }
@@ -108,7 +97,9 @@ export interface CollectionCreateResponse extends CollectionInterface {}
* Collection modify * Collection modify
*/ */
export interface CollectionUpdateRequest { export interface CollectionUpdateRequest {
target: CollectionIdentifier; provider: string;
service: string | number;
identifier: string | number;
properties: CollectionMutableProperties; properties: CollectionMutableProperties;
} }
@@ -118,13 +109,14 @@ export interface CollectionUpdateResponse extends CollectionInterface {}
* Collection delete * Collection delete
*/ */
export interface CollectionDeleteRequest { export interface CollectionDeleteRequest {
target: CollectionIdentifier; provider: string;
service: string | number;
identifier: string | number;
options?: { options?: {
force?: boolean; // Whether to force delete even if collection is not empty force?: boolean; // Whether to force delete even if collection is not empty
}; };
} }
export interface CollectionDeleteResponse { export interface CollectionDeleteResponse {
disposition: 'deleted' | 'moved'; success: boolean;
mutation?: CollectionInterface | null; // If moved, the new location of the collection
} }
+23 -49
View File
@@ -44,60 +44,34 @@ export interface ApiErrorResponse {
export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse; export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse;
/** /**
* Stream control start line. * Selector for targeting specific providers, services, collections, or entities in list or extant operations.
* *
* `total`, when present, is the expected number of data frames (the progress * Example usage:
* denominator). Streams that cannot cheaply know their size up front omit it. * {
* "provider1": true, // Select all services/collections/entities under provider1
* "provider2": {
* "serviceA": true, // Select all collections/entities under serviceA of provider2
* "serviceB": {
* "collectionX": true, // Select all entities under collectionX of serviceB of provider2
* "collectionY": [1, 2, 3] // Select entities with identifiers 1, 2, and 3 under collectionY of serviceB of provider2
* }
* }
* }
*/ */
export interface ApiStreamStartResponse { export type SourceSelector = {
type: 'control'; [provider: string]: boolean | ServiceSelector;
status: 'start'; };
version: number;
transaction: string;
total?: number;
}
/** export type ServiceSelector = {
* Stream control end line [service: string]: boolean | CollectionSelector;
*/ };
export interface ApiStreamEndResponse {
type: 'control';
status: 'end';
total: number;
}
/** export type CollectionSelector = {
* Stream error line [collection: string | number]: boolean | EntitySelector;
*/ };
export interface ApiStreamErrorResponse {
type: 'error';
message: string;
}
export interface ApiStreamDataResponse<T = any> { export type EntitySelector = (string | number)[];
type: 'data';
data: T;
}
/**
* Shared stream control lines
*/
export type ApiStreamResponse<T = any> =
| ApiStreamStartResponse
| ApiStreamEndResponse
| ApiStreamErrorResponse
| ApiStreamDataResponse<T>;
/**
* Identifiers for targeting specific providers, services, collections, or entities in list or extant operations.
*
* Operations accept flat arrays of colon-separated identifier strings, e.g.
* ["carddav:account1:contacts", "carddav:account1:contacts:1001"].
*/
export type ProviderIdentifier = `${string}`;
export type ServiceIdentifier = `${string}:${string}`;
export type CollectionIdentifier = `${string}:${string}:${string | number}`;
export type EntityIdentifier = `${string}:${string}:${string}:${string | number}`;
/** /**
* Filter comparison for list operations * Filter comparison for list operations
+56 -110
View File
@@ -1,86 +1,64 @@
/** /**
* Entity type definitions * Entity type definitions
*/ */
import type { import type { ListFilter, ListRange, ListSort, SourceSelector } from './common';
CollectionIdentifier,
EntityIdentifier,
ListFilter,
ListRange,
ListSort,
} from './common';
import type { GroupInterface } from './group'; import type { GroupInterface } from './group';
import type { IndividualInterface } from './individual'; import type { IndividualInterface } from './individual';
import type { OrganizationInterface } from './organization'; import type { OrganizationInterface } from './organization';
import type { ImportDisposition, ImportFileOptions } from './import';
export type EntityPropertiesInterface = IndividualInterface | OrganizationInterface | GroupInterface;
/** /**
* Entity definition * Entity definition
*/ */
export interface EntityInterface<T = EntityPropertiesInterface> { export interface EntityInterface<T = IndividualInterface | OrganizationInterface | GroupInterface> {
'@type': string;
version: number;
provider: string; provider: string;
service: string; service: string;
collection: CollectionIdentifier; collection: string | number;
identifier: EntityIdentifier; identifier: string | number;
signature: string | null; signature: string | null;
created: string | null; created: string | null;
modified: string | null; modified: string | null;
properties: T; properties: T;
} }
export interface EntityModelInterface extends Omit<EntityInterface<EntityPropertiesInterface>, '@type' | 'version'> {}
/** /**
* Entity list bulk * Entity list
*/ */
export interface EntityListBulkRequest { export interface EntityListRequest {
sources?: CollectionIdentifier[]; sources?: SourceSelector;
filter?: ListFilter; filter?: ListFilter;
sort?: ListSort; sort?: ListSort;
range?: ListRange; range?: ListRange;
} }
export interface EntityListBulkResponse { export interface EntityListResponse {
[providerId: string]: { [providerId: string]: {
[serviceId: string]: { [serviceId: string]: {
[collectionId: string]: { [collectionId: string]: {
[identifier: string]: EntityInterface; [identifier: string]: EntityInterface<IndividualInterface | OrganizationInterface | GroupInterface>;
}; };
}; };
}; };
} }
/**
* Entity list stream
*/
export interface EntityListStreamRequest {
sources?: CollectionIdentifier[];
filter?: ListFilter;
sort?: ListSort;
range?: ListRange;
}
export interface EntityListStreamResponse extends EntityInterface {}
/** /**
* Entity fetch * Entity fetch
*/ */
export interface EntityFetchRequest { export interface EntityFetchRequest {
targets: EntityIdentifier[]; provider: string;
service: string | number;
collection: string | number;
identifiers: (string | number)[];
} }
export interface EntityFetchResponse { export interface EntityFetchResponse {
[identifier: string]: EntityInterface; [identifier: string]: EntityInterface<IndividualInterface | OrganizationInterface | GroupInterface>;
} }
/** /**
* Entity extant * Entity extant
*/ */
export interface EntityExtantRequest { export interface EntityExtantRequest {
targets: EntityIdentifier[]; sources: SourceSelector;
} }
export interface EntityExtantResponse { export interface EntityExtantResponse {
@@ -93,13 +71,50 @@ export interface EntityExtantResponse {
}; };
} }
/**
* Entity create
*/
export interface EntityCreateRequest<T = IndividualInterface | OrganizationInterface | GroupInterface> {
provider: string;
service: string | number;
collection: string | number;
properties: T;
}
export interface EntityCreateResponse<T = IndividualInterface | OrganizationInterface | GroupInterface> extends EntityInterface<T> {}
/**
* Entity update
*/
export interface EntityUpdateRequest<T = IndividualInterface | OrganizationInterface | GroupInterface> {
provider: string;
service: string | number;
collection: string | number;
identifier: string | number;
properties: T;
}
export interface EntityUpdateResponse<T = IndividualInterface | OrganizationInterface | GroupInterface> extends EntityInterface<T> {}
/**
* Entity delete
*/
export interface EntityDeleteRequest {
provider: string;
service: string | number;
collection: string | number;
identifier: string | number;
}
export interface EntityDeleteResponse {
success: boolean;
}
/** /**
* Entity delta * Entity delta
*/ */
export interface EntityDeltaRequest { export interface EntityDeltaRequest {
// Each target is provider:service:collection, or provider:service:collection:signature sources: SourceSelector;
// to request a delta relative to a known signature (the signature is the entity slot).
targets: (CollectionIdentifier | EntityIdentifier)[];
} }
export interface EntityDeltaResponse { export interface EntityDeltaResponse {
@@ -113,73 +128,4 @@ export interface EntityDeltaResponse {
}; };
}; };
}; };
} }
/**
* Entity create
*/
export interface EntityCreateRequest<T = EntityPropertiesInterface> {
target: CollectionIdentifier;
properties: T;
options?: Record<string, any>;
}
export interface EntityCreateResponse<T = EntityPropertiesInterface> extends EntityInterface<T> {}
/**
* Entity update
*/
export interface EntityUpdateRequest<T = EntityPropertiesInterface> {
target: EntityIdentifier;
properties: T;
}
export interface EntityUpdateResponse<T = EntityPropertiesInterface> extends EntityInterface<T> {}
/**
* Entity delete
*/
export interface EntityDeleteRequest {
targets: EntityIdentifier[];
}
export interface EntityDeleteResponse {
[targetIdentifier: EntityIdentifier]: {
disposition: 'deleted' | 'moved' | 'error';
destination: CollectionIdentifier | null;
mutation: EntityIdentifier | null;
error?: string;
};
}
/**
* Entity move
*/
export interface EntityMoveRequest {
target: CollectionIdentifier;
sources: EntityIdentifier[];
}
export interface EntityMoveResponse {
[sourceIdentifier: EntityIdentifier]: {
disposition: 'moved' | 'error';
destination: CollectionIdentifier | null;
mutation: EntityIdentifier | null;
error?: string;
};
}
/**
* Entity import
*/
export interface EntityImportRequest {
target: CollectionIdentifier;
data: string;
options: ImportFileOptions;
}
export interface EntityImportResponse {
identifier: string | null;
disposition: ImportDisposition;
errors: string[];
}
-74
View File
@@ -1,74 +0,0 @@
/**
* Types for the VCF / vCard contact import UI flow (file queue, options, and
* live session state).
*
* The wire request/response for the `entity.import` operation live alongside the
* other entity operations in `./entity` ({@link EntityImportRequest},
* {@link EntityImportResponse}).
*/
import type { CollectionIdentifier } from './common';
import type { EntityImportResponse } from './entity';
export type ImportDisposition = 'created' | 'updated' | 'exists' | 'error';
export type ImportSessionStage = 'idle' | 'preparing' | 'selecting' | 'importing' | 'completed' | 'error';
/**
* Per-file import options sent to the backend.
*/
export interface ImportFileOptions {
supersede: boolean;
}
/**
* A file queued for import (raw contents read from disk).
*/
export interface ImportFileSource {
id: number;
name: string;
contents: string;
size: number;
type: string;
}
/**
* Payload for queueing a file (id is assigned by the store).
*/
export type ImportFileAdd = Omit<ImportFileSource, 'id'>;
/**
* A queued file paired with its chosen target collection and options.
*/
export interface ImportFileEntry {
file: ImportFileSource;
collectionId: CollectionIdentifier | null;
options: ImportFileOptions;
}
/**
* Aggregate counters for an import run.
*/
export interface ImportCounters {
discovered: number;
processed: number;
created: number;
updated: number;
exists: number;
error: number;
}
/**
* Live state for one file's import session.
*/
export interface ImportSession {
fileId: number;
fileName: string;
targetDisplayName: string;
targetIdentifier: CollectionIdentifier | null;
status: 'pending' | 'importing' | 'completed' | 'error';
counters: ImportCounters;
/** Bounded rolling window of recent object results, capped (see RECENT_RESULTS_CAP). */
recentResults: EntityImportResponse[];
lastError: string | null;
}
-1
View File
@@ -2,7 +2,6 @@ export type * from './collection';
export type * from './common'; export type * from './common';
export type * from './entity'; export type * from './entity';
export type * from './group'; export type * from './group';
export type * from './import';
export type * from './individual'; export type * from './individual';
export type * from './organization'; export type * from './organization';
export type * from './provider'; export type * from './provider';
+6 -9
View File
@@ -1,7 +1,7 @@
/** /**
* Provider type definitions * Provider type definitions
*/ */
import type { ProviderIdentifier } from "./common"; import type { SourceSelector } from "./common";
/** /**
* Provider capabilities * Provider capabilities
@@ -23,30 +23,27 @@ export interface ProviderCapabilitiesInterface {
*/ */
export interface ProviderInterface { export interface ProviderInterface {
'@type': string; '@type': string;
version: number;
identifier: string; identifier: string;
label: string; label: string;
capabilities: ProviderCapabilitiesInterface; capabilities: ProviderCapabilitiesInterface;
} }
export interface ProviderModelInterface extends Omit<ProviderInterface, '@type' | 'version'> {}
/** /**
* Provider list * Provider list
*/ */
export interface ProviderListRequest { export interface ProviderListRequest {
targets?: ProviderIdentifier[]; sources?: SourceSelector;
} }
export interface ProviderListResponse { export interface ProviderListResponse {
[identifier: ProviderIdentifier]: ProviderInterface; [identifier: string]: ProviderInterface;
} }
/** /**
* Provider fetch * Provider fetch
*/ */
export interface ProviderFetchRequest { export interface ProviderFetchRequest {
target: ProviderIdentifier; identifier: string;
} }
export interface ProviderFetchResponse extends ProviderInterface {} export interface ProviderFetchResponse extends ProviderInterface {}
@@ -55,9 +52,9 @@ export interface ProviderFetchResponse extends ProviderInterface {}
* Provider extant * Provider extant
*/ */
export interface ProviderExtantRequest { export interface ProviderExtantRequest {
targets: ProviderIdentifier[]; sources: SourceSelector;
} }
export interface ProviderExtantResponse { export interface ProviderExtantResponse {
[identifier: ProviderIdentifier]: boolean; [identifier: string]: boolean;
} }
+4 -31
View File
@@ -1,12 +1,7 @@
/** /**
* Service type definitions * Service type definitions
*/ */
import type { Identity } from '@/models/identity'; import type { SourceSelector, ListFilterComparisonOperator } from './common';
import type {
ServiceIdentifier,
CollectionIdentifier,
ListFilterComparisonOperator
} from './common';
/** /**
* Service capabilities * Service capabilities
@@ -42,7 +37,6 @@ export interface ServiceCapabilitiesInterface {
*/ */
export interface ServiceInterface { export interface ServiceInterface {
'@type': string; '@type': string;
version: number;
provider: string; provider: string;
identifier: string | number | null; identifier: string | number | null;
label: string | null; label: string | null;
@@ -53,18 +47,11 @@ export interface ServiceInterface {
auxiliary?: Record<string, any>; // Provider-specific extension data auxiliary?: Record<string, any>; // Provider-specific extension data
} }
export interface ServiceModelInterface extends Omit<{
[K in keyof ServiceInterface]-?: Exclude<ServiceInterface[K], undefined>;
}, '@type' | 'version' | 'location' | 'identity'> {
location: Location | null;
identity: Identity | null;
}
/** /**
* Service list * Service list
*/ */
export interface ServiceListRequest { export interface ServiceListRequest {
targets?: ServiceIdentifier[] | CollectionIdentifier[]; sources?: SourceSelector;
} }
export interface ServiceListResponse { export interface ServiceListResponse {
@@ -87,7 +74,7 @@ export interface ServiceFetchResponse extends ServiceInterface {}
* Service extant * Service extant
*/ */
export interface ServiceExtantRequest { export interface ServiceExtantRequest {
targets: ServiceIdentifier[]; sources: SourceSelector;
} }
export interface ServiceExtantResponse { export interface ServiceExtantResponse {
@@ -112,7 +99,6 @@ export interface ServiceCreateResponse extends ServiceInterface {}
export interface ServiceUpdateRequest { export interface ServiceUpdateRequest {
provider: string; provider: string;
identifier: string | number; identifier: string | number;
delta?: boolean; // If true, 'data' contains only fields to update (partial update). If false or omitted, 'data' is a full replacement.
data: Partial<ServiceInterface>; data: Partial<ServiceInterface>;
} }
@@ -139,20 +125,7 @@ export interface ServiceDiscoverRequest {
} }
export interface ServiceDiscoverResponse { export interface ServiceDiscoverResponse {
provider: string; [provider: string]: ServiceLocation; // Uses existing ServiceLocation discriminated union
location: ServiceLocation;
}
export interface ProviderDiscoveryStatus {
provider: string;
status: 'pending' | 'discovering' | 'success' | 'failed';
location?: ServiceLocation;
metadata?: {
host?: string;
port?: number;
protocol?: string;
};
error?: string;
} }
/** /**
-30
View File
@@ -1,30 +0,0 @@
import { describe, it, expect } from 'vitest'
describe('Basic Tests', () => {
it('should perform basic assertion', () => {
expect(true).toBe(true)
})
it('should test array operations', () => {
const array = ['foo', 'bar', 'baz']
expect(array).toHaveLength(3)
expect(array).toContain('bar')
expect(array[0]).toBe('foo')
})
it('should test string operations', () => {
const string = 'Hello, World!'
expect(string).toContain('World')
expect(string.length).toBe(13)
})
it('should test object operations', () => {
const obj = { foo: 'bar', count: 42 }
expect(obj).toHaveProperty('foo')
expect(obj.foo).toBe('bar')
expect(obj.count).toBeGreaterThan(40)
})
})
-31
View File
@@ -1,31 +0,0 @@
import { fileURLToPath } from 'node:url'
import { defineConfig, configDefaults } from 'vitest/config'
import path from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, '../../src'),
'@KTXC': path.resolve(__dirname, '../../../../core/src'),
},
},
test: {
environment: 'jsdom',
exclude: [...configDefaults.exclude, 'e2e/**'],
root: fileURLToPath(new URL('../../', import.meta.url)),
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: [
'node_modules/',
'tests/',
'**/*.d.ts',
'**/*.config.*',
'**/dist/**',
],
},
},
})
-29
View File
@@ -1,29 +0,0 @@
<?php
namespace KTXT\PeopleManager\Tests\Integration;
use PHPUnit\Framework\TestCase;
class BaseTest extends TestCase
{
public function testBasicAssertion(): void
{
$this->assertTrue(true);
}
public function testArrayOperations(): void
{
$array = ['foo' => 'bar'];
$this->assertArrayHasKey('foo', $array);
$this->assertEquals('bar', $array['foo']);
}
public function testStringOperations(): void
{
$string = 'Hello, World!';
$this->assertStringContainsString('World', $string);
$this->assertEquals(13, strlen($string));
}
}
-29
View File
@@ -1,29 +0,0 @@
<?php
namespace KTXT\PeopleManager\Tests\Unit;
use PHPUnit\Framework\TestCase;
class BaseTest extends TestCase
{
public function testBasicAssertion(): void
{
$this->assertTrue(true);
}
public function testArrayOperations(): void
{
$array = ['foo' => 'bar'];
$this->assertArrayHasKey('foo', $array);
$this->assertEquals('bar', $array['foo']);
}
public function testStringOperations(): void
{
$string = 'Hello, World!';
$this->assertStringContainsString('World', $string);
$this->assertEquals(13, strlen($string));
}
}
-17
View File
@@ -1,17 +0,0 @@
<?php
require dirname(__DIR__, 2).'/lib/vendor/autoload.php';
// When this module is checked out inside a full server (server/modules/<handle>,
// as it is in CI and in this monorepo checkout), also load the server's own
// core/shared autoloader so tests can reference framework (KTXC/KTXF) types.
// Standalone module checkouts without a server alongside them skip this.
define('SERVER_ROOT', dirname(__DIR__, 4));
$serverAutoload = SERVER_ROOT . '/vendor/autoload.php';
if (is_file($serverAutoload)) {
require $serverAutoload;
}
if (isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG']) {
umask(0000);
}
-41
View File
@@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../lib/vendor/phpunit/phpunit/phpunit.xsd"
colors="true"
failOnDeprecation="true"
failOnNotice="true"
failOnWarning="true"
bootstrap="bootstrap.php"
cacheDirectory="../../.phpunit.cache"
>
<php>
<ini name="display_errors" value="1" />
<ini name="error_reporting" value="-1" />
<server name="APP_ENV" value="test" force="true" />
<server name="SHELL_VERBOSITY" value="-1" />
</php>
<testsuites>
<testsuite name="Unit Tests">
<directory>Unit</directory>
</testsuite>
<testsuite name="Integration Tests">
<directory>Integration</directory>
</testsuite>
</testsuites>
<source ignoreSuppressionOfDeprecations="true"
ignoreIndirectDeprecations="true"
restrictNotices="true"
restrictWarnings="true"
>
<include>
<directory>../../lib</directory>
</include>
</source>
<extensions>
</extensions>
</phpunit>