akanjs 0.0.1 → 2.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CODE_OF_CONDUCT.md +54 -0
- package/CONTRIBUTING.md +83 -0
- package/LICENSE +21 -0
- package/README.ko.md +244 -0
- package/README.md +237 -6
- package/base/base.ts +194 -0
- package/base/baseEnv.ts +162 -0
- package/base/index.ts +6 -0
- package/base/primitiveRegistry.ts +342 -0
- package/base/symbols.ts +11 -0
- package/base/types.ts +137 -0
- package/base/utils.ts +30 -0
- package/cli/application/application.command.ts +213 -0
- package/cli/application/application.interface.tsx +225 -0
- package/cli/application/application.runner.ts +359 -0
- package/cli/application/application.script.ts +244 -0
- package/cli/build.ts +25 -0
- package/cli/cloud/cloud.command.ts +48 -0
- package/cli/cloud/cloud.runner.ts +158 -0
- package/cli/cloud/cloud.script.ts +40 -0
- package/cli/guideline/guideline.command.ts +31 -0
- package/cli/guideline/guideline.prompt.ts +212 -0
- package/cli/guideline/guideline.runner.ts +53 -0
- package/cli/guideline/guideline.script.ts +33 -0
- package/cli/guidelines/___library/sharedUiStructureDescription.en.md +767 -0
- package/cli/guidelines/___library/utilUiStructureDescription.en.md +395 -0
- package/cli/guidelines/___lint/lintRuleDescription.en.md +64 -0
- package/cli/guidelines/___module/moduleStructureDescription.en.md +80 -0
- package/cli/guidelines/componentRule/componentRule.generate.json +131 -0
- package/cli/guidelines/componentRule/componentRule.instruction.md +637 -0
- package/cli/guidelines/cssRule/cssRule.generate.json +93 -0
- package/cli/guidelines/cssRule/cssRule.instruction.md +435 -0
- package/cli/guidelines/databaseModule/databaseModule.generate.json +51 -0
- package/cli/guidelines/databaseModule/databaseModule.instruction.md +612 -0
- package/cli/guidelines/docPageRule/docPageRule.generate.json +72 -0
- package/cli/guidelines/docPageRule/docPageRule.instruction.md +389 -0
- package/cli/guidelines/enumConstant/enumConstant.generate.json +24 -0
- package/cli/guidelines/enumConstant/enumConstant.instruction.md +232 -0
- package/cli/guidelines/framework/framework.generate.json +119 -0
- package/cli/guidelines/framework/framework.instruction.md +1110 -0
- package/cli/guidelines/howToUseStore/howToUseStore.generate.json +0 -0
- package/cli/guidelines/modelConstant/modelConstant.generate.json +128 -0
- package/cli/guidelines/modelConstant/modelConstant.instruction.md +506 -0
- package/cli/guidelines/modelDictionary/modelDictionary.generate.json +108 -0
- package/cli/guidelines/modelDictionary/modelDictionary.instruction.md +547 -0
- package/cli/guidelines/modelDocument/modelDocument.generate.json +129 -0
- package/cli/guidelines/modelDocument/modelDocument.instruction.md +536 -0
- package/cli/guidelines/modelService/modelService.generate.json +135 -0
- package/cli/guidelines/modelService/modelService.instruction.md +708 -0
- package/cli/guidelines/modelSignal/modelSignal.generate.json +201 -0
- package/cli/guidelines/modelSignal/modelSignal.instruction.md +552 -0
- package/cli/guidelines/modelStore/modelStore.generate.json +130 -0
- package/cli/guidelines/modelStore/modelStore.instruction.md +585 -0
- package/cli/guidelines/modelTemplate/modelTemplate.generate.json +104 -0
- package/cli/guidelines/modelTemplate/modelTemplate.instruction.md +604 -0
- package/cli/guidelines/modelUnit/modelUnit.generate.json +92 -0
- package/cli/guidelines/modelUnit/modelUnit.instruction.md +541 -0
- package/cli/guidelines/modelUtil/modelUtil.generate.json +93 -0
- package/cli/guidelines/modelUtil/modelUtil.instruction.md +752 -0
- package/cli/guidelines/modelView/modelView.generate.json +80 -0
- package/cli/guidelines/modelView/modelView.instruction.md +1005 -0
- package/cli/guidelines/modelZone/modelZone.generate.json +126 -0
- package/cli/guidelines/modelZone/modelZone.instruction.md +528 -0
- package/cli/guidelines/scalarConstant/scalarConstant.generate.json +106 -0
- package/cli/guidelines/scalarConstant/scalarConstant.instruction.md +442 -0
- package/cli/guidelines/scalarDictionary/scalarDictionary.generate.json +83 -0
- package/cli/guidelines/scalarDictionary/scalarDictionary.instruction.md +273 -0
- package/cli/guidelines/scalarModule/scalarModule.generate.json +35 -0
- package/cli/guidelines/scalarModule/scalarModule.instruction.md +81 -0
- package/cli/guidelines/sharedUiUsage/sharedUiUsage.generate.json +108 -0
- package/cli/guidelines/sharedUiUsage/sharedUiUsage.instruction.md +310 -0
- package/cli/guidelines/utilUiUsage/utilUiUsage.generate.json +140 -0
- package/cli/guidelines/utilUiUsage/utilUiUsage.instruction.md +339 -0
- package/cli/index.js +11399 -0
- package/cli/index.ts +24 -0
- package/cli/library/library.command.ts +28 -0
- package/cli/library/library.runner.ts +69 -0
- package/cli/library/library.script.ts +39 -0
- package/cli/module/module.command.ts +35 -0
- package/cli/module/module.prompt.ts +18 -0
- package/cli/module/module.request.ts +319 -0
- package/cli/module/module.runner.ts +76 -0
- package/cli/module/module.script.ts +161 -0
- package/cli/package/package.command.ts +32 -0
- package/cli/package/package.runner.ts +64 -0
- package/cli/package/package.script.ts +35 -0
- package/cli/page/page.command.ts +14 -0
- package/cli/page/page.runner.ts +14 -0
- package/cli/page/page.script.ts +12 -0
- package/cli/scalar/scalar.command.ts +21 -0
- package/cli/scalar/scalar.prompt.ts +131 -0
- package/cli/scalar/scalar.runner.ts +38 -0
- package/cli/scalar/scalar.script.ts +16 -0
- package/cli/templates/__scalar/__model__/__model__.constant.ts +15 -0
- package/cli/templates/__scalar/__model__/__model__.dictionary.ts +19 -0
- package/cli/templates/__scalar/__model__/__model__.document.ts +15 -0
- package/cli/templates/app/akan.config.ts +14 -0
- package/cli/templates/app/capacitor.config.ts.template +8 -0
- package/cli/templates/app/common/commonLogic.ts +12 -0
- package/cli/templates/app/common/index.ts +10 -0
- package/cli/templates/app/env/env.client.debug.ts.template +7 -0
- package/cli/templates/app/env/env.client.develop.ts.template +7 -0
- package/cli/templates/app/env/env.client.local.ts.template +7 -0
- package/cli/templates/app/env/env.client.main.ts.template +7 -0
- package/cli/templates/app/env/env.client.testing.ts.template +7 -0
- package/cli/templates/app/env/env.client.ts +21 -0
- package/cli/templates/app/env/env.client.type.ts +16 -0
- package/cli/templates/app/env/env.server.debug.ts.template +7 -0
- package/cli/templates/app/env/env.server.develop.ts.template +9 -0
- package/cli/templates/app/env/env.server.local.ts.template +14 -0
- package/cli/templates/app/env/env.server.main.ts.template +9 -0
- package/cli/templates/app/env/env.server.testing.ts.template +6 -0
- package/cli/templates/app/env/env.server.ts +20 -0
- package/cli/templates/app/lib/___appName__/__appName__.dictionary.ts +17 -0
- package/cli/templates/app/lib/___appName__/__appName__.service.ts +13 -0
- package/cli/templates/app/lib/___appName__/__appName__.signal.ts +17 -0
- package/cli/templates/app/lib/___appName__/__appName__.store.ts +15 -0
- package/cli/templates/app/lib/option.ts +17 -0
- package/cli/templates/app/main.ts +16 -0
- package/cli/templates/app/package.json.template +5 -0
- package/cli/templates/app/page/_index.tsx +172 -0
- package/cli/templates/app/page/_layout.tsx +32 -0
- package/cli/templates/app/page/styles.css.template +53 -0
- package/cli/templates/app/public/favicon.ico +0 -0
- package/cli/templates/app/public/logo.png +0 -0
- package/cli/templates/app/srvkit/backendLogic.ts +12 -0
- package/cli/templates/app/srvkit/index.ts +10 -0
- package/cli/templates/app/tsconfig.json.template +21 -0
- package/cli/templates/app/ui/UiComponent.ts +16 -0
- package/cli/templates/app/ui/index.ts +10 -0
- package/cli/templates/app/webkit/frontendLogic.ts +12 -0
- package/cli/templates/app/webkit/index.ts +10 -0
- package/cli/templates/client.ts +46 -0
- package/cli/templates/crudPages/[__model__Id]/edit/page.tsx +47 -0
- package/cli/templates/crudPages/[__model__Id]/page.tsx +52 -0
- package/cli/templates/crudPages/new/page.tsx +42 -0
- package/cli/templates/crudPages/page.tsx +43 -0
- package/cli/templates/crudSinglePage/page.tsx +37 -0
- package/cli/templates/env/_env.server.type.ts +16 -0
- package/cli/templates/facetIndex/index.ts +32 -0
- package/cli/templates/index.ts +10 -0
- package/cli/templates/lib/__lib/lib.constant.ts +38 -0
- package/cli/templates/lib/__lib/lib.dictionary.ts +33 -0
- package/cli/templates/lib/__lib/lib.document.ts +35 -0
- package/cli/templates/lib/__lib/lib.service.ts +33 -0
- package/cli/templates/lib/__lib/lib.signal.ts +34 -0
- package/cli/templates/lib/__lib/lib.store.ts +33 -0
- package/cli/templates/lib/cnst.ts +29 -0
- package/cli/templates/lib/db.ts +32 -0
- package/cli/templates/lib/dict.ts +49 -0
- package/cli/templates/lib/sig.ts +60 -0
- package/cli/templates/lib/srv.ts +34 -0
- package/cli/templates/lib/st.ts +31 -0
- package/cli/templates/lib/useClient.ts +19 -0
- package/cli/templates/lib/useServer.ts +7 -0
- package/cli/templates/libRoot/.gitignore.template +16 -0
- package/cli/templates/libRoot/akan.config.ts +12 -0
- package/cli/templates/libRoot/base/baseLogic.ts +10 -0
- package/cli/templates/libRoot/base/index.ts +8 -0
- package/cli/templates/libRoot/common/commonLogic.ts +10 -0
- package/cli/templates/libRoot/common/index.ts +8 -0
- package/cli/templates/libRoot/env/env.server.example.ts.template +6 -0
- package/cli/templates/libRoot/env/env.server.testing.ts.template +6 -0
- package/cli/templates/libRoot/lib/___libName__/__libName__.dictionary.ts +15 -0
- package/cli/templates/libRoot/lib/___libName__/__libName__.service.ts +11 -0
- package/cli/templates/libRoot/lib/___libName__/__libName__.store.ts +13 -0
- package/cli/templates/libRoot/lib/option.ts +17 -0
- package/cli/templates/libRoot/package.json.template +5 -0
- package/cli/templates/libRoot/srvkit/backendLogic.ts +10 -0
- package/cli/templates/libRoot/srvkit/index.ts +8 -0
- package/cli/templates/libRoot/tsconfig.json.template +11 -0
- package/cli/templates/libRoot/ui/index.ts +7 -0
- package/cli/templates/libRoot/webkit/frontendLogic.ts +10 -0
- package/cli/templates/libRoot/webkit/index.ts +8 -0
- package/cli/templates/localDev/docker-compose.yaml.template +37 -0
- package/cli/templates/module/__Model__.Template.tsx +36 -0
- package/cli/templates/module/__Model__.Unit.tsx +26 -0
- package/cli/templates/module/__Model__.Util.tsx +30 -0
- package/cli/templates/module/__Model__.View.tsx +29 -0
- package/cli/templates/module/__Model__.Zone.tsx +43 -0
- package/cli/templates/module/__model__.constant.ts +24 -0
- package/cli/templates/module/__model__.dictionary.ts +30 -0
- package/cli/templates/module/__model__.document.ts +23 -0
- package/cli/templates/module/__model__.service.ts +16 -0
- package/cli/templates/module/__model__.signal.ts +27 -0
- package/cli/templates/module/__model__.store.ts +19 -0
- package/cli/templates/module/index.tsx +44 -0
- package/cli/templates/moduleRoot/index.tsx +31 -0
- package/cli/templates/pkgRoot/tsconfig.json.template +10 -0
- package/cli/templates/server.ts +45 -0
- package/cli/templates/workspaceRoot/.env.template +14 -0
- package/cli/templates/workspaceRoot/.gitignore.template +130 -0
- package/cli/templates/workspaceRoot/.vscode/settings.json.template +23 -0
- package/cli/templates/workspaceRoot/biome.json.template +175 -0
- package/cli/templates/workspaceRoot/bunfig.toml +4 -0
- package/cli/templates/workspaceRoot/infra/app/Chart.yaml.template +6 -0
- package/cli/templates/workspaceRoot/infra/app/templates/frontend.yaml.template +182 -0
- package/cli/templates/workspaceRoot/infra/app/values/_common-values.yaml.template +183 -0
- package/cli/templates/workspaceRoot/package.json.template +7 -0
- package/cli/templates/workspaceRoot/tsconfig.json.template +26 -0
- package/cli/testHelpers.ts +171 -0
- package/cli/workspace/workspace.command.ts +59 -0
- package/cli/workspace/workspace.runner.ts +57 -0
- package/cli/workspace/workspace.script.ts +68 -0
- package/client/capacitor.ts +68 -0
- package/client/clientRuntime.ts +141 -0
- package/client/cookie.ts +121 -0
- package/client/createFont.ts +8 -0
- package/client/csrTypes.ts +259 -0
- package/client/decorators.ts +25 -0
- package/client/device.ts +147 -0
- package/client/fetch.ts +1 -0
- package/client/index.ts +15 -0
- package/client/locale.ts +4 -0
- package/client/makePageProto.tsx +178 -0
- package/client/router.ts +286 -0
- package/client/rscNavigation.ts +19 -0
- package/client/storage.ts +33 -0
- package/client/translator.ts +43 -0
- package/client/types.ts +228 -0
- package/client/useClient.ts +1 -0
- package/common/Logger.ts +177 -0
- package/common/applyMixins.ts +14 -0
- package/common/capitalize.ts +4 -0
- package/common/deepObjectify.ts +27 -0
- package/common/formatNumber.ts +14 -0
- package/common/formatPhone.ts +7 -0
- package/common/getAllPropertyDescriptors.ts +13 -0
- package/common/hmrPhase.ts +17 -0
- package/common/httpClient.ts +101 -0
- package/common/index.ts +50 -0
- package/common/isDayjs.ts +3 -0
- package/common/isEmail.ts +2 -0
- package/common/isPhoneNumber.ts +8 -0
- package/common/isQueryEqual.ts +23 -0
- package/common/isValidDate.ts +14 -0
- package/common/localeConfig.ts +41 -0
- package/common/lowerlize.ts +4 -0
- package/common/mergeVersion.ts +10 -0
- package/common/objectify.ts +7 -0
- package/common/pathGet.ts +13 -0
- package/common/pathSet.ts +16 -0
- package/common/randomPick.ts +1 -0
- package/common/randomPicks.ts +12 -0
- package/common/routeConvention.ts +203 -0
- package/common/sleep.ts +8 -0
- package/common/splitVersion.ts +11 -0
- package/common/subRoute.ts +34 -0
- package/common/types.ts +15 -0
- package/constant/constantRegistry.ts +334 -0
- package/constant/crystalize.ts +45 -0
- package/constant/deserialize.ts +70 -0
- package/constant/fieldInfo.ts +415 -0
- package/constant/getDefault.ts +18 -0
- package/constant/immerify.ts +16 -0
- package/constant/index.ts +10 -0
- package/constant/purify.ts +118 -0
- package/constant/serialize.ts +87 -0
- package/constant/types.ts +105 -0
- package/constant/via.ts +360 -0
- package/devkit/aiEditor.ts +299 -0
- package/devkit/akanApp/akanApp.host.ts +356 -0
- package/devkit/akanApp/index.ts +1 -0
- package/devkit/akanConfig/akanConfig.ts +332 -0
- package/devkit/akanConfig/index.ts +2 -0
- package/devkit/akanConfig/types.ts +187 -0
- package/devkit/applicationBuildReporter.ts +69 -0
- package/devkit/applicationBuildRunner.ts +302 -0
- package/devkit/applicationReleasePackager.ts +205 -0
- package/devkit/artifact/implicitRootLayout.ts +155 -0
- package/devkit/artifact/index.ts +1 -0
- package/devkit/artifact/routeSeedIndex.ts +128 -0
- package/devkit/auth.ts +41 -0
- package/devkit/builder.ts +164 -0
- package/devkit/capacitor.base.config.ts +74 -0
- package/devkit/capacitorApp.ts +385 -0
- package/devkit/commandDecorators/argMeta.ts +88 -0
- package/devkit/commandDecorators/command.ts +314 -0
- package/devkit/commandDecorators/commandBuilder.ts +188 -0
- package/devkit/commandDecorators/commandMeta.ts +6 -0
- package/devkit/commandDecorators/dependencyBuilder.ts +100 -0
- package/devkit/commandDecorators/helpFormatter.ts +217 -0
- package/devkit/commandDecorators/index.ts +8 -0
- package/devkit/commandDecorators/targetMeta.ts +31 -0
- package/devkit/commandDecorators/types.ts +10 -0
- package/devkit/constants.ts +25 -0
- package/devkit/createTunnel.ts +36 -0
- package/devkit/dependencyScanner.ts +339 -0
- package/devkit/executors.ts +1325 -0
- package/devkit/extractDeps.ts +85 -0
- package/devkit/fileEditor.ts +106 -0
- package/devkit/fileSys.ts +39 -0
- package/devkit/frontendBuild/allRoutesBuilder.ts +103 -0
- package/devkit/frontendBuild/clientBuildTypes.ts +114 -0
- package/devkit/frontendBuild/clientEntriesBundler.ts +300 -0
- package/devkit/frontendBuild/clientEntryDiscovery.ts +196 -0
- package/devkit/frontendBuild/csrArtifactBuilder.ts +237 -0
- package/devkit/frontendBuild/cssCompiler.ts +279 -0
- package/devkit/frontendBuild/cssImportResolver.ts +116 -0
- package/devkit/frontendBuild/fontOptimizer.ts +427 -0
- package/devkit/frontendBuild/hmrChangeClassifier.ts +28 -0
- package/devkit/frontendBuild/hmrWatcher.ts +101 -0
- package/devkit/frontendBuild/index.ts +18 -0
- package/devkit/frontendBuild/pagesBundleBuilder.ts +137 -0
- package/devkit/frontendBuild/pagesEntrySourceGenerator.ts +37 -0
- package/devkit/frontendBuild/precompressArtifacts.ts +59 -0
- package/devkit/frontendBuild/routeClientBuilder.ts +290 -0
- package/devkit/frontendBuild/routesManifestArtifactSerializer.ts +62 -0
- package/devkit/frontendBuild/ssrBaseArtifactBuilder.ts +139 -0
- package/devkit/frontendBuild/vendorSpecifiers.ts +16 -0
- package/devkit/frontendBuild/watchRootResolver.ts +28 -0
- package/devkit/getCredentials.ts +19 -0
- package/devkit/getDirname.ts +3 -0
- package/devkit/getModelFileData.ts +59 -0
- package/devkit/getRelatedCnsts.ts +300 -0
- package/devkit/guideline.ts +19 -0
- package/devkit/incrementalBuilder/incrementalBuilder.host.ts +78 -0
- package/devkit/incrementalBuilder/incrementalBuilder.proc.ts +330 -0
- package/devkit/incrementalBuilder/index.ts +1 -0
- package/devkit/index.ts +36 -0
- package/devkit/lint/no-import-client-functions.grit +32 -0
- package/devkit/lint/no-import-external-library.grit +21 -0
- package/devkit/lint/no-js-private-class-method.grit +42 -0
- package/devkit/lint/no-use-client-in-server.grit +7 -0
- package/devkit/lint/non-scalar-props-restricted.grit +13 -0
- package/devkit/linter.ts +248 -0
- package/devkit/mobile/index.ts +1 -0
- package/devkit/mobile/mobileTarget.ts +47 -0
- package/devkit/prompter.ts +71 -0
- package/devkit/scanInfo.ts +605 -0
- package/devkit/selectModel.ts +11 -0
- package/devkit/spinner.ts +54 -0
- package/devkit/sshTunnel.ts +151 -0
- package/devkit/streamAi.ts +45 -0
- package/devkit/transforms/barrelAnalyzer.ts +249 -0
- package/devkit/transforms/barrelImportsPlugin.ts +451 -0
- package/devkit/transforms/externalizeFrameworkPlugin.ts +159 -0
- package/devkit/transforms/index.ts +5 -0
- package/devkit/transforms/rscUseClientTransform.ts +52 -0
- package/devkit/transforms/useClientBundlePlugin.ts +47 -0
- package/devkit/typeChecker.ts +260 -0
- package/devkit/types.ts +42 -0
- package/devkit/ui/MultiScrollList.tsx +228 -0
- package/devkit/ui/ScrollList.tsx +106 -0
- package/devkit/ui/index.ts +2 -0
- package/devkit/uploadRelease.ts +95 -0
- package/devkit/useStdoutDimensions.ts +20 -0
- package/dictionary/base.dictionary.ts +91 -0
- package/dictionary/dictInfo.ts +1079 -0
- package/dictionary/dictionary.ts +10 -0
- package/dictionary/index.ts +12 -0
- package/dictionary/locale.ts +230 -0
- package/dictionary/trans.ts +196 -0
- package/document/by.ts +39 -0
- package/document/dataLoader.ts +91 -0
- package/document/database.ts +168 -0
- package/document/databaseRegistry.ts +113 -0
- package/document/documentQuery.ts +143 -0
- package/document/documentSchema.ts +91 -0
- package/document/filterMeta.ts +210 -0
- package/document/index.ts +11 -0
- package/document/into.ts +169 -0
- package/document/loaderInfo.ts +50 -0
- package/document/schema.ts +24 -0
- package/document/types.ts +41 -0
- package/fetch/client/fetchClient.ts +600 -0
- package/fetch/client/httpClient.ts +157 -0
- package/fetch/client/index.ts +3 -0
- package/fetch/client/wsClient.ts +246 -0
- package/fetch/fetchType/appliedReturn.type.ts +108 -0
- package/fetch/fetchType/buildFetch.type.ts +24 -0
- package/fetch/fetchType/clientSignal.type.ts +22 -0
- package/fetch/fetchType/endpointFetch.type.ts +56 -0
- package/fetch/fetchType/index.ts +5 -0
- package/fetch/fetchType/sliceFetch.type.ts +173 -0
- package/fetch/index.ts +4 -0
- package/fetch/requestStorage.ts +127 -0
- package/fetch/serializer/fetch.serializer.ts +131 -0
- package/fetch/serializer/index.ts +1 -0
- package/fetch/types.ts +28 -0
- package/package.json +202 -5
- package/server/SSR_MEMORY_DIAGNOSIS.md +107 -0
- package/server/akanApp.ts +855 -0
- package/server/akanLib.ts +43 -0
- package/server/akanOption.ts +42 -0
- package/server/akanServer.ts +369 -0
- package/server/artifact/builderRpc.ts +124 -0
- package/server/artifact/index.ts +6 -0
- package/server/artifact/ipcTypes.ts +46 -0
- package/server/artifact/manifestTypes.ts +19 -0
- package/server/artifact/routeClientCache.ts +224 -0
- package/server/artifact/routeSeedIndexStore.ts +89 -0
- package/server/artifact/routesManifestStore.ts +120 -0
- package/server/decorators.ts +95 -0
- package/server/di/diLifecycle.ts +520 -0
- package/server/di/index.ts +4 -0
- package/server/di/predefinedAdaptor.ts +77 -0
- package/server/di/resolveAdaptorHierarchy.ts +82 -0
- package/server/di/resolveHierarchy.ts +89 -0
- package/server/di/resolveServiceHierarchy.ts +47 -0
- package/server/di/utils.ts +40 -0
- package/server/hmr/changeBatch.ts +14 -0
- package/server/hmr/clientScript.ts +310 -0
- package/server/hmr/devHmrController.ts +395 -0
- package/server/hmr/index.ts +4 -0
- package/server/hmr/wsHub.ts +56 -0
- package/server/imageOptimizer.ts +427 -0
- package/server/imageOptimizerError.ts +8 -0
- package/server/index.ts +14 -0
- package/server/lifecycle/shutdownManager.ts +52 -0
- package/server/logging/rotatingLogWriter.ts +190 -0
- package/server/processMetricsCollector.ts +78 -0
- package/server/proxy/akanResponse.ts +16 -0
- package/server/proxy/bunRequestFields.ts +12 -0
- package/server/proxy/hostBasePathWebProxy.ts +112 -0
- package/server/proxy/index.ts +15 -0
- package/server/proxy/localeWebProxy.ts +71 -0
- package/server/proxy/types.ts +41 -0
- package/server/proxy/webProxyRunner.ts +90 -0
- package/server/resolver/database.resolver.ts +340 -0
- package/server/resolver/index.ts +3 -0
- package/server/resolver/resolver.contract.fixture.ts +222 -0
- package/server/resolver/service.resolver.ts +176 -0
- package/server/resolver/signal.resolver.ts +386 -0
- package/server/robots.ts +32 -0
- package/server/routeElementComposer.tsx +91 -0
- package/server/routeTreeBuilder.ts +279 -0
- package/server/routing/apiRouter.ts +226 -0
- package/server/rscClient.tsx +140 -0
- package/server/rscWorker.tsx +625 -0
- package/server/rscWorkerHost.ts +616 -0
- package/server/sitemap.ts +90 -0
- package/server/ssrFromRscRenderer.tsx +285 -0
- package/server/ssrTypes.ts +48 -0
- package/server/types/react-server-dom-webpack.d.ts +91 -0
- package/server/types.tsx +109 -0
- package/server/vendor/akanjs-base.ts +1 -0
- package/server/vendor/akanjs-common.ts +1 -0
- package/server/vendor/akanjs-constant.ts +1 -0
- package/server/vendor/akanjs-store.ts +1 -0
- package/server/vendor/react-dom-client.ts +5 -0
- package/server/vendor/react-dom.ts +21 -0
- package/server/vendor/react-jsx-dev-runtime.ts +5 -0
- package/server/vendor/react-jsx-runtime.ts +5 -0
- package/server/vendor/react-refresh-runtime.ts +6 -0
- package/server/vendor/react-server-dom-webpack-client-browser.ts +12 -0
- package/server/vendor/react.ts +51 -0
- package/server/vendor/scheduler.ts +23 -0
- package/server/webRouter.ts +712 -0
- package/service/adapt.ts +47 -0
- package/service/base.service.ts +18 -0
- package/service/index.ts +10 -0
- package/service/injectInfo.ts +393 -0
- package/service/ipcTypes.ts +127 -0
- package/service/predefinedAdaptor/cache.adaptor.ts +105 -0
- package/service/predefinedAdaptor/compress.adaptor.ts +357 -0
- package/service/predefinedAdaptor/database.adaptor.ts +1310 -0
- package/service/predefinedAdaptor/index.ts +13 -0
- package/service/predefinedAdaptor/logging.adaptor.ts +36 -0
- package/service/predefinedAdaptor/queue.adaptor.ts +42 -0
- package/service/predefinedAdaptor/role.adaptor.ts +18 -0
- package/service/predefinedAdaptor/schedule.adaptor.ts +188 -0
- package/service/predefinedAdaptor/solidCache.adaptor.ts +143 -0
- package/service/predefinedAdaptor/solidPubsub.adaptor.ts +98 -0
- package/service/predefinedAdaptor/solidQueue.adaptor.ts +203 -0
- package/service/predefinedAdaptor/solidSqlite.ts +85 -0
- package/service/predefinedAdaptor/sqlitePath.ts +20 -0
- package/service/predefinedAdaptor/storage.adaptor.ts +121 -0
- package/service/predefinedAdaptor/websocket.adaptor.ts +313 -0
- package/service/serve.ts +223 -0
- package/service/serviceModule.ts +221 -0
- package/service/serviceRegistry.ts +26 -0
- package/service/types.ts +113 -0
- package/signal/base.signal.ts +46 -0
- package/signal/endpoint.ts +122 -0
- package/signal/endpointInfo.ts +374 -0
- package/signal/exception.ts +50 -0
- package/signal/guard.ts +18 -0
- package/signal/guards.ts +16 -0
- package/signal/index.ts +18 -0
- package/signal/intercept.ts +39 -0
- package/signal/internal.ts +56 -0
- package/signal/internalArg.ts +38 -0
- package/signal/internalInfo.ts +208 -0
- package/signal/middleware.ts +108 -0
- package/signal/serializer/fetch.serializer.ts +128 -0
- package/signal/serializer/index.ts +1 -0
- package/signal/serverSignal.ts +114 -0
- package/signal/signalContext.ts +446 -0
- package/signal/signalRegistry.ts +82 -0
- package/signal/slice.ts +158 -0
- package/signal/sliceInfo.ts +254 -0
- package/signal/types.ts +131 -0
- package/store/action.ts +1067 -0
- package/store/baseSt.ts +81 -0
- package/store/hooks.ts +2 -0
- package/store/index.ts +8 -0
- package/store/rootStore.ts +26 -0
- package/store/state.ts +226 -0
- package/store/stateBuilder.ts +429 -0
- package/store/stateInfo.ts +66 -0
- package/store/store.ts +194 -0
- package/store/storeInstance.ts +382 -0
- package/store/storeRegistry.ts +84 -0
- package/store/types.ts +69 -0
- package/store/withSelector.ts +62 -0
- package/test/index.ts +16 -0
- package/test/playwright.config.base.ts +48 -0
- package/test/playwright.pageAgent.ts +41 -0
- package/test/sample.ts +19 -0
- package/test/sampleOf.ts +70 -0
- package/test/signalTest.preload.ts +10 -0
- package/test/signalTestRuntime.ts +126 -0
- package/test/testServer.ts +187 -0
- package/ui/BottomSheet.tsx +103 -0
- package/ui/Button.tsx +70 -0
- package/ui/ClientSide.tsx +11 -0
- package/ui/Clipboard.tsx +49 -0
- package/ui/Constant/Doc.tsx +696 -0
- package/ui/Constant/Mermaid.tsx +149 -0
- package/ui/Constant/index.ts +6 -0
- package/ui/Constant/schemaDoc.ts +324 -0
- package/ui/Copy.tsx +27 -0
- package/ui/CsrImage.tsx +38 -0
- package/ui/Data/CardList.tsx +141 -0
- package/ui/Data/Dashboard.tsx +72 -0
- package/ui/Data/Insight.tsx +35 -0
- package/ui/Data/Item.tsx +285 -0
- package/ui/Data/ListContainer.tsx +320 -0
- package/ui/Data/Pagination.tsx +54 -0
- package/ui/Data/QueryMaker.tsx +21 -0
- package/ui/Data/TableList.tsx +161 -0
- package/ui/Data/index.ts +11 -0
- package/ui/Data/index_.tsx +11 -0
- package/ui/DatePicker.tsx +184 -0
- package/ui/Dialog/Action.tsx +15 -0
- package/ui/Dialog/Close.tsx +22 -0
- package/ui/Dialog/Content.tsx +11 -0
- package/ui/Dialog/Modal.tsx +137 -0
- package/ui/Dialog/Provider.tsx +33 -0
- package/ui/Dialog/Title.tsx +15 -0
- package/ui/Dialog/Trigger.tsx +22 -0
- package/ui/Dialog/context.ts +20 -0
- package/ui/Dialog/index.tsx +15 -0
- package/ui/DragAction.tsx +129 -0
- package/ui/DraggableList.tsx +230 -0
- package/ui/Dropdown.tsx +51 -0
- package/ui/Empty.tsx +32 -0
- package/ui/Field.tsx +1556 -0
- package/ui/FontFace.tsx +26 -0
- package/ui/Image.tsx +185 -0
- package/ui/InfiniteScroll.tsx +67 -0
- package/ui/Input.tsx +636 -0
- package/ui/KeyboardAvoiding.tsx +62 -0
- package/ui/Layout/BottomAction.tsx +15 -0
- package/ui/Layout/BottomInset.tsx +42 -0
- package/ui/Layout/BottomTab.tsx +71 -0
- package/ui/Layout/Header.tsx +38 -0
- package/ui/Layout/LeftSider.tsx +34 -0
- package/ui/Layout/Navbar.tsx +46 -0
- package/ui/Layout/RightSider.tsx +41 -0
- package/ui/Layout/Sider.tsx +69 -0
- package/ui/Layout/Template.tsx +11 -0
- package/ui/Layout/TopLeftAction.tsx +28 -0
- package/ui/Layout/Unit.tsx +19 -0
- package/ui/Layout/View.tsx +12 -0
- package/ui/Layout/Zone.tsx +10 -0
- package/ui/Layout/index.ts +27 -0
- package/ui/Link/Back.tsx +15 -0
- package/ui/Link/Close.tsx +20 -0
- package/ui/Link/CsrLink.tsx +41 -0
- package/ui/Link/Lang.tsx +16 -0
- package/ui/Link/SsrLink.tsx +68 -0
- package/ui/Link/index.tsx +32 -0
- package/ui/Link/types.ts +47 -0
- package/ui/Load/Edit.tsx +19 -0
- package/ui/Load/Edit_Client.tsx +120 -0
- package/ui/Load/Page.tsx +40 -0
- package/ui/Load/PageCSR.tsx +39 -0
- package/ui/Load/Pagination.tsx +89 -0
- package/ui/Load/Units.tsx +330 -0
- package/ui/Load/View.tsx +115 -0
- package/ui/Load/index.ts +11 -0
- package/ui/Load/index_.tsx +6 -0
- package/ui/Loading/Area.tsx +10 -0
- package/ui/Loading/Button.tsx +17 -0
- package/ui/Loading/Input.tsx +17 -0
- package/ui/Loading/ProgressBar.tsx +14 -0
- package/ui/Loading/Skeleton.tsx +22 -0
- package/ui/Loading/Spin.tsx +22 -0
- package/ui/Loading/index.tsx +8 -0
- package/ui/Menu.tsx +273 -0
- package/ui/Modal.tsx +87 -0
- package/ui/Model/AdminPanel.tsx +51 -0
- package/ui/Model/Edit.tsx +46 -0
- package/ui/Model/EditModal.tsx +301 -0
- package/ui/Model/EditWrapper.tsx +48 -0
- package/ui/Model/LoadInit.tsx +11 -0
- package/ui/Model/New.tsx +46 -0
- package/ui/Model/NewWrapper.tsx +20 -0
- package/ui/Model/NewWrapper_Client.tsx +57 -0
- package/ui/Model/Remove.tsx +75 -0
- package/ui/Model/RemoveWrapper.tsx +38 -0
- package/ui/Model/SureToRemove.tsx +108 -0
- package/ui/Model/View.tsx +65 -0
- package/ui/Model/ViewEditModal.tsx +125 -0
- package/ui/Model/ViewModal.tsx +71 -0
- package/ui/Model/ViewWrapper.tsx +38 -0
- package/ui/Model/index.ts +33 -0
- package/ui/Model/index_.tsx +16 -0
- package/ui/More.tsx +56 -0
- package/ui/ObjectId.tsx +29 -0
- package/ui/Pagination.tsx +120 -0
- package/ui/Popconfirm.tsx +135 -0
- package/ui/Portal.tsx +10 -0
- package/ui/Radio.tsx +53 -0
- package/ui/RecentTime.tsx +123 -0
- package/ui/Refresh.tsx +24 -0
- package/ui/ScreenNavigator.tsx +129 -0
- package/ui/Select.tsx +322 -0
- package/ui/Signal/Arg.tsx +352 -0
- package/ui/Signal/Doc.tsx +231 -0
- package/ui/Signal/Listener.tsx +74 -0
- package/ui/Signal/Message.tsx +267 -0
- package/ui/Signal/Object.tsx +131 -0
- package/ui/Signal/PubSub.tsx +247 -0
- package/ui/Signal/Request.tsx +30 -0
- package/ui/Signal/Response.tsx +76 -0
- package/ui/Signal/RestApi.tsx +390 -0
- package/ui/Signal/WebSocket.tsx +47 -0
- package/ui/Signal/index.ts +10 -0
- package/ui/Signal/makeExample.ts +75 -0
- package/ui/System/CSR.tsx +420 -0
- package/ui/System/Client.tsx +296 -0
- package/ui/System/Common.tsx +83 -0
- package/ui/System/DevModeToggle.tsx +21 -0
- package/ui/System/Gtag.tsx +69 -0
- package/ui/System/Messages.tsx +175 -0
- package/ui/System/Reconnect.tsx +156 -0
- package/ui/System/Root.tsx +10 -0
- package/ui/System/SSR.tsx +163 -0
- package/ui/System/SelectLanguage.tsx +47 -0
- package/ui/System/ThemeToggle.tsx +98 -0
- package/ui/System/index.tsx +23 -0
- package/ui/Tab/Menu.tsx +56 -0
- package/ui/Tab/Menus.tsx +10 -0
- package/ui/Tab/Panel.tsx +25 -0
- package/ui/Tab/Provider.tsx +25 -0
- package/ui/Tab/context.ts +16 -0
- package/ui/Tab/index.tsx +11 -0
- package/ui/Table.tsx +131 -0
- package/ui/ToggleSelect.tsx +144 -0
- package/ui/Unauthorized.tsx +29 -0
- package/ui/animated.tsx +8 -0
- package/ui/fontCss.ts +86 -0
- package/ui/index.ts +44 -0
- package/ui/styles.css +617 -0
- package/webkit/bootCsr.tsx +275 -0
- package/webkit/createRobotPage.ts +15 -0
- package/webkit/createSitemapPage.ts +4 -0
- package/webkit/index.ts +19 -0
- package/webkit/lazy.tsx +37 -0
- package/webkit/types.ts +7 -0
- package/webkit/useCamera.tsx +99 -0
- package/webkit/useCodepush.tsx +99 -0
- package/webkit/useContact.tsx +48 -0
- package/webkit/useCsrValues.ts +661 -0
- package/webkit/useDebounce.ts +24 -0
- package/webkit/useFetch.ts +48 -0
- package/webkit/useGeoLocation.tsx +24 -0
- package/webkit/useHistory.ts +76 -0
- package/webkit/useInterval.ts +21 -0
- package/webkit/useLocation.ts +69 -0
- package/webkit/usePurchase.tsx +156 -0
- package/webkit/usePushNoti.tsx +48 -0
- package/webkit/useThrottle.ts +22 -0
- package/src/index.js +0 -2
- package/src/index.js.map +0 -1
- package/src/lib/akan2.js +0 -4
- package/src/lib/akan2.js.map +0 -1
- package/src/run.js +0 -4
- package/src/run.js.map +0 -1
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import sharp from "sharp";
|
|
5
|
+
import { ImageOptimizerError } from "./imageOptimizerError";
|
|
6
|
+
import {
|
|
7
|
+
type AkanImageConfig,
|
|
8
|
+
type AkanImageFormat,
|
|
9
|
+
type AkanImagePattern,
|
|
10
|
+
getAkanImageWidths,
|
|
11
|
+
mergeAkanImageConfig,
|
|
12
|
+
} from "./types";
|
|
13
|
+
|
|
14
|
+
export interface ImageOptimizerOptions {
|
|
15
|
+
publicDir: string;
|
|
16
|
+
cacheDir: string;
|
|
17
|
+
prodMode: boolean;
|
|
18
|
+
config?: Partial<AkanImageConfig>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface ParsedImageRequest {
|
|
22
|
+
href: string;
|
|
23
|
+
width: number;
|
|
24
|
+
quality: number;
|
|
25
|
+
outputType: AkanImageFormat | "";
|
|
26
|
+
isRemote: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface ImageSource {
|
|
30
|
+
buffer: Buffer;
|
|
31
|
+
contentType: string;
|
|
32
|
+
cacheControl?: string | null;
|
|
33
|
+
upstreamTag: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface OptimizedImage {
|
|
37
|
+
buffer: Buffer;
|
|
38
|
+
contentType: string;
|
|
39
|
+
etag: string;
|
|
40
|
+
maxAge: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class ImageOptimizer {
|
|
44
|
+
static readonly #optimizerPath = "/_akan/image";
|
|
45
|
+
static readonly #svg = "image/svg+xml";
|
|
46
|
+
static readonly #jpeg = "image/jpeg";
|
|
47
|
+
static readonly #png = "image/png";
|
|
48
|
+
static readonly #webp = "image/webp";
|
|
49
|
+
static readonly #gif = "image/gif";
|
|
50
|
+
static readonly #avif = "image/avif";
|
|
51
|
+
static readonly #bypassTypes = new Set(["image/x-icon", "image/x-icns", "image/bmp", "image/jxl", "image/heic"]);
|
|
52
|
+
|
|
53
|
+
#publicDir: string;
|
|
54
|
+
#cacheDir: string;
|
|
55
|
+
#prodMode: boolean;
|
|
56
|
+
#config: AkanImageConfig;
|
|
57
|
+
|
|
58
|
+
constructor({ publicDir, cacheDir, prodMode, config }: ImageOptimizerOptions) {
|
|
59
|
+
this.#publicDir = publicDir;
|
|
60
|
+
this.#cacheDir = cacheDir;
|
|
61
|
+
this.#prodMode = prodMode;
|
|
62
|
+
this.#config = mergeAkanImageConfig(config);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async handle(req: Request): Promise<Response> {
|
|
66
|
+
const parsed = this.#parseRequest(req);
|
|
67
|
+
if ("error" in parsed) return new Response(parsed.error, { status: 400 });
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
const source = parsed.isRemote
|
|
71
|
+
? await this.#fetchRemoteImage(parsed.href)
|
|
72
|
+
: await this.#readLocalImage(parsed.href);
|
|
73
|
+
const optimized = await this.#getOptimizedImage(source, parsed);
|
|
74
|
+
return this.#imageResponse(req, optimized);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
const message = error instanceof ImageOptimizerError ? error.message : "Unable to optimize image";
|
|
77
|
+
const status = error instanceof ImageOptimizerError ? error.status : 500;
|
|
78
|
+
return new Response(message, { status });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
#parseRequest(req: Request): ParsedImageRequest | { error: string } {
|
|
83
|
+
const reqUrl = new URL(req.url);
|
|
84
|
+
const url = reqUrl.searchParams.get("url");
|
|
85
|
+
const widthParam = reqUrl.searchParams.get("w");
|
|
86
|
+
const qualityParam = reqUrl.searchParams.get("q");
|
|
87
|
+
|
|
88
|
+
if (!url) return { error: '"url" parameter is required' };
|
|
89
|
+
if (url.length > 3072) return { error: '"url" parameter is too long' };
|
|
90
|
+
if (url.startsWith("//")) return { error: '"url" parameter cannot be a protocol-relative URL' };
|
|
91
|
+
|
|
92
|
+
let href: string;
|
|
93
|
+
let isRemote = false;
|
|
94
|
+
if (url.startsWith("/")) {
|
|
95
|
+
href = url;
|
|
96
|
+
const pathname = ImageOptimizer.#safeDecodePathname(url);
|
|
97
|
+
if (!pathname) return { error: '"url" parameter is invalid' };
|
|
98
|
+
if (pathname === ImageOptimizer.#optimizerPath || pathname.startsWith(`${ImageOptimizer.#optimizerPath}/`)) {
|
|
99
|
+
return { error: '"url" parameter cannot be recursive' };
|
|
100
|
+
}
|
|
101
|
+
if (!ImageOptimizer.#hasLocalMatch(this.#config.localPatterns, url)) {
|
|
102
|
+
return { error: '"url" parameter is not allowed' };
|
|
103
|
+
}
|
|
104
|
+
} else {
|
|
105
|
+
let parsed: URL;
|
|
106
|
+
try {
|
|
107
|
+
parsed = new URL(url);
|
|
108
|
+
} catch {
|
|
109
|
+
return { error: '"url" parameter is invalid' };
|
|
110
|
+
}
|
|
111
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return { error: '"url" parameter is invalid' };
|
|
112
|
+
if (!ImageOptimizer.#hasRemoteMatch(this.#config.remotePatterns, parsed)) {
|
|
113
|
+
return { error: '"url" parameter is not allowed' };
|
|
114
|
+
}
|
|
115
|
+
href = parsed.toString();
|
|
116
|
+
isRemote = true;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (!widthParam || !/^[0-9]+$/.test(widthParam)) {
|
|
120
|
+
return { error: '"w" parameter (width) must be an integer greater than 0' };
|
|
121
|
+
}
|
|
122
|
+
const width = Number.parseInt(widthParam, 10);
|
|
123
|
+
if (!getAkanImageWidths(this.#config).includes(width)) {
|
|
124
|
+
return { error: `"w" parameter (width) of ${width} is not allowed` };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (!qualityParam || !/^[0-9]+$/.test(qualityParam)) {
|
|
128
|
+
return { error: '"q" parameter (quality) must be an integer between 1 and 100' };
|
|
129
|
+
}
|
|
130
|
+
const quality = Number.parseInt(qualityParam, 10);
|
|
131
|
+
if (quality < 1 || quality > 100) return { error: '"q" parameter (quality) must be an integer between 1 and 100' };
|
|
132
|
+
if (!this.#config.qualities.includes(quality)) {
|
|
133
|
+
return { error: `"q" parameter (quality) of ${quality} is not allowed` };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
href,
|
|
138
|
+
width,
|
|
139
|
+
quality,
|
|
140
|
+
outputType: ImageOptimizer.#getPreferredOutputType(req.headers.get("accept") ?? "", this.#config.formats),
|
|
141
|
+
isRemote,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async #readLocalImage(href: string): Promise<ImageSource> {
|
|
146
|
+
const url = new URL(href, "http://local.akan");
|
|
147
|
+
const filePath = ImageOptimizer.#safeResolve(this.#publicDir, url.pathname);
|
|
148
|
+
if (!filePath) throw new ImageOptimizerError(400, '"url" parameter is not allowed');
|
|
149
|
+
const file = Bun.file(filePath);
|
|
150
|
+
if (!(await file.exists())) throw new ImageOptimizerError(404, "Image not found");
|
|
151
|
+
const stat = await fs.stat(filePath);
|
|
152
|
+
const buffer = Buffer.from(await file.arrayBuffer());
|
|
153
|
+
return {
|
|
154
|
+
buffer,
|
|
155
|
+
contentType: file.type || ImageOptimizer.#detectContentType(buffer) || "application/octet-stream",
|
|
156
|
+
upstreamTag: `${stat.mtimeMs}:${stat.size}`,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async #fetchRemoteImage(href: string): Promise<ImageSource> {
|
|
161
|
+
let current = new URL(href);
|
|
162
|
+
for (let redirect = 0; redirect <= this.#config.maximumRedirects; redirect += 1) {
|
|
163
|
+
if (!ImageOptimizer.#hasRemoteMatch(this.#config.remotePatterns, current)) {
|
|
164
|
+
throw new ImageOptimizerError(400, '"url" parameter is not allowed');
|
|
165
|
+
}
|
|
166
|
+
const controller = new AbortController();
|
|
167
|
+
const timeout = setTimeout(() => controller.abort(), this.#config.fetchTimeoutMs);
|
|
168
|
+
try {
|
|
169
|
+
const res = await fetch(current, {
|
|
170
|
+
redirect: "manual",
|
|
171
|
+
signal: controller.signal,
|
|
172
|
+
headers: { accept: "image/*" },
|
|
173
|
+
});
|
|
174
|
+
if (res.status >= 300 && res.status < 400) {
|
|
175
|
+
const location = res.headers.get("location");
|
|
176
|
+
if (!location) throw new ImageOptimizerError(502, "Remote image redirect is missing location");
|
|
177
|
+
current = new URL(location, current);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (!res.ok) throw new ImageOptimizerError(res.status, "Remote image request failed");
|
|
181
|
+
const buffer = await ImageOptimizer.#readResponseBuffer(res, this.#config.maxRemoteBytes);
|
|
182
|
+
return {
|
|
183
|
+
buffer,
|
|
184
|
+
contentType:
|
|
185
|
+
res.headers.get("content-type")?.split(";")[0]?.trim() || ImageOptimizer.#detectContentType(buffer) || "",
|
|
186
|
+
cacheControl: res.headers.get("cache-control"),
|
|
187
|
+
upstreamTag: res.headers.get("etag") ?? ImageOptimizer.#hashBuffer(buffer),
|
|
188
|
+
};
|
|
189
|
+
} finally {
|
|
190
|
+
clearTimeout(timeout);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
throw new ImageOptimizerError(400, "Remote image exceeded maximum redirects");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async #getOptimizedImage(source: ImageSource, params: ParsedImageRequest): Promise<OptimizedImage> {
|
|
197
|
+
const inputType = ImageOptimizer.#detectContentType(source.buffer) || source.contentType;
|
|
198
|
+
if (!inputType || !inputType.startsWith("image/") || inputType.includes(",")) {
|
|
199
|
+
throw new ImageOptimizerError(400, "The requested resource is not a valid image");
|
|
200
|
+
}
|
|
201
|
+
if (inputType === ImageOptimizer.#svg && !this.#config.dangerouslyAllowSVG) {
|
|
202
|
+
throw new ImageOptimizerError(400, '"url" parameter is valid but image type is not allowed');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const maxAge = Math.max(this.#config.minimumCacheTTL, ImageOptimizer.#getMaxAge(source.cacheControl));
|
|
206
|
+
const shouldBypass =
|
|
207
|
+
inputType === ImageOptimizer.#svg ||
|
|
208
|
+
ImageOptimizer.#bypassTypes.has(inputType) ||
|
|
209
|
+
(await ImageOptimizer.#isAnimated(source.buffer, inputType));
|
|
210
|
+
const outputType =
|
|
211
|
+
shouldBypass || !params.outputType || inputType === ImageOptimizer.#webp || inputType === ImageOptimizer.#avif
|
|
212
|
+
? inputType
|
|
213
|
+
: params.outputType;
|
|
214
|
+
const cachePath = this.#getCachePath({
|
|
215
|
+
href: params.href,
|
|
216
|
+
width: params.width,
|
|
217
|
+
quality: params.quality,
|
|
218
|
+
outputType,
|
|
219
|
+
upstreamTag: source.upstreamTag,
|
|
220
|
+
});
|
|
221
|
+
const cached = Bun.file(cachePath);
|
|
222
|
+
if (await cached.exists()) {
|
|
223
|
+
const buffer = Buffer.from(await cached.arrayBuffer());
|
|
224
|
+
return { buffer, contentType: outputType, etag: ImageOptimizer.#hashBuffer(buffer), maxAge };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
let buffer = source.buffer;
|
|
228
|
+
let contentType = inputType;
|
|
229
|
+
let cacheable = true;
|
|
230
|
+
if (!shouldBypass) {
|
|
231
|
+
try {
|
|
232
|
+
buffer = await ImageOptimizer.#optimizeWithSharp(source.buffer, {
|
|
233
|
+
width: params.width,
|
|
234
|
+
quality: params.quality,
|
|
235
|
+
contentType: outputType,
|
|
236
|
+
});
|
|
237
|
+
contentType = outputType;
|
|
238
|
+
} catch {
|
|
239
|
+
buffer = source.buffer;
|
|
240
|
+
contentType = inputType;
|
|
241
|
+
cacheable = false;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (cacheable) {
|
|
246
|
+
await fs.mkdir(this.#cacheDir, { recursive: true });
|
|
247
|
+
await Bun.write(cachePath, buffer);
|
|
248
|
+
}
|
|
249
|
+
return { buffer, contentType, etag: ImageOptimizer.#hashBuffer(buffer), maxAge };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
#getCachePath(input: Record<string, string | number>) {
|
|
253
|
+
const contentType = String(input.outputType);
|
|
254
|
+
return path.join(
|
|
255
|
+
this.#cacheDir,
|
|
256
|
+
`${ImageOptimizer.#getCacheKey(input)}.${ImageOptimizer.#getExtension(contentType)}`,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
#imageResponse(req: Request, image: OptimizedImage) {
|
|
261
|
+
const headers = new Headers({
|
|
262
|
+
"Content-Type": image.contentType,
|
|
263
|
+
"Cache-Control": this.#prodMode
|
|
264
|
+
? `public, max-age=${image.maxAge}, must-revalidate`
|
|
265
|
+
: "public, max-age=0, must-revalidate",
|
|
266
|
+
ETag: image.etag,
|
|
267
|
+
Vary: "Accept",
|
|
268
|
+
});
|
|
269
|
+
if (req.headers.get("if-none-match") === image.etag) return new Response(null, { status: 304, headers });
|
|
270
|
+
return new Response(ImageOptimizer.#toArrayBuffer(image.buffer), { headers });
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
static async #optimizeWithSharp(
|
|
274
|
+
buffer: Buffer,
|
|
275
|
+
options: { width: number; quality: number; contentType: string },
|
|
276
|
+
): Promise<Buffer> {
|
|
277
|
+
if (sharp.concurrency() > 1) sharp.concurrency(Math.max(Math.floor(sharp.concurrency() / 2), 1));
|
|
278
|
+
const transformer = sharp(buffer, {
|
|
279
|
+
limitInputPixels: 268_402_689,
|
|
280
|
+
sequentialRead: true,
|
|
281
|
+
}).resize(options.width, undefined, { withoutEnlargement: true });
|
|
282
|
+
|
|
283
|
+
if (options.contentType === ImageOptimizer.#avif)
|
|
284
|
+
return await transformer.avif({ quality: options.quality }).toBuffer();
|
|
285
|
+
if (options.contentType === ImageOptimizer.#webp)
|
|
286
|
+
return await transformer.webp({ quality: options.quality }).toBuffer();
|
|
287
|
+
if (options.contentType === ImageOptimizer.#png)
|
|
288
|
+
return await transformer.png({ quality: options.quality }).toBuffer();
|
|
289
|
+
return await transformer.jpeg({ quality: options.quality }).toBuffer();
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
static #getPreferredOutputType(accept: string, formats: AkanImageFormat[]): AkanImageFormat | "" {
|
|
293
|
+
return formats.find((format) => accept.includes(format)) ?? "";
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
static #hasRemoteMatch(patterns: AkanImagePattern[], url: URL): boolean {
|
|
297
|
+
return patterns.some((pattern) => {
|
|
298
|
+
if (pattern.protocol && `${pattern.protocol}:` !== url.protocol) return false;
|
|
299
|
+
if (pattern.port !== undefined && pattern.port !== url.port) return false;
|
|
300
|
+
if (pattern.hostname && !ImageOptimizer.#globMatch(pattern.hostname, url.hostname)) return false;
|
|
301
|
+
if (pattern.pathname && !ImageOptimizer.#globMatch(pattern.pathname, url.pathname)) return false;
|
|
302
|
+
if (pattern.search !== undefined && pattern.search !== url.search) return false;
|
|
303
|
+
return true;
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
static #hasLocalMatch(patterns: Pick<AkanImagePattern, "pathname" | "search">[], href: string): boolean {
|
|
308
|
+
const url = new URL(href, "http://local.akan");
|
|
309
|
+
return patterns.some((pattern) => {
|
|
310
|
+
if (pattern.pathname && !ImageOptimizer.#globMatch(pattern.pathname, url.pathname)) return false;
|
|
311
|
+
if (pattern.search !== undefined && pattern.search !== url.search) return false;
|
|
312
|
+
return true;
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
static #globMatch(pattern: string, value: string): boolean {
|
|
317
|
+
const escaped = pattern
|
|
318
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
319
|
+
.replace(/\*\*/g, "__AKAN_DOUBLE_STAR__")
|
|
320
|
+
.replace(/\*/g, "[^/]*")
|
|
321
|
+
.replace(/__AKAN_DOUBLE_STAR__/g, ".*");
|
|
322
|
+
return new RegExp(`^${escaped}$`).test(value);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
static #safeDecodePathname(href: string): string | null {
|
|
326
|
+
try {
|
|
327
|
+
return decodeURIComponent(new URL(href, "http://local.akan").pathname);
|
|
328
|
+
} catch {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
static #safeResolve(baseDir: string, urlPath: string): string | null {
|
|
334
|
+
let decoded: string;
|
|
335
|
+
try {
|
|
336
|
+
decoded = decodeURIComponent(urlPath);
|
|
337
|
+
} catch {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
if (decoded.includes("\0")) return null;
|
|
341
|
+
const normalizedBase = path.resolve(baseDir);
|
|
342
|
+
const rel = decoded.replace(/^[/\\]+/, "");
|
|
343
|
+
const resolved = path.resolve(normalizedBase, rel);
|
|
344
|
+
if (resolved === normalizedBase) return resolved;
|
|
345
|
+
const baseWithSep = normalizedBase.endsWith(path.sep) ? normalizedBase : normalizedBase + path.sep;
|
|
346
|
+
return resolved.startsWith(baseWithSep) ? resolved : null;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
static async #readResponseBuffer(res: Response, maxBytes: number): Promise<Buffer> {
|
|
350
|
+
const contentLength = Number.parseInt(res.headers.get("content-length") ?? "0", 10);
|
|
351
|
+
if (contentLength > maxBytes) throw new ImageOptimizerError(413, "Remote image is too large");
|
|
352
|
+
const reader = res.body?.getReader();
|
|
353
|
+
if (!reader) return Buffer.from(await res.arrayBuffer());
|
|
354
|
+
const chunks: Uint8Array[] = [];
|
|
355
|
+
let bytes = 0;
|
|
356
|
+
while (true) {
|
|
357
|
+
const { done, value } = await reader.read();
|
|
358
|
+
if (done) break;
|
|
359
|
+
bytes += value.byteLength;
|
|
360
|
+
if (bytes > maxBytes) throw new ImageOptimizerError(413, "Remote image is too large");
|
|
361
|
+
chunks.push(value);
|
|
362
|
+
}
|
|
363
|
+
return Buffer.concat(chunks);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
static async #isAnimated(buffer: Buffer, contentType: string): Promise<boolean> {
|
|
367
|
+
if (
|
|
368
|
+
contentType !== ImageOptimizer.#gif &&
|
|
369
|
+
contentType !== ImageOptimizer.#webp &&
|
|
370
|
+
contentType !== ImageOptimizer.#png
|
|
371
|
+
)
|
|
372
|
+
return false;
|
|
373
|
+
try {
|
|
374
|
+
const metadata = await sharp(buffer, { animated: true }).metadata();
|
|
375
|
+
return Boolean(metadata.pages && metadata.pages > 1);
|
|
376
|
+
} catch {
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
static #detectContentType(buffer: Buffer): string | null {
|
|
382
|
+
if (buffer.length < 12) return null;
|
|
383
|
+
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return ImageOptimizer.#jpeg;
|
|
384
|
+
if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47)
|
|
385
|
+
return ImageOptimizer.#png;
|
|
386
|
+
if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) return ImageOptimizer.#gif;
|
|
387
|
+
if (buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP")
|
|
388
|
+
return ImageOptimizer.#webp;
|
|
389
|
+
if (buffer.toString("ascii", 4, 12).includes("ftypavif")) return ImageOptimizer.#avif;
|
|
390
|
+
const prefix = buffer.toString("utf8", 0, Math.min(buffer.length, 256)).trimStart().toLowerCase();
|
|
391
|
+
if (prefix.startsWith("<svg") || prefix.startsWith("<?xml")) return ImageOptimizer.#svg;
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
static #getMaxAge(cacheControl: string | null | undefined): number {
|
|
396
|
+
const match = cacheControl?.match(/\b(?:s-maxage|max-age)=(\d+)/i);
|
|
397
|
+
return match ? Number.parseInt(match[1], 10) : 0;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
static #getCacheKey(input: Record<string, string | number>) {
|
|
401
|
+
return createHash("sha256").update(JSON.stringify(input)).digest("hex");
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
static #hashBuffer(buffer: Buffer) {
|
|
405
|
+
return `"${createHash("sha256").update(buffer).digest("base64url")}"`;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
static #toArrayBuffer(buffer: Buffer): ArrayBuffer {
|
|
409
|
+
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) as ArrayBuffer;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
static #getExtension(contentType: string) {
|
|
413
|
+
switch (contentType) {
|
|
414
|
+
case ImageOptimizer.#avif:
|
|
415
|
+
return "avif";
|
|
416
|
+
case ImageOptimizer.#webp:
|
|
417
|
+
return "webp";
|
|
418
|
+
case ImageOptimizer.#png:
|
|
419
|
+
return "png";
|
|
420
|
+
case ImageOptimizer.#gif:
|
|
421
|
+
return "gif";
|
|
422
|
+
case ImageOptimizer.#svg:
|
|
423
|
+
return "svg";
|
|
424
|
+
}
|
|
425
|
+
return "jpg";
|
|
426
|
+
}
|
|
427
|
+
}
|
package/server/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export * from "./akanApp";
|
|
2
|
+
export * from "./akanLib";
|
|
3
|
+
export * from "./akanOption";
|
|
4
|
+
export * from "./akanServer";
|
|
5
|
+
export * from "./artifact";
|
|
6
|
+
export * from "./decorators";
|
|
7
|
+
export type { ChangeBatch, ChangeKind } from "./hmr/changeBatch";
|
|
8
|
+
export * from "./processMetricsCollector";
|
|
9
|
+
export * from "./proxy";
|
|
10
|
+
export * from "./routeElementComposer";
|
|
11
|
+
export * from "./routeTreeBuilder";
|
|
12
|
+
export * from "./sitemap";
|
|
13
|
+
export type { SsrManifest, SsrManifestEntry } from "./ssrTypes";
|
|
14
|
+
export * from "./types";
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Logger } from "akanjs/common";
|
|
2
|
+
|
|
3
|
+
export class ShutdownManager {
|
|
4
|
+
/**
|
|
5
|
+
* Registers process-level handlers that drive `onShutdown` on:
|
|
6
|
+
* - SIGTERM / SIGINT (graceful stop → exit(0) on success, exit(1) on error)
|
|
7
|
+
* - uncaughtException / unhandledRejection (best-effort stop → exit(1))
|
|
8
|
+
*
|
|
9
|
+
* Kept separate from `AkanServer` so the server class doesn't have to know about
|
|
10
|
+
* Node-level process events, and so tests can opt out by not calling it.
|
|
11
|
+
*/
|
|
12
|
+
static register(logger: Logger, onShutdown: () => Promise<void>): void {
|
|
13
|
+
const signals: NodeJS.Signals[] = ["SIGTERM", "SIGINT"];
|
|
14
|
+
|
|
15
|
+
for (const signal of signals) {
|
|
16
|
+
process.on(signal, async () => {
|
|
17
|
+
logger.info(`Received ${signal}, starting graceful shutdown...`);
|
|
18
|
+
try {
|
|
19
|
+
await onShutdown();
|
|
20
|
+
process.exit(0);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
logger.error(`Failed to shutdown gracefully: ${error instanceof Error ? error.message : String(error)}`);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
process.on("uncaughtException", async (error) => {
|
|
29
|
+
logger.error(`Uncaught exception: ${ShutdownManager.#formatError(error)}`);
|
|
30
|
+
try {
|
|
31
|
+
await onShutdown();
|
|
32
|
+
process.exit(1);
|
|
33
|
+
} catch {
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
process.on("unhandledRejection", async (reason) => {
|
|
39
|
+
logger.error(`Unhandled rejection: ${ShutdownManager.#formatError(reason)}`);
|
|
40
|
+
try {
|
|
41
|
+
await onShutdown();
|
|
42
|
+
process.exit(1);
|
|
43
|
+
} catch {
|
|
44
|
+
process.exit(1);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
static #formatError(error: unknown): string {
|
|
50
|
+
return error instanceof Error ? (error.stack ?? error.message) : String(error);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { appendFile, mkdir, readdir, rm, stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { getEnv } from "akanjs/base";
|
|
4
|
+
import dayjs from "dayjs";
|
|
5
|
+
|
|
6
|
+
interface RotatingLogWriterState {
|
|
7
|
+
date: string;
|
|
8
|
+
sequence: number;
|
|
9
|
+
sizeBytes: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface RotatingLogWriterFile {
|
|
13
|
+
fileName: string;
|
|
14
|
+
date: string;
|
|
15
|
+
sequence: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RotatingLogWriterOptions {
|
|
19
|
+
logDir: string;
|
|
20
|
+
appName: string;
|
|
21
|
+
environment: string;
|
|
22
|
+
operationMode: string;
|
|
23
|
+
maxSizeBytes?: number;
|
|
24
|
+
maxFiles?: number;
|
|
25
|
+
now?: () => Date;
|
|
26
|
+
warn?: (message: string) => void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class RotatingLogWriter {
|
|
30
|
+
static readonly defaultMaxSizeBytes = 50 * 1024 * 1024;
|
|
31
|
+
static readonly defaultMaxFiles = 100;
|
|
32
|
+
|
|
33
|
+
readonly #logDir: string;
|
|
34
|
+
readonly #basePrefix: string;
|
|
35
|
+
readonly #maxSizeBytes: number;
|
|
36
|
+
readonly #maxFiles: number;
|
|
37
|
+
readonly #now: () => Date;
|
|
38
|
+
readonly #warn: (message: string) => void;
|
|
39
|
+
readonly #states = new Map<string, RotatingLogWriterState>();
|
|
40
|
+
readonly #queues = new Map<string, Promise<void>>();
|
|
41
|
+
readonly #encoder = new TextEncoder();
|
|
42
|
+
#ready: Promise<void> | null = null;
|
|
43
|
+
|
|
44
|
+
constructor(options: RotatingLogWriterOptions) {
|
|
45
|
+
this.#logDir = options.logDir;
|
|
46
|
+
this.#basePrefix = [
|
|
47
|
+
RotatingLogWriter.sanitizeFilePart(options.appName),
|
|
48
|
+
RotatingLogWriter.sanitizeFilePart(options.environment),
|
|
49
|
+
RotatingLogWriter.sanitizeFilePart(options.operationMode),
|
|
50
|
+
].join("-");
|
|
51
|
+
this.#maxSizeBytes = options.maxSizeBytes ?? RotatingLogWriter.defaultMaxSizeBytes;
|
|
52
|
+
this.#maxFiles = options.maxFiles ?? RotatingLogWriter.defaultMaxFiles;
|
|
53
|
+
this.#now = options.now ?? (() => new Date());
|
|
54
|
+
this.#warn = options.warn ?? RotatingLogWriter.#defaultWarn;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
static fromRuntimeDir(runtimeDir: string): RotatingLogWriter | null {
|
|
58
|
+
if (process.env.AKAN_LOG_TO_FILE === "0") return null;
|
|
59
|
+
try {
|
|
60
|
+
const env = getEnv();
|
|
61
|
+
return new RotatingLogWriter({
|
|
62
|
+
logDir: path.resolve(process.env.AKAN_LOG_DIR ?? path.join(runtimeDir, "logs")),
|
|
63
|
+
appName: env.appName,
|
|
64
|
+
environment: env.environment,
|
|
65
|
+
operationMode: env.operationMode,
|
|
66
|
+
maxSizeBytes: RotatingLogWriter.#parseMaxSizeBytes(process.env.AKAN_LOG_MAX_SIZE_MB),
|
|
67
|
+
maxFiles: RotatingLogWriter.#parseMaxFiles(process.env.AKAN_LOG_MAX_FILES),
|
|
68
|
+
});
|
|
69
|
+
} catch (error) {
|
|
70
|
+
RotatingLogWriter.#defaultWarn(
|
|
71
|
+
`File logging disabled because runtime env could not be resolved: ${
|
|
72
|
+
error instanceof Error ? error.message : String(error)
|
|
73
|
+
}`,
|
|
74
|
+
);
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
static sanitizeFilePart(value: string) {
|
|
80
|
+
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
write(processKey: string, chunk: string) {
|
|
84
|
+
if (!chunk) return;
|
|
85
|
+
const safeProcessKey = RotatingLogWriter.sanitizeFilePart(processKey);
|
|
86
|
+
const date = dayjs(this.#now()).format("YYYY-MM-DD");
|
|
87
|
+
const queue = (this.#queues.get(safeProcessKey) ?? Promise.resolve())
|
|
88
|
+
.then(() => this.#writeQueued(safeProcessKey, date, chunk))
|
|
89
|
+
.catch((error) => {
|
|
90
|
+
this.#warn(`Failed to write Akan log file: ${error instanceof Error ? error.message : String(error)}`);
|
|
91
|
+
});
|
|
92
|
+
this.#queues.set(safeProcessKey, queue);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async close() {
|
|
96
|
+
await Promise.all([...this.#queues.values()].map((queue) => queue.catch(() => undefined)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async #writeQueued(processKey: string, date: string, chunk: string) {
|
|
100
|
+
await this.#ensureReady();
|
|
101
|
+
const byteLength = this.#encoder.encode(chunk).byteLength;
|
|
102
|
+
let state = this.#states.get(processKey);
|
|
103
|
+
let createdState = false;
|
|
104
|
+
|
|
105
|
+
if (!state || state.date !== date || (state.sizeBytes > 0 && state.sizeBytes + byteLength > this.#maxSizeBytes)) {
|
|
106
|
+
state = await this.#createState(processKey, date);
|
|
107
|
+
this.#states.set(processKey, state);
|
|
108
|
+
createdState = true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const filePath = this.#getFilePath(processKey, state.date, state.sequence);
|
|
112
|
+
await appendFile(filePath, chunk);
|
|
113
|
+
state.sizeBytes += byteLength;
|
|
114
|
+
if (createdState) await this.#cleanupRetention(processKey);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async #ensureReady() {
|
|
118
|
+
this.#ready ??= mkdir(this.#logDir, { recursive: true }).then(() => undefined);
|
|
119
|
+
await this.#ready;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async #createState(processKey: string, date: string): Promise<RotatingLogWriterState> {
|
|
123
|
+
const sequence = await this.#getNextSequence(processKey, date);
|
|
124
|
+
const filePath = this.#getFilePath(processKey, date, sequence);
|
|
125
|
+
let sizeBytes = 0;
|
|
126
|
+
try {
|
|
127
|
+
sizeBytes = (await stat(filePath)).size;
|
|
128
|
+
} catch {
|
|
129
|
+
sizeBytes = 0;
|
|
130
|
+
}
|
|
131
|
+
return { date, sequence, sizeBytes };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async #getNextSequence(processKey: string, date: string) {
|
|
135
|
+
const files = await this.#listProcessFiles(processKey);
|
|
136
|
+
const latestSequence = files
|
|
137
|
+
.filter((file) => file.date === date)
|
|
138
|
+
.reduce((latest, file) => Math.max(latest, file.sequence), 0);
|
|
139
|
+
return latestSequence + 1;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async #cleanupRetention(processKey: string) {
|
|
143
|
+
const files = await this.#listProcessFiles(processKey);
|
|
144
|
+
const staleFiles = files
|
|
145
|
+
.sort((a, b) => b.date.localeCompare(a.date) || b.sequence - a.sequence)
|
|
146
|
+
.slice(this.#maxFiles);
|
|
147
|
+
await Promise.all(staleFiles.map((file) => rm(path.join(this.#logDir, file.fileName), { force: true })));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async #listProcessFiles(processKey: string): Promise<RotatingLogWriterFile[]> {
|
|
151
|
+
let fileNames: string[];
|
|
152
|
+
try {
|
|
153
|
+
fileNames = await readdir(this.#logDir);
|
|
154
|
+
} catch {
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
return fileNames.flatMap((fileName) => {
|
|
158
|
+
if (!fileName.startsWith(`${this.#basePrefix}-`)) return [];
|
|
159
|
+
const rest = fileName.slice(this.#basePrefix.length + 1);
|
|
160
|
+
const match = /^(\d{4}-\d{2}-\d{2})-(.+)-(\d{4})\.log$/.exec(rest);
|
|
161
|
+
if (!match) return [];
|
|
162
|
+
const [, date, fileProcessKey, sequenceRaw] = match;
|
|
163
|
+
if (fileProcessKey !== processKey || !sequenceRaw) return [];
|
|
164
|
+
return [{ fileName, date, sequence: Number(sequenceRaw) }];
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
#getFilePath(processKey: string, date: string, sequence: number) {
|
|
169
|
+
return path.join(
|
|
170
|
+
this.#logDir,
|
|
171
|
+
`${this.#basePrefix}-${date}-${processKey}-${String(sequence).padStart(4, "0")}.log`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
static #parseMaxSizeBytes(value: string | undefined) {
|
|
176
|
+
const parsed = Number(value);
|
|
177
|
+
if (!Number.isFinite(parsed) || parsed <= 0) return RotatingLogWriter.defaultMaxSizeBytes;
|
|
178
|
+
return Math.floor(parsed * 1024 * 1024);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
static #parseMaxFiles(value: string | undefined) {
|
|
182
|
+
const parsed = Number.parseInt(value ?? "", 10);
|
|
183
|
+
if (!Number.isFinite(parsed) || parsed <= 0) return RotatingLogWriter.defaultMaxFiles;
|
|
184
|
+
return parsed;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
static #defaultWarn(message: string) {
|
|
188
|
+
process.stderr.write(`[AkanLog] ${message}\n`);
|
|
189
|
+
}
|
|
190
|
+
}
|